text
stringlengths
2.5k
6.39M
kind
stringclasses
3 values
import * as sinon from "sinon" import * as nock from "nock" import { Probot } from 'probot' const ArgocdBot = require("..") // test fixtures const payloadPr1 = require("./fixtures/issue_comment.created.pr1.json") const payloadPr1Closed = require("./fixtures/pull_request.closed.pr1.json") const payloadPr1UnlockComment = require("./fixtures/issue_comment.created.unlock.pr1.json") const payloadPr2 = require("./fixtures/issue_comment.created.pr2.json") nock.disableNetConnect() describe("argo-cd-bot", () => { let probot let sandbox // constants const argoCDToken = "token" const argoCDServer = "1.2.3.4" beforeEach(() => { probot = new Probot({}) const app = probot.load(ArgocdBot) app.app = () => "test" sandbox = sinon.createSandbox(); // few tests take longer to finish than the default time out of 5000 jest.setTimeout(7000) // node env variables process.env.ARGOCD_AUTH_TOKEN = argoCDToken process.env.ARGOCD_SERVER = argoCDServer }) afterEach(() => { sandbox.restore() }) test("diff comment posted on PR, one app in argocd server", async() => { nock("https://api.github.com") .post("/app/installations/2/access_tokens") .reply(200, {token: "test"}) // test constants const branch = "newBranch" const appDiff = "===== App Diff ====" const appName = "app1" const appDir = "projects/app1" nock("https://api.github.com").get("/repos/robotland/test/pulls").reply(200, {"data": {"number": 109, "head": { "ref": branch}}}) // bot should get sha for commit and post status check on PR nock("https://api.github.com").get("/repos/robotland/test/pulls").reply(200, {"data": {"number": 109, "head": { "ref": branch, "sha": "6dcb09b5b57875f334f61aebed695e2e4193db5e", "repo": { "id": 1296269, "node_id": "MDEwOlJlcG9zaXRvcnkxMjk2MjY5", "name": "Hello-World", "full_name": "octocat/Hello-World", "owner": { "login": "octocat" }}}}}); nock("https://api.github.com").post("/repos/octocat/Hello-World/statuses/6dcb09b5b57875f334f61aebed695e2e4193db5e", /success/).reply(200) const child_process = require("child_process") const execStub = sandbox.stub(child_process, "exec") // first exec, will fork script to clone repo execStub.onCall(0).yields(false) // second will be diff exec execStub.onCall(1).yields(false, appDiff, "") nock("http://" + argoCDServer).get("/api/v1/applications?fields=items.metadata.name,items.spec.source.path,items.spec.source.repoURL") .reply(200, {"items": [{"metadata": { "name": appName }, "spec": { "source": { "path": appDir } } }] }) // regex match post body should match diff produced by API nock("https://api.github.com").post("/repos/robotland/test/issues/109/comments", /===== App Diff ====/).reply(200) nock("https://api.github.com").post("/repos/robotland/test/issues/109/comments", /If Auto-sync is enabled just merge this PR to deploy the above changes/).reply(200) await probot.receive({name: "issue_comment", payload: payloadPr1}) }) test("diff comment posted on PR, one app in argocd server error in diff", async() => { nock("https://api.github.com") .post("/app/installations/2/access_tokens") .reply(200, {token: "test"}) // test constants const branch = "newBranch" const appDiff = "===== App Diff ====" const appName = "app1" const appDir = "projects/app1" nock("https://api.github.com").get("/repos/robotland/test/pulls").reply(200, {"data": {"number": 109, "head": { "ref": branch}}}) nock("https://api.github.com").get("/repos/robotland/test/pulls").reply(200, {"data": {"number": 109, "head": { "ref": branch, "sha": "6dcb09b5b57875f334f61aebed695e2e4193db5e", "repo": { "id": 1296269, "node_id": "MDEwOlJlcG9zaXRvcnkxMjk2MjY5", "name": "Hello-World", "full_name": "octocat/Hello-World", "owner": { "login": "octocat" }}}}}); // bot should post status check on PR nock("https://api.github.com").post("/repos/octocat/Hello-World/statuses/6dcb09b5b57875f334f61aebed695e2e4193db5e", /failure/).reply(200) const child_process = require("child_process") const execStub = sandbox.stub(child_process, "exec") // first exec, will fork script to clone repo execStub.onCall(0).yields(false) nock("http://" + argoCDServer).get("/api/v1/applications?fields=items.metadata.name,items.spec.source.path,items.spec.source.repoURL") .reply(200, {"items": [{"metadata": { "name": appName }, "spec": { "source": { "path": appDir } } }] }) execStub.onCall(1).yields({code: 2}, "", "stderr") nock("https://api.github.com").post("/repos/robotland/test/issues/109/comments", /returned an error/).reply(200) await probot.receive({name: "issue_comment", payload: payloadPr1}) }) test("diff comment posted on PR with non-existent --dir", async() => { nock("https://api.github.com") .post("/app/installations/2/access_tokens") .reply(200, {token: "test"}) // test constants const branch = "newBranch" const appDiff = "===== App Diff ====" const appName = "app1" const appDir = "projects/app1" nock("https://api.github.com").get("/repos/robotland/test/pulls").reply(200, {"data": {"number": 109, "head": { "ref": branch}}}) nock("https://api.github.com").get("/repos/robotland/test/pulls").reply(200, {"data": {"number": 109, "head": { "ref": branch, "sha": "6dcb09b5b57875f334f61aebed695e2e4193db5e", "repo": { "id": 1296269, "node_id": "MDEwOlJlcG9zaXRvcnkxMjk2MjY5", "name": "Hello-World", "full_name": "octocat/Hello-World", "owner": { "login": "octocat" }}}}}); // bot should post status check on PR nock("https://api.github.com").post("/repos/octocat/Hello-World/statuses/6dcb09b5b57875f334f61aebed695e2e4193db5e", /failure/).reply(200) const child_process = require("child_process") const execStub = sandbox.stub(child_process, "exec") // first exec, will fork script to clone repo execStub.onCall(0).yields(false) nock("http://" + argoCDServer).get("/api/v1/applications?fields=items.metadata.name,items.spec.source.path,items.spec.source.repoURL") .reply(200, {"items": [{"metadata": { "name": appName }, "spec": { "source": { "path": appDir } } }, {"metadata": { "name": appName + "2" }, "spec": { "source": { "path": appDir + "2"} } }] }) execStub.onCall(1).yields(false, appDiff) // regex match post body should match diff produced by API nock("https://api.github.com").post("/repos/robotland/test/issues/109/comments", /No Kubernetes deployments found, try running/).reply(200) let diffPayload = JSON.parse(JSON.stringify(payloadPr1)) diffPayload["comment"]["body"] = "argo diff --dir ./non-existent" await probot.receive({name: "issue_comment", payload: diffPayload}) }) test("diff comment posted on PR with --dir flag", async() => { nock("https://api.github.com") .post("/app/installations/2/access_tokens") .reply(200, {token: "test"}) // test constants const branch = "newBranch" const appDiff = "===== App Diff ====" const appName = "app1" const appDir = "projects/app1" nock("https://api.github.com").get("/repos/robotland/test/pulls").reply(200, {"data": {"number": 109, "head": { "ref": branch}}}) nock("https://api.github.com").get("/repos/robotland/test/pulls").reply(200, {"data": {"number": 109, "head": { "ref": branch, "sha": "6dcb09b5b57875f334f61aebed695e2e4193db5e", "repo": { "id": 1296269, "node_id": "MDEwOlJlcG9zaXRvcnkxMjk2MjY5", "name": "Hello-World", "full_name": "octocat/Hello-World", "owner": { "login": "octocat" }}}}}); // bot should post status check on PR nock("https://api.github.com").post("/repos/octocat/Hello-World/statuses/6dcb09b5b57875f334f61aebed695e2e4193db5e", /success/).reply(200) const child_process = require("child_process") const execStub = sandbox.stub(child_process, "exec") // first exec, will fork script to clone repo execStub.onCall(0).yields(false) nock("http://" + argoCDServer).get("/api/v1/applications?fields=items.metadata.name,items.spec.source.path,items.spec.source.repoURL") .reply(200, {"items": [{"metadata": { "name": appName }, "spec": { "source": { "path": appDir } } }, {"metadata": { "name": appName + "2" }, "spec": { "source": { "path": "randomDir"} } }] }) execStub.onCall(1).yields(false, appDiff) // regex match post body should match diff produced by API nock("https://api.github.com").post("/repos/robotland/test/issues/109/comments", /===== App Diff ====/).reply(200) nock("https://api.github.com").post("/repos/robotland/test/issues/109/comments", /If Auto-sync is enabled just merge this PR to deploy the above changes/).reply(200) let diffPayload = JSON.parse(JSON.stringify(payloadPr1)) diffPayload["comment"]["body"] = "argo diff --dir " + appDir await probot.receive({name: "issue_comment", payload: diffPayload}) }) // same test as above, but using -d instead of --dir test("diff comment posted on PR with -d flag", async() => { nock("https://api.github.com") .post("/app/installations/2/access_tokens") .reply(200, {token: "test"}) // test constants const branch = "newBranch" const appDiff = "===== App Diff ====" const appName = "app1" const appDir = "projects/app1" nock("https://api.github.com").get("/repos/robotland/test/pulls").reply(200, {"data": {"number": 109, "head": { "ref": branch}}}) nock("https://api.github.com").get("/repos/robotland/test/pulls").reply(200, {"data": {"number": 109, "head": { "ref": branch, "sha": "6dcb09b5b57875f334f61aebed695e2e4193db5e", "repo": { "id": 1296269, "node_id": "MDEwOlJlcG9zaXRvcnkxMjk2MjY5", "name": "Hello-World", "full_name": "octocat/Hello-World", "owner": { "login": "octocat" }}}}}); // bot should post status check on PR nock("https://api.github.com").post("/repos/octocat/Hello-World/statuses/6dcb09b5b57875f334f61aebed695e2e4193db5e", /success/).reply(200) const child_process = require("child_process") const execStub = sandbox.stub(child_process, "exec") // first exec, will fork script to clone repo execStub.onCall(0).yields(false) nock("http://" + argoCDServer).get("/api/v1/applications?fields=items.metadata.name,items.spec.source.path,items.spec.source.repoURL") .reply(200, {"items": [{"metadata": { "name": appName }, "spec": { "source": { "path": appDir } } }, {"metadata": { "name": appName + "2" }, "spec": { "source": { "path": "randomdir"} } }] }) execStub.onCall(1).yields(false, appDiff) // regex match post body should match diff produced by API nock("https://api.github.com").post("/repos/robotland/test/issues/109/comments", /===== App Diff ====/).reply(200) nock("https://api.github.com").post("/repos/robotland/test/issues/109/comments", /If Auto-sync is enabled just merge this PR to deploy the above changes/).reply(200) let diffPayload = JSON.parse(JSON.stringify(payloadPr1)) diffPayload["comment"]["body"] = "argo diff -d " + appDir await probot.receive({name: "issue_comment", payload: diffPayload}) }) test("diff comment posted on PR, two apps in argocd server, one app has diff", async() => { nock("https://api.github.com") .post("/app/installations/2/access_tokens") .reply(200, {token: "test"}) // test constants const branch = "newBranch" const appDiff = "===== App Diff ====" const appName = "app1" const appDir = "projects/app1" nock("https://api.github.com").get("/repos/robotland/test/pulls").reply(200, {"data": {"number": 109, "head": { "ref": branch}}}) const child_process = require("child_process") const execStub = sandbox.stub(child_process, "exec") // first exec, will fork script to clone repo execStub.onCall(0).yields(false) nock("http://" + argoCDServer).get("/api/v1/applications?fields=items.metadata.name,items.spec.source.path,items.spec.source.repoURL") .reply(200, {"items": [{"metadata": { "name": appName }, "spec": { "source": { "path": appDir } } }, {"metadata": { "name": appName + "2" }, "spec": { "source": { "path": appDir + "2"} } }] }) // exec calls to argocd app diff, return diff for both one app execStub.onCall(1).yields(false, appDiff) // second call returns an empty diff in stdout execStub.onCall(2).yields(false, "") // regex match post body should match diff produced by API nock("https://api.github.com").post("/repos/robotland/test/issues/109/comments", /===== App Diff ====/).reply(200) nock("https://api.github.com").post("/repos/robotland/test/issues/109/comments", /If Auto-sync is enabled just merge this PR to deploy the above changes/).reply(200) // bot should post status check on PR nock("https://api.github.com").get("/repos/robotland/test/pulls").reply(200, {"data": {"number": 109, "head": { "ref": branch, "sha": "6dcb09b5b57875f334f61aebed695e2e4193db5e", "repo": { "id": 1296269, "node_id": "MDEwOlJlcG9zaXRvcnkxMjk2MjY5", "name": "Hello-World", "full_name": "octocat/Hello-World", "owner": { "login": "octocat" }}}}}); nock("https://api.github.com").post("/repos/octocat/Hello-World/statuses/6dcb09b5b57875f334f61aebed695e2e4193db5e", /success/).reply(200) await probot.receive({name: "issue_comment", payload: payloadPr1}) }) test("diff comment posted on PR, two apps in argocd server", async() => { nock("https://api.github.com") .post("/app/installations/2/access_tokens") .reply(200, {token: "test"}) // test constants const branch = "newBranch" const appDiff = "===== App Diff ====" const appName = "app1" const appDir = "projects/app1" nock("https://api.github.com").get("/repos/robotland/test/pulls").reply(200, {"data": {"number": 109, "head": { "ref": branch}}}) nock("https://api.github.com").get("/repos/robotland/test/pulls").reply(200, {"data": {"number": 109, "head": { "ref": branch, "sha": "6dcb09b5b57875f334f61aebed695e2e4193db5e", "repo": { "id": 1296269, "node_id": "MDEwOlJlcG9zaXRvcnkxMjk2MjY5", "name": "Hello-World", "full_name": "octocat/Hello-World", "owner": { "login": "octocat" }}}}}); // bot should post status check on PR nock("https://api.github.com").post("/repos/octocat/Hello-World/statuses/6dcb09b5b57875f334f61aebed695e2e4193db5e", /success/).reply(200) const child_process = require("child_process") const execStub = sandbox.stub(child_process, "exec") // first exec, will fork script to clone repo execStub.onCall(0).yields(false) nock("http://" + argoCDServer).get("/api/v1/applications?fields=items.metadata.name,items.spec.source.path,items.spec.source.repoURL") .reply(200, {"items": [{"metadata": { "name": appName }, "spec": { "source": { "path": appDir } } }, {"metadata": { "name": appName + "2" }, "spec": { "source": { "path": appDir + "2"} } }] }) // exec calls to argocd app diff, return diff for both apps execStub.onCall(1).yields(false, appDiff) execStub.onCall(2).yields(false, appDiff) // regex match post body should match diff produced by API // since there are two apps with diffs, bot will produce a comment for each app diff nock("https://api.github.com").post("/repos/robotland/test/issues/109/comments", /===== App Diff ====/).reply(200) nock("https://api.github.com").post("/repos/robotland/test/issues/109/comments", /If Auto-sync is enabled just merge this PR to deploy the above changes/).reply(200) nock("https://api.github.com").post("/repos/robotland/test/issues/109/comments", /===== App Diff ====/).reply(200) nock("https://api.github.com").post("/repos/robotland/test/issues/109/comments", /If Auto-sync is enabled just merge this PR to deploy the above changes/).reply(200) await probot.receive({name: "issue_comment", payload: payloadPr1}) }) test("diff --auto-sync comment posted on PR", async() => { nock("https://api.github.com") .post("/app/installations/2/access_tokens") .reply(200, {token: "test"}) // test constants const branch = "newBranch" const appDiff = "===== App Diff ====" const appName = "app1" const appDir = "projects/app1" nock("https://api.github.com").get("/repos/robotland/test/pulls").reply(200, {"data": {"number": 109, "head": { "ref": branch}}}) nock("https://api.github.com").get("/repos/robotland/test/pulls").reply(200, {"data": {"number": 109, "head": { "ref": branch, "sha": "6dcb09b5b57875f334f61aebed695e2e4193db5e", "repo": { "id": 1296269, "node_id": "MDEwOlJlcG9zaXRvcnkxMjk2MjY5", "name": "Hello-World", "full_name": "octocat/Hello-World", "owner": { "login": "octocat" }}}}}); // bot should post status check on PR nock("https://api.github.com").post("/repos/octocat/Hello-World/statuses/6dcb09b5b57875f334f61aebed695e2e4193db5e", /success/).reply(200) const child_process = require("child_process") const execStub = sandbox.stub(child_process, "exec") // first exec, will fork script to clone repo execStub.onCall(0).yields(false) nock("http://" + argoCDServer).get("/api/v1/applications?fields=items.metadata.name,items.spec.source.path,items.spec.source.repoURL,items.spec.syncPolicy.automated") .reply(200, {"items": [{"metadata": { "name": appName }, "spec": { "source": { "path": appDir } } }, {"metadata":{"name":"atlantis"},"spec":{"source": { "path": appDir }, "syncPolicy":{"automated":{}}}}] }) execStub.onCall(1).yields(false, appDiff) // regex match post body should match diff produced by API nock("https://api.github.com").post("/repos/robotland/test/issues/109/comments", /===== App Diff ====/).reply(200) nock("https://api.github.com").post("/repos/robotland/test/issues/109/comments", /If Auto-sync is enabled just merge this PR to deploy the above changes/).reply(200) // copy json object let autoSyncPayload = JSON.parse(JSON.stringify(payloadPr1)) autoSyncPayload["comment"]["body"] = "argo diff --auto-sync" await probot.receive({name: "issue_comment", payload: autoSyncPayload}) }) test("diff comment posted on PR with --app flag", async() => { nock("https://api.github.com") .post("/app/installations/2/access_tokens") .reply(200, {token: "test"}) // test constants const branch = "newBranch" const appDiff = "===== App Diff ====" const appName = "app1" const appDir = "projects/app1" nock("https://api.github.com").get("/repos/robotland/test/pulls").reply(200, {"data": {"number": 109, "head": { "ref": branch}}}) nock("https://api.github.com").get("/repos/robotland/test/pulls").reply(200, {"data": {"number": 109, "head": { "ref": branch, "sha": "6dcb09b5b57875f334f61aebed695e2e4193db5e", "repo": { "id": 1296269, "node_id": "MDEwOlJlcG9zaXRvcnkxMjk2MjY5", "name": "Hello-World", "full_name": "octocat/Hello-World", "owner": { "login": "octocat" }}}}}); // bot should post status check on PR nock("https://api.github.com").post("/repos/octocat/Hello-World/statuses/6dcb09b5b57875f334f61aebed695e2e4193db5e", /success/).reply(200) const child_process = require("child_process") const execStub = sandbox.stub(child_process, "exec") // first exec, will fork script to clone repo execStub.onCall(0).yields(false) nock("http://" + argoCDServer).get("/api/v1/applications/" + appName) .reply(200, {"metadata": {}, "spec": {"source": { "path": appDir } } }) execStub.onCall(1).yields(false, appDiff) // regex match post body should match diff produced by API nock("https://api.github.com").post("/repos/robotland/test/issues/109/comments", /===== App Diff ====/).reply(200) nock("https://api.github.com").post("/repos/robotland/test/issues/109/comments", /If Auto-sync is enabled just merge this PR to deploy the above changes/).reply(200) let diffPayload = JSON.parse(JSON.stringify(payloadPr1)) diffPayload["comment"]["body"] = "argo diff --app " + appName await probot.receive({name: "issue_comment", payload: diffPayload}) }) })
the_stack
import * as funcs from './funcs'; import { Vec4, Point, CoorList, RegionPoint, Rect, Edge } from './types'; /** * Create a LineSegmentDetector object. * Specifying scale, number of subdivisions for the image, * should the lines be refined and other constants as follows: * * @param refine How should the lines found be refined? * REFINE_NONE - No refinement applied. * REFINE_STD - Standard refinement is applied. E.g. breaking arches into smaller line approximations. * REFINE_ADV - Advanced refinement. Number of false alarms is calculated, * lines are refined through increase of precision, decrement in size, etc. * @param scale The scale of the image that will be used to find the lines. Range (0..1]. * @param sigmaScale Sigma for Gaussian filter is computed as sigma = _sigma_scale/_scale. * @param quant Bound to the quantization error on the gradient norm. * @param angTh Gradient angle tolerance in degrees. * @param logEps Detection threshold: -log10(NFA) > _log_eps * @param densityTh Minimal density of aligned region points in rectangle. * @param nBins Number of bins in pseudo-ordering of gradient modulus. */ export default class LSD { image?: ImageData; private imageData?: Uint8ClampedArray; width = 0; height = 0; list: CoorList[] = []; angles?: Float64Array; modgrad?: Float64Array; used?: Uint8Array; constructor( public refineType = funcs.REFINE_NONE, public scale = 0.8, public sigmaScale = 0.6, public quant = 2.0, public angTh = 22.5, public logEps = 0.0, public densityTh = 0.7, public nBins = 1024 ) { } /** * Detect lines in the input image. * @param {ImageData} image * @return {Vec4[]} */ detect(image: ImageData) { this.image = image; this.width = image.width; this.height = image.height; const lines = this.lsd(); return lines; } /** * Draws the line segments on a given image. * @param {CanvasRenderingContext2D} context * @param {Vec4[]} lines * @param {string} color */ drawSegments(context: CanvasRenderingContext2D, lines: Vec4[], color = '#ff0000') { context.strokeStyle = color; context.lineWidth = 1; lines.forEach(v => { context.beginPath(); context.moveTo(v.x1, v.y1); context.lineTo(v.x2, v.y2); context.stroke(); context.closePath(); }); } /** * for debug * @param {CanvasRenderingContext2D} context */ putImageData(context: CanvasRenderingContext2D) { let src = this.imageData, image = context.createImageData(this.width, this.height), dst = image.data, len = image.data.length; if (!src) throw new Error('imageData required'); // type guard for (let i = 0; i < len; i += 4) { dst[i] = dst[i + 1] = dst[i + 2] = src[i/4]; dst[i + 3] = 255; } context.putImageData(image, 0, 0); } /** * @return {Vec4[]} Return: A vector of Vec4f elements specifying the beginning and ending point of a line. * Where Vec4f is (x1, y1, x2, y2), point 1 is the start, point 2 - end. * Returned lines are strictly oriented depending on the gradient. */ lsd() { if (!this.image || !this.angles) throw new Error('image and angles required'); // type guard /** @type {Vec4[]} */ let lines = []; const prec = Math.PI * this.angTh / 180; const p = this.angTh / 180; const rho = this.quant / Math.sin(prec); if (this.scale != 1) { const sigma = this.scale < 1 ? this.sigmaScale / this.scale : this.sigmaScale; const sprec = 3; const h = Math.ceil(sigma * Math.sqrt(2 * sprec * Math.log(10.0))); const kSize = 1 + 2 * h; const reshaped = this.reshape(this.image); this.imageData = this.gaussianBlur(reshaped, kSize, sigma); this.computeLevelLineAngles(rho, this.nBins); } else { this.imageData = this.reshape(this.image); this.computeLevelLineAngles(rho, this.nBins); } const LOG_NT = 5 * (Math.log10(this.width) + Math.log10(this.height)) / 2 + Math.log10(11.0); const minRegSize = -LOG_NT / Math.log10(p); this.used = new Uint8Array(this.imageData.length); for (let i = 0, listSize = this.list.length; i < listSize; i++) { const point = this.list[i].p; if ((this.at(this.used, point) === funcs.NOT_USED) && (this.at(this.angles, point) !== funcs.NOT_DEF)) { let regAngle = 0.0; let reg: RegionPoint[] = []; regAngle = this.regionGrow(this.list[i].p, reg, regAngle, prec); if (reg.length < minRegSize) { continue; } let rect = new Rect(); this.region2Rect(reg, regAngle, prec, p, rect); let logNfa = -1; if (this.refineType > funcs.REFINE_NONE) { if (!this.refine(reg, regAngle, prec, p, rect, this.densityTh)) { continue; } if (this.refineType >= funcs.REFINE_ADV) { logNfa = this.improveRect(rect); if (logNfa <= this.logEps) { continue; } } } rect.x1 += 0.5; rect.y1 += 0.5; rect.x2 += 0.5; rect.y2 += 0.5; /* if (this.scale != 1) { rect.x1 /= this.scale; rect.y1 /= this.scale; rect.x2 /= this.scale; rect.y2 /= this.scale; rect.width /= this.scale; } */ lines.push(new Vec4(rect.x1, rect.y1, rect.x2, rect.y2)); } } return lines; } /** * @param {number} threshold The minimum value of the angle that is considered defined, otherwise NOTDEF * @param {number} nBins The number of bins with which gradients are ordered by, using bucket sort. */ computeLevelLineAngles(threshold: number, nBins: number) { const imageData = this.imageData; if (!imageData) throw new Error('imageData required'); // type guard const width = this.width; const height = this.height; this.angles = new Float64Array(imageData.length); this.modgrad = new Float64Array(imageData.length); this.angles = this.setRow(this.angles, height - 1, funcs.NOT_DEF); this.angles = this.setCol(this.angles, width - 1, funcs.NOT_DEF); let maxGrad = -1.0; for (let y = 0; y < height - 1; y++) { const step = y * width; const nextStep = (y + 1) * width; for (let x = 0; x < width - 1; x++) { const DA = imageData[x + 1 + nextStep] - imageData[x + step]; const BC = imageData[x + 1 + step] - imageData[x + nextStep]; const gx = DA + BC; const gy = DA - BC; const norm = Math.sqrt((gx * gx + gy * gy) / 4.0); this.modgrad[x + step] = norm; if (norm <= threshold) { this.angles[x + step] = funcs.NOT_DEF; } else { this.angles[x + step] = Math.atan2(gx, -gy); if (norm > maxGrad) { maxGrad = norm; } } } } /** @type {CoorList[]} */ let rangeS = []; rangeS.length = nBins; /** @type {CoorList[]} */ let rangeE = []; rangeE.length = nBins; let count = 0; const binCoef = (maxGrad > 0) ? (nBins - 1) / maxGrad : 0; for (let y = 0; y < height - 1; y++) { let step = y * width; for (let x = 0; x < width - 1; x++) { let i = Math.floor(this.modgrad[x + step] * binCoef); if (!rangeE[i]) { this.list[count] = new CoorList(); rangeE[i] = rangeS[i] = this.list[count]; count++; } else { this.list[count] = new CoorList(); rangeE[i] = this.list[count]; rangeE[i].next = this.list[count]; count++; } rangeE[i].p = new Point(x, y); rangeE[i].next = null; } } let idx = nBins - 1; for (; idx > 0 && !rangeS[idx]; idx--) { // do nothing. } let start = rangeS[idx]; let endIdx = idx; if (start) { while (idx > 0) { idx--; if (rangeS[idx]) { rangeE[endIdx].next = rangeS[idx]; rangeE[endIdx] = rangeE[idx]; endIdx = idx; } } } } regionGrow(s: Point, reg: RegionPoint[], regAngle: number, prec: number) { if (!this.used || !this.angles || !this.modgrad) throw new Error('used, angles and modgrad required'); // type guard let seed = new RegionPoint(); seed.x = s.x; seed.y = s.y; seed.used = this.at(this.used, s); regAngle = this.at(this.angles, s); seed.angle = regAngle; seed.modgrad = this.at(this.modgrad, s); seed.used = funcs.USED; reg.push(seed); let sumdx = Math.cos(regAngle); let sumdy = Math.sin(regAngle); for (let i = 0; i < reg.length; i++) { const rpoint = reg[i], xxMin = Math.max(rpoint.x - 1, 0), xxMax = Math.min(rpoint.x + 1, this.width - 1), yyMin = Math.max(rpoint.y - 1, 0), yyMax = Math.min(rpoint.y + 1, this.height - 1); for (let yy = yyMin; yy <= yyMax; yy++) { const step = yy * this.width; for (let xx = xxMin; xx <= xxMax; xx++) { let isUsed = this.used[xx + step]; if (isUsed != funcs.USED && this.isAligned(xx, yy, regAngle, prec)) { const angle = this.angles[xx + step]; isUsed = funcs.USED; this.used[xx + step] = funcs.USED; let regionPoint = new RegionPoint( xx, yy, angle, this.modgrad[xx + step], isUsed ); reg.push(regionPoint); sumdx += Math.cos(angle); sumdy += Math.sin(angle); regAngle = Math.atan2(sumdy, sumdx); } } } } return regAngle; } isAligned(x: number, y: number, theta: number, prec: number) { if (x < 0 || y < 0 || x >= this.width || y >= this.height) { return false; } const a = this.angles![x + y * this.width]; if (a === funcs.NOT_DEF) { return false; } let nTheta = theta - a; if (nTheta < 0) { nTheta = -nTheta; } if (nTheta > funcs.M_3_2_PI) { nTheta -= funcs.M_2__PI; if (nTheta < 0) { nTheta = -nTheta; } } return nTheta <= prec; } region2Rect(reg: RegionPoint[], regAngle: number, prec: number, p: number, rect: Rect) { let x = 0, y = 0, sum = 0; for (let i = 0; i < reg.length; i++) { const pnt = reg[i]; const weight = pnt.modgrad; x += pnt.x * weight; y += pnt.y * weight; sum += weight; } if (sum <= 0) { throw new Error('weighted sum must differ from 0'); } x /= sum; y /= sum; const theta = this.getTheta(reg, x, y, regAngle, prec); const dx = Math.cos(theta); const dy = Math.sin(theta); let lMin = 0, lMax = 0, wMin = 0, wMax = 0; for (let i = 0; i < reg.length; i++) { let regdx = reg[i].x - x; let regdy = reg[i].y - y; let l = regdx * dx + regdy * dy; let w = -regdx * dy + regdy * dx; if (l > lMax) { lMax = l; } else if (l < lMin) { lMin = l; } if (w > wMax) { wMax = w; } else if (w < wMin) { wMin = w; } } rect.x1 = x + lMin * dx; rect.y1 = y + lMin * dy; rect.x2 = x + lMax * dx; rect.y2 = y + lMax * dy; rect.width = wMax - wMin; rect.x = x; rect.y = y; rect.theta = theta; rect.dx = dx; rect.dy = dy; rect.prec = prec; rect.p = p; if (rect.width < 1.0) { rect.width = 1.0; } } getTheta(reg: RegionPoint[], x: number, y: number, regAngle: number, prec: number) { let ixx = 0.0, iyy = 0.0, ixy = 0.0; for (let i = 0; i < reg.length; i++) { const regx = reg[i].x; const regy = reg[i].y; const weight = reg[i].modgrad; let dx = regx - x; let dy = regy - y; ixx += dy * dy * weight; iyy += dx * dx * weight; ixy -= dx * dy * weight; } let check = (funcs.doubleEqual(ixx, 0) && funcs.doubleEqual(iyy, 0) && funcs.doubleEqual(ixy, 0)); if (check) { throw new Error('check if inertia matrix is null'); } let lambda = 0.5 * (ixx + iyy - Math.sqrt((ixx - iyy) * (ixx - iyy) + 4.0 * ixy * ixy)); let theta = (Math.abs(ixx) > Math.abs(iyy)) ? Math.atan2(lambda - ixx, ixy) : Math.atan2(ixy, lambda - iyy); if (funcs.angleDiff(theta, regAngle) > prec) { theta += Math.PI; } return theta; } refine(reg: RegionPoint[], regAngle: number, prec: number, p: number, rect: Rect, densityTh: number) { let density = reg.length / (funcs.dist(rect.x1, rect.y1, rect.x2, rect.y2) * rect.width); if (density >= densityTh) { return true; } let xc = reg[0].x; let yc = reg[0].y; const angC = reg[0].angle; let sum = 0, sSum = 0, n = 0; for (let i = 0; i < reg.length; i++) { reg[i].used = funcs.NOT_USED; if (funcs.dist(xc, yc, reg[i].x, reg[i].y) < rect.width) { const angle = reg[i].angle; let angD = funcs.angleDiff(angle, angC); sum += angD; sSum += angD * angD; n++; } let meanAngle = sum / n; let tau = 2.0 * Math.sqrt((sSum - 2.0 * meanAngle * sum) / n + meanAngle * meanAngle); this.regionGrow(new Point(reg[0].x, reg[0].y), reg, regAngle, tau); if (reg.length < 2) { return false; } this.region2Rect(reg, regAngle, prec, p, rect); density = reg.length / (funcs.dist(rect.x1, rect.y1, rect.x2, rect.y2) * rect.width); if (density < densityTh) { return this.reduceRegionRadius(reg, regAngle, prec, p, rect, density, densityTh); } else { return true; } } return false; // type guard (unreachable) } reduceRegionRadius(reg: RegionPoint[], regAngle: number, prec: number, p: number, rect: Rect, density: number, densityTh: number) { let xc = reg[0].x; let yc = reg[0].y; let radSq1 = funcs.distSq(xc, yc, rect.x1, rect.y1); let radSq2 = funcs.distSq(xc, yc, rect.x2, rect.y2); let radSq = radSq1 > radSq2 ? radSq1 : radSq2; while (density < densityTh) { radSq *= 0.75 * 0.75; // reduce region's radius to 75% for (let i = 0; i < reg.length; i++) { if (funcs.distSq(xc, yc, reg[i].x, reg[i].y) > radSq) { // remove point from the region reg[i].used = funcs.NOT_USED; const tmp = reg[i]; reg[i] = reg[reg.length - 1]; reg[reg.length - 1] = tmp; reg.pop(); --i; } } if (reg.length < 2) { return false; } this.region2Rect(reg, regAngle, prec, p, rect); density = reg.length / (funcs.dist(rect.x1, rect.y1, rect.x2, rect.y2) * rect.width); } return true; } improveRect(rect: Rect) { let delta = 0.5; let delta2 = delta / 2.0; let logNfa = this.rectNfa(rect); if (logNfa > this.logEps) { return logNfa; } let r = new Rect(); r.copy(rect); for (let n = 0; n < 5; n++) { r.p /= 2; r.prec = r.p * Math.PI; let logNfaNew = this.rectNfa(rect); if (logNfaNew > logNfa) { logNfa = logNfaNew; rect.copy(r); } } if (logNfa > this.logEps) { return logNfa; } r.copy(rect); for (let n = 0; n < 5; n++) { if ((r.width - delta) >= 0.5) { r.width -= delta; let logNfaNew = this.rectNfa(r); if (logNfaNew > logNfa) { rect.copy(r); logNfa = logNfaNew; } } } if (logNfa > this.logEps) { return logNfa; } r.copy(rect); for (let n = 0; n < 5; n++) { if ((r.width - delta) >= 0.5) { r.x1 -= -r.dy * delta2; r.y1 -= r.dx * delta2; r.x2 -= -r.dy * delta2; r.y2 -= r.dx * delta2; r.width -= delta; let logNfaNew = this.rectNfa(r); if (logNfaNew > logNfa) { rect.copy(r); logNfa = logNfaNew; } } } if (logNfa > this.logEps) { return logNfa; } r.copy(rect); for (let n = 0; n < 5; n++) { if ((r.width - delta) >= 0.5) { r.p /= 2; r.prec = r.p * Math.PI; let logNfaNew = this.rectNfa(r); if (logNfaNew > logNfa) { rect.copy(r); logNfa = logNfaNew; } } } return logNfa; } rectNfa(rect: Rect) { let totalPts = 0, algPts = 0, halfWidth = rect.width / 2.0, dyhw = rect.dy * halfWidth, dxhw = rect.dx * halfWidth, orderedX = [ new Edge(), new Edge(), new Edge(), new Edge() ], minY = orderedX[0], maxY = orderedX[0]; orderedX[0].p.x = rect.x1 - dyhw; orderedX[0].p.y = rect.y1 + dxhw; orderedX[1].p.x = rect.x2 - dyhw; orderedX[1].p.y = rect.y2 + dxhw; orderedX[2].p.x = rect.x2 + dyhw; orderedX[2].p.y = rect.y2 - dxhw; orderedX[3].p.x = rect.x1 + dyhw; orderedX[3].p.y = rect.y1 - dxhw; orderedX.sort(funcs.AsmallerB_XoverY); for (let i = 1; i < 4; i++) { if (minY.p.y > orderedX[i].p.y) { minY = orderedX[i]; } if (maxY.p.y < orderedX[i].p.y) { maxY = orderedX[i]; } } minY.taken = true; let leftmost = null; for (let i = 0; i < 4; i++) { if (!orderedX[i].taken) { if (!leftmost) { leftmost = orderedX[i]; } else if (leftmost.p.x > orderedX[i].p.x) { leftmost = orderedX[i]; } } } if (!leftmost) throw new Error('leftmost error'); // type guard leftmost.taken = true; let rightmost = null; for (let i = 0; i < 4; i++) { if (!orderedX[i].taken) { if (!rightmost) { rightmost = orderedX[i]; } else if (rightmost.p.x < orderedX[i].p.x) { rightmost = orderedX[i]; } } } if (!rightmost) throw new Error('rightmost error'); // type guard rightmost.taken = true; let tailp = null; for (let i = 0; i < 4; i++) { if (!orderedX[i].taken) { if (!tailp) { tailp = orderedX[i]; } else if (tailp.p.x > orderedX[i].p.x) { tailp = orderedX[i]; } } } if (!tailp) throw new Error('tailp error'); // type guard tailp.taken = true; let flstep = (minY.p.y != leftmost.p.y) ? (minY.p.x + leftmost.p.x) / (minY.p.y - leftmost.p.y) : 0; let slstep = (leftmost.p.y != tailp.p.x) ? (leftmost.p.x = tailp.p.x) / (leftmost.p.y - tailp.p.x) : 0; let frstep = (minY.p.y != rightmost.p.y) ? (minY.p.x - rightmost.p.x) / (minY.p.y - rightmost.p.y) : 0; let srstep = (rightmost.p.y != tailp.p.x) ? (rightmost.p.x - tailp.p.x) / (rightmost.p.y - tailp.p.x) : 0; let lstep = flstep, rstep = frstep; let leftX = minY.p.x, rightX = minY.p.x; let minIter = minY.p.y; let maxIter = maxY.p.y; for (let y = minIter; y <= maxIter; y++) { if (y < 0 || y >= this.height) { continue; } for (let x = leftX; x <= rightX; x++) { if (x < 0 || x >= this.width) { continue; } totalPts++; if (this.isAligned(x, y, rect.theta, rect.prec)) { algPts++; } } if (y >= leftmost.p.y) { lstep = slstep; } if (y >= rightmost.p.y) { rstep = srstep; } leftX += lstep; rightX += rstep; } return this.nfa(totalPts, algPts, rect.p); } nfa(n: number, k: number, p: number) { const LOG_NT = 5 * (Math.log10(this.width) + Math.log10(this.height)) / 2 + Math.log10(11.0); if (n == 0 || k == 0) { return -LOG_NT; } if (n == k) { return -LOG_NT - n * Math.log10(p); } let pTerm = p / (1 - p); let log1Term = (n + 1) - funcs.logGamma(k + 1) - funcs.logGamma(n - k + 1) + k * Math.log(p) + (n - k) * Math.log(1.0 - p); let term = Math.exp(log1Term); if (funcs.doubleEqual(term, 0)) { if (k > n * p) { return -log1Term / funcs.M_LN10 - LOG_NT; } else { return -LOG_NT; } } let binTail = term; let tolerance = 0.1; for (let i = k + 1; i <= n; i++) { let binTerm = (n - i + 1) / i; let multTerm = binTerm * pTerm; term *= multTerm; binTail += term; if (binTerm < 1) { let err = term * ((1 - Math.pow(multTerm, (n - i + 1))) / (1 - multTerm) - 1); if (err < tolerance * Math.abs(-Math.log10(binTail) - LOG_NT) * binTail) { break; } } } return -Math.log10(binTail) - LOG_NT; } gaussianBlur(imageData: Uint8ClampedArray, kSize: number, sigma: number) { let width = this.width, height = this.height, src = imageData, ctx = document.createElement('canvas').getContext('2d'), tmp = ctx!.createImageData(width, height), dst = null, kernel = this.getGaussianKernel(kSize, sigma), r = (kSize - 1) / 2; const tmp2 = this.reshape(tmp); dst = new Uint8ClampedArray(tmp2.length); // separate 2d-filter for (let y = 0; y < height; y++) { let step = y * width; for (let x = 0; x < width; x++) { let buff = 0; let i = x + step; let k = 0; for (let kx = -r; kx <= r; kx++) { let px = x + kx; if (px <= 0 || width <= px) { px = x; } let j = px + step; buff += src[j] * kernel[k]; k++; } tmp2[i] = buff; } } for (let x = 0; x < width; x++) { for (let y = 0; y < height; y++) { let step = y * width; let buff = 0; let i = x + step; let k = 0; for (let ky = -r; ky <= r; ky++) { let py = y + ky; let kStep = ky * width; if (py <= 0 || height <= py) { py = y; kStep = 0; } let j = i + kStep; buff += tmp2[j] * kernel[k]; k++; } dst[i] = buff; } } return dst; } getGaussianKernel(kSize: number, sigma: number) { // 1d-kernel let kernel = []; let sigmaX = sigma > 0 ? sigma : ((kSize - 1) * 0.5 - 1) * 0.3 + 0.8; let scale2X = -0.5 / (sigmaX * sigmaX); let sum = 0.0; for (let i = 0; i < kSize; i++) { let x = i - (kSize - 1) * 0.5; kernel[i] = Math.exp(scale2X * x * x); sum += kernel[i]; } sum = 1. / sum; for (let i = 0; i < kSize; i++) { kernel[i] *= sum; } return kernel; } reshape(image: ImageData) { let src = image.data; let reshaped = new Uint8ClampedArray(src.length / 4); let len = reshaped.length; for (let i = 0; i < len; i++) { reshaped[i] = src[i * 4]; } return reshaped; } at(data: Uint8Array|Float64Array, p: Point) { return data[p.x + (p.y * this.width)]; } row(data: Float64Array, rowIndex: number) { let i = rowIndex * this.width; return data.subarray(i, i + this.width); } setRow(data: Float64Array, index: number, value: number) { let from = index * this.width; let to = from + this.width; for (let i = from; i < to; i++) { data[i] = value; } return data; } setCol(data: Float64Array, index: number, value: number) { let to = this.height * this.width; let step = this.width; for (let i = index; i < to; i += step) { data[i] = value; } return data; } }
the_stack
import {Switch} from '@material/mwc-switch/mwc-switch'; import {html} from 'lit'; import {customElement} from 'lit/decorators.js'; import {ifDefined} from 'lit/directives/if-defined.js'; import {fixture, simulateFormDataEvent, TestFixture} from '../../../test/src/util/helpers'; @customElement('mwc-test-switch') class TestSwitch extends Switch { getFoundation() { return this.mdcFoundation; } async forceRenderRipple() { this.shouldRenderRipple = true; return this.ripple; } } declare global { interface HTMLElementTagNameMap { 'mwc-test-switch': TestSwitch; } } interface SwitchProps { selected: boolean; disabled: boolean; name: string; value: string; } function renderSwitch(propsInit: Partial<SwitchProps> = {}) { return html` <mwc-test-switch ?selected=${propsInit.selected === true} ?disabled=${propsInit.disabled === true} .name=${propsInit.name ?? ''} value=${ifDefined(propsInit.value)}></mwc-test-switch> ` } function renderSwitchInForm(propsInit: Partial<SwitchProps> = {}) { return html` <form>${renderSwitch(propsInit)}</form> `; } describe('mwc-switch', () => { const fixtures: TestFixture[] = []; async function switchElement( propsInit: Partial<SwitchProps> = {}, template = renderSwitch) { const fixt = await fixture(template(propsInit)); fixtures.push(fixt); const element = fixt.root.querySelector('mwc-test-switch')!; await element.updateComplete; return element; } afterEach(() => { for (const fixt of fixtures) { fixt.remove(); } }); let toggle: TestSwitch; beforeEach(async () => { toggle = await switchElement(); }) describe('selected', () => { let selected: TestSwitch; beforeEach(async () => { selected = await switchElement({selected: true}); }); it('should be false by default', () => { expect(toggle.selected).toBeFalse(); }); it('should set `aria-checked` of button', () => { const toggleButton = toggle.shadowRoot!.querySelector('button')!; expect(toggleButton.getAttribute('aria-checked')).toEqual('false'); const selectedButton = selected.shadowRoot!.querySelector('button')!; expect(selectedButton.getAttribute('aria-checked')).toEqual('true'); }); it('should set checked of hidden input', () => { const toggleInput = toggle.shadowRoot!.querySelector('input')!; expect(toggleInput.checked).toBeFalse(); const selectedInput = selected.shadowRoot!.querySelector('input')!; expect(selectedInput.checked).toBeTrue(); }); it('should add mdc-switch--selected class when true', () => { const toggleRoot = toggle.shadowRoot!.querySelector('.mdc-switch')!; expect(Array.from(toggleRoot.classList)) .not.toContain('mdc-switch--selected'); const selectedRoot = selected.shadowRoot!.querySelector('.mdc-switch')!; expect(Array.from(selectedRoot.classList)) .toContain('mdc-switch--selected'); }); it('should add mdc-switch--unselected class when false', () => { const toggleRoot = toggle.shadowRoot!.querySelector('.mdc-switch')!; expect(Array.from(toggleRoot.classList)) .toContain('mdc-switch--unselected'); const selectedRoot = selected.shadowRoot!.querySelector('.mdc-switch')!; expect(Array.from(selectedRoot.classList)) .not.toContain('mdc-switch--unselected'); }); }); describe('processing', () => { it('should be false by default', () => { expect(toggle.processing).toBeFalse(); }); }); describe('disabled', () => { let disabled: TestSwitch; beforeEach(async () => { disabled = await switchElement({disabled: true}); }); it('should be false by default', () => { expect(toggle.disabled).toBeFalse(); }); it('should set disabled of button', () => { const toggleButton = toggle.shadowRoot!.querySelector('button')!; expect(toggleButton.disabled).toBeFalse(); const selectedButton = disabled.shadowRoot!.querySelector('button')!; expect(selectedButton.disabled).toBeTrue(); }); it('should disable ripple', async () => { const toggleRipple = await toggle.forceRenderRipple(); expect(toggleRipple?.disabled).toBeFalse(); const disabledRipple = await disabled.forceRenderRipple(); expect(disabledRipple?.disabled).toBeTrue(); }); }); describe('aria', () => { it('should be an empty string by default', () => { expect(toggle.ariaLabel).toEqual(''); }); it('delegates aria-label to the proper element', async () => { const button = toggle.shadowRoot!.querySelector('button')!; toggle.setAttribute('aria-label', 'foo'); await toggle.updateComplete; expect(toggle.ariaLabel).toEqual('foo'); expect(toggle.getAttribute('aria-label')).toEqual(null); expect(button.getAttribute('aria-label')).toEqual('foo'); }); it('delegates .ariaLabel to the proper element', async () => { const button = toggle.shadowRoot!.querySelector('button')!; toggle.ariaLabel = 'foo'; await toggle.updateComplete; expect(toggle.ariaLabel).toEqual('foo'); expect(toggle.getAttribute('aria-label')).toEqual(null); expect(button.getAttribute('aria-label')).toEqual('foo'); }); it('delegates aria-labelledby to the proper element', async () => { const button = toggle.shadowRoot!.querySelector('button')!; toggle.setAttribute('aria-labelledby', 'foo'); await toggle.updateComplete; expect(toggle.ariaLabelledBy).toEqual('foo'); expect(toggle.getAttribute('aria-labelledby')).toEqual(null); expect(button.getAttribute('aria-labelledby')).toEqual('foo'); }); it('delegates .ariaLabelledBy to the proper element', async () => { const button = toggle.shadowRoot!.querySelector('button')!; toggle.ariaLabelledBy = 'foo'; await toggle.updateComplete; expect(toggle.ariaLabelledBy).toEqual('foo'); expect(toggle.getAttribute('aria-labelledby')).toEqual(null); expect(button.getAttribute('aria-labelledby')).toEqual('foo'); }); }); describe('name', () => { let named: TestSwitch; beforeEach(async () => { named = await switchElement({name: 'foo'}); }); it('should be an empty string by default', () => { expect(toggle.name).toEqual(''); }); it('should reflect as an attribute', async () => { toggle.name = 'foo'; await toggle.updateComplete; expect(toggle.getAttribute('name')).toEqual('foo'); }); it('should set name of hidden input', () => { const input = named.shadowRoot!.querySelector('input')!; expect(input.getAttribute('name')).toEqual('foo'); }); }); describe('value', () => { let withValue: TestSwitch; beforeEach(async () => { withValue = await switchElement({value: 'bar'}); }); it('should be "on" by default', () => { expect(toggle.value).toEqual('on'); }); it('should set value of hidden input', () => { const input = withValue.shadowRoot!.querySelector('input')!; expect(input.value).toEqual('bar'); }); }); describe('click()', () => { it('should focus and click root element', () => { const root = toggle.shadowRoot!.querySelector('button')!; spyOn(root, 'focus'); spyOn(root, 'click'); toggle.click(); expect(root.focus).toHaveBeenCalledTimes(1); expect(root.click).toHaveBeenCalledTimes(1); }); it('should do nothing if disabled', () => { const root = toggle.shadowRoot!.querySelector('button')!; spyOn(root, 'focus'); spyOn(root, 'click'); toggle.disabled = true; toggle.click(); expect(root.focus).not.toHaveBeenCalled(); expect(root.click).not.toHaveBeenCalled(); }); it('should not focus or click hidden input form element', () => { const input = toggle.shadowRoot!.querySelector('input')!; spyOn(input, 'focus'); spyOn(input, 'click'); toggle.click(); expect(input.focus).not.toHaveBeenCalled(); expect(input.click).not.toHaveBeenCalled(); }); }); describe('handleClick()', () => { it('should call foundation.handleClick()', () => { const foundation = toggle.getFoundation()!; spyOn(foundation, 'handleClick').and.callThrough(); toggle.click(); expect(foundation.handleClick).toHaveBeenCalledTimes(1); }); }); // IE11 can only append to FormData, not inspect it if (Boolean(FormData.prototype.get)) { describe('form submission', () => { let form: HTMLFormElement; it('does not submit if not selected', async () => { toggle = await switchElement({name: 'foo'}, renderSwitchInForm); form = toggle.parentElement as HTMLFormElement; const formData = simulateFormDataEvent(form); expect(formData.get('foo')).toBeNull(); }); it('does not submit if disabled', async () => { toggle = await switchElement( {name: 'foo', selected: true, disabled: true}, renderSwitchInForm); form = toggle.parentElement as HTMLFormElement; const formData = simulateFormDataEvent(form); expect(formData.get('foo')).toBeNull(); }); it('does not submit if name is not provided', async () => { toggle = await switchElement({selected: true}, renderSwitchInForm); form = toggle.parentElement as HTMLFormElement; const formData = simulateFormDataEvent(form); const keys = Array.from(formData.keys()); expect(keys.length).toEqual(0); }); it('submits under correct conditions', async () => { toggle = await switchElement( {name: 'foo', selected: true, value: 'bar'}, renderSwitchInForm); form = toggle.parentElement as HTMLFormElement; const formData = simulateFormDataEvent(form); expect(formData.get('foo')).toEqual('bar'); }); }); } });
the_stack
describe('list - Tab', () => { test('can sink list item at everywhere', async () => { // at head await page.evaluate(() => { editor.setHTML('<ul><li>123</li></ul>'); editor.setSelection({ index: 2 }); }); await page.keyboard.press('Tab'); const html = await page.evaluate(() => editor.getHTML()); expect(html).toBe('<ul><ul><li>123</li></ul></ul>'); // at inner await page.evaluate(() => { editor.setHTML('<ul><li>123</li></ul>'); editor.setSelection({ index: 4 }); }); await page.keyboard.press('Tab'); const html1 = await page.evaluate(() => editor.getHTML()); expect(html1).toBe('<ul><ul><li>123</li></ul></ul>'); // raw list_item await page.evaluate(() => { editor.setHTML('<li>123</li>'); editor.setSelection({ index: 1 }); }); await page.keyboard.press('Tab'); const html2 = await page.evaluate(() => editor.getHTML()); expect(html2).toBe('<ul><li>123</li></ul>'); }); test('can sink empty list item', async () => { await page.evaluate(() => { editor.setHTML('<ul><li></li></ul>'); editor.setSelection({ index: 2 }); }); await page.keyboard.press('Tab'); const html = await page.evaluate(() => editor.getHTML()); expect(html).toBe('<ul><ul><li><br></li></ul></ul>'); }); test('can merge list when sink', async () => { // merge before await page.evaluate(() => { editor.setHTML('<ul><ul><li>123</li></ul><li>321</li></ul>'); editor.setSelection({ index: 9 }); }); await page.keyboard.press('Tab'); const html = await page.evaluate(() => editor.getHTML()); expect(html).toBe('<ul><ul><li>123</li><li>321</li></ul></ul>'); // merge after await page.evaluate(() => { editor.setHTML('<ul><li>123</li><ul><li>321</li></ul></ul>'); editor.setSelection({ index: 2 }); }); await page.keyboard.press('Tab'); const html1 = await page.evaluate(() => editor.getHTML()); expect(html1).toBe('<ul><ul><li>123</li><li>321</li></ul></ul>'); // merge siblings await page.evaluate(() => { editor.setHTML('<ul><ul><li>123</li></ul><li>321</li><ul><li>123</li></ul></ul>'); editor.setSelection({ index: 9 }); }); await page.keyboard.press('Tab'); const html2 = await page.evaluate(() => editor.getHTML()); expect(html2).toBe('<ul><ul><li>123</li><li>321</li><li>123</li></ul></ul>'); }); test('Tab - sink list item can not over maxNestedLevel(set 2)', async () => { await page.evaluate(() => { editor.setHTML('<ul><ul><li>123</li></ul></ul>'); editor.setSelection({ index: 3 }); }); await page.keyboard.press('Tab'); const html = await page.evaluate(() => { return editor.getHTML(); }); expect(html).toEqual('<ul><ul><li>123</li></ul></ul>'); }); }); describe('list - Shift + Tab', () => { test('can lift list item at everywhere', async () => { // at head await page.evaluate(() => { editor.setHTML('<ul><ul><li>123</li></ul></ul>'); editor.setSelection({ index: 3 }); }); await page.keyboard.down('ShiftLeft'); await page.keyboard.press('Tab'); await page.keyboard.up('ShiftLeft'); const html = await page.evaluate(() => editor.getHTML()); expect(html).toBe('<ul><li>123</li></ul>'); // at inner await page.evaluate(() => { editor.setHTML('<ul><ul><li>123</li></ul></ul>'); editor.setSelection({ index: 5 }); }); await page.keyboard.down('ShiftLeft'); await page.keyboard.press('Tab'); await page.keyboard.up('ShiftLeft'); const html1 = await page.evaluate(() => editor.getHTML()); expect(html1).toBe('<ul><li>123</li></ul>'); // clear await page.evaluate(() => { editor.setHTML('<ul><li></li></ul>'); editor.setSelection({ index: 2 }); }); await page.keyboard.down('ShiftLeft'); await page.keyboard.press('Tab'); await page.keyboard.up('ShiftLeft'); const html2 = await page.evaluate(() => editor.getHTML()); expect(html2).toBe(''); }); test('can lift empty list item', async () => { await page.evaluate(() => { editor.setHTML('<ul><ul><li></li></ul></ul>'); editor.setSelection({ index: 3 }); }); await page.keyboard.down('ShiftLeft'); await page.keyboard.press('Tab'); await page.keyboard.up('ShiftLeft'); const html = await page.evaluate(() => editor.getHTML()); expect(html).toBe('<ul><li><br></li></ul>'); }); test('can merge list when lift', async () => { // merge before await page.evaluate(() => { editor.setHTML('<ul><li>123</li><ul><li>321</li></ul></ul>'); editor.setSelection({ index: 8 }); }); await page.keyboard.down('ShiftLeft'); await page.keyboard.press('Tab'); await page.keyboard.up('ShiftLeft'); const html = await page.evaluate(() => editor.getHTML()); expect(html).toBe('<ul><li>123</li><li>321</li></ul>'); // merge after await page.evaluate(() => { editor.setHTML('<ul><ul><li>123</li></ul><li>321</li></ul>'); editor.setSelection({ index: 3 }); }); await page.keyboard.down('ShiftLeft'); await page.keyboard.press('Tab'); await page.keyboard.up('ShiftLeft'); const html1 = await page.evaluate(() => editor.getHTML()); expect(html1).toBe('<ul><li>123</li><li>321</li></ul>'); // merge siblings await page.evaluate(() => { editor.setHTML('<ul><li>123</li><ul><li>321</li></ul><li>123</li></ul>'); editor.setSelection({ index: 8 }); }); await page.keyboard.down('ShiftLeft'); await page.keyboard.press('Tab'); await page.keyboard.up('ShiftLeft'); const html2 = await page.evaluate(() => editor.getHTML()); expect(html2).toBe('<ul><li>123</li><li>321</li><li>123</li></ul>'); }); }); describe('list - Enter', () => { test('will lift empty list item in head', async () => { await page.evaluate(() => { editor.setHTML('<ul><li></li></ul>'); editor.setSelection({ index: 2 }); }); await page.keyboard.down('Enter'); const html = await page.evaluate(() => editor.getHTML()); expect(html).toBe(''); }); test('will split list item when inner', async () => { // head await page.evaluate(() => { editor.setHTML('<ul><li>123</li></ul>'); editor.setSelection({ index: 2 }); }); await page.keyboard.down('Enter'); const html = await page.evaluate(() => editor.getHTML()); expect(html).toBe('<ul><li><br></li><li>123</li></ul>'); // inner await page.evaluate(() => { editor.setHTML('<ul><li>123</li></ul>'); editor.setSelection({ index: 3 }); }); await page.keyboard.down('Enter'); const html1 = await page.evaluate(() => editor.getHTML()); expect(html1).toBe('<ul><li>1</li><li>23</li></ul>'); // tail await page.evaluate(() => { editor.setHTML('<ul><li>123</li></ul>'); editor.setSelection({ index: 5 }); }); await page.keyboard.down('Enter'); const html2 = await page.evaluate(() => editor.getHTML()); expect(html2).toBe('<ul><li>123</li><li><br></li></ul>'); }); test('Enter - split list keep mark', async () => { await page.evaluate(() => { editor.setHTML('<ul><li><em>123</em></li></ul>'); editor.setSelection({ index: 3, length: 0 }); }); await page.keyboard.press('Enter'); const html = await page.evaluate(() => { return editor.getHTML(); }); expect(html).toEqual('<ul><li><em>1</em></li><li><em>23</em></li></ul>'); }); }); describe('list - Backspace', () => { test('can remove empty list', async () => { await page.evaluate(() => { editor.setHTML('<ul><li></li></ul>'); editor.setSelection({ index: 2, length: 0 }); }); await page.keyboard.press('Backspace'); const html = await page.evaluate(() => { return editor.getHTML(); }); expect(html).toEqual(''); }); test('can remove single list_item', async () => { await page.evaluate(() => { editor.setHTML('<li></li>'); editor.setSelection({ index: 1, length: 0 }); }); await page.keyboard.press('Backspace'); const html = await page.evaluate(() => { return editor.getHTML(); }); await page.keyboard.press('Backspace'); expect(html).toEqual(''); }); test('can can delete character in list', async () => { await page.evaluate(() => { editor.setHTML('<ul><li>12</li></ul>'); editor.setSelection({ index: 4, length: 0 }); }); await page.keyboard.press('Backspace'); const html = await page.evaluate(() => { return editor.getHTML(); }); expect(html).toEqual('<ul><li>1</li></ul>'); }); test('can lift list item only at head', async () => { await page.evaluate(() => { editor.setHTML('<ul><ul><li>123</li></ul></ul>'); editor.setSelection({ index: 3, length: 0 }); }); await page.keyboard.press('Backspace'); const html1 = await page.evaluate(() => { return editor.getHTML(); }); await page.evaluate(() => { editor.setHTML('<ul><ul><li>123</li></ul></ul>'); editor.setSelection({ index: 4, length: 0 }); }); await page.keyboard.press('Backspace'); const html2 = await page.evaluate(() => { return editor.getHTML(); }); expect(html1).toEqual('<ul><li>123</li></ul>'); expect(html2).toEqual('<ul><ul><li>23</li></ul></ul>'); }); test('can lift list item to p when only 1 level', async () => { await page.evaluate(() => { editor.setHTML('<ul><li></li></ul>'); editor.setSelection({ index: 2, length: 0 }); }); await page.keyboard.press('Backspace'); const html = await page.evaluate(() => { return editor.getHTML(); }); expect(html).toEqual(''); }); test('can keep the order after split list', async () => { await page.evaluate(() => { editor.setHTML('<ol><li>123</li><li></li><li>123</li></ol>'); editor.setSelection({ index: 7 }); }); await page.keyboard.press('Backspace'); const html = await page.evaluate(() => { return editor.getHTML(); }); expect(html).toEqual('<ol start="1"><li>123</li></ol><p><br></p><ol start="2"><li>123</li></ol>'); }); test('can merge sibling list', async () => { await page.keyboard.press('Backspace'); const html = await page.evaluate(() => { return editor.getHTML(); }); expect(html).toEqual('<ol start="1"><li>123</li><li>123</li></ol>'); }); test('treat as defining node, will not replace parent node', async () => { const html = await page.evaluate(() => { editor.setHTML(`<ul><li>1</li><li></li></ul>`); editor.setSelection({ index: 5 }); editor.pasteContent(`<meta charset='utf-8'><li data-pm-slice="1 1 [&quot;bullet_list&quot;,{}]">c</li>`); return editor.getHTML(); }); expect(html).toEqual('<ul><li>1</li><li>c</li></ul>'); const html1 = await page.evaluate(() => { editor.setHTML(`<ul><li>1</li><li>2</li></ul>`); editor.setSelection({ index: 5 }); editor.pasteContent(`<meta charset='utf-8'><li data-pm-slice="1 1 [&quot;bullet_list&quot;,{}]">c</li>`); return editor.getHTML(); }); expect(html1).toEqual('<ul><li>1</li><li>c2</li></ul>'); }); test('can paste list from outside', async () => { const html = await page.evaluate(() => { editor.setHTML(''); editor.pasteContent(`<ul><li>1</li><li>2</li></ul>`); return editor.getHTML(); }); expect(html).toEqual('<ul><li>1</li><li>2</li></ul>'); }); });
the_stack
/** * @license Copyright © 2013 onwards, Andrew Whewell * All rights reserved. * * Redistribution and use of this software in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * * Neither the name of the author nor the names of the program's contributors may be used to endorse or promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHORS OF THE SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /** * @fileoverview Aircraft list handling. */ namespace VRS { /** * An associative array of aircraft. The index is their unique ID number. */ export class AircraftCollection { /** * Loops through every aircraft in the list passing each in turn to a callback. */ foreachAircraft(callback: (aircraft: Aircraft) => void) : AircraftCollection { for(var id in this) { var aircraft = this[id]; if(aircraft && aircraft instanceof VRS.Aircraft) callback(aircraft); } return this; } /** * Returns the aircraft with the specified ID or undefined if no such aircraft exists. */ findAircraftById(id: number) : Aircraft { var aircraft = this[id]; return aircraft && aircraft instanceof VRS.Aircraft ? this[id] : undefined; } /** * Passes each aircraft to the callback in turn until the callback returns true. Returns * the aircraft that the callback returned true for or null if the callback never returned * true. * @param callback */ findAircraft(callback: (Aircraft: Aircraft) => boolean) : Aircraft { var result: Aircraft = null; for(var id in this) { var aircraft = this[id]; if(aircraft && aircraft instanceof VRS.Aircraft) { if(callback(aircraft)) { result = aircraft; break; } } } return result; } /** * Returns the list of aircraft as an unordered array. */ toList(filterCallback?: (aircraft:Aircraft) => boolean) : Aircraft[] { var result: Aircraft[] = []; this.foreachAircraft(function(aircraft) { if(!filterCallback || filterCallback(aircraft)) result.push(aircraft); }); return result; } } /** * A collection of aircraft being tracked by the server. */ export class AircraftList { // Events private _Dispatcher = new EventHandler({ name: 'VRS.AircraftList' }); private _Events = { fetchingList: 'fetchingList', selectedChanged: 'selectedChanged', selectedReselected: 'selectedReselected', appliedJson: 'appliedJson', updated: 'updated' }; private _Aircraft = new AircraftCollection(); /** * Returns the aircraft being tracked by the object. */ getAircraft() : AircraftCollection { return this._Aircraft; } private _CountTrackedAircraft = 0; /** * Gets the number of aircraft currently being tracked by the server. If filtering is in force then this may * be larger than the number of aircraft sent in the last update. */ getCountTrackedAircraft() : number { return this._CountTrackedAircraft; } private _CountAvailableAircraft = 0; /** * Gets the number of aircraft sent in the last update. This may be smaller than the number of tracked aircraft * if filtering is in force. */ getCountAvailableAircraft() : number { return this._CountAvailableAircraft; } private _AircraftListSource = VRS.AircraftListSource.Unknown; /** * Gets the VRS.AircraftListSource value indicating where the list came from. */ getAircraftListSource() : AircraftListSourceEnum { return this._AircraftListSource; } private _ServerHasSilhouettes = false; /** * Gets a value indicating whether the server has silhouette images. */ getServerHasSilhouettes() : boolean { return this._ServerHasSilhouettes; } private _ServerHasOperatorFlags = false; /** * Gets a value indicating whether the server has operator flag images. */ getServerHasOperatorFlags() { return this._ServerHasOperatorFlags; } private _ServerHasPictures = false; /** * Gets a value indicating whether the server has aircraft pictures. */ getServerHasPictures() { return this._ServerHasPictures; } private _FlagWidth = 85; /** * Gets the width of operator flag and silhouette images. No longer used. */ getFlagWidth() { return this._FlagWidth; } private _FlagHeight = 20; /** * Gets the height of operator flag and silhouette images. No longer used. */ getFlagHeight() : number { return this._FlagHeight; } private _DataVersion: number = undefined; /** * Gets the data version number from the last update. This goes up for each update. */ getDataVersion() : number { return this._DataVersion; } private _ShortTrailSeconds = 0; /** * Gets the length of the short trails in seconds. */ getShortTrailSeconds() : number { return this._ShortTrailSeconds; } private _ServerTicks = 0; /** * Gets the time at the server of the last update in ticks. */ getServerTicks() : number { return this._ServerTicks; } private _WasAircraftSelectedByUser = false; /** * Gets a value indicating that the selected aircraft was selected manually by the user - false if it was selected by code. */ getWasAircraftSelectedByUser() : boolean { return this._WasAircraftSelectedByUser; } private _SelectedAircraft: Aircraft = undefined; /** * Gets the selected aircraft or undefined if no aircraft is selected. */ getSelectedAircraft() : Aircraft { return this._SelectedAircraft; } /** * Sets the selected aircraft. */ setSelectedAircraft(value: Aircraft, wasSelectedByUser: boolean) { if(value === null) value = undefined; if(wasSelectedByUser === undefined) throw 'You must indicate whether the aircraft was selected by the user'; if(wasSelectedByUser && VRS.timeoutManager) VRS.timeoutManager.resetTimer(); if(this._SelectedAircraft !== value) { var oldSelectedAircraft = this._SelectedAircraft; this._SelectedAircraft = value; this._WasAircraftSelectedByUser = wasSelectedByUser; this._Dispatcher.raise(this._Events.selectedChanged, [ oldSelectedAircraft ]); } } /** * Raised after the aircraft list has had new JSON applied to it. This is raised before the updated event and can be * used to make changes to the aircraft list before the rest of the system refreshes on the updated event. */ hookAppliedJson(callback: (newAircraft: AircraftCollection, offRadar: AircraftCollection) => void, forceThis?: Object) : IEventHandle { return this._Dispatcher.hook(this._Events.appliedJson, callback, forceThis); } /** * Raised after the aircraft list has been updated. */ hookUpdated(callback: (newAircraft: AircraftCollection, offRadar: AircraftCollection) => void, forceThis?: Object) : IEventHandle { return this._Dispatcher.hook(this._Events.updated, callback, forceThis); } /** * Raised after the selected aircraft has been changed. * @param {function(VRS.Aircraft=)} callback Passed the previously selected aircraft. * @param {object=} forceThis The object to use for 'this' in the call. * @returns {object} */ hookSelectedAircraftChanged(callback: (wasSelected: Aircraft) => void, forceThis?: Object) : IEventHandle { return this._Dispatcher.hook(this._Events.selectedChanged, callback, forceThis); } /** * Raised after the selected aircraft has changed its object. This can happen if the selected aircraft goes off * the radar and comes back - when it returns to the radar it is given a new object. */ hookSelectedReselected(callback: () => void, forceThis?: Object) : IEventHandle { return this._Dispatcher.hook(this._Events.selectedReselected, callback, forceThis); } /** * Raised by anything that causes an aircraft list to be fetched from the server. */ hookFetchingList(callback: (parameters: Object, headers: Object, postBody: Object) => void, forceThis?: Object) : IEventHandle { return this._Dispatcher.hook(this._Events.fetchingList, callback, forceThis); } /** * Raises the FetchingList event. * @param {*} xhrParams The object holding the URL query string parameters to pass to the server. * @param {*} xhrHeaders The object holding the HTML headers to pass to the server. * @param {*} xhrPostBody The object holding the post body to pass to the server. */ raiseFetchingList(xhrParams: Object, xhrHeaders: Object, xhrPostBody: Object) { this._Dispatcher.raise(this._Events.fetchingList, [ xhrParams, xhrHeaders, xhrPostBody ]); } /** * Unhooks an event that was hooked on the object. */ unhook(hookResult: IEventHandle) { this._Dispatcher.unhook(hookResult); } /** * Loops through every aircraft passing each in turn to a callback. * @param {function(VRS.Aircraft)} callback * @returns {VRS.AircraftCollection} */ foreachAircraft(callback: (aircraft:Aircraft) => void) : AircraftCollection { return this._Aircraft.foreachAircraft(callback); } /** * Returns the aircraft as an unordered array. */ toList(filterCallback?: (aircraft: Aircraft) => boolean) : Aircraft[] { return this._Aircraft.toList(filterCallback); } /** * Returns the aircraft with the specified ID. */ findAircraftById = function(id: number) : Aircraft { return this._Aircraft.findAircraftById(id); } /** * Passes each aircraft to a callback, if the callback returns true then that aircraft gets * returned, otherwise null is returned. * @param callback */ findAircraft(callback: (Aircraft: Aircraft) => boolean) : Aircraft { return this._Aircraft.findAircraft(callback); } /** * Returns the aircraft with the ICAO passed across or null if no such aircraft could be found. * @param icao */ findAircraftByIcao(icao: string) : Aircraft { return this.findAircraft((aircraft: Aircraft) => { return aircraft.icao.val === icao; }); } /** * Returns the ID of every aircraft being tracked as a comma-delimited string. */ getAllAircraftIdsString() : string { var result = ''; this._Aircraft.foreachAircraft(function(aircraft) { if(result) result += ','; result += aircraft.id; }); return result; } /** * Returns the ICAO of every aircraft being tracked as a hyphen-delimited string. */ getAllAircraftIcaosString() : string { var result = ''; this._Aircraft.foreachAircraft(function(aircraft) { if(result) result += '-'; result += aircraft.icao.val; }); return result; } /** * Applies details about an aircraft's current state to the aircraft list. */ applyJson(aircraftListJson: IAircraftList, aircraftListFetcher: AircraftListFetcher) { if(aircraftListJson) { this._CountTrackedAircraft = aircraftListJson.totalAc || 0; this._AircraftListSource = aircraftListJson.src || 0; this._ServerHasSilhouettes = !!aircraftListJson.showSil; this._ServerHasOperatorFlags = !!aircraftListJson.showFlg; this._ServerHasPictures = !!aircraftListJson.showPic; this._FlagWidth = aircraftListJson.flgW || 0; this._FlagHeight = aircraftListJson.flgH || 0; this._DataVersion = aircraftListJson.lastDv || -1; this._ShortTrailSeconds = aircraftListJson.shtTrlSec || 0; this._ServerTicks = aircraftListJson.stm || 0; var aircraft = new AircraftCollection(); var newAircraft = new AircraftCollection(); var jsonList = aircraftListJson.acList || []; var length = jsonList.length; var aircraftApplyJsonSettings = { shortTrailTickThreshold: this._ServerTicks === 0 || this._ShortTrailSeconds <= 0 ? -1 : (this._ServerTicks - ((1000 * this._ShortTrailSeconds) + 500)), picturesEnabled: VRS.serverConfig ? VRS.serverConfig.picturesEnabled() : false }; var reselectedAircraft = null; for(var i = 0;i < length;++i) { var aircraftJson = jsonList[i]; if(isNaN(aircraftJson.Id)) continue; var id = aircraftJson.Id; var aircraftState = this._Aircraft[id]; var isNew = !aircraftState; if(!isNew) delete this._Aircraft[id]; else { aircraftState = new VRS.Aircraft(); newAircraft[id] = aircraftState; } aircraftState.applyJson(aircraftJson, aircraftListFetcher, aircraftApplyJsonSettings, this._ServerTicks); aircraft[id] = aircraftState; if(isNew && this._SelectedAircraft && this._SelectedAircraft.id === id) reselectedAircraft = aircraftState; } var offRadar = this._Aircraft; this._Aircraft = aircraft; this._CountAvailableAircraft = length; this._Dispatcher.raise(this._Events.appliedJson, [ newAircraft, offRadar ]); if(reselectedAircraft) { this._SelectedAircraft = reselectedAircraft; this._Dispatcher.raise(this._Events.selectedReselected); } this._Dispatcher.raise(this._Events.updated, [ newAircraft, offRadar ]); VRS.globalDispatch.raise(VRS.globalEvent.displayUpdated); } } } }
the_stack
import { formatTitle } from '../title' const fragmentSplitFactor = 12 const dashExtensions = ['.mp4', '.m4a'] export interface BatchExtractorConfig { itemFilter: (item: BatchItem) => boolean api?: (aid: number | string, cid: number | string, quality?: number | string) => string } export interface BatchTitleParameter { [key: string]: string n: string ep: string } interface BatchItem { aid: number | string cid: number | string titleParameters?: BatchTitleParameter title: string } export interface RawItemFragment { length: number, size: number, url: string } export interface RawItem { fragments: RawItemFragment[] title: string totalSize: number cid: number | string referer: string } abstract class Batch { constructor(public config: BatchExtractorConfig) { } itemList: BatchItem[] = [] abstract getItemList(): Promise<BatchItem[]> abstract collectData(quality: number | string): Promise<string> /** * Returns formated Title. * * @param parameters - TYPE: BatchTitleParameter * @returns escapeFilename * */ static formatTitle(parameters: BatchTitleParameter | undefined) { const format = settings.batchFilenameFormat const title = formatTitle(format, true, parameters) return escapeFilename(title, ' ') } async getRawItems(quality: number | string): Promise<RawItem[]> { const { BannedResponse, throwBannedError } = await import('./batch-warning') try { const items = await this.collectData(quality) return JSON.parse(items) } catch (error) { if ((error as Error).message.includes(BannedResponse.toString())) { throwBannedError() } throw error } } extension(url: string, index: number) { const match = [ '.flv', '.mp4' ].find(it => url.includes(it)) if (match) { return match } else if (url.includes('.m4s')) { return dashExtensions[index] } else { return '.flv' } } async collectAria2(quality: number | string, rpc: boolean) { const json = await this.getRawItems(quality) const { getNumber } = await import('./get-number') if (rpc) { const option = settings.aria2RpcOption const { sendRpc, parseRpcOptions } = await import('./aria2-rpc') for (const item of json) { const params = item.fragments.map((fragment: { url: string }, index: number) => { let indexNumber = '' if (item.fragments.length > 1 && !fragment.url.includes('.m4s')) { indexNumber = ' - ' + getNumber(index + 1, item.fragments.length) } const params = [] if (option.secretKey !== '') { params.push(`token:${option.secretKey}`) } params.push([fragment.url]) params.push({ referer: document.URL.replace(window.location.search, ''), 'user-agent': UserAgent, out: `${item.title}${indexNumber}${this.extension(fragment.url, index)}`, split: fragmentSplitFactor, dir: option.dir || undefined, ...parseRpcOptions(option.other), }) const id = encodeURIComponent(`${item.title}${indexNumber}`) return { params, id, } }) await sendRpc(params, true) } } else { return ` # Generated by Bilibili Evolved Video Export # https://github.com/the1812/Bilibili-Evolved/ ${json.map(item => { return item.fragments.map((f, index) => { let indexNumber = '' if (item.fragments.length > 1 && !f.url.includes('.m4s')) { indexNumber = ` - ${getNumber(index + 1, item.fragments.length)}` } return ` ${f.url} referer=${item.referer} user-agent=${UserAgent} out=${item.title}${indexNumber}${this.extension(f.url, index)} split=${fragmentSplitFactor} `.trim() }).join('\n') }).join('\n')} `.trim() } } } class VideoEpisodeBatch extends Batch { aid = unsafeWindow.aid! static async test() { if (document.URL.startsWith('https://www.bilibili.com/video/')) { return await SpinQuery.select('#multi_page') !== null } return false } async getItemList() { if (this.itemList.length > 0) { return this.itemList } const api = `https://api.bilibili.com/x/web-interface/view?aid=${this.aid}` const json = await Ajax.getJson(api) if (json.code !== 0) { Toast.error(`获取视频选集列表失败, message=${json.message}`, '批量下载') return [] } const pages = json.data.pages if (pages === undefined) { Toast.error(`获取视频选集列表失败, 没有找到选集信息.`, '批量下载') return [] } const { getNumber } = await import('./get-number') this.itemList = pages.map((page: any) => { return { title: `P${page.page} ${page.part}`, titleParameters: { n: getNumber(page.page, this.itemList.length), ep: page.part }, cid: page.cid, aid: this.aid, } as BatchItem }) return this.itemList } async collectData(quality: number | string) { const result = [] for (const item of (await this.getItemList()).filter(this.config.itemFilter)) { const url = this.config.api ? this.config.api(item.aid, item.cid, quality) : `https://api.bilibili.com/x/player/playurl?avid=${item.aid}&cid=${item.cid}&qn=${quality}&otype=json` const json = await Ajax.getJsonWithCredentials(url) const data = json.data || json.result || json if (data.quality !== quality) { console.warn(`${item.title} 不支持所选画质, 已回退到较低画质. (quality=${data.quality})`) } let fragments: RawItemFragment[] if (data.durl) { fragments = data.durl.map((it: any) => { return { length: it.length, size: it.size, url: it.url } }) } else if (data.dash) { const { getDashInfo, dashToFragments } = await import('./video-dash') const info = await getDashInfo(url, typeof quality === 'string' ? parseInt(quality) : quality, true) fragments = dashToFragments(info) } else { throw new Error(`获取链接失败: ${json.code} ${json.message}`) } result.push({ fragments, // title: item.title.replace(/[\/\\:\*\?"<>\|]/g, ' '), title: Batch.formatTitle(item.titleParameters), totalSize: fragments.map(it => it.size).reduce((acc, it) => acc + it), cid: item.cid, referer: document.URL.replace(window.location.search, '') }) } return JSON.stringify(result) } } class Bnj2020Batch extends Batch { mainVideo: VideoEpisodeBatch spVideo: VideoEpisodeBatch constructor(config: BatchExtractorConfig) { super(config) // 拜年祭就硬编码 aid 了( this.mainVideo = new VideoEpisodeBatch(config) this.mainVideo.aid = '78976165' this.spVideo = new VideoEpisodeBatch(config) this.spVideo.aid = '78979124' } static async test() { return document.URL.includes('//www.bilibili.com/blackboard/bnj2020.html') } async getItemList() { return (await this.mainVideo.getItemList()).concat(await this.spVideo.getItemList()) } async collectData(quality: string | number) { return (await this.mainVideo.collectData(quality)).concat(await this.spVideo.collectData(quality)) } } class Bnj2021Batch extends VideoEpisodeBatch { videos = _.get(unsafeWindow, '__INITIAL_STATE__.videoSections', []) .map((it: any) => it.episodes) .flat() as { aid: number cid: number title: string }[] constructor(public config: BatchExtractorConfig) { super(config) } static async test() { return document.URL.includes('//www.bilibili.com/festival/2021bnj') } async getItemList() { const { getNumber } = await import('./get-number') return this.videos.map(({ aid, cid, title }, index) => { return { title: `P${index + 1} ${title}`, titleParameters: { n: getNumber(index + 1, this.videos.length), ep: title, }, aid, cid, } as BatchItem }) } } class BangumiBatch extends Batch { static async test() { return document.URL.includes('/www.bilibili.com/bangumi') } /** * Get bangumi from api * * @returns a json list of multiple part bangumi * */ async getItemList() { if (this.itemList.length > 0) { return this.itemList } const metaUrl = document.querySelector("meta[property='og:url']") if (metaUrl === null) { Toast.error('获取番剧数据失败: 无法找到 Season ID', '批量下载') return [] } const seasonId = metaUrl.getAttribute('content')!.match(/play\/ss(\d+)/)![1] if (seasonId === undefined) { Toast.error('获取番剧数据失败: 无法解析 Season ID', '批量下载') return [] } const json = await Ajax.getJson(`https://api.bilibili.com/pgc/web/season/section?season_id=${seasonId}`) if (json.code !== 0) { Toast.error(`获取番剧数据失败: 无法获取番剧集数列表, message=${json.message}`, '批量下载') return [] } const { getNumber } = await import('./get-number') this.itemList = json.result.main_section.episodes.map((it: any, index: number) => { const n: string = it.long_title ? it.title : (index + 1).toString() const title: string = it.long_title ? it.long_title : it.title return { aid: it.aid, cid: it.cid, title: `${n} - ${title}`, // title: it.long_title ? `${it.title} - ${it.long_title}` : `${index + 1} - ${it.title}`, titleParameters: { n: getNumber(parseFloat(n), this.itemList.length, it.title), ep: title, }, } as BatchItem }) return this.itemList } async collectData(quality: string | number) { const result = [] for (const item of (await this.getItemList()).filter(this.config.itemFilter)) { const url = this.config.api ? this.config.api(item.aid, item.cid, quality) : `https://api.bilibili.com/pgc/player/web/playurl?avid=${item.aid}&cid=${item.cid}&qn=${quality}&otype=json` const json = await Ajax.getJsonWithCredentials(url) const data = json.data || json.result || json if (data.quality !== quality) { console.warn(`${item.title} 不支持所选画质, 已回退到较低画质. (quality=${data.quality})`) } let fragments: RawItemFragment[] if (data.durl) { fragments = data.durl.map((it: any) => { return { length: it.length, size: it.size, url: it.url } }) } else { const { getDashInfo, dashToFragments } = await import('./video-dash') const info = await getDashInfo(url, typeof quality === 'string' ? parseInt(quality) : quality) fragments = dashToFragments(info) } result.push({ fragments, // title: item.title.replace(/[\/\\:\*\?"<>\|]/g, ' '), title: Batch.formatTitle(item.titleParameters), totalSize: fragments.map(it => it.size).reduce((acc, it) => acc + it), cid: item.cid, referer: document.URL.replace(window.location.search, '') }) } return JSON.stringify(result) } } export class ManualInputBatch extends VideoEpisodeBatch { items: string[] = [] async getItemList() { const { VideoInfo } = await import('../video-info') const { getNumber } = await import('./get-number') const pages = await Promise.all(this.items.map(async aid => { const info = new VideoInfo(aid) await info.fetchInfo() return info.pages.map((p, index) => { return { aid, cid: p.cid, titleParameters: { aid, cid: p.cid.toString(), n: getNumber(index + 1, info.pages.length), ep: info.pages.length > 1 ? p.title : '', title: info.title, }, title: `P${(index + 1)} ${p.title}`, } }) })) console.log("%cClass ManualInputBatch%c, data: ","color:yellow;", _.flatten(_.cloneDeep(pages))) return _.flatten(pages) } } const extractors = [BangumiBatch, VideoEpisodeBatch, Bnj2020Batch, Bnj2021Batch] let ExtractorClass: new (config: BatchExtractorConfig) => Batch export class BatchExtractor { config: BatchExtractorConfig constructor(config?: BatchExtractorConfig) { this.config = Object.assign({ itemFilter: () => true, }, config) } static async test() { for (const e of extractors) { if (await e.test() === true) { ExtractorClass = e return true } } return false } getExtractor() { if (ExtractorClass === null) { logError('[批量下载] 未找到合适的解析模块.') throw new Error(`[Batch Download] module not found.`) } const extractor = new ExtractorClass(this.config) return extractor } async getItemList() { const extractor = this.getExtractor() return await extractor.getItemList() } async getRawItems(format: { quality: number | string }) { const extractor = this.getExtractor() return await extractor.getRawItems(format.quality) } async collectData(format: { quality: number | string }, toast: Toast) { const extractor = this.getExtractor() const result = await extractor.collectData(format.quality) toast.dismiss() return result } async collectAria2(format: { quality: number | string }, toast: Toast, rpc: false): Promise<string> async collectAria2(format: { quality: number | string }, toast: Toast, rpc: true): Promise<undefined> async collectAria2(format: { quality: number | string }, toast: Toast, rpc = false) { const extractor = this.getExtractor() const result = await extractor.collectAria2(format.quality, rpc) toast.dismiss() return result } formatTitle(parameters: BatchTitleParameter | undefined) { return Batch.formatTitle(parameters) } } export default { export: { BatchExtractor, ManualInputBatch, } }
the_stack
import {reactive} from '@lume/element' import {getInheritedDescriptor} from 'lowclass' import {stringToArray} from './utils.js' export type XYZValuesArray<T> = [T, T, T] export type XYZPartialValuesArray<T> = [T] | [T, T] | [T, T, T] // Is there a better way to make a tuplet from 1 to 3 items? export type XYZValuesObject<T> = {x: T; y: T; z: T} export type XYZPartialValuesObject<T> = Partial<XYZValuesObject<T>> export type XYZValuesParameters<T> = /*XYZValues | */ XYZPartialValuesArray<T> | XYZPartialValuesObject<T> | string | T const defaultValues: XYZValuesObject<any> = {x: undefined, y: undefined, z: undefined} /** * @class XYZValues * * Represents a set of values for the X, Y, and Z axes. For example, the * position of an object can be described using a set of 3 numbers, one for each * axis in 3D space: {x:10, y:10, z:10}. * * The values don't have to be numerical. For example, * {x:'foo', y:'bar', z:'baz'} */ @reactive export abstract class XYZValues<T = any> extends Object { #x: T = undefined! #y: T = undefined! #z: T = undefined! /** * @property {any} x - * * *reactive* * * Default: `undefined` * * The X value. */ @reactive set x(value: T) { if (typeof value === 'string') value = this.deserializeValue('x', value) if (!this.checkValue('x', value)) return this.#x = value } get x(): T { return this.#x } /** * @property {any} y - * * *reactive* * * Default: `undefined` * * The Y value. */ @reactive set y(value: T) { if (typeof value === 'string') value = this.deserializeValue('y', value) if (!this.checkValue('y', value)) return this.#y = value } get y(): T { return this.#y } /** * @property {any} z - * * *reactive* * * Default: `undefined` * * The Z value. */ @reactive set z(value: T) { if (typeof value === 'string') value = this.deserializeValue('z', value) if (!this.checkValue('z', value)) return this.#z = value } get z(): T { return this.#z } /** * @constructor - The constructor accepts the initial x, y, and z values for * the respective properties, as well as a string list of values, an array * of values, an object of values with matching x, y, and z properties, or * another XYZValues object. This class allows for any type of values, so if * anything other than the string, array, or objects are passed for the * first arg, then whatever that value is becomes the value of `x`. * * Examples: * * ```js * // default values for all axes * new XYZValues() * * // individual args * new XYZValues(foo) * new XYZValues(foo, bar) * new XYZValues(foo, bar, baz) * * // string of values * new XYZValues('') * new XYZValues('foo') * new XYZValues('foo, bar') * new XYZValues('foo, bar, baz') * // commas are optional, these are the same as the last two: * new XYZValues('foo bar') * new XYZValues('foo bar baz') * * // array of values * new XYZValues([]) * new XYZValues([foo]) * new XYZValues([foo, bar]) * new XYZValues([foo, bar, baz]) * * // array of values * new XYZValues({}) * new XYZValues({x: foo}) * new XYZValues({y: bar}) * new XYZValues({z: baz}) * new XYZValues({y: bar, z: baz}) * new XYZValues({x: foo, z: baz}) * new XYZValues({x: foo, y: bar}) * new XYZValues({x: foo, y: bar, z: baz}) * * // other XYZValues * let other = new XYZValues(...) * new XYZValues(other) * ``` * * @param {string | [x?: any, y?: any, z?: any] | {x?: any, y?: any, z?: any} | XYZValues | any} x -The X value, or a string of values, an array of values, or object of values. * @param {any} y - The Y value. * @param {any} z - The Z value. */ constructor(x?: XYZValuesParameters<T>, y?: T, z?: T) { super() this.#from(x, y, z) } /** * @param {string | [x?: any, y?: any, z?: any] | {x?: any, y?: any, z?: any} | XYZValues | any} default - * * *readonly, *abstract* * * Subclasses can define a `default` getter to define what default values * should be for any new instance without constructor arguments. */ abstract get default(): XYZValuesParameters<T> get #default(): XYZValuesParameters<T> { return this.default || defaultValues } /** * @method fromDefault - Resets the `x`, `y`, and `z` values of the instance back * to their defaults, as defined by the `default` getter. If no `default` * getter is assigned, the default is ultimately `undefined` for `x`, `y`, and * `z`. * * ```js * values.fromDefault() * ``` * * @returns {this} - Returns the instance for method chaining. */ // TODO @return(s) jsdoc tag not working. fromDefault(): this { this.from(this.#default) return this } #from(x?: XYZValuesParameters<T> | null, y?: T, z?: T): this { if (x == null && y === undefined && z === undefined) { this.fromDefault() } else if (Array.isArray(x)) { this.fromArray(x) } else if (typeof x === 'object' && x !== null) { if (x === this) return this this.fromObject(x as XYZValuesObject<T>) } else if (typeof x === 'string' && y === undefined && z === undefined) { this.fromString(x) } else this.set(x as any, y as any, z as any) return this } /** * @method from - Accepts multiple types of values to set the object's `x`, `y`, and `z` properties from. The args are the same as for the [`constructor()`](#constructor). * * ```js * // similar to the constructor: * values.from(foo, bar, baz) * values.from('foo, bar, baz') * values.from('foo bar baz') * values.from([foo, bar, baz]) * values.from({x: foo, y: bar, z: baz}) * ``` * * @param {string | [x?: any, y?: any, z?: any] | {x?: any, y?: any, z?: any} | XYZValues | any} x -The X value, or a string of values, an array of values, or object of values. * @param {any} y - The Y value. * @param {any} z - The Z value. * * @returns {this} - Returns the instance for method chaining. */ from(x: XYZValuesParameters<T>, y?: T, z?: T): this { return this.#from(x, y, z) } /** * @method set - Sets specific values for `x`, `y`, and `z`. Unlike * [`.from()`](#from), this does not accept different sorts of values, but * only specific values for each axis. * * ```js * values.set(foo, bar, baz) * ``` * * @returns {this} - Returns the instance for method chaining. */ set(x: T, y: T, z: T): this { this.x = x this.y = y this.z = z return this } /** * @method fromArray - Sets the object's `x`, `y`, and `z` values from an array of values. * * ```js * values.fromArray([foo, bar, baz]) * ``` * * @returns {this} - Returns the instance for method chaining. */ fromArray(array: XYZPartialValuesArray<T>): this { this.set(array[0] as any, array[1] as any, array[2] as any) return this } /** * @method toArray - Returns the `x`, `y`, and `z` values in array form. * * ```js * values.toArray() // [foo, bar, baz] * ``` * * @returns {[any, any, any]} - The array of values. */ toArray(): XYZValuesArray<T> { return [this.x, this.y, this.z] } /** * @method fromObject - Sets the object's `x`, `y`, and `z` values from an * object with `x`, `y`, and `z` properties. * * ```js * values.fromObject({x: foo, y: bar, z: baz}) * ``` * * @returns {this} - Returns the instance for method chaining. */ fromObject(object: XYZPartialValuesObject<T>): this { this.set(object.x as any, object.y as any, object.z as any) return this } /** * @method toObject - Returns the `x`, `y`, and `z` values in object form. * * ```js * values.toObject() // {x: foo, y: bar, z: baz} * ``` * * @returns {{x: any, y: any, z: any}} - The object of values. */ toObject(): XYZValuesObject<T> { return {x: this.x, y: this.y, z: this.z} } /** * @method fromString - Sets the object's `x`, `y`, and `z` values from a * string containing a list of values. * * ```js * values.fromString('foo, bar, baz') * values.fromString('foo bar baz') * ``` * * @returns {this} - Returns the instance for method chaining. */ fromString(string: string, separator: string = ','): this { this.fromArray(this.#stringToArray(string, separator)) return this } /** * @method toString - Returns the `x`, `y`, and `z` values in string of values form, with an optional separator. * * `override` * * ```js * values.toString() // 'foo bar baz' * values.toString(',') // 'foo, bar, baz' * ``` * * @param {string} separator - The separator to use, otherwise only spaces are used. * * @returns {string} - The string of values. */ override toString(separator: string = ''): string { if (separator) { return `${this.x}${separator} ${this.y}${separator} ${this.z}` } else { return `${this.x} ${this.y} ${this.z}` } } /** * @method deserializeValue - Defines how to deserialize an incoming string * being set onto one of the x, y, or z properties. Subclasses should * override this. This class does not perform any transformation of the * string values. * * @param {'x' | 'y' | 'z'} _prop The property name of the axis a value is being deserialized for, one of 'x', 'y', or 'z'. * @param {any} value The value to be deserialized. * * @returns {any} - The deserialized value. */ deserializeValue(_prop: 'x' | 'y' | 'z', value: string): T { return value as unknown as T } #stringToArray(string: string, separator: string = ','): XYZPartialValuesArray<T> { const values = stringToArray(string, separator) const result = [] as unknown as XYZPartialValuesArray<T> const length = values.length if (length > 0) result[0] = this.deserializeValue('x', values[0]) if (length > 1) result[1] = this.deserializeValue('y', values[1]) if (length > 2) result[2] = this.deserializeValue('z', values[2]) return result } /** * @method checkValue - Subclasses extend this to implement type checks. * Return `true` if the value should be assigned, or `false` to ignore the * value and not set anything. A subclass could also throw an error when * receiving an unexpected value. * * Returning `false`, for example, can allow 'undefined' values to be * ignored, which allows us to do things like `values.fromObject({z: 123})` * to set only `z` and ignore `x` and `y`. * * @param {'x' | 'y' | 'z'} _prop The property name of the axis a value is being assigned to, one of 'x', 'y', or 'z'. * @param {any} _value The value being assigned. */ checkValue(_prop: 'x' | 'y' | 'z', _value: T): boolean { return true } /** * A method that when called in a effect makes all three x/y/z properties a * dependency of the effect. */ asDependency = () => { this.x this.y this.z } } // TODO make this a decorator function enumerable<T extends object>(obj: T, prop: keyof T) { Object.defineProperty(obj, prop, {...getInheritedDescriptor(obj, prop), enumerable: true}) } enumerable(XYZValues.prototype, 'x') enumerable(XYZValues.prototype, 'y') enumerable(XYZValues.prototype, 'z')
the_stack
namespace ts { export const enum ImportKind { Named, Default, Namespace, CommonJS, } export const enum ExportKind { Named, Default, ExportEquals, UMD, } export interface SymbolExportInfo { readonly symbol: Symbol; readonly moduleSymbol: Symbol; /** Set if `moduleSymbol` is an external module, not an ambient module */ moduleFileName: string | undefined; exportKind: ExportKind; targetFlags: SymbolFlags; /** True if export was only found via the package.json AutoImportProvider (for telemetry). */ isFromPackageJson: boolean; } interface CachedSymbolExportInfo { // Used to rehydrate `symbol` and `moduleSymbol` when transient id: number; symbolName: string; symbolTableKey: __String; moduleName: string; moduleFile: SourceFile | undefined; // SymbolExportInfo, but optional symbols readonly symbol: Symbol | undefined; readonly moduleSymbol: Symbol | undefined; moduleFileName: string | undefined; exportKind: ExportKind; targetFlags: SymbolFlags; isFromPackageJson: boolean; } export interface ExportInfoMap { isUsableByFile(importingFile: Path): boolean; clear(): void; add(importingFile: Path, symbol: Symbol, key: __String, moduleSymbol: Symbol, moduleFile: SourceFile | undefined, exportKind: ExportKind, isFromPackageJson: boolean, scriptTarget: ScriptTarget, checker: TypeChecker): void; get(importingFile: Path, key: string): readonly SymbolExportInfo[] | undefined; forEach(importingFile: Path, action: (info: readonly SymbolExportInfo[], name: string, isFromAmbientModule: boolean, key: string) => void): void; releaseSymbols(): void; isEmpty(): boolean; /** @returns Whether the change resulted in the cache being cleared */ onFileChanged(oldSourceFile: SourceFile, newSourceFile: SourceFile, typeAcquisitionEnabled: boolean): boolean; } export interface CacheableExportInfoMapHost { getCurrentProgram(): Program | undefined; getPackageJsonAutoImportProvider(): Program | undefined; } export function createCacheableExportInfoMap(host: CacheableExportInfoMapHost): ExportInfoMap { let exportInfoId = 1; const exportInfo = createMultiMap<string, CachedSymbolExportInfo>(); const symbols = new Map<number, [symbol: Symbol, moduleSymbol: Symbol]>(); let usableByFileName: Path | undefined; const cache: ExportInfoMap = { isUsableByFile: importingFile => importingFile === usableByFileName, isEmpty: () => !exportInfo.size, clear: () => { exportInfo.clear(); symbols.clear(); usableByFileName = undefined; }, add: (importingFile, symbol, symbolTableKey, moduleSymbol, moduleFile, exportKind, isFromPackageJson, scriptTarget, checker) => { if (importingFile !== usableByFileName) { cache.clear(); usableByFileName = importingFile; } const isDefault = exportKind === ExportKind.Default; const namedSymbol = isDefault && getLocalSymbolForExportDefault(symbol) || symbol; // 1. A named export must be imported by its key in `moduleSymbol.exports` or `moduleSymbol.members`. // 2. A re-export merged with an export from a module augmentation can result in `symbol` // being an external module symbol; the name it is re-exported by will be `symbolTableKey` // (which comes from the keys of `moduleSymbol.exports`.) // 3. Otherwise, we have a default/namespace import that can be imported by any name, and // `symbolTableKey` will be something undesirable like `export=` or `default`, so we try to // get a better name. const importedName = exportKind === ExportKind.Named || isExternalModuleSymbol(namedSymbol) ? unescapeLeadingUnderscores(symbolTableKey) : getNameForExportedSymbol(namedSymbol, scriptTarget); const moduleName = stripQuotes(moduleSymbol.name); const id = exportInfoId++; const target = skipAlias(symbol, checker); const storedSymbol = symbol.flags & SymbolFlags.Transient ? undefined : symbol; const storedModuleSymbol = moduleSymbol.flags & SymbolFlags.Transient ? undefined : moduleSymbol; if (!storedSymbol || !storedModuleSymbol) symbols.set(id, [symbol, moduleSymbol]); exportInfo.add(key(importedName, symbol, isExternalModuleNameRelative(moduleName) ? undefined : moduleName, checker), { id, symbolTableKey, symbolName: importedName, moduleName, moduleFile, moduleFileName: moduleFile?.fileName, exportKind, targetFlags: target.flags, isFromPackageJson, symbol: storedSymbol, moduleSymbol: storedModuleSymbol, }); }, get: (importingFile, key) => { if (importingFile !== usableByFileName) return; const result = exportInfo.get(key); return result?.map(rehydrateCachedInfo); }, forEach: (importingFile, action) => { if (importingFile !== usableByFileName) return; exportInfo.forEach((info, key) => { const { symbolName, ambientModuleName } = parseKey(key); action(info.map(rehydrateCachedInfo), symbolName, !!ambientModuleName, key); }); }, releaseSymbols: () => { symbols.clear(); }, onFileChanged: (oldSourceFile: SourceFile, newSourceFile: SourceFile, typeAcquisitionEnabled: boolean) => { if (fileIsGlobalOnly(oldSourceFile) && fileIsGlobalOnly(newSourceFile)) { // File is purely global; doesn't affect export map return false; } if ( usableByFileName && usableByFileName !== newSourceFile.path || // If ATA is enabled, auto-imports uses existing imports to guess whether you want auto-imports from node. // Adding or removing imports from node could change the outcome of that guess, so could change the suggestions list. typeAcquisitionEnabled && consumesNodeCoreModules(oldSourceFile) !== consumesNodeCoreModules(newSourceFile) || // Module agumentation and ambient module changes can add or remove exports available to be auto-imported. // Changes elsewhere in the file can change the *type* of an export in a module augmentation, // but type info is gathered in getCompletionEntryDetails, which doesn’t use the cache. !arrayIsEqualTo(oldSourceFile.moduleAugmentations, newSourceFile.moduleAugmentations) || !ambientModuleDeclarationsAreEqual(oldSourceFile, newSourceFile) ) { cache.clear(); return true; } usableByFileName = newSourceFile.path; return false; }, }; if (Debug.isDebugging) { Object.defineProperty(cache, "__cache", { get: () => exportInfo }); } return cache; function rehydrateCachedInfo(info: CachedSymbolExportInfo): SymbolExportInfo { if (info.symbol && info.moduleSymbol) return info as SymbolExportInfo; const { id, exportKind, targetFlags, isFromPackageJson, moduleFileName } = info; const [cachedSymbol, cachedModuleSymbol] = symbols.get(id) || emptyArray; if (cachedSymbol && cachedModuleSymbol) { return { symbol: cachedSymbol, moduleSymbol: cachedModuleSymbol, moduleFileName, exportKind, targetFlags, isFromPackageJson, }; } const checker = (isFromPackageJson ? host.getPackageJsonAutoImportProvider()! : host.getCurrentProgram()!).getTypeChecker(); const moduleSymbol = info.moduleSymbol || cachedModuleSymbol || Debug.checkDefined(info.moduleFile ? checker.getMergedSymbol(info.moduleFile.symbol) : checker.tryFindAmbientModule(info.moduleName)); const symbol = info.symbol || cachedSymbol || Debug.checkDefined(exportKind === ExportKind.ExportEquals ? checker.resolveExternalModuleSymbol(moduleSymbol) : checker.tryGetMemberInModuleExportsAndProperties(unescapeLeadingUnderscores(info.symbolTableKey), moduleSymbol), `Could not find symbol '${info.symbolName}' by key '${info.symbolTableKey}' in module ${moduleSymbol.name}`); symbols.set(id, [symbol, moduleSymbol]); return { symbol, moduleSymbol, moduleFileName, exportKind, targetFlags, isFromPackageJson, }; } function key(importedName: string, symbol: Symbol, ambientModuleName: string | undefined, checker: TypeChecker): string { const moduleKey = ambientModuleName || ""; return `${importedName}|${getSymbolId(skipAlias(symbol, checker))}|${moduleKey}`; } function parseKey(key: string) { const symbolName = key.substring(0, key.indexOf("|")); const moduleKey = key.substring(key.lastIndexOf("|") + 1); const ambientModuleName = moduleKey === "" ? undefined : moduleKey; return { symbolName, ambientModuleName }; } function fileIsGlobalOnly(file: SourceFile) { return !file.commonJsModuleIndicator && !file.externalModuleIndicator && !file.moduleAugmentations && !file.ambientModuleNames; } function ambientModuleDeclarationsAreEqual(oldSourceFile: SourceFile, newSourceFile: SourceFile) { if (!arrayIsEqualTo(oldSourceFile.ambientModuleNames, newSourceFile.ambientModuleNames)) { return false; } let oldFileStatementIndex = -1; let newFileStatementIndex = -1; for (const ambientModuleName of newSourceFile.ambientModuleNames) { const isMatchingModuleDeclaration = (node: Statement) => isNonGlobalAmbientModule(node) && node.name.text === ambientModuleName; oldFileStatementIndex = findIndex(oldSourceFile.statements, isMatchingModuleDeclaration, oldFileStatementIndex + 1); newFileStatementIndex = findIndex(newSourceFile.statements, isMatchingModuleDeclaration, newFileStatementIndex + 1); if (oldSourceFile.statements[oldFileStatementIndex] !== newSourceFile.statements[newFileStatementIndex]) { return false; } } return true; } } export function isImportableFile( program: Program, from: SourceFile, to: SourceFile, preferences: UserPreferences, packageJsonFilter: PackageJsonImportFilter | undefined, moduleSpecifierResolutionHost: ModuleSpecifierResolutionHost, moduleSpecifierCache: ModuleSpecifierCache | undefined, ): boolean { if (from === to) return false; const cachedResult = moduleSpecifierCache?.get(from.path, to.path, preferences); if (cachedResult?.isAutoImportable !== undefined) { return cachedResult.isAutoImportable; } const getCanonicalFileName = hostGetCanonicalFileName(moduleSpecifierResolutionHost); const globalTypingsCache = moduleSpecifierResolutionHost.getGlobalTypingsCacheLocation?.(); const hasImportablePath = !!moduleSpecifiers.forEachFileNameOfModule( from.fileName, to.fileName, moduleSpecifierResolutionHost, /*preferSymlinks*/ false, toPath => { const toFile = program.getSourceFile(toPath); // Determine to import using toPath only if toPath is what we were looking at // or there doesnt exist the file in the program by the symlink return (toFile === to || !toFile) && isImportablePath(from.fileName, toPath, getCanonicalFileName, globalTypingsCache); } ); if (packageJsonFilter) { const isAutoImportable = hasImportablePath && packageJsonFilter.allowsImportingSourceFile(to, moduleSpecifierResolutionHost); moduleSpecifierCache?.setIsAutoImportable(from.path, to.path, preferences, isAutoImportable); return isAutoImportable; } return hasImportablePath; } /** * Don't include something from a `node_modules` that isn't actually reachable by a global import. * A relative import to node_modules is usually a bad idea. */ function isImportablePath(fromPath: string, toPath: string, getCanonicalFileName: GetCanonicalFileName, globalCachePath?: string): boolean { // If it's in a `node_modules` but is not reachable from here via a global import, don't bother. const toNodeModules = forEachAncestorDirectory(toPath, ancestor => getBaseFileName(ancestor) === "node_modules" ? ancestor : undefined); const toNodeModulesParent = toNodeModules && getDirectoryPath(getCanonicalFileName(toNodeModules)); return toNodeModulesParent === undefined || startsWith(getCanonicalFileName(fromPath), toNodeModulesParent) || (!!globalCachePath && startsWith(getCanonicalFileName(globalCachePath), toNodeModulesParent)); } export function forEachExternalModuleToImportFrom( program: Program, host: LanguageServiceHost, useAutoImportProvider: boolean, cb: (module: Symbol, moduleFile: SourceFile | undefined, program: Program, isFromPackageJson: boolean) => void, ) { forEachExternalModule(program.getTypeChecker(), program.getSourceFiles(), (module, file) => cb(module, file, program, /*isFromPackageJson*/ false)); const autoImportProvider = useAutoImportProvider && host.getPackageJsonAutoImportProvider?.(); if (autoImportProvider) { const start = timestamp(); forEachExternalModule(autoImportProvider.getTypeChecker(), autoImportProvider.getSourceFiles(), (module, file) => cb(module, file, autoImportProvider, /*isFromPackageJson*/ true)); host.log?.(`forEachExternalModuleToImportFrom autoImportProvider: ${timestamp() - start}`); } } function forEachExternalModule(checker: TypeChecker, allSourceFiles: readonly SourceFile[], cb: (module: Symbol, sourceFile: SourceFile | undefined) => void) { for (const ambient of checker.getAmbientModules()) { if (!stringContains(ambient.name, "*")) { cb(ambient, /*sourceFile*/ undefined); } } for (const sourceFile of allSourceFiles) { if (isExternalOrCommonJsModule(sourceFile)) { cb(checker.getMergedSymbol(sourceFile.symbol), sourceFile); } } } export function getExportInfoMap(importingFile: SourceFile, host: LanguageServiceHost, program: Program, cancellationToken: CancellationToken | undefined): ExportInfoMap { const start = timestamp(); // Pulling the AutoImportProvider project will trigger its updateGraph if pending, // which will invalidate the export map cache if things change, so pull it before // checking the cache. host.getPackageJsonAutoImportProvider?.(); const cache = host.getCachedExportInfoMap?.() || createCacheableExportInfoMap({ getCurrentProgram: () => program, getPackageJsonAutoImportProvider: () => host.getPackageJsonAutoImportProvider?.(), }); if (cache.isUsableByFile(importingFile.path)) { host.log?.("getExportInfoMap: cache hit"); return cache; } host.log?.("getExportInfoMap: cache miss or empty; calculating new results"); const compilerOptions = program.getCompilerOptions(); const scriptTarget = getEmitScriptTarget(compilerOptions); let moduleCount = 0; forEachExternalModuleToImportFrom(program, host, /*useAutoImportProvider*/ true, (moduleSymbol, moduleFile, program, isFromPackageJson) => { if (++moduleCount % 100 === 0) cancellationToken?.throwIfCancellationRequested(); const seenExports = new Map<__String, true>(); const checker = program.getTypeChecker(); const defaultInfo = getDefaultLikeExportInfo(moduleSymbol, checker, compilerOptions); // Note: I think we shouldn't actually see resolved module symbols here, but weird merges // can cause it to happen: see 'completionsImport_mergedReExport.ts' if (defaultInfo && isImportableSymbol(defaultInfo.symbol, checker)) { cache.add( importingFile.path, defaultInfo.symbol, defaultInfo.exportKind === ExportKind.Default ? InternalSymbolName.Default : InternalSymbolName.ExportEquals, moduleSymbol, moduleFile, defaultInfo.exportKind, isFromPackageJson, scriptTarget, checker); } checker.forEachExportAndPropertyOfModule(moduleSymbol, (exported, key) => { if (exported !== defaultInfo?.symbol && isImportableSymbol(exported, checker) && addToSeen(seenExports, key)) { cache.add( importingFile.path, exported, key, moduleSymbol, moduleFile, ExportKind.Named, isFromPackageJson, scriptTarget, checker); } }); }); host.log?.(`getExportInfoMap: done in ${timestamp() - start} ms`); return cache; } export function getDefaultLikeExportInfo(moduleSymbol: Symbol, checker: TypeChecker, compilerOptions: CompilerOptions) { const exported = getDefaultLikeExportWorker(moduleSymbol, checker); if (!exported) return undefined; const { symbol, exportKind } = exported; const info = getDefaultExportInfoWorker(symbol, checker, compilerOptions); return info && { symbol, exportKind, ...info }; } function isImportableSymbol(symbol: Symbol, checker: TypeChecker) { return !checker.isUndefinedSymbol(symbol) && !checker.isUnknownSymbol(symbol) && !isKnownSymbol(symbol) && !isPrivateIdentifierSymbol(symbol); } function getDefaultLikeExportWorker(moduleSymbol: Symbol, checker: TypeChecker): { readonly symbol: Symbol, readonly exportKind: ExportKind } | undefined { const exportEquals = checker.resolveExternalModuleSymbol(moduleSymbol); if (exportEquals !== moduleSymbol) return { symbol: exportEquals, exportKind: ExportKind.ExportEquals }; const defaultExport = checker.tryGetMemberInModuleExports(InternalSymbolName.Default, moduleSymbol); if (defaultExport) return { symbol: defaultExport, exportKind: ExportKind.Default }; } function getDefaultExportInfoWorker(defaultExport: Symbol, checker: TypeChecker, compilerOptions: CompilerOptions): { readonly symbolForMeaning: Symbol, readonly name: string } | undefined { const localSymbol = getLocalSymbolForExportDefault(defaultExport); if (localSymbol) return { symbolForMeaning: localSymbol, name: localSymbol.name }; const name = getNameForExportDefault(defaultExport); if (name !== undefined) return { symbolForMeaning: defaultExport, name }; if (defaultExport.flags & SymbolFlags.Alias) { const aliased = checker.getImmediateAliasedSymbol(defaultExport); if (aliased && aliased.parent) { // - `aliased` will be undefined if the module is exporting an unresolvable name, // but we can still offer completions for it. // - `aliased.parent` will be undefined if the module is exporting `globalThis.something`, // or another expression that resolves to a global. return getDefaultExportInfoWorker(aliased, checker, compilerOptions); } } if (defaultExport.escapedName !== InternalSymbolName.Default && defaultExport.escapedName !== InternalSymbolName.ExportEquals) { return { symbolForMeaning: defaultExport, name: defaultExport.getName() }; } return { symbolForMeaning: defaultExport, name: getNameForExportedSymbol(defaultExport, compilerOptions.target) }; } function getNameForExportDefault(symbol: Symbol): string | undefined { return symbol.declarations && firstDefined(symbol.declarations, declaration => { if (isExportAssignment(declaration)) { return tryCast(skipOuterExpressions(declaration.expression), isIdentifier)?.text; } else if (isExportSpecifier(declaration)) { Debug.assert(declaration.name.text === InternalSymbolName.Default, "Expected the specifier to be a default export"); return declaration.propertyName && declaration.propertyName.text; } }); } }
the_stack
import { config } from "./config.ts"; import { encoding } from "./deps/encoding_japanese.ts"; import { JpNum } from "./deps/japanese_numeral.ts"; import { zip } from "./deps/std/collections.ts"; import { iter } from "./deps/std/io.ts"; import { Encode } from "./types.ts"; import type { Encoding, SkkServerOptions } from "./types.ts"; import { Cell } from "./util.ts"; const okuriAriMarker = ";; okuri-ari entries."; const okuriNasiMarker = ";; okuri-nasi entries."; const lineRegexp = /^(\S+) \/(.*)\/$/; function toZenkaku(n: number): string { return n.toString().replaceAll(/[0-9]/g, (c): string => { const zenkakuNumbers = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"]; return zenkakuNumbers[parseInt(c)]; }); } function toKanjiModern(n: number): string { return n.toString().replaceAll(/[0-9]/g, (c): string => { const kanjiNumbers = ["〇", "一", "二", "三", "四", "五", "六", "七", "八", "九"]; return kanjiNumbers[parseInt(c)]; }); } const toKanjiClassic: (n: number) => string = JpNum.number2kanji; function convertNumber(pattern: string, entry: string): string { return zip(pattern.split(/(#[0-9]?)/g), entry.split(/([0-9]+)/g)) .map(([k, e]) => { switch (k) { case "#": case "#0": case "#4": case "#5": case "#6": case "#7": case "#8": case "#9": return e; case "#1": return toZenkaku(parseInt(e)); case "#2": return toKanjiModern(parseInt(e)); case "#3": return toKanjiClassic(parseInt(e)); default: return k; } }) .join(""); } export interface Jisyo { getCandidate(type: HenkanType, word: string): Promise<string[]>; getCandidates(word: string): Promise<[string, string[]][]>; } function encode(str: string, encode: Encoding): Uint8Array { const utf8Encoder = new TextEncoder(); const utf8Bytes = utf8Encoder.encode(str); const eucBytesArray = encoding.convert(utf8Bytes, Encode[encode], "UTF8"); const eucBytes = Uint8Array.from(eucBytesArray); return eucBytes; } export class LocalJisyo implements Jisyo { #okuriari: Map<string, string[]>; #okurinasi: Map<string, string[]>; constructor( okuriari?: Map<string, string[]>, okurinasi?: Map<string, string[]>, ) { this.#okuriari = okuriari ?? new Map(); this.#okurinasi = okurinasi ?? new Map(); } getCandidate(type: HenkanType, word: string): Promise<string[]> { const target = type === "okuriari" ? this.#okuriari : this.#okurinasi; return Promise.resolve( (target.get(word.replaceAll(/[0-9]+/g, "#")) ?? []) .map((candidate) => convertNumber(candidate, word)), ); } getCandidates(prefix: string): Promise<[string, string[]][]> { const candidates = new Map<string, string[]>(); for (const [key, value] of this.#okurinasi) { if (key.startsWith(prefix)) { // TODO: to get numebric candidates candidates.set(key, value); } } return Promise.resolve(Array.from(candidates.entries())); } registerCandidate(type: HenkanType, word: string, candidate: string) { const target = type === "okuriari" ? this.#okuriari : this.#okurinasi; target.set( word, Array.from(new Set([candidate, ...target.get(word) ?? []])), ); } toString(): string { return [ [okuriAriMarker], linesToString(Array.from(this.#okuriari.entries())), [okuriNasiMarker], linesToString(Array.from(this.#okurinasi.entries())), [""], // The text file must end with a new line ].flat().join("\n"); } } export function encodeJisyo(jisyo: LocalJisyo) { return jisyo.toString(); } export type HenkanType = "okuriari" | "okurinasi"; function decode(str: Uint8Array, encode: Encoding): string { const decoder = new TextDecoder(encode); return decoder.decode(str); } export class SkkServer { #conn: Deno.Conn | undefined; responseEncoding: Encoding; requestEncoding: Encoding; connectOptions: Deno.ConnectOptions; constructor(opts: SkkServerOptions) { this.requestEncoding = opts.requestEnc; this.responseEncoding = opts.responseEnc; this.connectOptions = { hostname: opts.hostname, port: opts.port, }; } async connect() { this.#conn = await Deno.connect(this.connectOptions); } async getCandidate(word: string): Promise<string[]> { if (!this.#conn) return []; await this.#conn.write(encode(`1${word} `, this.requestEncoding)); const result: string[] = []; for await (const res of iter(this.#conn)) { const str = decode(res, this.responseEncoding); result.push(...(str.at(0) === "4") ? [] : str.split("/").slice(1, -1)); if (str.endsWith("\n")) { break; } } return result; } getCandidates(_prefix: string): [string, string[]][] { // TODO: add support for ddc.vim return [["", [""]]]; } close() { this.#conn?.write(encode("0", this.requestEncoding)); this.#conn?.close(); } } export class Library { #globalJisyo: LocalJisyo; #userJisyo: LocalJisyo; #userJisyoPath: string; #userJisyoTimestamp = -1; #skkServer: SkkServer | undefined; constructor( globalJisyo?: LocalJisyo, userJisyo?: LocalJisyo, userJisyoPath?: string, skkServer?: SkkServer, ) { this.#globalJisyo = globalJisyo ?? new LocalJisyo(); this.#userJisyo = userJisyo ?? new LocalJisyo(); this.#userJisyoPath = userJisyoPath ?? ""; this.#skkServer = skkServer; } async getCandidate(type: HenkanType, word: string): Promise<string[]> { const userCandidates = await this.#userJisyo.getCandidate(type, word); const merged = userCandidates.slice(); const globalCandidates = await this.#globalJisyo.getCandidate(type, word); const remoteCandidates = await this.#skkServer?.getCandidate(word); if (globalCandidates) { for (const c of globalCandidates) { if (!merged.includes(c)) { merged.push(c); } } } if (remoteCandidates) { for (const c of remoteCandidates) { if (!merged.includes(c)) { merged.push(c); } } } return merged; } async getCandidates(prefix: string): Promise<[string, string[]][]> { if (prefix.length < 2) { return []; } const candidates = new Map<string, string[]>(); for (const [key, value] of await this.#userJisyo.getCandidates(prefix)) { candidates.set( key, Array.from(new Set([...candidates.get(key) ?? [], ...value])), ); } for (const [key, value] of await this.#globalJisyo.getCandidates(prefix)) { candidates.set( key, Array.from(new Set([...candidates.get(key) ?? [], ...value])), ); } return Array.from(candidates.entries()); } registerCandidate(type: HenkanType, word: string, candidate: string) { if (!candidate) { return; } this.#userJisyo.registerCandidate(type, word, candidate); if (config.immediatelyJisyoRW) { this.saveJisyo(); } } async loadJisyo() { if (this.#userJisyoPath) { try { const stat = await Deno.stat(this.#userJisyoPath); const time = stat.mtime?.getTime() ?? -1; if (time === this.#userJisyoTimestamp) { return; } this.#userJisyoTimestamp = time; this.#userJisyo = decodeJisyo( await Deno.readTextFile(this.#userJisyoPath), ); } catch { // do nothing } } } async saveJisyo() { if (this.#userJisyoPath) { try { await Deno.writeTextFile( this.#userJisyoPath, encodeJisyo(this.#userJisyo), ); } catch { console.log( `warning(skkeleton): can't write userJisyo to ${this.#userJisyoPath}`, ); return; } const stat = await Deno.stat(this.#userJisyoPath); const time = stat.mtime?.getTime() ?? -1; this.#userJisyoTimestamp = time; } } } export function decodeJisyo(data: string): LocalJisyo { const lines = data.split("\n"); const okuriAriIndex = lines.indexOf(okuriAriMarker); const okuriNasiIndex = lines.indexOf(okuriNasiMarker); const okuriAriEntries = lines.slice(okuriAriIndex + 1, okuriNasiIndex).map( (s) => s.match(lineRegexp), ).filter((m) => m).map((m) => [m![1], m![2].split("/")] as [string, string[]] ); const okuriNasiEntries = lines.slice(okuriNasiIndex + 1, lines.length).map( (s) => s.match(lineRegexp), ).filter((m) => m).map((m) => [m![1], m![2].split("/")] as [string, string[]] ); return new LocalJisyo( new Map(okuriAriEntries), new Map(okuriNasiEntries), ); } /** * load SKK jisyo from `path` */ export async function loadJisyo( path: string, jisyoEncoding: string, ): Promise<LocalJisyo> { const decoder = new TextDecoder(jisyoEncoding); return decodeJisyo(decoder.decode(await Deno.readFile(path))); } function linesToString(entries: [string, string[]][]): string[] { return entries.sort((a, b) => a[0].localeCompare(b[0])).map((entry) => `${entry[0]} /${entry[1].join("/")}/` ); } export function ensureJisyo(x: unknown): asserts x is Jisyo { if (x instanceof LocalJisyo) { return; } throw new Error("corrupt jisyo detected"); } export async function load( globalJisyoPath: string, userJisyoPath: string, jisyoEncoding = "euc-jp", skkServer?: SkkServer, ): Promise<Library> { let globalJisyo = new LocalJisyo(); let userJisyo = new LocalJisyo(); try { globalJisyo = await loadJisyo( globalJisyoPath, jisyoEncoding, ); } catch (e) { console.error("globalJisyo loading failed"); console.error(`at ${globalJisyoPath}`); if (config.debug) { console.error(e); } } try { userJisyo = await loadJisyo( userJisyoPath, "utf-8", ); } catch (e) { if (config.debug) { console.log("userJisyo loading failed"); console.log(e); } // do nothing } try { if (skkServer) { skkServer.connect(); } } catch (e) { if (config.debug) { console.log("connecting to skk server is failed"); console.log(e); } } return new Library(globalJisyo, userJisyo, userJisyoPath, skkServer); } export const currentLibrary = new Cell(() => new Library());
the_stack
import Eventful from './Eventful'; import env from './env'; import { ZRRawEvent } from './types'; import {isCanvasEl, transformCoordWithViewport} from './dom'; const isDomLevel2 = (typeof window !== 'undefined') && !!window.addEventListener; const MOUSE_EVENT_REG = /^(?:mouse|pointer|contextmenu|drag|drop)|click/; const _calcOut: number[] = []; type FirefoxMouseEvent = { layerX: number layerY: number } /** * Get the `zrX` and `zrY`, which are relative to the top-left of * the input `el`. * CSS transform (2D & 3D) is supported. * * The strategy to fetch the coords: * + If `calculate` is not set as `true`, users of this method should * ensure that `el` is the same or the same size & location as `e.target`. * Otherwise the result coords are probably not expected. Because we * firstly try to get coords from e.offsetX/e.offsetY. * + If `calculate` is set as `true`, the input `el` can be any element * and we force to calculate the coords based on `el`. * + The input `el` should be positionable (not position:static). * * The force `calculate` can be used in case like: * When mousemove event triggered on ec tooltip, `e.target` is not `el`(zr painter.dom). * * @param el DOM element. * @param e Mouse event or touch event. * @param out Get `out.zrX` and `out.zrY` as the result. * @param calculate Whether to force calculate * the coordinates but not use ones provided by browser. */ export function clientToLocal( el: HTMLElement, e: ZRRawEvent | FirefoxMouseEvent | Touch, out: {zrX?: number, zrY?: number}, calculate?: boolean ) { out = out || {}; // According to the W3C Working Draft, offsetX and offsetY should be relative // to the padding edge of the target element. The only browser using this convention // is IE. Webkit uses the border edge, Opera uses the content edge, and FireFox does // not support the properties. // (see http://www.jacklmoore.com/notes/mouse-position/) // In zr painter.dom, padding edge equals to border edge. if (calculate || !env.canvasSupported) { calculateZrXY(el, e as ZRRawEvent, out); } // Caution: In FireFox, layerX/layerY Mouse position relative to the closest positioned // ancestor element, so we should make sure el is positioned (e.g., not position:static). // BTW1, Webkit don't return the same results as FF in non-simple cases (like add // zoom-factor, overflow / opacity layers, transforms ...) // BTW2, (ev.offsetY || ev.pageY - $(ev.target).offset().top) is not correct in preserve-3d. // <https://bugs.jquery.com/ticket/8523#comment:14> // BTW3, In ff, offsetX/offsetY is always 0. else if (env.browser.firefox // use offsetX/offsetY for Firefox >= 39 // PENDING: consider Firefox for Android and Firefox OS? >= 43 && env.browser.version < '39' && (e as FirefoxMouseEvent).layerX != null && (e as FirefoxMouseEvent).layerX !== (e as MouseEvent).offsetX ) { out.zrX = (e as FirefoxMouseEvent).layerX; out.zrY = (e as FirefoxMouseEvent).layerY; } // For IE6+, chrome, safari, opera, firefox >= 39 else if ((e as MouseEvent).offsetX != null) { out.zrX = (e as MouseEvent).offsetX; out.zrY = (e as MouseEvent).offsetY; } // For some other device, e.g., IOS safari. else { calculateZrXY(el, e as ZRRawEvent, out); } return out; } function calculateZrXY( el: HTMLElement, e: ZRRawEvent, out: {zrX?: number, zrY?: number} ) { // BlackBerry 5, iOS 3 (original iPhone) don't have getBoundingRect. if (env.domSupported && el.getBoundingClientRect) { const ex = (e as MouseEvent).clientX; const ey = (e as MouseEvent).clientY; if (isCanvasEl(el)) { // Original approach, which do not support CSS transform. // marker can not be locationed in a canvas container // (getBoundingClientRect is always 0). We do not support // that input a pre-created canvas to zr while using css // transform in iOS. const box = el.getBoundingClientRect(); out.zrX = ex - box.left; out.zrY = ey - box.top; return; } else { if (transformCoordWithViewport(_calcOut, el, ex, ey)) { out.zrX = _calcOut[0]; out.zrY = _calcOut[1]; return; } } } out.zrX = out.zrY = 0; } /** * Find native event compat for legency IE. * Should be called at the begining of a native event listener. * * @param e Mouse event or touch event or pointer event. * For lagency IE, we use `window.event` is used. * @return The native event. */ export function getNativeEvent(e: ZRRawEvent): ZRRawEvent { return e || (window.event as any); // For IE } /** * Normalize the coordinates of the input event. * * Get the `e.zrX` and `e.zrY`, which are relative to the top-left of * the input `el`. * Get `e.zrDelta` if using mouse wheel. * Get `e.which`, see the comment inside this function. * * Do not calculate repeatly if `zrX` and `zrY` already exist. * * Notice: see comments in `clientToLocal`. check the relationship * between the result coords and the parameters `el` and `calculate`. * * @param el DOM element. * @param e See `getNativeEvent`. * @param calculate Whether to force calculate * the coordinates but not use ones provided by browser. * @return The normalized native UIEvent. */ export function normalizeEvent( el: HTMLElement, e: ZRRawEvent, calculate?: boolean ) { e = getNativeEvent(e); if (e.zrX != null) { return e; } const eventType = e.type; const isTouch = eventType && eventType.indexOf('touch') >= 0; if (!isTouch) { clientToLocal(el, e, e, calculate); const wheelDelta = getWheelDeltaMayPolyfill(e); // FIXME: IE8- has "wheelDeta" in event "mousewheel" but hat different value (120 times) // with Chrome and Safari. It's not correct for zrender event but we left it as it was. e.zrDelta = wheelDelta ? wheelDelta / 120 : -(e.detail || 0) / 3; } else { const touch = eventType !== 'touchend' ? (<TouchEvent>e).targetTouches[0] : (<TouchEvent>e).changedTouches[0]; touch && clientToLocal(el, touch, e, calculate); } // Add which for click: 1 === left; 2 === middle; 3 === right; otherwise: 0; // See jQuery: https://github.com/jquery/jquery/blob/master/src/event.js // If e.which has been defined, it may be readonly, // see: https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent/which const button = (<MouseEvent>e).button; if (e.which == null && button !== undefined && MOUSE_EVENT_REG.test(e.type)) { (e as any).which = (button & 1 ? 1 : (button & 2 ? 3 : (button & 4 ? 2 : 0))); } // [Caution]: `e.which` from browser is not always reliable. For example, // when press left button and `mousemove (pointermove)` in Edge, the `e.which` // is 65536 and the `e.button` is -1. But the `mouseup (pointerup)` and // `mousedown (pointerdown)` is the same as Chrome does. return e; } // TODO: also provide prop "deltaX" "deltaY" in zrender "mousewheel" event. function getWheelDeltaMayPolyfill(e: ZRRawEvent): number { // Although event "wheel" do not has the prop "wheelDelta" in spec, // agent like Chrome and Safari still provide "wheelDelta" like // event "mousewheel" did (perhaps for backward compat). // Since zrender has been using "wheelDeta" in zrender event "mousewheel". // we currently do not break it. // But event "wheel" in firefox do not has "wheelDelta", so we calculate // "wheelDeta" from "deltaX", "deltaY" (which is the props in spec). const rawWheelDelta = (e as any).wheelDelta; // Theroetically `e.wheelDelta` won't be 0 unless some day it has been deprecated // by agent like Chrome or Safari. So we also calculate it if rawWheelDelta is 0. if (rawWheelDelta) { return rawWheelDelta; } const deltaX = (e as any).deltaX; const deltaY = (e as any).deltaY; if (deltaX == null || deltaY == null) { return rawWheelDelta; } // Test in Chrome and Safari (MacOS): // The sign is corrent. // The abs value is 99% corrent (inconsist case only like 62~63, 125~126 ...) const delta = deltaY !== 0 ? Math.abs(deltaY) : Math.abs(deltaX); const sign = deltaY > 0 ? -1 : deltaY < 0 ? 1 : deltaX > 0 ? -1 : 1; return 3 * delta * sign; } type AddEventListenerParams = Parameters<typeof HTMLElement.prototype.addEventListener> type RemoveEventListenerParams = Parameters<typeof HTMLElement.prototype.removeEventListener> /** * @param el * @param name * @param handler * @param opt If boolean, means `opt.capture` * @param opt.capture * @param opt.passive */ export function addEventListener( el: HTMLElement | HTMLDocument, name: AddEventListenerParams[0], handler: AddEventListenerParams[1], opt?: AddEventListenerParams[2] ) { if (isDomLevel2) { // Reproduct the console warning: // [Violation] Added non-passive event listener to a scroll-blocking <some> event. // Consider marking event handler as 'passive' to make the page more responsive. // Just set console log level: verbose in chrome dev tool. // then the warning log will be printed when addEventListener called. // See https://github.com/WICG/EventListenerOptions/blob/gh-pages/explainer.md // We have not yet found a neat way to using passive. Because in zrender the dom event // listener delegate all of the upper events of element. Some of those events need // to prevent default. For example, the feature `preventDefaultMouseMove` of echarts. // Before passive can be adopted, these issues should be considered: // (1) Whether and how a zrender user specifies an event listener passive. And by default, // passive or not. // (2) How to tread that some zrender event listener is passive, and some is not. If // we use other way but not preventDefault of mousewheel and touchmove, browser // compatibility should be handled. // const opts = (env.passiveSupported && name === 'mousewheel') // ? {passive: true} // // By default, the third param of el.addEventListener is `capture: false`. // : void 0; // el.addEventListener(name, handler /* , opts */); el.addEventListener(name, handler, opt); } else { // For simplicity, do not implement `setCapture` for IE9-. (el as any).attachEvent('on' + name, handler); } } /** * Parameter are the same as `addEventListener`. * * Notice that if a listener is registered twice, one with capture and one without, * remove each one separately. Removal of a capturing listener does not affect a * non-capturing version of the same listener, and vice versa. */ export function removeEventListener( el: HTMLElement | HTMLDocument, name: RemoveEventListenerParams[0], handler: RemoveEventListenerParams[1], opt: RemoveEventListenerParams[2] ) { if (isDomLevel2) { el.removeEventListener(name, handler, opt); } else { (el as any).detachEvent('on' + name, handler); } } /** * preventDefault and stopPropagation. * Notice: do not use this method in zrender. It can only be * used by upper applications if necessary. * * @param {Event} e A mouse or touch event. */ export const stop = isDomLevel2 ? function (e: MouseEvent | TouchEvent | PointerEvent) { e.preventDefault(); e.stopPropagation(); e.cancelBubble = true; } : function (e: MouseEvent | TouchEvent | PointerEvent) { e.returnValue = false; e.cancelBubble = true; }; /** * This method only works for mouseup and mousedown. The functionality is restricted * for fault tolerance, See the `e.which` compatibility above. * * params can be MouseEvent or ElementEvent */ export function isMiddleOrRightButtonOnMouseUpDown(e: { which: number }) { return e.which === 2 || e.which === 3; } /** * To be removed. * @deprecated */ export function notLeftMouse(e: MouseEvent) { // If e.which is undefined, considered as left mouse event. return e.which > 1; } // For backward compatibility export {Eventful as Dispatcher};
the_stack
import PnAnyDeclarative from '../../../src/extensions/payment-network/declarative'; import Utils from '@requestnetwork/utils'; import { ExtensionTypes } from '@requestnetwork/types'; import * as TestDataDeclarative from '../../utils/payment-network/any/generator-data-create'; import * as TestData from '../../utils/test-data-generator'; const pnAnyDeclarative = new PnAnyDeclarative(); /* eslint-disable @typescript-eslint/no-unused-expressions */ describe('extensions/payment-network/any/declarative', () => { describe('createCreationAction', () => { it('can createCreationAction with payment and refund instruction', () => { // 'extensionsdata is wrong' expect( pnAnyDeclarative.createCreationAction({ paymentInfo: TestDataDeclarative.paymentInfo, refundInfo: TestDataDeclarative.refundInfo, payeeDelegate: TestDataDeclarative.payeeDelegate, }), ).toEqual(TestDataDeclarative.actionCreationWithPaymentAndRefund); }); it('can createCreationAction with only payment instruction', () => { // deep copy to remove the undefined properties to comply deep.equal() // 'extensionsdata is wrong' expect( Utils.deepCopy( pnAnyDeclarative.createCreationAction({ paymentInfo: TestDataDeclarative.paymentInfo, }), ), ).toEqual(TestDataDeclarative.actionCreationOnlyPayment); }); it('can createCreationAction with only refund instruction', () => { // deep copy to remove the undefined properties to comply deep.equal() // 'extensionsdata is wrong' expect( Utils.deepCopy( pnAnyDeclarative.createCreationAction({ refundInfo: TestDataDeclarative.refundInfo, }), ), ).toEqual(TestDataDeclarative.actionCreationOnlyRefund); }); it('can createCreationAction with payee delegate', () => { // deep copy to remove the undefined properties to comply deep.equal() // 'extensionsdata is wrong' expect( Utils.deepCopy( pnAnyDeclarative.createCreationAction({ payeeDelegate: TestDataDeclarative.payeeDelegate, }), ), ).toEqual(TestDataDeclarative.actionCreationPayeeDelegate); }); }); describe('createAddPaymentInstructionAction', () => { it('can createAddPaymentInstructionAction', () => { // 'extensionsdata is wrong' expect( pnAnyDeclarative.createAddPaymentInstructionAction({ paymentInfo: TestDataDeclarative.paymentInfo, }), ).toEqual(TestDataDeclarative.actionPaymentInstruction); }); }); describe('createAddRefundInstructionAction', () => { it('can createAddRefundInstructionAction', () => { // 'extensionsdata is wrong' expect( pnAnyDeclarative.createAddRefundInstructionAction({ refundInfo: TestDataDeclarative.refundInfo, }), ).toEqual(TestDataDeclarative.actionRefundInstruction); }); }); describe('createDeclareSentPaymentAction', () => { it('can createDeclareSentPaymentAction', () => { // 'extensionsdata is wrong' expect( pnAnyDeclarative.createDeclareSentPaymentAction({ amount: TestDataDeclarative.amount, note: TestDataDeclarative.note, }), ).toEqual(TestDataDeclarative.actionDeclareSentPayment); }); }); describe('createDeclareSentRefundAction', () => { it('can createDeclareSentRefundAction', () => { // 'extensionsdata is wrong' expect( pnAnyDeclarative.createDeclareSentRefundAction({ amount: TestDataDeclarative.amount, note: TestDataDeclarative.note, }), ).toEqual(TestDataDeclarative.actionDeclareSentRefund); }); }); describe('createDeclareReceivedPaymentAction', () => { it('can createDeclareReceivedPaymentAction', () => { // 'extensionsdata is wrong' expect( pnAnyDeclarative.createDeclareReceivedPaymentAction({ amount: TestDataDeclarative.amount, note: TestDataDeclarative.note, }), ).toEqual(TestDataDeclarative.actionDeclareReceivedPayment); }); }); describe('createDeclareReceivedRefundAction', () => { it('can createDeclareReceivedRefundAction', () => { // 'extensionsdata is wrong' expect( pnAnyDeclarative.createDeclareReceivedRefundAction({ amount: TestDataDeclarative.amount, note: TestDataDeclarative.note, }), ).toEqual(TestDataDeclarative.actionDeclareReceivedRefund); }); }); describe('createAddDelegateAction', () => { it('can createAddDelegateAction', () => { // 'extensionsdata is wrong' expect( pnAnyDeclarative.createAddDelegateAction({ delegate: TestDataDeclarative.delegateToAdd, }), ).toEqual(TestDataDeclarative.actionAddDelegate); }); }); describe('applyActionToExtension', () => { describe('applyActionToExtension/unknown action', () => { it('cannot applyActionToExtensions of unknown action', () => { const unknownAction = Utils.deepCopy(TestDataDeclarative.actionCreationEmpty); unknownAction.action = 'unknown action' as any; // 'must throw' expect(() => { pnAnyDeclarative.applyActionToExtension( TestDataDeclarative.requestStateCreatedEmpty.extensions, unknownAction, TestDataDeclarative.requestStateCreatedEmpty, TestData.payeeRaw.identity, TestData.arbitraryTimestamp, ); }).toThrowError('Unknown action: unknown action'); }); }); describe('applyActionToExtension/create', () => { it('can applyActionToExtensions of creation', () => { // 'new extension state wrong' expect( pnAnyDeclarative.applyActionToExtension( TestDataDeclarative.requestStateNoExtensions.extensions, TestDataDeclarative.actionCreationWithPaymentAndRefund, TestDataDeclarative.requestStateNoExtensions, TestData.otherIdRaw.identity, TestData.arbitraryTimestamp, ), ).toEqual(TestDataDeclarative.extensionStateWithPaymentAndRefund); }); it('cannot applyActionToExtensions of creation with a previous state', () => { // 'must throw' expect(() => { pnAnyDeclarative.applyActionToExtension( TestDataDeclarative.requestStateCreatedWithPaymentAndRefund.extensions, TestDataDeclarative.actionCreationWithPaymentAndRefund, TestDataDeclarative.requestStateCreatedWithPaymentAndRefund, TestData.otherIdRaw.identity, TestData.arbitraryTimestamp, ); }).toThrowError('This extension has already been created'); }); }); it('keeps the version used at creation', () => { const newState = pnAnyDeclarative.applyActionToExtension( {}, { ...TestDataDeclarative.actionCreationWithPaymentAndRefund, version: 'ABCD' }, TestDataDeclarative.requestStateNoExtensions, TestData.otherIdRaw.identity, TestData.arbitraryTimestamp, ); expect(newState[pnAnyDeclarative.extensionId].version).toBe('ABCD'); }); it('requires a version at creation', () => { expect(() => { pnAnyDeclarative.applyActionToExtension( {}, { ...TestDataDeclarative.actionCreationWithPaymentAndRefund, version: '' }, TestDataDeclarative.requestStateNoExtensions, TestData.otherIdRaw.identity, TestData.arbitraryTimestamp, ); }).toThrowError('version is required at creation'); }); describe('applyActionToExtension/addPaymentInstruction', () => { it('can applyActionToExtensions of addPaymentInstruction', () => { // 'new extension state wrong' expect( pnAnyDeclarative.applyActionToExtension( TestDataDeclarative.requestStateCreatedEmpty.extensions, TestDataDeclarative.actionPaymentInstruction, TestDataDeclarative.requestStateCreatedEmpty, TestData.payeeRaw.identity, TestData.arbitraryTimestamp, ), ).toEqual(TestDataDeclarative.extensionStateCreatedEmptyPaymentInstructionAdded); }); it('can applyActionToExtensions of addPaymentInstruction from payeeDelegate', () => { const expectedFromPayeeDelegate = Utils.deepCopy( TestDataDeclarative.extensionStateCreatedEmptyPaymentInstructionAdded, ); expectedFromPayeeDelegate[ ExtensionTypes.ID.PAYMENT_NETWORK_ANY_DECLARATIVE as string ].events[1].from = TestDataDeclarative.payeeDelegate; // 'new extension state wrong' expect( pnAnyDeclarative.applyActionToExtension( TestDataDeclarative.requestStateCreatedEmpty.extensions, TestDataDeclarative.actionPaymentInstruction, TestDataDeclarative.requestStateCreatedEmpty, TestData.payeeDelegateRaw.identity, TestData.arbitraryTimestamp, ), ).toEqual(expectedFromPayeeDelegate); }); it('cannot applyActionToExtensions of addPaymentInstruction without a previous state', () => { // 'must throw' expect(() => { pnAnyDeclarative.applyActionToExtension( TestDataDeclarative.requestStateNoExtensions.extensions, TestDataDeclarative.actionPaymentInstruction, TestDataDeclarative.requestStateNoExtensions, TestData.payeeRaw.identity, TestData.arbitraryTimestamp, ); }).toThrowError(`The extension should be created before receiving any other action`); }); it('cannot applyActionToExtensions of addPaymentInstruction without a payee', () => { const previousState = Utils.deepCopy(TestDataDeclarative.requestStateCreatedEmpty); previousState.payee = undefined; previousState.extensions[ ExtensionTypes.ID.PAYMENT_NETWORK_ANY_DECLARATIVE as string ].values.payeeDelegate = undefined; // 'must throw' expect(() => { pnAnyDeclarative.applyActionToExtension( previousState.extensions, TestDataDeclarative.actionPaymentInstruction, previousState, TestData.payeeRaw.identity, TestData.arbitraryTimestamp, ); }).toThrowError(`The request must have a payee`); }); it('cannot applyActionToExtensions of addPaymentInstruction signed by someone else than the payee', () => { const previousState = Utils.deepCopy(TestDataDeclarative.requestStateCreatedEmpty); // 'must throw' expect(() => { pnAnyDeclarative.applyActionToExtension( previousState.extensions, TestDataDeclarative.actionPaymentInstruction, previousState, TestData.payerRaw.identity, TestData.arbitraryTimestamp, ); }).toThrowError(`The signer must be the payee`); }); it('cannot applyActionToExtensions of addPaymentInstruction with payment instruction already assigned', () => { // 'must throw' expect(() => { pnAnyDeclarative.applyActionToExtension( TestDataDeclarative.requestStateCreatedWithPaymentAndRefund.extensions, TestDataDeclarative.actionPaymentInstruction, TestDataDeclarative.requestStateCreatedWithPaymentAndRefund, TestData.payeeRaw.identity, TestData.arbitraryTimestamp, ); }).toThrowError(`The payment instruction already assigned`); }); }); describe('applyActionToExtension/addRefundInstruction', () => { it('can applyActionToExtensions of addRefundInstruction', () => { // 'new extension state wrong' expect( pnAnyDeclarative.applyActionToExtension( TestDataDeclarative.requestStateCreatedEmpty.extensions, TestDataDeclarative.actionRefundInstruction, TestDataDeclarative.requestStateCreatedEmpty, TestData.payerRaw.identity, TestData.arbitraryTimestamp, ), ).toEqual(TestDataDeclarative.extensionStateCreatedEmptyRefundInstructionAdded); }); it('can applyActionToExtensions of addRefundInstruction from payerDelegate', () => { const expectedFromThirdParty = Utils.deepCopy( TestDataDeclarative.extensionStateCreatedEmptyRefundInstructionAdded, ); expectedFromThirdParty[ ExtensionTypes.ID.PAYMENT_NETWORK_ANY_DECLARATIVE as string ].events[1].from = TestDataDeclarative.payerDelegate; // 'new extension state wrong' expect( pnAnyDeclarative.applyActionToExtension( TestDataDeclarative.requestStateCreatedEmpty.extensions, TestDataDeclarative.actionRefundInstruction, TestDataDeclarative.requestStateCreatedEmpty, TestData.payerDelegateRaw.identity, TestData.arbitraryTimestamp, ), ).toEqual(expectedFromThirdParty); }); it('cannot applyActionToExtensions of addRefundInstruction without a previous state', () => { // 'must throw' expect(() => { pnAnyDeclarative.applyActionToExtension( TestDataDeclarative.requestStateNoExtensions.extensions, TestDataDeclarative.actionRefundInstruction, TestDataDeclarative.requestStateNoExtensions, TestData.payerRaw.identity, TestData.arbitraryTimestamp, ); }).toThrowError(`The extension should be created before receiving any other action`); }); it('cannot applyActionToExtensions of addRefundInstruction without a payer', () => { const previousState = Utils.deepCopy(TestDataDeclarative.requestStateCreatedEmpty); previousState.payer = undefined; previousState.extensions[ ExtensionTypes.ID.PAYMENT_NETWORK_ANY_DECLARATIVE as string ].values.payeeDelegate = undefined; // 'must throw' expect(() => { pnAnyDeclarative.applyActionToExtension( previousState.extensions, TestDataDeclarative.actionRefundInstruction, previousState, TestData.payerRaw.identity, TestData.arbitraryTimestamp, ); }).toThrowError(`The request must have a payer`); }); it('cannot applyActionToExtensions of addRefundInstruction signed by someone else than the payer', () => { const previousState = Utils.deepCopy(TestDataDeclarative.requestStateCreatedEmpty); // 'must throw' expect(() => { pnAnyDeclarative.applyActionToExtension( previousState.extensions, TestDataDeclarative.actionRefundInstruction, previousState, TestData.payeeRaw.identity, TestData.arbitraryTimestamp, ); }).toThrowError(`The signer must be the payer`); }); it('cannot applyActionToExtensions of addRefundInstruction with payment instruction already assigned', () => { // 'must throw' expect(() => { pnAnyDeclarative.applyActionToExtension( TestDataDeclarative.requestStateCreatedWithPaymentAndRefund.extensions, TestDataDeclarative.actionRefundInstruction, TestDataDeclarative.requestStateCreatedWithPaymentAndRefund, TestData.payerRaw.identity, TestData.arbitraryTimestamp, ); }).toThrowError(`The refund instruction already assigned`); }); }); describe('applyActionToExtension/declareSentPayment', () => { it('can applyActionToExtensions of declareSentPayment', () => { // 'new extension state wrong' expect( pnAnyDeclarative.applyActionToExtension( TestDataDeclarative.requestStateCreatedEmpty.extensions, TestDataDeclarative.actionDeclareSentPayment, TestDataDeclarative.requestStateCreatedEmpty, TestData.payerRaw.identity, TestData.arbitraryTimestamp, ), ).toEqual(TestDataDeclarative.extensionStateCreatedEmptySentPayment); }); it('can applyActionToExtensions of declareSentPayment from payerDelegate', () => { const expectedFromThirdParty = Utils.deepCopy( TestDataDeclarative.extensionStateCreatedEmptySentPayment, ); expectedFromThirdParty[ ExtensionTypes.ID.PAYMENT_NETWORK_ANY_DECLARATIVE as string ].events[1].from = TestDataDeclarative.payerDelegate; // 'new extension state wrong' expect( pnAnyDeclarative.applyActionToExtension( TestDataDeclarative.requestStateCreatedEmpty.extensions, TestDataDeclarative.actionDeclareSentPayment, TestDataDeclarative.requestStateCreatedEmpty, TestData.payerDelegateRaw.identity, TestData.arbitraryTimestamp, ), ).toEqual(expectedFromThirdParty); }); it('cannot applyActionToExtensions of declareSentPayment without a previous state', () => { // 'must throw' expect(() => { pnAnyDeclarative.applyActionToExtension( TestDataDeclarative.requestStateNoExtensions.extensions, TestDataDeclarative.actionDeclareSentPayment, TestDataDeclarative.requestStateNoExtensions, TestData.payerRaw.identity, TestData.arbitraryTimestamp, ); }).toThrowError(`The extension should be created before receiving any other action`); }); it('cannot applyActionToExtensions of declareSentPayment without a payer', () => { const previousState = Utils.deepCopy(TestDataDeclarative.requestStateCreatedEmpty); previousState.payer = undefined; previousState.extensions[ ExtensionTypes.ID.PAYMENT_NETWORK_ANY_DECLARATIVE as string ].values.payeeDelegate = undefined; // 'must throw' expect(() => { pnAnyDeclarative.applyActionToExtension( previousState.extensions, TestDataDeclarative.actionDeclareSentPayment, previousState, TestData.payerRaw.identity, TestData.arbitraryTimestamp, ); }).toThrowError(`The request must have a payer`); }); it('cannot applyActionToExtensions of declareSentPayment signed by someone else than the payer', () => { const previousState = Utils.deepCopy(TestDataDeclarative.requestStateCreatedEmpty); // 'must throw' expect(() => { pnAnyDeclarative.applyActionToExtension( previousState.extensions, TestDataDeclarative.actionDeclareSentPayment, previousState, TestData.payeeRaw.identity, TestData.arbitraryTimestamp, ); }).toThrowError(`The signer must be the payer`); }); it('cannot applyActionToExtensions of declareSentPayment with an invalid amount', () => { TestDataDeclarative.actionDeclareSentPayment.parameters.amount = 'invalid amount'; // 'must throw' expect(() => { pnAnyDeclarative.applyActionToExtension( TestDataDeclarative.requestStateCreatedEmpty.extensions, TestDataDeclarative.actionDeclareSentPayment, TestDataDeclarative.requestStateCreatedEmpty, TestData.payerRaw.identity, TestData.arbitraryTimestamp, ); }).toThrowError(`The amount is not a valid amount`); }); }); describe('applyActionToExtension/declareReceivedRefund', () => { it('can applyActionToExtensions of declareReceivedRefund', () => { // 'new extension state wrong' expect( pnAnyDeclarative.applyActionToExtension( TestDataDeclarative.requestStateCreatedEmpty.extensions, TestDataDeclarative.actionDeclareReceivedRefund, TestDataDeclarative.requestStateCreatedEmpty, TestData.payerRaw.identity, TestData.arbitraryTimestamp, ), ).toEqual(TestDataDeclarative.extensionStateCreatedEmptyReceivedRefund); }); it('can applyActionToExtensions of declareReceivedRefund from payerDelegate', () => { const expectedFromThirdParty = Utils.deepCopy( TestDataDeclarative.extensionStateCreatedEmptyReceivedRefund, ); expectedFromThirdParty[ ExtensionTypes.ID.PAYMENT_NETWORK_ANY_DECLARATIVE as string ].events[1].from = TestDataDeclarative.payerDelegate; // 'new extension state wrong' expect( pnAnyDeclarative.applyActionToExtension( TestDataDeclarative.requestStateCreatedEmpty.extensions, TestDataDeclarative.actionDeclareReceivedRefund, TestDataDeclarative.requestStateCreatedEmpty, TestData.payerDelegateRaw.identity, TestData.arbitraryTimestamp, ), ).toEqual(expectedFromThirdParty); }); it('cannot applyActionToExtensions of declareReceivedRefund without a previous state', () => { // 'must throw' expect(() => { pnAnyDeclarative.applyActionToExtension( TestDataDeclarative.requestStateNoExtensions.extensions, TestDataDeclarative.actionDeclareReceivedRefund, TestDataDeclarative.requestStateNoExtensions, TestData.payerRaw.identity, TestData.arbitraryTimestamp, ); }).toThrowError(`The extension should be created before receiving any other action`); }); it('cannot applyActionToExtensions of declareReceivedRefund without a payer', () => { const previousState = Utils.deepCopy(TestDataDeclarative.requestStateCreatedEmpty); previousState.payer = undefined; previousState.extensions[ ExtensionTypes.ID.PAYMENT_NETWORK_ANY_DECLARATIVE as string ].values.payeeDelegate = undefined; // 'must throw' expect(() => { pnAnyDeclarative.applyActionToExtension( previousState.extensions, TestDataDeclarative.actionDeclareReceivedRefund, previousState, TestData.payerRaw.identity, TestData.arbitraryTimestamp, ); }).toThrowError(`The request must have a payer`); }); it('cannot applyActionToExtensions of declareReceivedRefund signed by someone else than the payer', () => { const previousState = Utils.deepCopy(TestDataDeclarative.requestStateCreatedEmpty); // 'must throw' expect(() => { pnAnyDeclarative.applyActionToExtension( previousState.extensions, TestDataDeclarative.actionDeclareReceivedRefund, previousState, TestData.payeeRaw.identity, TestData.arbitraryTimestamp, ); }).toThrowError(`The signer must be the payer`); }); it('cannot applyActionToExtensions of declareReceivedRefund with an invalid amount', () => { TestDataDeclarative.actionDeclareReceivedRefund.parameters.amount = 'invalid amount'; // 'must throw' expect(() => { pnAnyDeclarative.applyActionToExtension( TestDataDeclarative.requestStateCreatedEmpty.extensions, TestDataDeclarative.actionDeclareReceivedRefund, TestDataDeclarative.requestStateCreatedEmpty, TestData.payerRaw.identity, TestData.arbitraryTimestamp, ); }).toThrowError(`The amount is not a valid amount`); }); }); describe('applyActionToExtension/declareSentRefund', () => { it('can applyActionToExtensions of declareSentRefund', () => { // 'new extension state wrong' expect( pnAnyDeclarative.applyActionToExtension( TestDataDeclarative.requestStateCreatedEmpty.extensions, TestDataDeclarative.actionDeclareSentRefund, TestDataDeclarative.requestStateCreatedEmpty, TestData.payeeRaw.identity, TestData.arbitraryTimestamp, ), ).toEqual(TestDataDeclarative.extensionStateCreatedEmptySentRefund); }); it('can applyActionToExtensions of declareSentRefund from payeeDelegate', () => { const expectedFromThirdParty = Utils.deepCopy( TestDataDeclarative.extensionStateCreatedEmptySentRefund, ); expectedFromThirdParty[ ExtensionTypes.ID.PAYMENT_NETWORK_ANY_DECLARATIVE as string ].events[1].from = TestDataDeclarative.payeeDelegate; // 'new extension state wrong' expect( pnAnyDeclarative.applyActionToExtension( TestDataDeclarative.requestStateCreatedEmpty.extensions, TestDataDeclarative.actionDeclareSentRefund, TestDataDeclarative.requestStateCreatedEmpty, TestData.payeeDelegateRaw.identity, TestData.arbitraryTimestamp, ), ).toEqual(expectedFromThirdParty); }); it('cannot applyActionToExtensions of declareSentRefund without a previous state', () => { // 'must throw' expect(() => { pnAnyDeclarative.applyActionToExtension( TestDataDeclarative.requestStateNoExtensions.extensions, TestDataDeclarative.actionDeclareSentRefund, TestDataDeclarative.requestStateNoExtensions, TestData.payeeRaw.identity, TestData.arbitraryTimestamp, ); }).toThrowError(`The extension should be created before receiving any other action`); }); it('cannot applyActionToExtensions of declareSentRefund without a payee', () => { const previousState = Utils.deepCopy(TestDataDeclarative.requestStateCreatedEmpty); previousState.payee = undefined; previousState.extensions[ ExtensionTypes.ID.PAYMENT_NETWORK_ANY_DECLARATIVE as string ].values.payeeDelegate = undefined; // 'must throw' expect(() => { pnAnyDeclarative.applyActionToExtension( previousState.extensions, TestDataDeclarative.actionDeclareSentRefund, previousState, TestData.payeeRaw.identity, TestData.arbitraryTimestamp, ); }).toThrowError(`The request must have a payee`); }); it('cannot applyActionToExtensions of declareSentRefund signed by someone else than the payee', () => { const previousState = Utils.deepCopy(TestDataDeclarative.requestStateCreatedEmpty); // 'must throw' expect(() => { pnAnyDeclarative.applyActionToExtension( previousState.extensions, TestDataDeclarative.actionDeclareSentRefund, previousState, TestData.payerRaw.identity, TestData.arbitraryTimestamp, ); }).toThrowError(`The signer must be the payee`); }); it('cannot applyActionToExtensions of declareSentRefund with an invalid amount', () => { TestDataDeclarative.actionDeclareSentRefund.parameters.amount = 'invalid amount'; // 'must throw' expect(() => { pnAnyDeclarative.applyActionToExtension( TestDataDeclarative.requestStateCreatedEmpty.extensions, TestDataDeclarative.actionDeclareSentRefund, TestDataDeclarative.requestStateCreatedEmpty, TestData.payeeRaw.identity, TestData.arbitraryTimestamp, ); }).toThrowError(`The amount is not a valid amount`); }); }); describe('applyActionToExtension/declareReceivedPayment', () => { it('can applyActionToExtensions of declareReceivedPayment', () => { // 'new extension state wrong' expect( pnAnyDeclarative.applyActionToExtension( TestDataDeclarative.requestStateCreatedEmpty.extensions, TestDataDeclarative.actionDeclareReceivedPayment, TestDataDeclarative.requestStateCreatedEmpty, TestData.payeeRaw.identity, TestData.arbitraryTimestamp, ), ).toEqual(TestDataDeclarative.extensionStateCreatedEmptyReceivedPayment); }); it('can applyActionToExtensions of declareReceivedPayment from payeeDelegate', () => { const expectedFromThirdParty = Utils.deepCopy( TestDataDeclarative.extensionStateCreatedEmptyReceivedPayment, ); expectedFromThirdParty[ ExtensionTypes.ID.PAYMENT_NETWORK_ANY_DECLARATIVE as string ].events[1].from = TestDataDeclarative.payeeDelegate; // 'new extension state wrong' expect( pnAnyDeclarative.applyActionToExtension( TestDataDeclarative.requestStateCreatedEmpty.extensions, TestDataDeclarative.actionDeclareReceivedPayment, TestDataDeclarative.requestStateCreatedEmpty, TestData.payeeDelegateRaw.identity, TestData.arbitraryTimestamp, ), ).toEqual(expectedFromThirdParty); }); it('cannot applyActionToExtensions of declareReceivedPayment without a previous state', () => { // 'must throw' expect(() => { pnAnyDeclarative.applyActionToExtension( TestDataDeclarative.requestStateNoExtensions.extensions, TestDataDeclarative.actionDeclareReceivedPayment, TestDataDeclarative.requestStateNoExtensions, TestData.payeeRaw.identity, TestData.arbitraryTimestamp, ); }).toThrowError(`The extension should be created before receiving any other action`); }); it('cannot applyActionToExtensions of declareReceivedPayment without a payee', () => { const previousState = Utils.deepCopy(TestDataDeclarative.requestStateCreatedEmpty); previousState.payee = undefined; previousState.extensions[ ExtensionTypes.ID.PAYMENT_NETWORK_ANY_DECLARATIVE as string ].values.payeeDelegate = undefined; // 'must throw' expect(() => { pnAnyDeclarative.applyActionToExtension( previousState.extensions, TestDataDeclarative.actionDeclareReceivedPayment, previousState, TestData.payeeRaw.identity, TestData.arbitraryTimestamp, ); }).toThrowError(`The request must have a payee`); }); it('cannot applyActionToExtensions of declareReceivedPayment signed by someone else than the payee', () => { const previousState = Utils.deepCopy(TestDataDeclarative.requestStateCreatedEmpty); // 'must throw' expect(() => { pnAnyDeclarative.applyActionToExtension( previousState.extensions, TestDataDeclarative.actionDeclareReceivedPayment, previousState, TestData.payerRaw.identity, TestData.arbitraryTimestamp, ); }).toThrowError(`The signer must be the payee`); }); it('cannot applyActionToExtensions of declareReceivedPayment with an invalid amount', () => { TestDataDeclarative.actionDeclareReceivedPayment.parameters.amount = 'invalid amount'; // 'must throw' expect(() => { pnAnyDeclarative.applyActionToExtension( TestDataDeclarative.requestStateCreatedEmpty.extensions, TestDataDeclarative.actionDeclareReceivedPayment, TestDataDeclarative.requestStateCreatedEmpty, TestData.payeeRaw.identity, TestData.arbitraryTimestamp, ); }).toThrowError(`The amount is not a valid amount`); }); }); describe('applyActionToExtension/addDelegate', () => { it('can applyActionToExtensions of addDelegate from payee', () => { // 'new extension state wrong' expect( pnAnyDeclarative.applyActionToExtension( TestDataDeclarative.requestStateCreatedEmptyNoDelegate.extensions, TestDataDeclarative.actionAddDelegate, TestDataDeclarative.requestStateCreatedEmptyNoDelegate, TestData.payeeRaw.identity, TestData.arbitraryTimestamp, ), ).toEqual(TestDataDeclarative.extensionStateCreatedEmptyAddPayeeDelegate); }); it('can applyActionToExtensions of addDelegate from payer', () => { // 'new extension state wrong' expect( pnAnyDeclarative.applyActionToExtension( TestDataDeclarative.requestStateCreatedEmptyNoDelegate.extensions, TestDataDeclarative.actionAddDelegate, TestDataDeclarative.requestStateCreatedEmptyNoDelegate, TestData.payerRaw.identity, TestData.arbitraryTimestamp, ), ).toEqual(TestDataDeclarative.extensionStateCreatedEmptyAddPayerDelegate); }); it('cannot applyActionToExtensions of addDelegate if delegate already assigned', () => { // 'must throw' expect(() => { pnAnyDeclarative.applyActionToExtension( TestDataDeclarative.requestStateCreatedEmpty.extensions, TestDataDeclarative.actionAddDelegate, TestDataDeclarative.requestStateCreatedEmpty, TestData.payeeRaw.identity, TestData.arbitraryTimestamp, ); }).toThrowError(`The payeeDelegate is already assigned`); }); it('cannot applyActionToExtensions of addDelegate from a thirdparty', () => { // 'must throw' expect(() => { pnAnyDeclarative.applyActionToExtension( TestDataDeclarative.requestStateCreatedEmpty.extensions, TestDataDeclarative.actionAddDelegate, TestDataDeclarative.requestStateCreatedEmpty, TestData.otherIdRaw.identity, TestData.arbitraryTimestamp, ); }).toThrowError(`The signer must be the payee or the payer`); }); }); }); });
the_stack
import Vue from 'vue' import EventEmitter from 'eventemitter3' import { BaseClient, BaseEvents } from './base' import { Member } from './types' import { EVENT } from './events' import { accessor } from '~/store' import { DisconnectPayload, SignalProvidePayload, MemberListPayload, MemberDisconnectPayload, MemberPayload, ControlPayload, ControlTargetPayload, ChatPayload, EmotePayload, ControlClipboardPayload, ScreenConfigurationsPayload, ScreenResolutionPayload, AdminPayload, AdminTargetPayload, } from './messages' interface NekoEvents extends BaseEvents {} export class NekoClient extends BaseClient implements EventEmitter<NekoEvents> { private $vue!: Vue private $accessor!: typeof accessor init(vue: Vue) { this.$vue = vue this.$accessor = vue.$accessor } private cleanup() { this.$accessor.setConnected(false) this.$accessor.remote.reset() this.$accessor.user.reset() this.$accessor.video.reset() this.$accessor.chat.reset() } login(password: string, displayname: string) { const url = process.env.NODE_ENV === 'development' ? `ws://${location.host.split(':')[0]}:${process.env.VUE_APP_SERVER_PORT}/` : `${/https/gi.test(location.protocol) ? 'wss' : 'ws'}://${location.host}/` this.connect(url, password, displayname) } logout() { this.disconnect() this.cleanup() this.$vue.$swal({ title: this.$vue.$t('connection.logged_out'), icon: 'info', confirmButtonText: this.$vue.$t('connection.button_confirm') as string, }) } ///////////////////////////// // Internal Events ///////////////////////////// protected [EVENT.CONNECTING]() { this.$accessor.setConnnecting() } protected [EVENT.CONNECTED]() { this.$accessor.user.setMember(this.id) this.$accessor.setConnected(true) this.$accessor.setConnected(true) this.$vue.$notify({ group: 'neko', type: 'success', title: this.$vue.$t('connection.connected') as string, duration: 5000, speed: 1000, }) } protected [EVENT.DISCONNECTED](reason?: Error) { this.cleanup() this.$vue.$notify({ group: 'neko', type: 'error', title: this.$vue.$t('connection.disconnected') as string, text: reason ? reason.message : undefined, duration: 5000, speed: 1000, }) } protected [EVENT.TRACK](event: RTCTrackEvent) { const { track, streams } = event if (track.kind === 'audio') { return } this.$accessor.video.addTrack([track, streams[0]]) this.$accessor.video.setStream(0) } protected [EVENT.DATA](data: any) {} ///////////////////////////// // System Events ///////////////////////////// protected [EVENT.SYSTEM.DISCONNECT]({ message }: DisconnectPayload) { this.onDisconnected(new Error(message)) this.$vue.$swal({ title: this.$vue.$t('connection.disconnected'), text: message, icon: 'error', confirmButtonText: this.$vue.$t('connection.button_confirm') as string, }) } ///////////////////////////// // Member Events ///////////////////////////// protected [EVENT.MEMBER.LIST]({ members }: MemberListPayload) { this.$accessor.user.setMembers(members) this.$accessor.chat.newMessage({ id: this.id, content: this.$vue.$t('notifications.connected', { name: '' }) as string, type: 'event', created: new Date(), }) } protected [EVENT.MEMBER.CONNECTED](member: MemberPayload) { this.$accessor.user.addMember(member) if (member.id !== this.id) { this.$accessor.chat.newMessage({ id: member.id, content: this.$vue.$t('notifications.connected', { name: '' }) as string, type: 'event', created: new Date(), }) } } protected [EVENT.MEMBER.DISCONNECTED]({ id }: MemberDisconnectPayload) { const member = this.member(id) if (!member) { return } this.$accessor.chat.newMessage({ id: member.id, content: this.$vue.$t('notifications.disconnected', { name: '' }) as string, type: 'event', created: new Date(), }) this.$accessor.user.delMember(id) } ///////////////////////////// // Control Events ///////////////////////////// protected [EVENT.CONTROL.LOCKED]({ id }: ControlPayload) { this.$accessor.remote.setHost(id) this.$accessor.remote.changeKeyboard() const member = this.member(id) if (!member) { return } if (this.id === id) { this.$vue.$notify({ group: 'neko', type: 'info', title: this.$vue.$t('notifications.controls_taken', { name: this.$vue.$t('you') }) as string, duration: 5000, speed: 1000, }) } this.$accessor.chat.newMessage({ id: member.id, content: this.$vue.$t('notifications.controls_taken', { name: '' }) as string, type: 'event', created: new Date(), }) } protected [EVENT.CONTROL.RELEASE]({ id }: ControlPayload) { this.$accessor.remote.reset() const member = this.member(id) if (!member) { return } if (this.id === id) { this.$vue.$notify({ group: 'neko', type: 'info', title: this.$vue.$t('notifications.controls_released', { name: this.$vue.$t('you') }) as string, duration: 5000, speed: 1000, }) } this.$accessor.chat.newMessage({ id: member.id, content: this.$vue.$t('notifications.controls_released', { name: '' }) as string, type: 'event', created: new Date(), }) } protected [EVENT.CONTROL.REQUEST]({ id }: ControlPayload) { const member = this.member(id) if (!member) { return } this.$vue.$notify({ group: 'neko', type: 'info', title: this.$vue.$t('notifications.controls_has', { name: member.displayname }) as string, text: this.$vue.$t('notifications.controls_has_alt') as string, duration: 5000, speed: 1000, }) } protected [EVENT.CONTROL.REQUESTING]({ id }: ControlPayload) { const member = this.member(id) if (!member || member.ignored) { return } this.$vue.$notify({ group: 'neko', type: 'info', title: this.$vue.$t('notifications.controls_requesting', { name: member.displayname }) as string, duration: 5000, speed: 1000, }) } protected [EVENT.CONTROL.GIVE]({ id, target }: ControlTargetPayload) { const member = this.member(target) if (!member) { return } this.$accessor.remote.setHost(member) this.$accessor.remote.changeKeyboard() this.$accessor.chat.newMessage({ id, content: this.$vue.$t('notifications.controls_given', { name: member.id == this.id ? this.$vue.$t('you') : member.displayname, }) as string, type: 'event', created: new Date(), }) } protected [EVENT.CONTROL.CLIPBOARD]({ text }: ControlClipboardPayload) { this.$accessor.remote.setClipboard(text) } ///////////////////////////// // Chat Events ///////////////////////////// protected [EVENT.CHAT.MESSAGE]({ id, content }: ChatPayload) { const member = this.member(id) if (!member || member.ignored) { return } this.$accessor.chat.newMessage({ id, content, type: 'text', created: new Date(), }) } protected [EVENT.CHAT.EMOTE]({ id, emote }: EmotePayload) { const member = this.member(id) if (!member || member.ignored) { return } this.$accessor.chat.newEmote({ type: emote }) } ///////////////////////////// // Screen Events ///////////////////////////// protected [EVENT.SCREEN.CONFIGURATIONS]({ configurations }: ScreenConfigurationsPayload) { this.$accessor.video.setConfigurations(configurations) } protected [EVENT.SCREEN.RESOLUTION]({ id, width, height, rate }: ScreenResolutionPayload) { this.$accessor.video.setResolution({ width, height, rate }) if (!id) { return } const member = this.member(id) if (!member || member.ignored) { return } this.$accessor.chat.newMessage({ id, content: this.$vue.$t('notifications.resolution', { width: width, height: height, rate: rate, }) as string, type: 'event', created: new Date(), }) } ///////////////////////////// // Admin Events ///////////////////////////// protected [EVENT.ADMIN.BAN]({ id, target }: AdminTargetPayload) { if (!target) { return } const member = this.member(target) if (!member) { return } this.$accessor.chat.newMessage({ id, content: this.$vue.$t('notifications.banned', { name: member.id == this.id ? this.$vue.$t('you') : member.displayname, }) as string, type: 'event', created: new Date(), }) } protected [EVENT.ADMIN.KICK]({ id, target }: AdminTargetPayload) { if (!target) { return } const member = this.member(target) if (!member) { return } this.$accessor.chat.newMessage({ id, content: this.$vue.$t('notifications.kicked', { name: member.id == this.id ? this.$vue.$t('you') : member.displayname, }) as string, type: 'event', created: new Date(), }) } protected [EVENT.ADMIN.MUTE]({ id, target }: AdminTargetPayload) { if (!target) { return } this.$accessor.user.setMuted({ id: target, muted: true }) const member = this.member(target) if (!member) { return } this.$accessor.chat.newMessage({ id, content: this.$vue.$t('notifications.muted', { name: member.id == this.id ? this.$vue.$t('you') : member.displayname, }) as string, type: 'event', created: new Date(), }) } protected [EVENT.ADMIN.UNMUTE]({ id, target }: AdminTargetPayload) { if (!target) { return } this.$accessor.user.setMuted({ id: target, muted: false }) const member = this.member(target) if (!member) { return } this.$accessor.chat.newMessage({ id, content: this.$vue.$t('notifications.unmuted', { name: member.id == this.id ? this.$vue.$t('you') : member.displayname, }) as string, type: 'event', created: new Date(), }) } protected [EVENT.ADMIN.LOCK]({ id }: AdminPayload) { this.$accessor.setLocked(true) this.$accessor.chat.newMessage({ id, content: this.$vue.$t('notifications.room_locked') as string, type: 'event', created: new Date(), }) } protected [EVENT.ADMIN.UNLOCK]({ id }: AdminPayload) { this.$accessor.setLocked(false) this.$accessor.chat.newMessage({ id, content: this.$vue.$t('notifications.room_unlocked') as string, type: 'event', created: new Date(), }) } protected [EVENT.ADMIN.CONTROL]({ id, target }: AdminTargetPayload) { this.$accessor.remote.setHost(id) this.$accessor.remote.changeKeyboard() if (!target) { this.$accessor.chat.newMessage({ id, content: this.$vue.$t('notifications.controls_taken_force') as string, type: 'event', created: new Date(), }) return } const member = this.member(target) if (!member) { return } this.$accessor.chat.newMessage({ id, content: this.$vue.$t('notifications.controls_taken_steal', { name: member.id == this.id ? this.$vue.$t('you') : member.displayname, }) as string, type: 'event', created: new Date(), }) } protected [EVENT.ADMIN.RELEASE]({ id, target }: AdminTargetPayload) { this.$accessor.remote.reset() if (!target) { this.$accessor.chat.newMessage({ id, content: this.$vue.$t('notifications.controls_released_force') as string, type: 'event', created: new Date(), }) return } const member = this.member(target) if (!member) { return } this.$accessor.chat.newMessage({ id, content: this.$vue.$t('notifications.controls_released_steal', { name: member.id == this.id ? this.$vue.$t('you') : member.displayname, }) as string, type: 'event', created: new Date(), }) } protected [EVENT.ADMIN.GIVE]({ id, target }: AdminTargetPayload) { if (!target) { return } const member = this.member(target) if (!member) { return } this.$accessor.remote.setHost(member) this.$accessor.remote.changeKeyboard() this.$accessor.chat.newMessage({ id, content: this.$vue.$t('notifications.controls_given', { name: member.id == this.id ? this.$vue.$t('you') : member.displayname, }) as string, type: 'event', created: new Date(), }) } // Utilities protected member(id: string): Member | undefined { return this.$accessor.user.members[id] } }
the_stack
import chai from 'chai'; import Chance from 'chance'; import { Datastore } from '@google-cloud/datastore'; import { Gstore, Entity, EntityKey } from '../../src'; type GenericObject = { [key: string]: any }; const gstore = new Gstore(); const gstoreWithCache = new Gstore({ cache: { config: { ttl: { queries: 600 } } } }); const ds = new Datastore({ projectId: 'gstore-integration-tests' }); gstore.connect(ds); gstoreWithCache.connect(ds); const { Schema } = gstore; const { expect, assert } = chai; const chance = new Chance(); const userSchema = new Schema({ name: { type: String }, age: { type: Number }, address: { type: Schema.Types.Key }, createdAt: { type: Date }, }); const addressSchema = new Schema({ city: { type: String }, country: { type: String } }); let generatedIds: string[] = []; const allKeys: EntityKey[] = []; const UserModel = gstore.model('QueryTests-User', userSchema); const AddressModel = gstore.model('QueryTests-Address', addressSchema); const getId = (): string => { const id = chance.string({ pool: 'abcdefghijklmnopqrstuvwxyz' }); if (generatedIds.includes(id)) { return getId(); } generatedIds.push(id); return id; }; const getAddress = (): Entity<any> => { const key = AddressModel.key(getId()); allKeys.push(key); const data = { city: chance.city(), country: chance.country() }; const address = new AddressModel(data, undefined, undefined, undefined, key); return address; }; const getUser = (address: Entity<any>): Entity<any> & GenericObject => { const key = UserModel.key(getId()); allKeys.push(key); const data = { name: chance.string(), age: chance.integer({ min: 1 }), address: address.entityKey, createdAt: new Date('2019-01-20'), }; const user = new UserModel(data, undefined, undefined, undefined, key); return user; }; const addresses = [getAddress(), getAddress(), getAddress(), getAddress()]; const users = [getUser(addresses[0]), getUser(addresses[1]), getUser(addresses[2]), getUser(addresses[3])]; const mapAddressToId = addresses.reduce( (acc, address) => ({ ...acc, [address.entityKey.name as string]: address, }), {} as any, ); const mapUserToId = users.reduce( (acc, user) => ({ ...acc, [user.entityKey.name as string]: user, }), {} as any, ); const cleanUp = (): Promise<any> => ((ds.delete(allKeys) as unknown) as Promise<any>) .then(() => Promise.all([UserModel.deleteAll(), AddressModel.deleteAll()])) .catch((err) => { console.log('Error cleaning up'); // eslint-disable-line console.log(err); // eslint-disable-line }); describe('Queries (Integration Tests)', () => { beforeAll(() => { generatedIds = []; return gstore.save([...users, ...addresses]); }); afterAll(() => cleanUp()); describe('Setup', () => { test('Return all the User and Addresses entities', () => UserModel.query() .run() .then(({ entities }) => { expect(entities.length).equal(users.length); }) .then(() => AddressModel.query().run()) .then(({ entities }) => { expect(entities.length).equal(addresses.length); })); }); describe('list()', () => { describe('populate()', () => { test('should populate the address of all users', () => UserModel.list() .populate() .then(({ entities }) => { expect(entities.length).equal(users.length); entities.forEach((entity) => { const entityKey = (entity as any)[gstore.ds.KEY]; const addressId = mapUserToId[entityKey.name].address.name; const address = mapAddressToId[addressId]; expect((entity.address as any).city).equal(address.city); expect((entity.address as any).country).equal(address.country); }); })); test('should also work with ENTITY format', () => UserModel.list({ format: 'ENTITY' }) .populate() .then(({ entities }) => { expect(entities.length).equal(users.length); entities.forEach((entity) => { const { entityKey } = entity; const addressId = mapUserToId[entityKey.name as string].address.name; const address = mapAddressToId[addressId]; expect((entity.address as any).city).equal(address.city); expect((entity.address as any).country).equal(address.country); }); })); test('should allow to select specific reference entity fields', () => UserModel.list() .populate('address', 'country') .then(({ entities }) => { expect(entities.length).equal(users.length); entities.forEach((entity) => { const entityKey = (entity as any)[gstore.ds.KEY]; const addressId = mapUserToId[entityKey.name].address.name; const address = mapAddressToId[addressId]; expect((entity.address as any).country).equal(address.country); assert.isUndefined((entity.address as any).city); }); })); describe('when cache is active', () => { beforeAll(() => { gstore.cache = gstoreWithCache.cache; }); afterAll(() => { delete gstore.cache; }); afterEach(() => { gstore.cache!.reset(); }); test('should also populate() fields', () => UserModel.list() .populate() .then(({ entities }) => { expect(entities.length).equal(users.length); entities.forEach((entity) => { const entityKey = (entity as any)[gstore.ds.KEY]; const addressId = mapUserToId[entityKey.name].address.name; const address = mapAddressToId[addressId]; expect((entity.address as any).city).equal(address.city); expect((entity.address as any).country).equal(address.country); }); })); }); }); }); describe('findOne()', () => { describe('populate()', () => { test('should populate the address of all users', () => UserModel.findOne({ name: users[0].name as string }) .populate() .then((entity) => { const addressId = mapUserToId[entity!.entityKey.name as string].address.name; const address = mapAddressToId[addressId]; expect((entity!.address as any).city).equal(address.city); expect((entity!.address as any).country).equal(address.country); })); test('should allow to select specific reference entity fields', () => UserModel.findOne({ name: users[0].name }) .populate('address', 'country') .then((entity) => { const addressId = mapUserToId[entity!.entityKey.name as string].address.name; const address = mapAddressToId[addressId]; expect((entity!.address as any).country).equal(address.country); assert.isUndefined((entity!.address as any).city); })); }); }); describe('findAround()', () => { describe('populate()', () => { test('should populate the address of all users', () => UserModel.findAround('createdAt', new Date('2019-01-01'), { after: 10 }) .populate() .then((entities) => { expect(entities.length).equal(users.length); entities.forEach((entity) => { const entityKey = (entity as any)[gstore.ds.KEY]; const addressId = mapUserToId[entityKey.name].address.name; const address = mapAddressToId[addressId]; expect((entity.address as any).city).equal(address.city); expect((entity.address as any).country).equal(address.country); }); })); test('should also work with ENTITY format', () => UserModel.findAround('createdAt', new Date('2019-01-01'), { after: 10, format: 'ENTITY' }) .populate() .then((entities) => { expect(entities.length).equal(users.length); entities.forEach((entity) => { const { entityKey } = entity; const addressId = mapUserToId[entityKey.name as string].address.name; const address = mapAddressToId[addressId]; expect((entity.address as any).city).equal(address.city); expect((entity.address as any).country).equal(address.country); }); })); test('should allow to select specific reference entity fields', () => UserModel.findAround('createdAt', new Date('2019-01-01'), { after: 10 }) .populate('address', 'country') .then((entities) => { expect(entities.length).equal(users.length); entities.forEach((entity) => { const entityKey = (entity as any)[gstore.ds.KEY]; const addressId = mapUserToId[entityKey.name].address.name; const address = mapAddressToId[addressId]; expect((entity.address as any).country).equal(address.country); assert.isUndefined((entity.address as any).city); }); })); }); }); describe('datastore Queries()', () => { describe('populate()', () => { test('should populate the address of all users', () => UserModel.query() .filter('createdAt', '>', new Date('2019-01-01')) .run() .populate() .then(({ entities }) => { expect(entities.length).equal(users.length); entities.forEach((entity) => { const entityKey = (entity as GenericObject)[gstore.ds.KEY as any]; const addressId = mapUserToId[entityKey.name].address.name; const address = mapAddressToId[addressId]; expect((entity.address as GenericObject).city).equal(address.city); expect((entity.address as GenericObject).country).equal(address.country); }); })); test('should also work with ENTITY format', () => UserModel.query<'ENTITY'>() .filter('createdAt', '>', new Date('2019-01-01')) .run({ format: 'ENTITY' }) .populate() .then(({ entities }) => { expect(entities.length).equal(users.length); entities.forEach((entity) => { const { entityKey } = entity; const addressId = mapUserToId[entityKey.name as string].address.name; const address = mapAddressToId[addressId]; expect((entity.address as GenericObject).city).equal(address.city); expect((entity.address as GenericObject).country).equal(address.country); }); })); test('should allow to select specific reference entity fields', () => UserModel.query() .filter('createdAt', '>', new Date('2019-01-01')) .run() .populate('address', 'country') .populate('unknown') .then(({ entities }) => { expect(entities.length).equal(users.length); entities.forEach((entity) => { const entityKey = (entity as GenericObject)[gstore.ds.KEY as any]; const addressId = mapUserToId[entityKey.name].address.name; const address = mapAddressToId[addressId]; expect((entity.address as GenericObject).country).equal(address.country); // eslint-disable-next-line @typescript-eslint/ban-ts-ignore // @ts-ignore expect(entity.unknown).equal(null); assert.isUndefined((entity.address as GenericObject).city); }); })); }); }); });
the_stack
import * as cp from "child_process"; import * as fse from "fs-extra"; import * as _ from "lodash"; import * as os from "os"; import * as path from "path"; const expandHomeDir = require("expand-home-dir"); const WinReg = require("winreg-utf8"); const isWindows: boolean = process.platform.indexOf("win") === 0; const isMac: boolean = process.platform.indexOf("darwin") === 0; const isLinux: boolean = process.platform.indexOf("linux") === 0; const JAVAC_FILENAME = "javac" + (isWindows ? ".exe" : ""); const JAVA_FILENAME = "java" + (isWindows ? ".exe" : ""); export interface JavaRuntime { home: string; version: number; sources: string[]; } /** * return metadata for all installed JDKs. */ export async function findJavaHomes(): Promise<JavaRuntime[]> { const ret: JavaRuntime[] = []; const jdkMap = new Map<string, string[]>(); updateJDKs(jdkMap, await fromEnv("JDK_HOME"), "env.JDK_HOME"); updateJDKs(jdkMap, await fromEnv("JAVA_HOME"), "env.JAVA_HOME"); updateJDKs(jdkMap, await fromPath(), "env.PATH"); updateJDKs(jdkMap, await fromWindowsRegistry(), "WindowsRegistry"); updateJDKs(jdkMap, await fromCommonPlaces(), "DefaultLocation"); for (const elem of jdkMap) { const home = elem[0]; const sources = elem[1]; const version = await getJavaVersion(home); if (version) { ret.push({ home, sources, version }); } else { console.warn(`Unknown version of JDK ${home}`); } } return ret; } function updateJDKs(map: Map<string, string[]>, newJdks: string[], source: string) { for (const newJdk of newJdks) { const sources = map.get(newJdk); if (sources !== undefined) { map.set(newJdk, [...sources, source]); } else { map.set(newJdk, [source]); } } } async function fromEnv(name: string): Promise<string[]> { const ret: string[] = []; const proposed = process.env[name]; if (proposed) { const javaHome = await verifyJavaHome(proposed, JAVAC_FILENAME); if (javaHome) { ret.push(javaHome); } } return ret; } async function fromPath(): Promise<string[]> { const ret: string[] = []; const paths = process.env.PATH ? process.env.PATH.split(path.delimiter).filter(Boolean) : []; for (const p of paths) { const proposed = path.dirname(p); // remove "bin" const javaHome = await verifyJavaHome(proposed, JAVAC_FILENAME); if (javaHome) { ret.push(javaHome); } if (isMac) { let dir = expandHomeDir(p); dir = await findLinkedFile(dir); // on mac, java install has a utility script called java_home const macUtility = path.join(dir, "java_home"); if (await fse.pathExists(macUtility)) { let buffer; try { buffer = cp.execSync(macUtility, { cwd: dir }); const absoluteJavaHome = "" + buffer.toString().replace(/\n$/, ""); const verified = await verifyJavaHome(absoluteJavaHome, JAVAC_FILENAME); if (verified) { ret.push(absoluteJavaHome); } } catch (error) { // do nothing } } } } if (isMac) { // Exclude /usr, because in macOS Big Sur /usr/bin/javac is no longer symlink. // See https://github.com/redhat-developer/vscode-java/issues/1700#issuecomment-729478810 return ret.filter(item => item !== "/usr"); } else { return ret; } } async function fromWindowsRegistry(): Promise<string[]> { if (!isWindows) { return []; } const keyPaths: string[] = [ "\\SOFTWARE\\JavaSoft\\JDK", "\\SOFTWARE\\JavaSoft\\Java Development Kit" ]; const promisifyFindPossibleRegKey = (keyPath: string, regArch: string): Promise<Winreg.Registry[]> => { return new Promise<Winreg.Registry[]>((resolve) => { const winreg: Winreg.Registry = new WinReg({ hive: WinReg.HKLM, key: keyPath, arch: regArch }); winreg.keys((err, result) => { if (err) { return resolve([]); } resolve(result); }); }); }; const promisifyFindJavaHomeInRegKey = (reg: Winreg.Registry): Promise<string | null> => { return new Promise<string | null>((resolve) => { reg.get("JavaHome", (err, home) => { if (err || !home) { return resolve(null); } resolve(home.value); }); }); }; const promises = []; for (const arch of ["x64", "x86"]) { for (const keyPath of keyPaths) { promises.push(promisifyFindPossibleRegKey(keyPath, arch)); } } const keysFoundSegments: Winreg.Registry[][] = await Promise.all(promises); const keysFound: Winreg.Registry[] = Array.prototype.concat.apply([], keysFoundSegments); if (!keysFound.length) { return []; } const sortedKeysFound = keysFound.sort((a, b) => { const aVer = parseFloat(a.key); const bVer = parseFloat(b.key); return bVer - aVer; }); const javaHomes: string[] = []; for (const key of sortedKeysFound) { const candidate = await promisifyFindJavaHomeInRegKey(key); if (candidate) { javaHomes.push(candidate); } } const ret: string[] = []; for (const proposed of javaHomes) { const javaHome = await verifyJavaHome(proposed, JAVAC_FILENAME); if (javaHome) { ret.push(javaHome); } } return ret; } async function fromCommonPlaces(): Promise<string[]> { const ret: string[] = []; // common place for mac if (isMac) { const jvmStore = "/Library/Java/JavaVirtualMachines"; const subfolder = "Contents/Home"; let jvms: string[] = []; try { jvms = await fse.readdir(jvmStore); } catch (error) { // ignore } for (const jvm of jvms) { const proposed = path.join(jvmStore, jvm, subfolder); const javaHome = await verifyJavaHome(proposed, JAVAC_FILENAME); if (javaHome) { ret.push(javaHome); } } } // common place for Windows if (isWindows) { const localAppDataFolder = process.env.LOCALAPPDATA ? process.env.LOCALAPPDATA : path.join(os.homedir(), "AppData", "Local"); const possibleLocations: string[] = [ process.env.ProgramFiles && path.join(process.env.ProgramFiles, "Java"), // Oracle JDK per machine process.env.ProgramW6432 && path.join(process.env.ProgramW6432, "Java"), // Oracle JDK per machine process.env.ProgramFiles && path.join(process.env.ProgramFiles, "AdoptOpenJDK"), // AdoptOpenJDK per machine process.env.ProgramW6432 && path.join(process.env.ProgramW6432, "AdoptOpenJDK"), // AdoptOpenJDK per machine path.join(localAppDataFolder, "Programs", "AdoptOpenJDK"), // AdoptOpenJDK per user ].filter(Boolean) as string[]; const jvmStores = _.uniq(possibleLocations); for (const jvmStore of jvmStores) { let jvms: string[] = []; try { jvms = await fse.readdir(jvmStore); } catch (error) { // ignore } for (const jvm of jvms) { const proposed = path.join(jvmStore, jvm); const javaHome = await verifyJavaHome(proposed, JAVAC_FILENAME); if (javaHome) { ret.push(javaHome); } } } } // common place for Linux if (isLinux) { const jvmStore = "/usr/lib/jvm"; let jvms: string[] = []; try { jvms = await fse.readdir(jvmStore); } catch (error) { // ignore } for (const jvm of jvms) { const proposed = path.join(jvmStore, jvm); const javaHome = await verifyJavaHome(proposed, JAVAC_FILENAME); if (javaHome) { ret.push(javaHome); } } } return ret; } export async function verifyJavaHome(raw: string, javaFilename: string): Promise<string | undefined> { const dir = expandHomeDir(raw); const targetJavaFile = await findLinkedFile(path.resolve(dir, "bin", javaFilename)); const proposed = path.dirname(path.dirname(targetJavaFile)); if (await fse.pathExists(proposed) && await fse.pathExists(path.resolve(proposed, "bin", javaFilename)) ) { return proposed; } return undefined; } // iterate through symbolic links until file is found async function findLinkedFile(file: string): Promise<string> { if (!await fse.pathExists(file) || !(await fse.lstat(file)).isSymbolicLink()) { return file; } return await findLinkedFile(await fse.readlink(file)); } export async function getJavaVersion(javaHome: string): Promise<number> { let javaVersion = await checkVersionInReleaseFile(javaHome); if (!javaVersion) { javaVersion = await checkVersionByCLI(javaHome); } return javaVersion; } export function parseMajorVersion(version: string): number { if (!version) { return 0; } // Ignore '1.' prefix for legacy Java versions if (version.startsWith("1.")) { version = version.substring(2); } // look into the interesting bits now const regexp = /\d+/g; const match = regexp.exec(version); let javaVersion = 0; if (match) { javaVersion = parseInt(match[0]); } return javaVersion; } /** * Get version by checking file JAVA_HOME/release */ async function checkVersionInReleaseFile(javaHome: string): Promise<number> { if (!javaHome) { return 0; } const releaseFile = path.join(javaHome, "release"); if (!await fse.pathExists(releaseFile)) { return 0; } try { const content = await fse.readFile(releaseFile); const regexp = /^JAVA_VERSION="(.*)"/gm; const match = regexp.exec(content.toString()); if (!match) { return 0; } const majorVersion = parseMajorVersion(match[1]); return majorVersion; } catch (error) { // ignore } return 0; } /** * Get version by parsing `JAVA_HOME/bin/java -version` */ async function checkVersionByCLI(javaHome: string): Promise<number> { if (!javaHome) { return 0; } return new Promise((resolve, _reject) => { const javaBin = path.join(javaHome, "bin", JAVA_FILENAME); cp.execFile(javaBin, ["-version"], {}, (_error, _stdout, stderr) => { const regexp = /version "(.*)"/g; const match = regexp.exec(stderr); if (!match) { return resolve(0); } const javaVersion = parseMajorVersion(match[1]); resolve(javaVersion); }); }); }
the_stack
/** * @license Copyright © 2014 onwards, Andrew Whewell * All rights reserved. * * Redistribution and use of this software in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * * Neither the name of the author nor the names of the program's contributors may be used to endorse or promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHORS OF THE SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /** * @fileoverview Code that manages the fetching and display of polar plot slices. */ namespace VRS { /* * Global options */ export var globalOptions: GlobalOptions = VRS.globalOptions || {}; VRS.globalOptions.polarPlotEnabled = VRS.globalOptions.polarPlotEnabled !== undefined ? VRS.globalOptions.polarPlotEnabled : true; // True if the polar plotter is enabled, false if it is not. VRS.globalOptions.polarPlotFetchUrl = VRS.globalOptions.polarPlotFetchUrl || 'PolarPlot.json'; // The URL to fetch polar plots from. VRS.globalOptions.polarPlotFetchTimeout = VRS.globalOptions.polarPlotFetchTimeout || 10000; // The timeout when fetching polar plots. VRS.globalOptions.polarPlotAutoRefreshSeconds = VRS.globalOptions.polarPlotAutoRefreshSeconds !== undefined ? VRS.globalOptions.polarPlotAutoRefreshSeconds : 5; // The number of seconds between automatic refreshes of displayed polar plots. Set to a value less than 1 to disable automatic refreshes. VRS.globalOptions.polarPlotAltitudeConfigs = VRS.globalOptions.polarPlotAltitudeConfigs || [ // An array of the altitudes ranges to show in the polar plot menu and the colours for each range. Note that the ranges are defined on the server, if you change the upper or lower bounds of a range you need to modify the server to match and recompile it. { low: -1, high: -1, colour: '#000000', zIndex: -5 }, { low: -1, high: 9999, colour: '#FFFFFF', zIndex: -1 }, { low: 10000, high: 19999, colour: '#00FF00', zIndex: -2 }, { low: 20000, high: 29999, colour: '#0000FF', zIndex: -3 }, { low: 30000, high: -1, colour: '#FF0000', zIndex: -4 } ]; VRS.globalOptions.polarPlotUserConfigurable = VRS.globalOptions.polarPlotUserConfigurable !== undefined ? VRS.globalOptions.polarPlotUserConfigurable : true; // True if the user can change the colours, false if they can't. VRS.globalOptions.polarPlotStrokeWeight = VRS.globalOptions.polarPlotStrokeWeight !== undefined ? VRS.globalOptions.polarPlotStrokeWeight : 2; // The weight in pixels of the line to draw around the edge of a polar plot. VRS.globalOptions.polarPlotStrokeColour = VRS.globalOptions.polarPlotStrokeColour !== undefined ? VRS.globalOptions.polarPlotStrokeColour : '#000000'; // The colour of the polar plot stroke. VRS.globalOptions.polarPlotStrokeOpacity = VRS.globalOptions.polarPlotStrokeOpacity !== undefined ? VRS.globalOptions.polarPlotStrokeOpacity : 1.0; // The opacity of the polar plot stroke. VRS.globalOptions.polarPlotFillOpacity = VRS.globalOptions.polarPlotFillOpacity !== undefined ? VRS.globalOptions.polarPlotFillOpacity : 0.50; // The transparency of the fill area for a polar plot. VRS.globalOptions.polarPlotStrokeColourCallback = VRS.globalOptions.polarPlotStrokeColourCallback || undefined; // A function that is passed the feed id, low altitude and high altitude, and returns a CSS colour for the stroke. VRS.globalOptions.polarPlotFillColourCallback = VRS.globalOptions.polarPlotFillColourCallback || undefined; // A function that is passed the feed id, low altitude and high altitude, and returns a CSS colour for the fill. VRS.globalOptions.polarPlotDisplayOnStartup = VRS.globalOptions.polarPlotDisplayOnStartup || []; // An array of polar plots to show when the site is loaded. The array of objects is { feedName: string, low: number, high: number }. /** * The settings to pass when creating a new instance of a PolarPlotter. */ export interface PolarPlotter_Settings { name?: string; map: IMap; aircraftListFetcher: AircraftListFetcher autoSaveState?: boolean; unitDisplayPreferences: UnitDisplayPreferences; } /** * Describes a range of altitudes. */ export interface AltitudeRange { lowAlt: number; highAlt: number; } /** * Describes a polar plot slice - a range of altitudes and the entire polygon path of the plot for that range. */ export interface PolarPlot_Slice { lowAlt: number; highAlt: number; plots: ILatLng[]; } /** * Associates a slice with a feed. */ interface PolarPlot_FeedSlice { feedId: number; slice: PolarPlot_Slice; } /** * An external description of a feed's slice. This is a part of the polar plotter's saved state. */ export interface PolarPlot_FeedSliceAbstract { feedName: string; low: number; high: number; } /** * Carries all of the slices for a feed. This is what the server sends to us. */ export interface PolarPlot_AllFeedSlices { feedId: number; slices: PolarPlot_Slice[]; } /** * Describes the display configuration for a single slice. */ export interface PolarPlot_AltitudeRangeConfig { low: number; high: number; colour: string; zIndex: number; } /** * The settings that are saved between sessions by PolarPlotter. */ export interface PolarPlotter_SaveState { altitudeRangeConfigs: PolarPlot_AltitudeRangeConfig[]; plotsOnDisplay: PolarPlot_FeedSliceAbstract[]; strokeOpacity: number; fillOpacity: number; } /** * An object whose properties can identify a polar plot slice. */ export interface PolarPlot_Id { feedId: number; lowAlt: number; highAlt: number; colour?: string; } /** * Creates a new polar plotter object. */ export class PolarPlotter implements ISelfPersist<PolarPlotter_SaveState> { private _Settings: PolarPlotter_Settings; private _AutoRefreshTimerId: number; private _PlotsOnDisplay: PolarPlot_FeedSlice[] = []; // The slices being shown on display private _PolarPlot: PolarPlot_AllFeedSlices = null; // The last set of polar plots fetched from the server private _AltitudeRangeConfigs: PolarPlot_AltitudeRangeConfig[] = VRS.globalOptions.polarPlotAltitudeConfigs.slice(); private _StrokeOpacity: number = VRS.globalOptions.polarPlotStrokeOpacity; private _FillOpacity: number = VRS.globalOptions.polarPlotFillOpacity; constructor(settings: PolarPlotter_Settings) { if(!settings) throw 'You must supply a settings object'; if(!settings.aircraftListFetcher) throw 'You must supply an aircraftListFetcher object'; if(!settings.map) throw 'You must supply a map'; if(!settings.unitDisplayPreferences) throw 'You must supply the unit display references'; this._Settings = $.extend({ name: 'default', autoSaveState: true }, settings); } /** * Gets the index number of a plot that is being shown for a feed. */ private getPlotsOnDisplayIndex = (feedId: number, slice: PolarPlot_Slice) : number => { return VRS.arrayHelper.indexOfMatch(this._PlotsOnDisplay, (item) => { return item.feedId === feedId && item.slice.lowAlt === slice.lowAlt && item.slice.highAlt === slice.highAlt; }); } /** * Records a polar plot slice against a feed. If the feed already has a slice assigned to it then this * function does nothing. */ private addToPlotsOnDisplay = (feedId: number, slice: PolarPlot_Slice) => { if(this.getPlotsOnDisplayIndex(feedId, slice) === -1) { this._PlotsOnDisplay.push({ feedId: feedId, slice: slice }); } } /** * Removes a slice from the plots recorded as being shown for a feed. If the feed does not already have * the slice's altitudes recorded as being on display then this function does nothing. */ private removeFromPlotsOnDisplay = (feedId: number, slice: PolarPlot_Slice) => { var index = this.getPlotsOnDisplayIndex(feedId, slice); if(index !== -1) { this._PlotsOnDisplay.splice(index, 1); } } /** * Returns an array of every slice being shown for a feed. */ private getPlotsOnDisplayForFeed = (feedId: number) : PolarPlot_FeedSlice[] => { return VRS.arrayHelper.filter(this._PlotsOnDisplay, function(plotOnDisplay) { return plotOnDisplay.feedId === feedId; }) } /** * Returns the name of the object for the purposes of state persistence. */ getName = () : string => { return this._Settings.name; } /** * Returns the last polar plot fetched or null if there is none. */ getPolarPlot = () : PolarPlot_AllFeedSlices => { return this._PolarPlot; } /** * Returns an array of feeds that have polar plots. */ getPolarPlotterFeeds = () : IReceiver[] => { var result: IReceiver[] = []; if(!VRS.serverConfig || VRS.serverConfig.polarPlotsEnabled()) { result = VRS.arrayHelper.filter(this._Settings.aircraftListFetcher.getFeeds(), function(feed) { return feed.polarPlot; }); } return result; } /** * Returns an array of feeds that have polar plots in order of feed name. */ getSortedPolarPlotterFeeds = () : IReceiver[] => { var result = this.getPolarPlotterFeeds(); result.sort(function(lhs, rhs) { if(lhs.id !== undefined && rhs.id !== undefined) return lhs.name.localeCompare(rhs.name); else if(lhs.id === undefined && rhs.id === undefined) return 0; else if(lhs.id === undefined) return -1; else return 1; }); return result; } /** * Returns an array of plots on display. */ getPlotsOnDisplay = () : PolarPlot_FeedSliceAbstract[] => { var result: PolarPlot_FeedSliceAbstract[] = []; var serverConfig = VRS.serverConfig ? VRS.serverConfig.get() : null; if(serverConfig) { $.each(this._PlotsOnDisplay, (idx, plotOnDisplay) => { var receiver = VRS.arrayHelper.findFirst(serverConfig.Receivers, function(serverReceiver) { return serverReceiver.UniqueId === plotOnDisplay.feedId; }); if(receiver) { var normalisedRange = this.getNormalisedSliceRange(plotOnDisplay.slice, -1, -1); result.push({ feedName: receiver.Name, low: normalisedRange.lowAlt, high: normalisedRange.highAlt }); } }); } return result; } getAltitudeRangeConfigs = () : PolarPlot_AltitudeRangeConfig[] => { return this._AltitudeRangeConfigs.slice(); } setAltitudeRangeConfigs = (value: PolarPlot_AltitudeRangeConfig[]) => { if(value && this._AltitudeRangeConfigs && value.length === this._AltitudeRangeConfigs.length) { var changed = false; var length = value.length; for(var i = 0;i < length;++i) { var current = this._AltitudeRangeConfigs[i]; var revised = value[i]; if(current.low === revised.low && current.high === revised.high && current.colour !== revised.colour) { current.colour = revised.colour; changed = true; } } if(changed) { this.refreshAllDisplayed(); } } } getStrokeOpacity = () : number => { return this._StrokeOpacity; } setStrokeOpacity = (value: number) => { if(value && value !== this._StrokeOpacity && value >= 0 && value <= 1) { this._StrokeOpacity = value; this.refreshAllDisplayed(); } } getFillOpacity = () : number => { return this._FillOpacity; } setFillOpacity = (value: number) => { if(value && value !== this._FillOpacity && value >= 0 && value <= 1) { this._FillOpacity = value; this.refreshAllDisplayed(); } } /** * Saves the current state of the object. */ saveState = () => { var settings = this.createSettings(); // Remove the plotsOnDisplay if the site has a VRS.globalOptions.polarPlotDisplayOnStartup declared and it's // exactly the same as the VRS.globalOptions.polarPlotDisplayOnStartup. if(VRS.globalOptions.polarPlotDisplayOnStartup && VRS.globalOptions.polarPlotDisplayOnStartup.length) { if(settings.plotsOnDisplay.length === VRS.globalOptions.polarPlotDisplayOnStartup.length) { if(VRS.arrayHelper.except(settings.plotsOnDisplay, VRS.globalOptions.polarPlotDisplayOnStartup, function(lhs, rhs) { return lhs.feedName === rhs.feedName && lhs.high === rhs.high && lhs.low === rhs.low; }).length === 0) { settings.plotsOnDisplay = undefined; } } } VRS.configStorage.save(this.persistenceKey(), settings); } /** * Loads the previously saved state of the object or the current state if it's never been saved. */ loadState = () : PolarPlotter_SaveState => { var savedSettings = VRS.configStorage.load(this.persistenceKey(), {}); if((!savedSettings || !savedSettings.plotsOnDisplay) && VRS.globalOptions.polarPlotDisplayOnStartup) { savedSettings = $.extend({ plotsOnDisplay: VRS.globalOptions.polarPlotDisplayOnStartup }, savedSettings); } var result = $.extend(this.createSettings(), savedSettings); var altitudeRangeConfigsBad = result.altitudeRangeConfigs.length !== this._AltitudeRangeConfigs.length; if(!altitudeRangeConfigsBad) { for(var i = 0;i < result.altitudeRangeConfigs.length;++i) { var current = this._AltitudeRangeConfigs[i]; var saved = result.altitudeRangeConfigs[i]; altitudeRangeConfigsBad = current.low !== saved.low || current.high !== saved.high; if(altitudeRangeConfigsBad) break; } } if(altitudeRangeConfigsBad) result.altitudeRangeConfigs = this.getAltitudeRangeConfigs(); var usePlotsOnDisplay = []; var serverConfig = VRS.serverConfig ? VRS.serverConfig.get() : null; var receivers = serverConfig ? serverConfig.Receivers : null; if(receivers) { $.each(result.plotsOnDisplay, function(idx, abstractReceiver) { var plotReceiver = VRS.arrayHelper.findFirst(receivers, function(serverReceiver) { return VRS.stringUtility.equals(serverReceiver.Name, abstractReceiver.feedName, true); }); if(plotReceiver) { usePlotsOnDisplay.push(abstractReceiver); } }); } result.plotsOnDisplay = usePlotsOnDisplay; return result; } /** * Applies a previously saved state to the object. */ applyState = (settings: PolarPlotter_SaveState) => { var polarPlotIdentifiers = []; var serverConfig = VRS.serverConfig ? VRS.serverConfig.get() : null; this.setAltitudeRangeConfigs(settings.altitudeRangeConfigs); this.setStrokeOpacity(settings.strokeOpacity); this.setFillOpacity(settings.fillOpacity); if(serverConfig && serverConfig.Receivers) { $.each(settings.plotsOnDisplay, function(idx, abstractReceiver) { var colourMaxAltitude = VRS.arrayHelper.findFirst(<PolarPlot_AltitudeRangeConfig[]>VRS.globalOptions.polarPlotAltitudeConfigs, function(obj) { return obj.low === abstractReceiver.low && obj.high === abstractReceiver.high; }); var receiver = VRS.arrayHelper.findFirst(serverConfig.Receivers, function(feed) { return VRS.stringUtility.equals(feed.Name, abstractReceiver.feedName, true); }); if(colourMaxAltitude && receiver) polarPlotIdentifiers.push({ feedId: receiver.UniqueId, lowAlt: colourMaxAltitude.low, highAlt: colourMaxAltitude.high, colour: colourMaxAltitude.colour }); }); this.fetchAndDisplayByIdentifiers(polarPlotIdentifiers); } } /** * Loads and then applies a previousy saved state to the object. */ loadAndApplyState = () => { this.applyState(this.loadState()); } /** * Returns the key under which the state will be saved. */ private persistenceKey() : string { return 'vrsPolarPlotter-' + this.getName(); } /** * Creates the saved state object. */ private createSettings() : PolarPlotter_SaveState { return { altitudeRangeConfigs: this.getAltitudeRangeConfigs(), plotsOnDisplay: this.getPlotsOnDisplay(), strokeOpacity: this.getStrokeOpacity(), fillOpacity: this.getFillOpacity() }; } /** * Creates the configuration pane for the polar plotter. */ createOptionPane = (displayOrder: number) : OptionPane => { var result = new VRS.OptionPane({ name: 'polarPlotColours', titleKey: 'PaneReceiverRange', displayOrder: displayOrder }); if((VRS.serverConfig && VRS.serverConfig.polarPlotsEnabled()) && VRS.globalOptions.polarPlotEnabled && VRS.globalOptions.polarPlotUserConfigurable) { var configs = this.getAltitudeRangeConfigs(); $.each(configs, (idx, polarPlotConfig) => { var colourField = new VRS.OptionFieldColour({ name: 'polarPlotColour' + idx, labelKey: () => this.getSliceRangeDescription(polarPlotConfig.low, polarPlotConfig.high), getValue: () => polarPlotConfig.colour, setValue: (value) => polarPlotConfig.colour = value, saveState: () => { this.saveState(); this.refreshAllDisplayed(); } }); result.addField(colourField); }); var commonOpacityOptions = { showSlider: true, min: 0.0, max: 1.0, step: 0.01, decimals: 2, inputWidth: VRS.InputWidth.ThreeChar }; result.addField(new VRS.OptionFieldNumeric($.extend({ name: 'polarPlotterFillOpacity', labelKey: 'FillOpacity', getValue: this.getFillOpacity, setValue: this.setFillOpacity, saveState: this.saveState }, commonOpacityOptions))); result.addField(new VRS.OptionFieldNumeric($.extend({ name: 'polarPlotterStrokeOpacity', labelKey: 'StrokeOpacity', getValue: this.getStrokeOpacity, setValue: this.setStrokeOpacity, saveState: this.saveState }, commonOpacityOptions))); } return result; } /** * Fetches a polar plot from the server. */ fetchPolarPlot = (feedId: number, callback?: () => void) => { this._PolarPlot = null; $.ajax({ url: VRS.globalOptions.polarPlotFetchUrl, dataType: 'json', data: { feedId: feedId }, success: (data: PolarPlot_AllFeedSlices) => { this._PolarPlot = data; if(callback) callback(); }, timeout: VRS.globalOptions.polarPlotFetchTimeout }); } /** * Returns the slice that matches the altitude range (where -1 represents an open end) or null if no slice matches. */ findSliceForAltitudeRange = (plots: PolarPlot_AllFeedSlices, lowAltitude: number, highAltitude: number) : PolarPlot_Slice => { var result = null; if(plots) { var length = plots.slices.length; for(var i = 0;i < length;++i) { var slice = plots.slices[i]; if(this.isSliceForAltitudeRange(slice, lowAltitude, highAltitude)) { result = slice; break; } } } return result; } /** * Returns true if the slice corresponds with the altitude range passed across. The altitude range can indicate * an open end with a value of -1. */ isSliceForAltitudeRange = (slice: PolarPlot_Slice, lowAltitude: number, highAltitude: number) : boolean => { return !!slice && ((lowAltitude === -1 && slice.lowAlt < -20000000) || (lowAltitude !== -1 && slice.lowAlt === lowAltitude)) && ((highAltitude === -1 && slice.highAlt > 20000000) || (highAltitude !== -1 && slice.highAlt === highAltitude)); } /** * Returns an object that normalises the 'open-ended' low and high altitudes to the undefined value (or to any * value that the caller passes across). */ getNormalisedSliceRange = (slice: PolarPlot_Slice, lowOpenEnd?: number, highOpenEnd?: number) : AltitudeRange => { return !slice ? null : { lowAlt: slice.lowAlt < -20000000 ? lowOpenEnd : slice.lowAlt, highAlt: slice.highAlt > 20000000 ? highOpenEnd : slice.highAlt }; } /** * Returns an object that normalises the 'open-ended' low and high altitudes to the values passed across. */ getNormalisedRange = (lowAltitude?: number, highAltitude?: number, lowOpenEnd?: number, highOpenEnd?: number) : AltitudeRange => { if(lowAltitude === undefined || lowAltitude < -20000000) lowAltitude = lowOpenEnd; if(highAltitude === undefined || highAltitude > 20000000) highAltitude = highOpenEnd; return { lowAlt: lowAltitude, highAlt: highAltitude }; } /** * Returns a description of the altitude range passed across. */ getSliceRangeDescription = (lowAltitude: number, highAltitude: number) : string => { var range = this.getNormalisedRange(lowAltitude, highAltitude, -1, -1); lowAltitude = range.lowAlt; highAltitude = range.highAlt; var lowAlt = VRS.format.altitude(lowAltitude, VRS.AltitudeType.Barometric, false, this._Settings.unitDisplayPreferences.getHeightUnit(), false, true, false); var highAlt = VRS.format.altitude(highAltitude, VRS.AltitudeType.Barometric, false, this._Settings.unitDisplayPreferences.getHeightUnit(), false, true, false); return lowAltitude === -1 && highAltitude === -1 ? VRS.$$.AllAltitudes : lowAltitude === -1 ? VRS.stringUtility.format(VRS.$$.ToAltitude, highAlt) : highAltitude === -1 ? VRS.stringUtility.format(VRS.$$.FromAltitude, lowAlt) : VRS.stringUtility.format(VRS.$$.FromToAltitude, lowAlt, highAlt); } /** * Returns true if the altitude range passed across represents all altitudes. */ isAllAltitudes = (lowAltitude: number, highAltitude: number) : boolean => { var range = this.getNormalisedRange(lowAltitude, highAltitude, -1, -1); lowAltitude = range.lowAlt; highAltitude = range.highAlt; return lowAltitude === -1 && highAltitude === -1; } /** * Returns the AltitudeRangeColour object for the low and high altitude passed across. The altitudes are normalised * to -1 before they're used in the search. */ getAltitudeRangeConfigRecord = (lowAltitude: number, highAltitude: number) : PolarPlot_AltitudeRangeConfig => { var altRange = this.getNormalisedRange(lowAltitude, highAltitude, -1, -1); lowAltitude = altRange.lowAlt; highAltitude = altRange.highAlt; var result = null; var length = this._AltitudeRangeConfigs.length; for(var i = 0;i < length;++i) { var range = this._AltitudeRangeConfigs[i]; if(range.low === lowAltitude && range.high === highAltitude) { result = range; break; } } return result; } /** * Gets the colour to use for the range or undefined if no colour has been declared for the range. */ getSliceRangeColour = (lowAltitude: number, highAltitude: number) : string => { var altitudeRangeConfig = this.getAltitudeRangeConfigRecord(lowAltitude, highAltitude); return altitudeRangeConfig ? altitudeRangeConfig.colour : null; } /** * Gets the z-index to use for the range or -1 if there is no AltitudeRangeColour object for the altitudes. */ getSliceRangeZIndex = (lowAltitude: number, highAltitude: number) : number => { var record = this.getAltitudeRangeConfigRecord(lowAltitude, highAltitude); return record ? record.zIndex : -1; } /** * Displays a polar plot slice. Does not remove any existing displays of slices. */ displayPolarPlotSlice = (feedId: number, slice: PolarPlot_Slice, colour?: string) => { if(slice) { var polygonId = this.getPolygonId(feedId, slice); var existingPolygon = this._Settings.map.getPolygon(polygonId); if(!slice.plots.length) { if(existingPolygon) { this._Settings.map.destroyPolygon(existingPolygon); } } else { if(colour === undefined) { colour = this.getSliceRangeColour(slice.lowAlt, slice.highAlt); } var fillColour = VRS.globalOptions.polarPlotFillColourCallback ? VRS.globalOptions.polarPlotFillColourCallback(feedId, slice.lowAlt, slice.highAlt) : colour || this.getPolygonColour(slice); var strokeColour = VRS.globalOptions.polarPlotStrokeColourCallback ? VRS.globalOptions.polarPlotStrokeColourCallback(feedId, slice.lowAlt, slice.highAlt) : VRS.globalOptions.polarPlotStrokeColour || fillColour; var fillOpacity = this.getFillOpacity(); var strokeOpacity = this.getStrokeOpacity(); var zIndex = this.getSliceRangeZIndex(slice.lowAlt, slice.highAlt); if(existingPolygon) { existingPolygon.setPaths([ slice.plots ]); existingPolygon.setFillColour(fillColour); existingPolygon.setStrokeColour(strokeColour); existingPolygon.setFillOpacity(fillOpacity); existingPolygon.setStrokeOpacity(strokeOpacity); existingPolygon.setZIndex(zIndex); } else { this._Settings.map.addPolygon(this.getPolygonId(feedId, slice), { strokeColour: strokeColour, strokeWeight: VRS.globalOptions.polarPlotStrokeWeight, strokeOpacity: strokeOpacity, fillColour: fillColour, fillOpacity: fillOpacity, paths: [ slice.plots ], zIndex: zIndex }); } } this.addToPlotsOnDisplay(feedId, slice); if(this._Settings.autoSaveState) { this.saveState(); } } } /** * Returns true if the polar plot for the feed and altitude range (where -1 can denote an open end in the range) * is currently on display. */ isOnDisplay = (feedId: number, lowAltitude: number, highAltitude: number) : boolean => { var result = false; var length = this._PlotsOnDisplay.length; for(var i = 0;i < length;++i) { var plotOnDisplay = this._PlotsOnDisplay[i]; if(plotOnDisplay.feedId === feedId && this.isSliceForAltitudeRange(plotOnDisplay.slice, lowAltitude, highAltitude)) { result = true; break; } } return result; } /** * Removes a polar plot slice. */ removePolarPlotSlice = (feedId: number, slice: PolarPlot_Slice) => { if(slice) { var polygonId = this.getPolygonId(feedId, slice); var existingPolygon = this._Settings.map.getPolygon(polygonId); if(existingPolygon) { this._Settings.map.destroyPolygon(existingPolygon); } this.removeFromPlotsOnDisplay(feedId, slice); if(this._Settings.autoSaveState) { this.saveState(); } } } /** * Removes all plots for the given feed. */ removeAllSlicesForFeed = (feedId: number) => { var slices = []; $.each(this._PlotsOnDisplay, (idx, displayInfo) => { if(displayInfo.feedId === feedId) { slices.push(displayInfo.slice); } }); $.each(slices, (idx, slice) => { this.removePolarPlotSlice(feedId, slice); }); } /** * Removes all plots for all feeds on display. */ removeAllSlicesForAllFeeds = () => { var plotsOnDisplay = this._PlotsOnDisplay.slice(); $.each(plotsOnDisplay, (idx, plot) => { this.removePolarPlotSlice(plot.feedId, plot.slice); }); } /** * Toggles the display of a polar plot slice. */ togglePolarPlotSlice = (feedId: number, slice: PolarPlot_Slice, colour?: string) : boolean => { var result = false; if(slice) { var exists = this.getPlotsOnDisplayIndex(feedId, slice) !== -1; if(exists) this.removePolarPlotSlice(feedId, slice); else this.displayPolarPlotSlice(feedId, slice, colour); result = !exists; } return result; } /** * Fetches the feeds and toggles the display of the array of polar plot identifiers passed across. */ fetchAndToggleByIdentifiers = (plotIdentifiers: PolarPlot_Id[]) : boolean => { var notOnDisplay = this.removeByIdentifiers(plotIdentifiers); this.fetchAndDisplayByIdentifiers(notOnDisplay); return notOnDisplay.length > 0; } /** * Fetches and displays all the identifiers specified. If the feed is already on display then it is refreshed. */ fetchAndDisplayByIdentifiers = (plotIdentifiers: PolarPlot_Id[]) => { var fetchFeeds = this.getDistinctFeedIds(plotIdentifiers); $.each(fetchFeeds, (idx, feedId) => { this.fetchPolarPlot(feedId, () => { var plots = this.getPolarPlot(); $.each(plotIdentifiers, (innerIdx, plotIdentifier) => { if(plotIdentifier.feedId === feedId) { var slice = this.findSliceForAltitudeRange(plots, plotIdentifier.lowAlt, plotIdentifier.highAlt); if(slice) this.displayPolarPlotSlice(feedId, slice); } }); }); }); } /** * Removes all plots identified. Returns an array of plot identifiers that could not be removed because they * are not on display. */ removeByIdentifiers = (plotIdentifiers: PolarPlot_Id[]) : PolarPlot_Id[] => { var result: PolarPlot_Id[] = []; $.each(plotIdentifiers, (idx, identifier) => { var removedSlice = false; var feedPlotsOnDisplay = this.getPlotsOnDisplayForFeed(identifier.feedId); $.each(feedPlotsOnDisplay, (innerIdx, plotOnDisplay) => { if(this.isSliceForAltitudeRange(plotOnDisplay.slice, identifier.lowAlt, identifier.highAlt)) { this.removePolarPlotSlice(identifier.feedId, plotOnDisplay.slice); removedSlice = true; } return !removedSlice; }); if(!removedSlice) result.push(identifier); }); return result; } /** * Generates the identifier for the polygon that represents a slice retrieved for a specific feed. */ private getPolygonId = (feedId: number, slice: PolarPlot_Slice) : string => { return 'polar$' + feedId + '$' + (slice.lowAlt === undefined ? 'min' : slice.lowAlt) + '-' + (slice.highAlt === undefined ? 'max' : slice.highAlt); } /** * Returns the colour to use for a particular slice, based on the minimum or maximum altitude. */ private getPolygonColour = (slice: PolarPlot_Slice) : string => { var sliceRange = this.getNormalisedSliceRange(slice); return sliceRange.lowAlt === undefined && sliceRange.highAlt === undefined ? '#000000' : VRS.colourHelper.colourToCssString( VRS.colourHelper.getColourWheelScale(sliceRange.lowAlt < -20000000 ? 0 : sliceRange.lowAlt, VRS.globalOptions.aircraftMarkerAltitudeTrailLow, VRS.globalOptions.aircraftMarkerAltitudeTrailHigh, true, true) ); } /** * Returns the list of distinct feed identifiers from the array passed across. */ private getDistinctFeedIds = (feedIdArray: PolarPlot_Id[] | PolarPlot_FeedSlice[]) : number[] => { var result: number[] = []; var length = feedIdArray.length; for(var i = 0;i < length;++i) { var feedId = feedIdArray[i].feedId; if(VRS.arrayHelper.indexOf(result, feedId) === -1) { result.push(feedId); } } return result; } /** * Fetches and redisplays all displayed plots. */ refetchAllDisplayed = () => { var fetchFeeds = this.getDistinctFeedIds(this._PlotsOnDisplay); $.each(fetchFeeds, (idx, feedId) => { this.fetchPolarPlot(feedId, () => { var plots = this.getPolarPlot(); var feedPlotsOnDisplay = this.getPlotsOnDisplayForFeed(feedId); $.each(feedPlotsOnDisplay, (innerIdx, plotOnDisplay) => { var plottedSlice = plotOnDisplay.slice; var slice = plottedSlice ? this.findSliceForAltitudeRange(plots, plottedSlice.lowAlt, plottedSlice.highAlt) : null; if(slice) { this.displayPolarPlotSlice(feedId, slice); } else if(plottedSlice) { this.removePolarPlotSlice(feedId, plottedSlice); } }); }); }); } /** * Repaints all displayed plots without fetching them from the server. */ refreshAllDisplayed = () => { var feedsCopy = this._PlotsOnDisplay.slice(); $.each(feedsCopy, (idx, plotOnDisplay) => { this.displayPolarPlotSlice(plotOnDisplay.feedId, plotOnDisplay.slice); }); } /** * Starts a timer that periodically refetches and repaints all polar plots currently on display. */ startAutoRefresh = () => { if(VRS.globalOptions.polarPlotAutoRefreshSeconds > 0) { if(this._AutoRefreshTimerId) { clearTimeout(this._AutoRefreshTimerId); } this._AutoRefreshTimerId = setTimeout(() => { var timedOut = VRS.timeoutManager && VRS.timeoutManager.getExpired(); if(!this._Settings.aircraftListFetcher.getPaused() && !timedOut) { this.refetchAllDisplayed(); } this.startAutoRefresh(); }, VRS.globalOptions.polarPlotAutoRefreshSeconds * 1000); } } } }
the_stack
import React, { PureComponent, ReactElement, ReactNode } from 'react'; import classNames from 'classnames'; import Animate from 'react-smooth'; import _ from 'lodash'; import { Sector, Props as SectorProps } from '../shape/Sector'; import { Layer } from '../container/Layer'; import { findAllByType } from '../util/ReactUtils'; import { Global } from '../util/Global'; import { ImplicitLabelListType, LabelList } from '../component/LabelList'; import { Cell } from '../component/Cell'; import { mathSign, interpolateNumber } from '../util/DataUtils'; import { getCateCoordinateOfBar, findPositionOfBar, getValueByDataKey, truncateByDomain, getBaseValueOfBar, getTooltipItem, } from '../util/ChartUtils'; import { LegendType, TooltipType, AnimationTiming, filterProps, TickItem, adaptEventsOfChild, PresentationAttributesAdaptChildEvent, } from '../util/types'; import { polarToCartesian } from '../util/PolarUtils'; // TODO: Cause of circular dependency. Needs refactoring of functions that need them. // import { AngleAxisProps, RadiusAxisProps } from './types'; type RadialBarDataItem = SectorProps & { value?: any; payload?: any; background?: SectorProps; }; type RadialBarShape = ReactElement | ((props: Props) => ReactNode); type RadialBarBackground = ReactElement | ((props: Props) => ReactNode) | SectorProps | boolean; interface RadialBarProps { animationId?: string | number; className?: string; angleAxisId?: string | number; radiusAxisId?: string | number; startAngle?: number; endAngle?: number; shape?: RadialBarShape; activeShape?: RadialBarShape; activeIndex?: number; dataKey: string | number | ((obj: any) => any); cornerRadius?: string | number; forceCornerRadius?: boolean; cornerIsExternal?: boolean; minPointSize?: number; maxBarSize?: number; data?: RadialBarDataItem[]; legendType?: LegendType; tooltipType?: TooltipType; hide?: boolean; label?: ImplicitLabelListType<any>; stackId?: string | number; background?: RadialBarBackground; onAnimationStart?: () => void; onAnimationEnd?: () => void; isAnimationActive?: boolean; animationBegin?: number; animationDuration?: number; animationEasing?: AnimationTiming; } export type Props = PresentationAttributesAdaptChildEvent<any, SVGElement> & RadialBarProps; interface State { readonly isAnimationFinished?: boolean; readonly prevData?: RadialBarDataItem[]; readonly curData?: RadialBarDataItem[]; readonly prevAnimationId?: string | number; } export class RadialBar extends PureComponent<Props, State> { static displayName = 'RadialBar'; static defaultProps = { angleAxisId: 0, radiusAxisId: 0, minPointSize: 0, hide: false, legendType: 'rect', data: [] as RadialBarDataItem[], isAnimationActive: !Global.isSsr, animationBegin: 0, animationDuration: 1500, animationEasing: 'ease', forceCornerRadius: false, cornerIsExternal: false, }; static getComposedData = ({ item, props, radiusAxis, radiusAxisTicks, angleAxis, angleAxisTicks, displayedData, dataKey, stackedData, barPosition, bandSize, dataStartIndex, }: { item: RadialBar; props: any; radiusAxis: any; // RadiusAxisProps; radiusAxisTicks: Array<TickItem>; angleAxis: any; // AngleAxisProps; angleAxisTicks: Array<TickItem>; displayedData: any[]; dataKey: Props['dataKey']; stackedData?: any[]; barPosition?: any[]; bandSize?: number; dataStartIndex: number; }) => { const pos = findPositionOfBar(barPosition, item); if (!pos) { return null; } const { cx, cy } = angleAxis; const { layout } = props; const { children, minPointSize } = item.props; const numericAxis = layout === 'radial' ? angleAxis : radiusAxis; const stackedDomain = stackedData ? numericAxis.scale.domain() : null; const baseValue = getBaseValueOfBar({ numericAxis }); const cells = findAllByType(children, Cell.displayName); const sectors = displayedData.map((entry: any, index: number) => { let value, innerRadius, outerRadius, startAngle, endAngle, backgroundSector; if (stackedData) { value = truncateByDomain(stackedData[dataStartIndex + index], stackedDomain); } else { value = getValueByDataKey(entry, dataKey); if (!_.isArray(value)) { value = [baseValue, value]; } } if (layout === 'radial') { innerRadius = getCateCoordinateOfBar({ axis: radiusAxis, ticks: radiusAxisTicks, bandSize, offset: pos.offset, entry, index, }); endAngle = angleAxis.scale(value[1]); startAngle = angleAxis.scale(value[0]); outerRadius = innerRadius + pos.size; const deltaAngle = endAngle - startAngle; if (Math.abs(minPointSize) > 0 && Math.abs(deltaAngle) < Math.abs(minPointSize)) { const delta = mathSign(deltaAngle || minPointSize) * (Math.abs(minPointSize) - Math.abs(deltaAngle)); endAngle += delta; } backgroundSector = { background: { cx, cy, innerRadius, outerRadius, startAngle: props.startAngle, endAngle: props.endAngle, }, }; } else { innerRadius = radiusAxis.scale(value[0]); outerRadius = radiusAxis.scale(value[1]); startAngle = getCateCoordinateOfBar({ axis: angleAxis, ticks: angleAxisTicks, bandSize, offset: pos.offset, entry, index, }); endAngle = startAngle + pos.size; const deltaRadius = outerRadius - innerRadius; if (Math.abs(minPointSize) > 0 && Math.abs(deltaRadius) < Math.abs(minPointSize)) { const delta = mathSign(deltaRadius || minPointSize) * (Math.abs(minPointSize) - Math.abs(deltaRadius)); outerRadius += delta; } } return { ...entry, ...backgroundSector, payload: entry, value: stackedData ? value : value[1], cx, cy, innerRadius, outerRadius, startAngle, endAngle, ...(cells && cells[index] && cells[index].props), tooltipPayload: [getTooltipItem(item, entry)], tooltipPosition: polarToCartesian(cx, cy, (innerRadius + outerRadius) / 2, (startAngle + endAngle) / 2), }; }); return { data: sectors, layout }; }; state: State = { isAnimationFinished: false, }; static getDerivedStateFromProps(nextProps: Props, prevState: State): State { if (nextProps.animationId !== prevState.prevAnimationId) { return { prevAnimationId: nextProps.animationId, curData: nextProps.data, prevData: prevState.curData, }; } if (nextProps.data !== prevState.curData) { return { curData: nextProps.data, }; } return null; } getDeltaAngle() { const { startAngle, endAngle } = this.props; const sign = mathSign(endAngle - startAngle); const deltaAngle = Math.min(Math.abs(endAngle - startAngle), 360); return sign * deltaAngle; } handleAnimationEnd = () => { const { onAnimationEnd } = this.props; this.setState({ isAnimationFinished: true }); if (_.isFunction(onAnimationEnd)) { onAnimationEnd(); } }; handleAnimationStart = () => { const { onAnimationStart } = this.props; this.setState({ isAnimationFinished: false }); if (_.isFunction(onAnimationStart)) { onAnimationStart(); } }; static renderSectorShape(shape: RadialBarBackground, props: any) { let sectorShape; if (React.isValidElement(shape)) { sectorShape = React.cloneElement(shape, props); } else if (_.isFunction(shape)) { sectorShape = shape(props); } else { sectorShape = React.createElement(Sector, props); } return sectorShape; } renderSectorsStatically(sectors: SectorProps[]) { const { shape, activeShape, activeIndex, cornerRadius, ...others } = this.props; const baseProps = filterProps(others); return sectors.map((entry, i) => { const props = { ...baseProps, cornerRadius, ...entry, ...adaptEventsOfChild(this.props, entry, i), key: `sector-${i}`, className: 'recharts-radial-bar-sector', forceCornerRadius: others.forceCornerRadius, cornerIsExternal: others.cornerIsExternal, }; return RadialBar.renderSectorShape(i === activeIndex ? activeShape : shape, props); }); } renderSectorsWithAnimation() { const { data, isAnimationActive, animationBegin, animationDuration, animationEasing, animationId } = this.props; const { prevData } = this.state; return ( <Animate begin={animationBegin} duration={animationDuration} isActive={isAnimationActive} easing={animationEasing} from={{ t: 0 }} to={{ t: 1 }} key={`radialBar-${animationId}`} onAnimationStart={this.handleAnimationStart} onAnimationEnd={this.handleAnimationEnd} > {({ t }: { t: number }) => { const stepData = data.map((entry, index) => { const prev = prevData && prevData[index]; if (prev) { const interpolatorStartAngle = interpolateNumber(prev.startAngle, entry.startAngle); const interpolatorEndAngle = interpolateNumber(prev.endAngle, entry.endAngle); return { ...entry, startAngle: interpolatorStartAngle(t), endAngle: interpolatorEndAngle(t), }; } const { endAngle, startAngle } = entry; const interpolator = interpolateNumber(startAngle, endAngle); return { ...entry, endAngle: interpolator(t) }; }); return <Layer>{this.renderSectorsStatically(stepData)}</Layer>; }} </Animate> ); } renderSectors() { const { data, isAnimationActive } = this.props; const { prevData } = this.state; if (isAnimationActive && data && data.length && (!prevData || !_.isEqual(prevData, data))) { return this.renderSectorsWithAnimation(); } return this.renderSectorsStatically(data); } renderBackground(sectors?: RadialBarDataItem[]) { const { cornerRadius } = this.props; const backgroundProps = filterProps(this.props.background); return sectors.map((entry, i) => { // eslint-disable-next-line @typescript-eslint/no-unused-vars const { value, background, ...rest } = entry; if (!background) { return null; } const props = { cornerRadius, ...rest, fill: '#eee', ...background, ...backgroundProps, ...adaptEventsOfChild(this.props, entry, i), index: i, key: `sector-${i}`, className: 'recharts-radial-bar-background-sector', }; return RadialBar.renderSectorShape(background, props); }); } render() { const { hide, data, className, background, isAnimationActive } = this.props; if (hide || !data || !data.length) { return null; } const { isAnimationFinished } = this.state; const layerClass = classNames('recharts-area', className); return ( <Layer className={layerClass}> {background && <Layer className="recharts-radial-bar-background">{this.renderBackground(data)}</Layer>} <Layer className="recharts-radial-bar-sectors">{this.renderSectors()}</Layer> {(!isAnimationActive || isAnimationFinished) && LabelList.renderCallByParent( { ...this.props, clockWise: this.getDeltaAngle() < 0, }, data, )} </Layer> ); } }
the_stack
module VORLON { export class _Core { _clientPlugins = new Array<ClientPlugin>(); _dashboardPlugins = new Array<DashboardPlugin>(); _messenger: ClientMessenger; _sessionID: string; _listenClientId: string; _side: RuntimeSide; _errorNotifier: any; _messageNotifier: any; _socketIOWaitCount = 0; public debug: boolean = false; _RetryTimeout = 1002; _isHttpsEnabled = false; public get Messenger(): ClientMessenger { return Core._messenger; } public get ClientPlugins(): Array<ClientPlugin> { return Core._clientPlugins; } public get IsHttpsEnabled(): boolean { return Core._isHttpsEnabled; } public get DashboardPlugins(): Array<DashboardPlugin> { return Core._dashboardPlugins; } public RegisterClientPlugin(plugin: ClientPlugin): void { Core._clientPlugins.push(plugin); } public RegisterDashboardPlugin(plugin: DashboardPlugin): void { Core._dashboardPlugins.push(plugin); } public StopListening(): void { if (Core._messenger) { Core._messenger.stopListening(); delete Core._messenger; } } public StartClientSide(serverUrl = "'http://localhost:1337/'", sessionId = "", listenClientId = ""): void { Core._side = RuntimeSide.Client; Core._sessionID = sessionId; Core._listenClientId = listenClientId; if(serverUrl[serverUrl.length-1] === '/'){ serverUrl = serverUrl.slice(0, -1); } if(serverUrl.match("^https:\/\/")){ Core._isHttpsEnabled = true; } // Checking socket.io if (Tools.IsWindowAvailable && (<any>window).io === undefined) { if (this._socketIOWaitCount < 10) { this._socketIOWaitCount++; // Let's wait a bit just in case socket.io was loaded asynchronously setTimeout(function() { console.log("Vorlon.js: waiting for socket.io to load..."); Core.StartClientSide(serverUrl, sessionId, listenClientId); }, 1000); } else { console.log("Vorlon.js: please load socket.io before referencing vorlon.js or use includeSocketIO = true in your catalog.json file."); Core.ShowError("Vorlon.js: please load socket.io before referencing vorlon.js or use includeSocketIO = true in your catalog.json file.", 0); } return; } // Cookie var clientId; if(Tools.IsWindowAvailable){ clientId = Tools.ReadCookie("vorlonJS_clientId"); if (!clientId) { clientId = Tools.CreateGUID(); Tools.CreateCookie("vorlonJS_clientId", clientId, 1); } } else { clientId = Tools.CreateGUID(); } // Creating the messenger if (Core._messenger) { Core._messenger.stopListening(); delete Core._messenger; } Core._messenger = new ClientMessenger(Core._side, serverUrl, sessionId, clientId, listenClientId); // Connect messenger to dispatcher Core.Messenger.onRealtimeMessageReceived = Core._Dispatch; Core.Messenger.onHeloReceived = Core._OnIdentificationReceived; Core.Messenger.onIdentifyReceived = Core._OnIdentifyReceived; Core.Messenger.onStopListenReceived = Core._OnStopListenReceived; Core.Messenger.onError = Core._OnError; Core.Messenger.onReload = Core._OnReloadClient; this.sendHelo(); // Launch plugins for (var index = 0; index < Core._clientPlugins.length; index++) { var plugin = Core._clientPlugins[index]; plugin.startClientSide(); } // Handle client disconnect if (Tools.IsWindowAvailable) { window.addEventListener("beforeunload", function() { Core.Messenger.sendRealtimeMessage("", { socketid: Core.Messenger.socketId }, Core._side, "clientclosed"); }, false); } else { process.stdin.resume();//so the program will not close instantly var exitMessageWritten = false; function exitHandler(options, err) { if(!exitMessageWritten){ Core.Messenger.sendRealtimeMessage("", { socketid: Core.Messenger.socketId }, Core._side, "clientclosed"); console.log('Disconnected from Vorlon.js instance'); exitMessageWritten = true; } process.exit(0); } //do something when app is closing process.on('exit', exitHandler.bind(null,{cleanup:true})); //catches ctrl+c event process.on('SIGINT', exitHandler.bind(null, {exit:true})); //catches uncaught exceptions process.on('uncaughtException', exitHandler.bind(null, {exit:true})); } // Start global dirty check, at this point document is not ready, // little timeout to defer starting dirtycheck setTimeout(() => { this.startClientDirtyCheck(); }, 500); } public sendHelo(){ // Say 'helo' var heloMessage = {}; if(Tools.IsWindowAvailable){ heloMessage = { ua: navigator.userAgent, identity : sessionStorage["vorlonClientIdentity"] || localStorage["vorlonClientIdentity"] }; } else { heloMessage = { ua: "Node.js", identity : "", noWindow: true }; } Core.Messenger.sendRealtimeMessage("", heloMessage, Core._side, "helo"); } public startClientDirtyCheck() { //sometimes refresh is called before document was loaded if (Tools.IsWindowAvailable && !document.body) { setTimeout(() => { this.startClientDirtyCheck(); }, 200); return; } var mutationObserver = Tools.IsWindowAvailable && ((<any>window).MutationObserver || (<any>window).WebKitMutationObserver); if (mutationObserver) { if (!document.body.__vorlon) document.body.__vorlon = {}; var config = { attributes: true, childList: true, subtree: true, characterData: true }; document.body.__vorlon._observerMutationObserver = new mutationObserver((mutations) => { var sended = false; var cancelSend = false; var sendComandId = []; mutations.forEach((mutation) => { if (cancelSend) { for (var i = 0; i < sendComandId.length; i++) { clearTimeout(sendComandId[i]); } cancelSend = false; } if (mutation.target && mutation.target.__vorlon && mutation.target.__vorlon.ignore) { cancelSend = true; return; } if (mutation.previousSibling && mutation.previousSibling.__vorlon && mutation.previousSibling.__vorlon.ignore) { cancelSend = true; return; } if (mutation.target && !sended && mutation.target.__vorlon && mutation.target.parentNode && mutation.target.parentNode.__vorlon && mutation.target.parentNode.__vorlon.internalId) { sendComandId.push(setTimeout(() => { var internalId = null; if (mutation && mutation.target && mutation.target.parentNode && mutation.target.parentNode.__vorlon && mutation.target.parentNode.__vorlon.internalId) internalId = mutation.target.parentNode.__vorlon.internalId; Core.Messenger.sendRealtimeMessage('ALL_PLUGINS', { type: 'contentchanged', internalId: internalId }, Core._side, 'message'); }, 300)); } sended = true; }); }); document.body.__vorlon._observerMutationObserver.observe(document.body, config); } else if (Tools.IsWindowAvailable) { console.log("dirty check using html string"); var content; if (document.body) content = document.body.innerHTML; setInterval(() => { var html = document.body.innerHTML; if (content != html) { content = html; Core.Messenger.sendRealtimeMessage('ALL_PLUGINS', { type: 'contentchanged' }, Core._side, 'message'); } }, 2000); } } public StartDashboardSide(serverUrl = "'http://localhost:1337/'", sessionId = "", listenClientId = "", divMapper: (string) => HTMLDivElement = null): void { Core._side = RuntimeSide.Dashboard; Core._sessionID = sessionId; Core._listenClientId = listenClientId; /* Notification elements */ Core._errorNotifier = document.createElement('x-notify'); Core._errorNotifier.setAttribute('type', 'error'); Core._errorNotifier.setAttribute('position', 'top'); Core._errorNotifier.setAttribute('duration', 5000); Core._messageNotifier = document.createElement('x-notify'); Core._messageNotifier.setAttribute('position', 'top'); Core._messageNotifier.setAttribute('duration', 4000); document.body.appendChild(Core._errorNotifier); document.body.appendChild(Core._messageNotifier); // Checking socket.io if (Tools.IsWindowAvailable && (<any>window).io === undefined) { if (this._socketIOWaitCount < 10) { this._socketIOWaitCount++; // Let's wait a bit just in case socket.io was loaded asynchronously setTimeout(function() { console.log("Vorlon.js: waiting for socket.io to load..."); Core.StartDashboardSide(serverUrl, sessionId, listenClientId, divMapper); }, 1000); } else { console.log("Vorlon.js: please load socket.io before referencing vorlon.js or use includeSocketIO = true in your catalog.json file."); Core.ShowError("Vorlon.js: please load socket.io before referencing vorlon.js or use includeSocketIO = true in your catalog.json file.", 0); } return; } // Cookie var clientId = Tools.ReadCookie("vorlonJS_clientId"); if (!clientId) { clientId = Tools.CreateGUID(); Tools.CreateCookie("vorlonJS_clientId", clientId, 1); } // Creating the messenger if (Core._messenger) { Core._messenger.stopListening(); delete Core._messenger; } Core._messenger = new ClientMessenger(Core._side, serverUrl, sessionId, clientId, listenClientId); // Connect messenger to dispatcher Core.Messenger.onRealtimeMessageReceived = Core._Dispatch; Core.Messenger.onHeloReceived = Core._OnIdentificationReceived; Core.Messenger.onIdentifyReceived = Core._OnIdentifyReceived; Core.Messenger.onStopListenReceived = Core._OnStopListenReceived; Core.Messenger.onError = Core._OnError; // Say 'helo' var heloMessage = { ua: navigator.userAgent }; Core.Messenger.sendRealtimeMessage("", heloMessage, Core._side, "helo"); // Launch plugins for (var index = 0; index < Core._dashboardPlugins.length; index++) { var plugin = Core._dashboardPlugins[index]; plugin.startDashboardSide(divMapper ? divMapper(plugin.getID()) : null); } } public GetNumClientPluginsReady() : Number { var ready = 0; Core.ClientPlugins.forEach(plugin => { if(plugin.isReady()) { ready++; } }); return ready; } public AllClientPluginsReady() : boolean { return Core.ClientPlugins.length === Core.GetNumClientPluginsReady(); } private _OnStopListenReceived(): void { Core._listenClientId = ""; } private _OnIdentifyReceived(message: string): void { //console.log('identify ' + message); if (Core._side === RuntimeSide.Dashboard) { Core._messageNotifier.innerHTML = message; Core._messageNotifier.show(); } else if (Tools.IsWindowAvailable) { var div = document.createElement("div"); div.className = "vorlonIdentifyNumber"; div.style.position = "absolute"; div.style.left = "0"; div.style.top = "50%"; div.style.marginTop = "-150px"; div.style.width = "100%"; div.style.height = "300px"; div.style.fontFamily = "Arial"; div.style.fontSize = "300px"; div.style.textAlign = "center"; div.style.color = "white"; div.style.textShadow = "2px 2px 5px black"; div.style.zIndex = "100"; div.innerHTML = message; document.body.appendChild(div); setTimeout(() => { document.body.removeChild(div); }, 4000); } else { console.log('Vorlon client n° ' + message); } } private ShowError(message: string, timeout = 5000) { if (Core._side === RuntimeSide.Dashboard) { Core._errorNotifier.innerHTML = message; Core._errorNotifier.setAttribute('duration', timeout); Core._errorNotifier.show(); } else if (Tools.IsWindowAvailable) { var divError = document.createElement("div"); divError.style.position = "absolute"; divError.style.top = "0"; divError.style.left = "0"; divError.style.width = "100%"; divError.style.height = "100px"; divError.style.backgroundColor = "red"; divError.style.textAlign = "center"; divError.style.fontSize = "30px"; divError.style.paddingTop = "20px"; divError.style.color = "white"; divError.style.fontFamily = "consolas"; divError.style.zIndex = "1001"; divError.innerHTML = message; document.body.appendChild(divError); if (timeout) { setTimeout(() => { document.body.removeChild(divError); }, timeout); } } } private _OnError(err: Error): void { Core.ShowError("Error while connecting to Vorlon server. Server may be offline.<BR>Error message: " + err.message); } private _OnIdentificationReceived(id: string): void { Core._listenClientId = id; if (Core._side === RuntimeSide.Client) { // Refresh plugins for (var index = 0; index < Core._clientPlugins.length; index++) { var plugin = Core._clientPlugins[index]; plugin.refresh(); } } } private _OnReloadClient(id: string): void { if (Tools.IsWindowAvailable) { document.location.reload(); } } private _RetrySendingRealtimeMessage(plugin: DashboardPlugin, message: VorlonMessage) { setTimeout(() => { if (plugin.isReady()) { Core._DispatchFromClientPluginMessage(plugin, message); return; } Core._RetrySendingRealtimeMessage(plugin, message); }, Core._RetryTimeout); } private _Dispatch(message: VorlonMessage): void { if (!message.metadata) { console.error('invalid message ' + JSON.stringify(message)); return; } if (message.metadata.pluginID == 'ALL_PLUGINS') { Core._clientPlugins.forEach((plugin) => { Core._DispatchPluginMessage(plugin, message); }); Core._dashboardPlugins.forEach((plugin) => { Core._DispatchPluginMessage(plugin, message); }); } else { Core._clientPlugins.forEach((plugin) => { if (plugin.getID() === message.metadata.pluginID) { Core._DispatchPluginMessage(plugin, message); return; } }); Core._dashboardPlugins.forEach((plugin) => { if (plugin.getID() === message.metadata.pluginID) { Core._DispatchPluginMessage(plugin, message); return; } }); } } private _DispatchPluginMessage(plugin: BasePlugin, message: VorlonMessage): void { plugin.trace('received ' + JSON.stringify(message)); if (message.metadata.side === RuntimeSide.Client) { if (!plugin.isReady()) { // Plugin is not ready, let's try again later Core._RetrySendingRealtimeMessage(<DashboardPlugin>plugin, message); } else { Core._DispatchFromClientPluginMessage(<DashboardPlugin>plugin, message); } } else { Core._DispatchFromDashboardPluginMessage(<ClientPlugin>plugin, message); } } private _DispatchFromClientPluginMessage(plugin: DashboardPlugin, message: VorlonMessage): void { if (message.command && plugin.DashboardCommands) { var command = plugin.DashboardCommands[message.command]; if (command) { command.call(plugin, message.data); return; } } plugin.onRealtimeMessageReceivedFromClientSide(message.data); } private _DispatchFromDashboardPluginMessage(plugin: ClientPlugin, message: VorlonMessage): void { if (message.command && plugin.ClientCommands) { var command = plugin.ClientCommands[message.command]; if (command) { command.call(plugin, message.data); return; } } plugin.onRealtimeMessageReceivedFromDashboardSide(message.data); } } export var Core = new _Core(); }
the_stack
import { IExecuteFunctions, } from 'n8n-core'; import { IDataObject, ILoadOptionsFunctions, INodeExecutionData, INodePropertyOptions, INodeType, INodeTypeDescription, } from 'n8n-workflow'; import { adjustMetadata, setFields, setMetadata, toSnakeCase, woocommerceApiRequest, woocommerceApiRequestAllItems, } from './GenericFunctions'; import { productFields, productOperations, } from './ProductDescription'; import { orderFields, orderOperations, } from './OrderDescription'; import { IDimension, IImage, IProduct, } from './ProductInterface'; import { IAddress, ICouponLine, IFeeLine, ILineItem, IOrder, IShoppingLine, } from './OrderInterface'; import { customerFields, customerOperations, } from './descriptions'; export class WooCommerce implements INodeType { description: INodeTypeDescription = { displayName: 'WooCommerce', name: 'wooCommerce', icon: 'file:wooCommerce.svg', group: ['output'], version: 1, subtitle: '={{$parameter["operation"] + ": " + $parameter["resource"]}}', description: 'Consume WooCommerce API', defaults: { name: 'WooCommerce', }, inputs: ['main'], outputs: ['main'], credentials: [ { name: 'wooCommerceApi', required: true, }, ], properties: [ { displayName: 'Resource', name: 'resource', type: 'options', options: [ { name: 'Customer', value: 'customer', }, { name: 'Order', value: 'order', }, { name: 'Product', value: 'product', }, ], default: 'product', description: 'Resource to consume.', }, ...customerOperations, ...customerFields, ...productOperations, ...productFields, ...orderOperations, ...orderFields, ], }; methods = { loadOptions: { // Get all the available categories to display them to user so that he can // select them easily async getCategories(this: ILoadOptionsFunctions): Promise<INodePropertyOptions[]> { const returnData: INodePropertyOptions[] = []; const categories = await woocommerceApiRequestAllItems.call(this, 'GET', '/products/categories', {}); for (const category of categories) { const categoryName = category.name; const categoryId = category.id; returnData.push({ name: categoryName, value: categoryId, }); } return returnData; }, // Get all the available tags to display them to user so that he can // select them easily async getTags(this: ILoadOptionsFunctions): Promise<INodePropertyOptions[]> { const returnData: INodePropertyOptions[] = []; const tags = await woocommerceApiRequestAllItems.call(this, 'GET', '/products/tags', {}); for (const tag of tags) { const tagName = tag.name; const tagId = tag.id; returnData.push({ name: tagName, value: tagId, }); } return returnData; }, }, }; async execute(this: IExecuteFunctions): Promise<INodeExecutionData[][]> { const items = this.getInputData(); const returnData: IDataObject[] = []; const length = items.length as unknown as number; let responseData; const qs: IDataObject = {}; const resource = this.getNodeParameter('resource', 0) as string; const operation = this.getNodeParameter('operation', 0) as string; for (let i = 0; i < length; i++) { if (resource === 'customer') { // ********************************************************************** // customer // ********************************************************************** // https://woocommerce.github.io/woocommerce-rest-api-docs/?shell#customer-properties if (operation === 'create') { // ---------------------------------------- // customer: create // ---------------------------------------- // https://woocommerce.github.io/woocommerce-rest-api-docs/?javascript#create-a-customer const body = { email: this.getNodeParameter('email', i), } as IDataObject; const additionalFields = this.getNodeParameter('additionalFields', i) as IDataObject; if (Object.keys(additionalFields).length) { Object.assign(body, adjustMetadata(additionalFields)); } responseData = await woocommerceApiRequest.call(this, 'POST', '/customers', body); } else if (operation === 'delete') { // ---------------------------------------- // customer: delete // ---------------------------------------- // https://woocommerce.github.io/woocommerce-rest-api-docs/?javascript#delete-a-customer const customerId = this.getNodeParameter('customerId', i); const qs: IDataObject = { force: true, // required, customers do not support trashing }; const endpoint = `/customers/${customerId}`; responseData = await woocommerceApiRequest.call(this, 'DELETE', endpoint, {}, qs); } else if (operation === 'get') { // ---------------------------------------- // customer: get // ---------------------------------------- // https://woocommerce.github.io/woocommerce-rest-api-docs/?javascript#retrieve-a-customer const customerId = this.getNodeParameter('customerId', i); const endpoint = `/customers/${customerId}`; responseData = await woocommerceApiRequest.call(this, 'GET', endpoint); } else if (operation === 'getAll') { // ---------------------------------------- // customer: getAll // ---------------------------------------- // https://woocommerce.github.io/woocommerce-rest-api-docs/?javascript#list-all-customers const qs = {} as IDataObject; const filters = this.getNodeParameter('filters', i) as IDataObject; const returnAll = this.getNodeParameter('returnAll', i) as boolean; if (Object.keys(filters).length) { Object.assign(qs, filters); } if (returnAll) { responseData = await woocommerceApiRequestAllItems.call(this, 'GET', '/customers', {}, qs); } else { qs.per_page = this.getNodeParameter('limit', i) as number; responseData = await woocommerceApiRequest.call(this, 'GET', '/customers', {}, qs); } } else if (operation === 'update') { // ---------------------------------------- // customer: update // ---------------------------------------- // https://woocommerce.github.io/woocommerce-rest-api-docs/?javascript#update-a-customer const body = {} as IDataObject; const updateFields = this.getNodeParameter('updateFields', i) as IDataObject; if (Object.keys(updateFields).length) { Object.assign(body, adjustMetadata(updateFields)); } const customerId = this.getNodeParameter('customerId', i); const endpoint = `/customers/${customerId}`; responseData = await woocommerceApiRequest.call(this, 'PUT', endpoint, body); } } else if (resource === 'product') { //https://woocommerce.github.io/woocommerce-rest-api-docs/#create-a-product if (operation === 'create') { const name = this.getNodeParameter('name', i) as string; const additionalFields = this.getNodeParameter('additionalFields', i) as IDataObject; const body: IProduct = { name, }; setFields(additionalFields, body); if (additionalFields.categories) { body.categories = (additionalFields.categories as string[]).map(category => ({ id: parseInt(category, 10) })) as unknown as IDataObject[]; } const images = (this.getNodeParameter('imagesUi', i) as IDataObject).imagesValues as IImage[]; if (images) { body.images = images; } const dimension = (this.getNodeParameter('dimensionsUi', i) as IDataObject).dimensionsValues as IDimension; if (dimension) { body.dimensions = dimension; } const metadata = (this.getNodeParameter('metadataUi', i) as IDataObject).metadataValues as IDataObject[]; if (metadata) { body.meta_data = metadata; } responseData = await woocommerceApiRequest.call(this, 'POST', '/products', body); } //https://woocommerce.github.io/woocommerce-rest-api-docs/#update-a-product if (operation === 'update') { const productId = this.getNodeParameter('productId', i) as string; const updateFields = this.getNodeParameter('updateFields', i) as IDataObject; const body: IProduct = {}; setFields(updateFields, body); const images = (this.getNodeParameter('imagesUi', i) as IDataObject).imagesValues as IImage[]; if (images) { body.images = images; } const dimension = (this.getNodeParameter('dimensionsUi', i) as IDataObject).dimensionsValues as IDimension; if (dimension) { body.dimensions = dimension; } const metadata = (this.getNodeParameter('metadataUi', i) as IDataObject).metadataValues as IDataObject[]; if (metadata) { body.meta_data = metadata; } responseData = await woocommerceApiRequest.call(this, 'PUT', `/products/${productId}`, body); } //https://woocommerce.github.io/woocommerce-rest-api-docs/#retrieve-a-product if (operation === 'get') { const productId = this.getNodeParameter('productId', i) as string; responseData = await woocommerceApiRequest.call(this, 'GET', `/products/${productId}`, {}, qs); } //https://woocommerce.github.io/woocommerce-rest-api-docs/#list-all-products if (operation === 'getAll') { const returnAll = this.getNodeParameter('returnAll', i) as boolean; const options = this.getNodeParameter('options', i) as IDataObject; if (options.after) { qs.after = options.after as string; } if (options.before) { qs.before = options.before as string; } if (options.category) { qs.category = options.category as string; } if (options.context) { qs.context = options.context as string; } if (options.featured) { qs.featured = options.featured as boolean; } if (options.maxPrice) { qs.max_price = options.maxPrice as string; } if (options.minPrice) { qs.max_price = options.minPrice as string; } if (options.order) { qs.order = options.order as string; } if (options.orderBy) { qs.orderby = options.orderBy as string; } if (options.search) { qs.search = options.search as string; } if (options.sku) { qs.sku = options.sku as string; } if (options.slug) { qs.slug = options.slug as string; } if (options.status) { qs.status = options.status as string; } if (options.stockStatus) { qs.stock_status = options.stockStatus as string; } if (options.tag) { qs.tag = options.tag as string; } if (options.taxClass) { qs.tax_class = options.taxClass as string; } if (options.type) { qs.type = options.type as string; } if (returnAll === true) { responseData = await woocommerceApiRequestAllItems.call(this, 'GET', '/products', {}, qs); } else { qs.per_page = this.getNodeParameter('limit', i) as number; responseData = await woocommerceApiRequest.call(this, 'GET', '/products', {}, qs); } } //https://woocommerce.github.io/woocommerce-rest-api-docs/#delete-a-product if (operation === 'delete') { const productId = this.getNodeParameter('productId', i) as string; responseData = await woocommerceApiRequest.call(this, 'DELETE', `/products/${productId}`, {}, { force: true }); } } if (resource === 'order') { //https://woocommerce.github.io/woocommerce-rest-api-docs/#create-an-order if (operation === 'create') { const additionalFields = this.getNodeParameter('additionalFields', i) as IDataObject; const body: IOrder = {}; setFields(additionalFields, body); const billing = (this.getNodeParameter('billingUi', i) as IDataObject).billingValues as IAddress; if (billing !== undefined) { body.billing = billing; toSnakeCase(billing as IDataObject); } const shipping = (this.getNodeParameter('shippingUi', i) as IDataObject).shippingValues as IAddress; if (shipping !== undefined) { body.shipping = shipping; toSnakeCase(shipping as IDataObject); } const couponLines = (this.getNodeParameter('couponLinesUi', i) as IDataObject).couponLinesValues as ICouponLine[]; if (couponLines) { body.coupon_lines = couponLines; setMetadata(couponLines); toSnakeCase(couponLines); } const feeLines = (this.getNodeParameter('feeLinesUi', i) as IDataObject).feeLinesValues as IFeeLine[]; if (feeLines) { body.fee_lines = feeLines; setMetadata(feeLines); toSnakeCase(feeLines); } const lineItems = (this.getNodeParameter('lineItemsUi', i) as IDataObject).lineItemsValues as ILineItem[]; if (lineItems) { body.line_items = lineItems; setMetadata(lineItems); toSnakeCase(lineItems); //@ts-ignore } const metadata = (this.getNodeParameter('metadataUi', i) as IDataObject).metadataValues as IDataObject[]; if (metadata) { body.meta_data = metadata; } const shippingLines = (this.getNodeParameter('shippingLinesUi', i) as IDataObject).shippingLinesValues as IShoppingLine[]; if (shippingLines) { body.shipping_lines = shippingLines; setMetadata(shippingLines); toSnakeCase(shippingLines); } responseData = await woocommerceApiRequest.call(this, 'POST', '/orders', body); } //https://woocommerce.github.io/woocommerce-rest-api-docs/#update-an-order if (operation === 'update') { const orderId = this.getNodeParameter('orderId', i) as string; const updateFields = this.getNodeParameter('updateFields', i) as IDataObject; const body: IOrder = {}; if (updateFields.currency) { body.currency = updateFields.currency as string; } if (updateFields.customerId) { body.customer_id = parseInt(updateFields.customerId as string, 10); } if (updateFields.customerNote) { body.customer_note = updateFields.customerNote as string; } if (updateFields.parentId) { body.parent_id = parseInt(updateFields.parentId as string, 10); } if (updateFields.paymentMethodId) { body.payment_method = updateFields.paymentMethodId as string; } if (updateFields.paymentMethodTitle) { body.payment_method_title = updateFields.paymentMethodTitle as string; } if (updateFields.status) { body.status = updateFields.status as string; } if (updateFields.transactionID) { body.transaction_id = updateFields.transactionID as string; } const billing = (this.getNodeParameter('billingUi', i) as IDataObject).billingValues as IAddress; if (billing !== undefined) { body.billing = billing; toSnakeCase(billing as IDataObject); } const shipping = (this.getNodeParameter('shippingUi', i) as IDataObject).shippingValues as IAddress; if (shipping !== undefined) { body.shipping = shipping; toSnakeCase(shipping as IDataObject); } const couponLines = (this.getNodeParameter('couponLinesUi', i) as IDataObject).couponLinesValues as ICouponLine[]; if (couponLines) { body.coupon_lines = couponLines; setMetadata(couponLines); toSnakeCase(couponLines); } const feeLines = (this.getNodeParameter('feeLinesUi', i) as IDataObject).feeLinesValues as IFeeLine[]; if (feeLines) { body.fee_lines = feeLines; setMetadata(feeLines); toSnakeCase(feeLines); } const lineItems = (this.getNodeParameter('lineItemsUi', i) as IDataObject).lineItemsValues as ILineItem[]; if (lineItems) { body.line_items = lineItems; setMetadata(lineItems); toSnakeCase(lineItems); } const metadata = (this.getNodeParameter('metadataUi', i) as IDataObject).metadataValues as IDataObject[]; if (metadata) { body.meta_data = metadata; } const shippingLines = (this.getNodeParameter('shippingLinesUi', i) as IDataObject).shippingLinesValues as IShoppingLine[]; if (shippingLines) { body.shipping_lines = shippingLines; setMetadata(shippingLines); toSnakeCase(shippingLines); } responseData = await woocommerceApiRequest.call(this, 'PUT', `/orders/${orderId}`, body); } //https://woocommerce.github.io/woocommerce-rest-api-docs/#retrieve-an-order if (operation === 'get') { const orderId = this.getNodeParameter('orderId', i) as string; responseData = await woocommerceApiRequest.call(this, 'GET', `/orders/${orderId}`, {}, qs); } //https://woocommerce.github.io/woocommerce-rest-api-docs/#list-all-orders if (operation === 'getAll') { const returnAll = this.getNodeParameter('returnAll', i) as boolean; const options = this.getNodeParameter('options', i) as IDataObject; if (options.after) { qs.after = options.after as string; } if (options.before) { qs.before = options.before as string; } if (options.category) { qs.category = options.category as string; } if (options.customer) { qs.customer = parseInt(options.customer as string, 10); } if (options.decimalPoints) { qs.dp = options.decimalPoints as number; } if (options.product) { qs.product = parseInt(options.product as string, 10); } if (options.order) { qs.order = options.order as string; } if (options.orderBy) { qs.orderby = options.orderBy as string; } if (options.search) { qs.search = options.search as string; } if (options.status) { qs.status = options.status as string; } if (returnAll === true) { responseData = await woocommerceApiRequestAllItems.call(this, 'GET', '/orders', {}, qs); } else { qs.per_page = this.getNodeParameter('limit', i) as number; responseData = await woocommerceApiRequest.call(this, 'GET', '/orders', {}, qs); } } //https://woocommerce.github.io/woocommerce-rest-api-docs/#delete-an-order if (operation === 'delete') { const orderId = this.getNodeParameter('orderId', i) as string; responseData = await woocommerceApiRequest.call(this, 'DELETE', `/orders/${orderId}`, {}, { force: true }); } } if (Array.isArray(responseData)) { returnData.push.apply(returnData, responseData as IDataObject[]); } else { returnData.push(responseData as IDataObject); } } return [this.helpers.returnJsonArray(returnData)]; } }
the_stack
import * as pulumi from "@pulumi/pulumi"; import * as utilities from "../utilities"; /** * Creates a Microsoft AD domain * * To get more information about Domain, see: * * * [API documentation](https://cloud.google.com/managed-microsoft-ad/reference/rest/v1/projects.locations.global.domains) * * How-to Guides * * [Managed Microsoft Active Directory Quickstart](https://cloud.google.com/managed-microsoft-ad/docs/quickstarts) * * ## Example Usage * ### Active Directory Domain Basic * * ```typescript * import * as pulumi from "@pulumi/pulumi"; * import * as gcp from "@pulumi/gcp"; * * const ad_domain = new gcp.activedirectory.Domain("ad-domain", { * domainName: "tfgen.org.com", * locations: ["us-central1"], * reservedIpRange: "192.168.255.0/24", * }); * ``` * * ## Import * * Domain can be imported using any of these accepted formats * * ```sh * $ pulumi import gcp:activedirectory/domain:Domain default {{name}} * ``` */ export class Domain extends pulumi.CustomResource { /** * Get an existing Domain resource's state with the given name, ID, and optional extra * properties used to qualify the lookup. * * @param name The _unique_ name of the resulting resource. * @param id The _unique_ provider ID of the resource to lookup. * @param state Any extra arguments used during the lookup. * @param opts Optional settings to control the behavior of the CustomResource. */ public static get(name: string, id: pulumi.Input<pulumi.ID>, state?: DomainState, opts?: pulumi.CustomResourceOptions): Domain { return new Domain(name, <any>state, { ...opts, id: id }); } /** @internal */ public static readonly __pulumiType = 'gcp:activedirectory/domain:Domain'; /** * Returns true if the given object is an instance of Domain. This is designed to work even * when multiple copies of the Pulumi SDK have been loaded into the same process. */ public static isInstance(obj: any): obj is Domain { if (obj === undefined || obj === null) { return false; } return obj['__pulumiType'] === Domain.__pulumiType; } /** * The name of delegated administrator account used to perform Active Directory operations. * If not specified, setupadmin will be used. */ public readonly admin!: pulumi.Output<string | undefined>; /** * The full names of the Google Compute Engine networks the domain instance is connected to. The domain is only available on networks listed in authorizedNetworks. * If CIDR subnets overlap between networks, domain creation will fail. */ public readonly authorizedNetworks!: pulumi.Output<string[] | undefined>; /** * The fully qualified domain name. e.g. mydomain.myorganization.com, with the restrictions, * https://cloud.google.com/managed-microsoft-ad/reference/rest/v1/projects.locations.global.domains. */ public readonly domainName!: pulumi.Output<string>; /** * The fully-qualified domain name of the exposed domain used by clients to connect to the service. Similar to what would * be chosen for an Active Directory set up on an internal network. */ public /*out*/ readonly fqdn!: pulumi.Output<string>; /** * Resource labels that can contain user-provided metadata */ public readonly labels!: pulumi.Output<{[key: string]: string} | undefined>; /** * Locations where domain needs to be provisioned. [regions][compute/docs/regions-zones/] * e.g. us-west1 or us-east4 Service supports up to 4 locations at once. Each location will use a /26 block. */ public readonly locations!: pulumi.Output<string[]>; /** * The unique name of the domain using the format: 'projects/{project}/locations/global/domains/{domainName}'. */ public /*out*/ readonly name!: pulumi.Output<string>; /** * The ID of the project in which the resource belongs. * If it is not provided, the provider project is used. */ public readonly project!: pulumi.Output<string>; /** * The CIDR range of internal addresses that are reserved for this domain. Reserved networks must be /24 or larger. * Ranges must be unique and non-overlapping with existing subnets in authorizedNetworks */ public readonly reservedIpRange!: pulumi.Output<string>; /** * Create a Domain resource with the given unique name, arguments, and options. * * @param name The _unique_ name of the resource. * @param args The arguments to use to populate this resource's properties. * @param opts A bag of options that control this resource's behavior. */ constructor(name: string, args: DomainArgs, opts?: pulumi.CustomResourceOptions) constructor(name: string, argsOrState?: DomainArgs | DomainState, opts?: pulumi.CustomResourceOptions) { let inputs: pulumi.Inputs = {}; opts = opts || {}; if (opts.id) { const state = argsOrState as DomainState | undefined; inputs["admin"] = state ? state.admin : undefined; inputs["authorizedNetworks"] = state ? state.authorizedNetworks : undefined; inputs["domainName"] = state ? state.domainName : undefined; inputs["fqdn"] = state ? state.fqdn : undefined; inputs["labels"] = state ? state.labels : undefined; inputs["locations"] = state ? state.locations : undefined; inputs["name"] = state ? state.name : undefined; inputs["project"] = state ? state.project : undefined; inputs["reservedIpRange"] = state ? state.reservedIpRange : undefined; } else { const args = argsOrState as DomainArgs | undefined; if ((!args || args.domainName === undefined) && !opts.urn) { throw new Error("Missing required property 'domainName'"); } if ((!args || args.locations === undefined) && !opts.urn) { throw new Error("Missing required property 'locations'"); } if ((!args || args.reservedIpRange === undefined) && !opts.urn) { throw new Error("Missing required property 'reservedIpRange'"); } inputs["admin"] = args ? args.admin : undefined; inputs["authorizedNetworks"] = args ? args.authorizedNetworks : undefined; inputs["domainName"] = args ? args.domainName : undefined; inputs["labels"] = args ? args.labels : undefined; inputs["locations"] = args ? args.locations : undefined; inputs["project"] = args ? args.project : undefined; inputs["reservedIpRange"] = args ? args.reservedIpRange : undefined; inputs["fqdn"] = undefined /*out*/; inputs["name"] = undefined /*out*/; } if (!opts.version) { opts = pulumi.mergeOptions(opts, { version: utilities.getVersion()}); } super(Domain.__pulumiType, name, inputs, opts); } } /** * Input properties used for looking up and filtering Domain resources. */ export interface DomainState { /** * The name of delegated administrator account used to perform Active Directory operations. * If not specified, setupadmin will be used. */ admin?: pulumi.Input<string>; /** * The full names of the Google Compute Engine networks the domain instance is connected to. The domain is only available on networks listed in authorizedNetworks. * If CIDR subnets overlap between networks, domain creation will fail. */ authorizedNetworks?: pulumi.Input<pulumi.Input<string>[]>; /** * The fully qualified domain name. e.g. mydomain.myorganization.com, with the restrictions, * https://cloud.google.com/managed-microsoft-ad/reference/rest/v1/projects.locations.global.domains. */ domainName?: pulumi.Input<string>; /** * The fully-qualified domain name of the exposed domain used by clients to connect to the service. Similar to what would * be chosen for an Active Directory set up on an internal network. */ fqdn?: pulumi.Input<string>; /** * Resource labels that can contain user-provided metadata */ labels?: pulumi.Input<{[key: string]: pulumi.Input<string>}>; /** * Locations where domain needs to be provisioned. [regions][compute/docs/regions-zones/] * e.g. us-west1 or us-east4 Service supports up to 4 locations at once. Each location will use a /26 block. */ locations?: pulumi.Input<pulumi.Input<string>[]>; /** * The unique name of the domain using the format: 'projects/{project}/locations/global/domains/{domainName}'. */ name?: pulumi.Input<string>; /** * The ID of the project in which the resource belongs. * If it is not provided, the provider project is used. */ project?: pulumi.Input<string>; /** * The CIDR range of internal addresses that are reserved for this domain. Reserved networks must be /24 or larger. * Ranges must be unique and non-overlapping with existing subnets in authorizedNetworks */ reservedIpRange?: pulumi.Input<string>; } /** * The set of arguments for constructing a Domain resource. */ export interface DomainArgs { /** * The name of delegated administrator account used to perform Active Directory operations. * If not specified, setupadmin will be used. */ admin?: pulumi.Input<string>; /** * The full names of the Google Compute Engine networks the domain instance is connected to. The domain is only available on networks listed in authorizedNetworks. * If CIDR subnets overlap between networks, domain creation will fail. */ authorizedNetworks?: pulumi.Input<pulumi.Input<string>[]>; /** * The fully qualified domain name. e.g. mydomain.myorganization.com, with the restrictions, * https://cloud.google.com/managed-microsoft-ad/reference/rest/v1/projects.locations.global.domains. */ domainName: pulumi.Input<string>; /** * Resource labels that can contain user-provided metadata */ labels?: pulumi.Input<{[key: string]: pulumi.Input<string>}>; /** * Locations where domain needs to be provisioned. [regions][compute/docs/regions-zones/] * e.g. us-west1 or us-east4 Service supports up to 4 locations at once. Each location will use a /26 block. */ locations: pulumi.Input<pulumi.Input<string>[]>; /** * The ID of the project in which the resource belongs. * If it is not provided, the provider project is used. */ project?: pulumi.Input<string>; /** * The CIDR range of internal addresses that are reserved for this domain. Reserved networks must be /24 or larger. * Ranges must be unique and non-overlapping with existing subnets in authorizedNetworks */ reservedIpRange: pulumi.Input<string>; }
the_stack
import { createSpan } from "../tracing"; import { KqlScriptOperations } from "../operationsInterfaces"; import * as coreClient from "@azure/core-client"; import * as coreTracing from "@azure/core-tracing"; import * as Mappers from "../models/mappers"; import * as Parameters from "../models/parameters"; import { ArtifactsClientContext } from "../artifactsClientContext"; import { PollerLike, PollOperationState, LroEngine } from "@azure/core-lro"; import { LroImpl } from "../lroImpl"; import { KqlScriptResource, KqlScriptCreateOrUpdateOptionalParams, KqlScriptCreateOrUpdateResponse, KqlScriptGetByNameOptionalParams, KqlScriptGetByNameResponse, KqlScriptDeleteByNameOptionalParams, ArtifactRenameRequest, KqlScriptRenameOptionalParams } from "../models"; /** Class containing KqlScriptOperations operations. */ export class KqlScriptOperationsImpl implements KqlScriptOperations { private readonly client: ArtifactsClientContext; /** * Initialize a new instance of the class KqlScriptOperations class. * @param client Reference to the service client */ constructor(client: ArtifactsClientContext) { this.client = client; } /** * Creates or updates a KQL Script * @param kqlScriptName KQL script name * @param kqlScript KQL script * @param options The options parameters. */ async beginCreateOrUpdate( kqlScriptName: string, kqlScript: KqlScriptResource, options?: KqlScriptCreateOrUpdateOptionalParams ): Promise< PollerLike< PollOperationState<KqlScriptCreateOrUpdateResponse>, KqlScriptCreateOrUpdateResponse > > { const { span } = createSpan( "ArtifactsClient-beginCreateOrUpdate", options || {} ); const directSendOperation = async ( args: coreClient.OperationArguments, spec: coreClient.OperationSpec ): Promise<KqlScriptCreateOrUpdateResponse> => { try { const result = await this.client.sendOperationRequest(args, spec); return result as KqlScriptCreateOrUpdateResponse; } catch (error) { span.setStatus({ code: coreTracing.SpanStatusCode.UNSET, message: error.message }); throw error; } finally { span.end(); } }; const sendOperation = async ( args: coreClient.OperationArguments, spec: coreClient.OperationSpec ) => { let currentRawResponse: | coreClient.FullOperationResponse | undefined = undefined; const providedCallback = args.options?.onResponse; const callback: coreClient.RawResponseCallback = ( rawResponse: coreClient.FullOperationResponse, flatResponse: unknown ) => { currentRawResponse = rawResponse; providedCallback?.(rawResponse, flatResponse); }; const updatedArgs = { ...args, options: { ...args.options, onResponse: callback } }; const flatResponse = await directSendOperation(updatedArgs, spec); return { flatResponse, rawResponse: { statusCode: currentRawResponse!.status, body: currentRawResponse!.parsedBody, headers: currentRawResponse!.headers.toJSON() } }; }; const lro = new LroImpl( sendOperation, { kqlScriptName, kqlScript, options }, createOrUpdateOperationSpec ); return new LroEngine(lro, { resumeFrom: options?.resumeFrom, intervalInMs: options?.updateIntervalInMs }); } /** * Creates or updates a KQL Script * @param kqlScriptName KQL script name * @param kqlScript KQL script * @param options The options parameters. */ async beginCreateOrUpdateAndWait( kqlScriptName: string, kqlScript: KqlScriptResource, options?: KqlScriptCreateOrUpdateOptionalParams ): Promise<KqlScriptCreateOrUpdateResponse> { const poller = await this.beginCreateOrUpdate( kqlScriptName, kqlScript, options ); return poller.pollUntilDone(); } /** * Get KQL script by name * @param kqlScriptName KQL script name * @param options The options parameters. */ async getByName( kqlScriptName: string, options?: KqlScriptGetByNameOptionalParams ): Promise<KqlScriptGetByNameResponse> { const { span } = createSpan("ArtifactsClient-getByName", options || {}); try { const result = await this.client.sendOperationRequest( { kqlScriptName, options }, getByNameOperationSpec ); return result as KqlScriptGetByNameResponse; } catch (error) { span.setStatus({ code: coreTracing.SpanStatusCode.UNSET, message: error.message }); throw error; } finally { span.end(); } } /** * Delete KQL script by name * @param kqlScriptName KQL script name * @param options The options parameters. */ async beginDeleteByName( kqlScriptName: string, options?: KqlScriptDeleteByNameOptionalParams ): Promise<PollerLike<PollOperationState<void>, void>> { const { span } = createSpan( "ArtifactsClient-beginDeleteByName", options || {} ); const directSendOperation = async ( args: coreClient.OperationArguments, spec: coreClient.OperationSpec ): Promise<void> => { try { const result = await this.client.sendOperationRequest(args, spec); return result as void; } catch (error) { span.setStatus({ code: coreTracing.SpanStatusCode.UNSET, message: error.message }); throw error; } finally { span.end(); } }; const sendOperation = async ( args: coreClient.OperationArguments, spec: coreClient.OperationSpec ) => { let currentRawResponse: | coreClient.FullOperationResponse | undefined = undefined; const providedCallback = args.options?.onResponse; const callback: coreClient.RawResponseCallback = ( rawResponse: coreClient.FullOperationResponse, flatResponse: unknown ) => { currentRawResponse = rawResponse; providedCallback?.(rawResponse, flatResponse); }; const updatedArgs = { ...args, options: { ...args.options, onResponse: callback } }; const flatResponse = await directSendOperation(updatedArgs, spec); return { flatResponse, rawResponse: { statusCode: currentRawResponse!.status, body: currentRawResponse!.parsedBody, headers: currentRawResponse!.headers.toJSON() } }; }; const lro = new LroImpl( sendOperation, { kqlScriptName, options }, deleteByNameOperationSpec ); return new LroEngine(lro, { resumeFrom: options?.resumeFrom, intervalInMs: options?.updateIntervalInMs }); } /** * Delete KQL script by name * @param kqlScriptName KQL script name * @param options The options parameters. */ async beginDeleteByNameAndWait( kqlScriptName: string, options?: KqlScriptDeleteByNameOptionalParams ): Promise<void> { const poller = await this.beginDeleteByName(kqlScriptName, options); return poller.pollUntilDone(); } /** * Rename KQL script * @param kqlScriptName KQL script name * @param renameRequest Rename request * @param options The options parameters. */ async beginRename( kqlScriptName: string, renameRequest: ArtifactRenameRequest, options?: KqlScriptRenameOptionalParams ): Promise<PollerLike<PollOperationState<void>, void>> { const { span } = createSpan("ArtifactsClient-beginRename", options || {}); const directSendOperation = async ( args: coreClient.OperationArguments, spec: coreClient.OperationSpec ): Promise<void> => { try { const result = await this.client.sendOperationRequest(args, spec); return result as void; } catch (error) { span.setStatus({ code: coreTracing.SpanStatusCode.UNSET, message: error.message }); throw error; } finally { span.end(); } }; const sendOperation = async ( args: coreClient.OperationArguments, spec: coreClient.OperationSpec ) => { let currentRawResponse: | coreClient.FullOperationResponse | undefined = undefined; const providedCallback = args.options?.onResponse; const callback: coreClient.RawResponseCallback = ( rawResponse: coreClient.FullOperationResponse, flatResponse: unknown ) => { currentRawResponse = rawResponse; providedCallback?.(rawResponse, flatResponse); }; const updatedArgs = { ...args, options: { ...args.options, onResponse: callback } }; const flatResponse = await directSendOperation(updatedArgs, spec); return { flatResponse, rawResponse: { statusCode: currentRawResponse!.status, body: currentRawResponse!.parsedBody, headers: currentRawResponse!.headers.toJSON() } }; }; const lro = new LroImpl( sendOperation, { kqlScriptName, renameRequest, options }, renameOperationSpec ); return new LroEngine(lro, { resumeFrom: options?.resumeFrom, intervalInMs: options?.updateIntervalInMs }); } /** * Rename KQL script * @param kqlScriptName KQL script name * @param renameRequest Rename request * @param options The options parameters. */ async beginRenameAndWait( kqlScriptName: string, renameRequest: ArtifactRenameRequest, options?: KqlScriptRenameOptionalParams ): Promise<void> { const poller = await this.beginRename( kqlScriptName, renameRequest, options ); return poller.pollUntilDone(); } } // Operation Specifications const serializer = coreClient.createSerializer(Mappers, /* isXml */ false); const createOrUpdateOperationSpec: coreClient.OperationSpec = { path: "/kqlScripts/{kqlScriptName}", httpMethod: "PUT", responses: { 200: { bodyMapper: Mappers.KqlScriptResource }, 201: { bodyMapper: Mappers.KqlScriptResource }, 202: { bodyMapper: Mappers.KqlScriptResource }, 204: { bodyMapper: Mappers.KqlScriptResource }, default: { bodyMapper: Mappers.ErrorContract } }, requestBody: Parameters.kqlScript, queryParameters: [Parameters.apiVersion], urlParameters: [Parameters.endpoint, Parameters.kqlScriptName], headerParameters: [Parameters.accept, Parameters.contentType], mediaType: "json", serializer }; const getByNameOperationSpec: coreClient.OperationSpec = { path: "/kqlScripts/{kqlScriptName}", httpMethod: "GET", responses: { 200: { bodyMapper: Mappers.KqlScriptResource }, default: { bodyMapper: Mappers.ErrorContract } }, queryParameters: [Parameters.apiVersion], urlParameters: [Parameters.endpoint, Parameters.kqlScriptName], headerParameters: [Parameters.accept], serializer }; const deleteByNameOperationSpec: coreClient.OperationSpec = { path: "/kqlScripts/{kqlScriptName}", httpMethod: "DELETE", responses: { 200: {}, 201: {}, 202: {}, 204: {}, default: { bodyMapper: Mappers.ErrorContract } }, queryParameters: [Parameters.apiVersion], urlParameters: [Parameters.endpoint, Parameters.kqlScriptName], headerParameters: [Parameters.accept], serializer }; const renameOperationSpec: coreClient.OperationSpec = { path: "/kqlScripts/{kqlScriptName}/rename", httpMethod: "POST", responses: { 200: {}, 201: {}, 202: {}, 204: {}, default: { bodyMapper: Mappers.ErrorContract } }, requestBody: Parameters.renameRequest, queryParameters: [Parameters.apiVersion], urlParameters: [Parameters.endpoint, Parameters.kqlScriptName], headerParameters: [Parameters.accept, Parameters.contentType], mediaType: "json", serializer };
the_stack
namespace typestate { /** * Transition grouping to faciliate fluent api */ export class Transitions<T> { constructor(public fsm: FiniteStateMachine<T>) { } public fromStates: T[]; public toStates: T[]; /** * Specify the end state(s) of a transition function */ public to(...states: T[]) { this.toStates = states; this.fsm.addTransitions(this); } /** * Specify that any state in the state enum is value * Takes the state enum as an argument */ public toAny(states: any) { var toStates: T[] = []; for (var s in states) { if (states.hasOwnProperty(s)) { toStates.push((<T>states[s])); } } this.toStates = toStates; this.fsm.addTransitions(this); } } /** * Internal representation of a transition function */ export class TransitionFunction<T> { constructor(public fsm: FiniteStateMachine<T>, public from: T, public to: T) { } } /** * A simple finite state machine implemented in TypeScript, the templated argument is meant to be used * with an enumeration. */ export class FiniteStateMachine<T> { public currentState: T; private _startState: T; private _allowImplicitSelfTransition: boolean; private _transitionFunctions: TransitionFunction<T>[] = []; private _onCallbacks: { [key: string]: { (from: T, event?: any): void; }[] } = {}; private _exitCallbacks: { [key: string]: { (to: T): boolean|Promise<boolean>; }[] } = {}; private _enterCallbacks: { [key: string]: { (from: T, event?: any): boolean|Promise<boolean>; }[] } = {}; private _invalidTransitionCallback: (to: T, from: T) => boolean = null; constructor(startState: T, allowImplicitSelfTransition: boolean = false) { this.currentState = startState; this._startState = startState; this._allowImplicitSelfTransition = allowImplicitSelfTransition; } public addTransitions(fcn: Transitions<T>) { fcn.fromStates.forEach(from => { fcn.toStates.forEach(to => { // Only add the transition if the state machine is not currently able to transition. if (!this._canGo(from, to)) { this._transitionFunctions.push(new TransitionFunction<T>(this, from, to)); } }); }); } /** * Listen for the transition to this state and fire the associated callback */ public on(state: T, callback: (from: T, event?: any) => any): FiniteStateMachine<T> { var key = state.toString(); if (!this._onCallbacks[key]) { this._onCallbacks[key] = []; } this._onCallbacks[key].push(callback); return this; } /** * Listen for the transition to this state and fire the associated callback, returning * false in the callback will block the transition to this state. */ public onEnter(state: T, callback: (from: T, event?: any) => boolean|Promise<boolean>): FiniteStateMachine<T> { var key = state.toString(); if (!this._enterCallbacks[key]) { this._enterCallbacks[key] = []; } this._enterCallbacks[key].push(callback); return this; } /** * Listen for the transition to this state and fire the associated callback, returning * false in the callback will block the transition from this state. */ public onExit(state: T, callback: (to: T) => boolean|Promise<boolean>): FiniteStateMachine<T> { var key = state.toString(); if (!this._exitCallbacks[key]) { this._exitCallbacks[key] = []; } this._exitCallbacks[key].push(callback); return this; } /** * List for an invalid transition and handle the error, returning a falsy value will throw an * exception, a truthy one will swallow the exception */ public onInvalidTransition(callback: (from: T, to: T) => boolean): FiniteStateMachine<T> { if(!this._invalidTransitionCallback){ this._invalidTransitionCallback = callback } return this; } /** * Declares the start state(s) of a transition function, must be followed with a '.to(...endStates)' */ public from(...states: T[]): Transitions<T> { var _transition = new Transitions<T>(this); _transition.fromStates = states; return _transition; } public fromAny(states: any): Transitions<T> { var fromStates: T[] = []; for (var s in states) { if (states.hasOwnProperty(s)) { fromStates.push((<T>states[s])); } } var _transition = new Transitions<T>(this); _transition.fromStates = fromStates; return _transition; } private _validTransition(from: T, to: T): boolean { return this._transitionFunctions.some(tf => { return (tf.from === from && tf.to === to); }); } /** * Check whether a transition between any two states is valid. * If allowImplicitSelfTransition is true, always allow transitions from a state back to itself. * Otherwise, check if it's a valid transition. */ private _canGo(fromState: T, toState: T): boolean { return (this._allowImplicitSelfTransition && fromState === toState) || this._validTransition(fromState, toState); } /** * Check whether a transition to a new state is valid */ public canGo(state: T): boolean { return this._canGo(this.currentState, state); } /** * Transition to another valid state */ public go(state: T, event?: any): Promise<void> { if (!this.canGo(state)) { if(!this._invalidTransitionCallback || !this._invalidTransitionCallback(this.currentState, state)){ throw new Error('Error no transition function exists from state ' + this.currentState.toString() + ' to ' + state.toString()); } } else { return this._transitionTo(state, event); } } /** * This method is availble for overridding for the sake of extensibility. * It is called in the event of a successful transition. */ public onTransition(from: T, to: T) { // pass, does nothing until overidden } /** * Reset the finite state machine back to the start state, DO NOT USE THIS AS A SHORTCUT for a transition. * This is for starting the fsm from the beginning. */ public reset(options?: ResetOptions) { options = { ...DefaultResetOptions, ...(options || {}) }; this.currentState = this._startState; if (options.runCallbacks) { this._onCallbacks[this.currentState.toString()].forEach(fcn => { fcn.call(this, null, null); }); } } /** * Whether or not the current state equals the given state */ public is(state: T): boolean { return this.currentState === state; } private async _transitionTo(state: T, event?: any): Promise<void> { if (!this._exitCallbacks[this.currentState.toString()]) { this._exitCallbacks[this.currentState.toString()] = []; } if (!this._enterCallbacks[state.toString()]) { this._enterCallbacks[state.toString()] = []; } if (!this._onCallbacks[state.toString()]) { this._onCallbacks[state.toString()] = []; } var canExit = true; for(var exitCallback of this._exitCallbacks[this.currentState.toString()]) { let returnValue: boolean|Promise<boolean> = exitCallback.call(this, state); // No return value if(returnValue === undefined) { // Default to true returnValue = true; } // If it's not a boolean, it's a promise if(returnValue !== false && returnValue !== true) { returnValue = await returnValue; } // Still no return value if(returnValue === undefined) { // Default to true returnValue = true; } canExit = canExit && returnValue; } var canEnter = true; for(var enterCallback of this._enterCallbacks[state.toString()]) { let returnValue: boolean|Promise<boolean> = enterCallback.call(this, this.currentState, event); // No return value if(returnValue === undefined) { // Default to true returnValue = true; } // If it's not a boolean, it's a promise if(returnValue !== false && returnValue !== true) { returnValue = await returnValue; } // Still no return value if(returnValue === undefined) { // Default to true returnValue = true; } canEnter = canEnter && returnValue; }; if (canExit && canEnter) { var old = this.currentState; this.currentState = state; this._onCallbacks[this.currentState.toString()].forEach(fcn => { fcn.call(this, old, event); }); this.onTransition(old, state); } } } /** * Options to pass to the `reset()` method. */ export interface ResetOptions { /** Whether or not the speciefied `on()` handlers for the start state should be called when resetted. */ runCallbacks?: boolean; }; /** * Default `ResetOptions` values used in the `reset()` mehtod. */ export const DefaultResetOptions: ResetOptions = { runCallbacks: false }; } // maintain backwards compatibility for people using the pascal cased version var TypeState = typestate;
the_stack
import { ConsoleLogger as Logger } from '@aws-amplify/core'; import SQLiteDatabase from './SQLiteDatabase'; import { generateSchemaStatements, queryByIdStatement, modelUpdateStatement, modelInsertStatement, queryAllStatement, queryOneStatement, deleteByIdStatement, deleteByPredicateStatement, ParameterizedStatement, } from './SQLiteUtils'; import { StorageAdapter, ModelInstanceCreator, ModelPredicateCreator, ModelSortPredicateCreator, InternalSchema, isPredicateObj, ModelInstanceMetadata, ModelPredicate, NamespaceResolver, OpType, PaginationInput, PersistentModel, PersistentModelConstructor, PredicateObject, PredicatesGroup, QueryOne, utils, } from '@aws-amplify/datastore'; const { traverseModel, validatePredicate, isModelConstructor } = utils; const logger = new Logger('DataStore'); export class SQLiteAdapter implements StorageAdapter { private schema: InternalSchema; private namespaceResolver: NamespaceResolver; private modelInstanceCreator: ModelInstanceCreator; private getModelConstructorByModelName: ( namsespaceName: string, modelName: string ) => PersistentModelConstructor<any>; private db: SQLiteDatabase; private initPromise: Promise<void>; private resolve: (value?: any) => void; private reject: (value?: any) => void; public async setUp( theSchema: InternalSchema, namespaceResolver: NamespaceResolver, modelInstanceCreator: ModelInstanceCreator, getModelConstructorByModelName: ( namsespaceName: string, modelName: string ) => PersistentModelConstructor<any> ) { if (!this.initPromise) { this.initPromise = new Promise((res, rej) => { this.resolve = res; this.reject = rej; }); } else { await this.initPromise; return; } this.schema = theSchema; this.namespaceResolver = namespaceResolver; this.modelInstanceCreator = modelInstanceCreator; this.getModelConstructorByModelName = getModelConstructorByModelName; try { if (!this.db) { this.db = new SQLiteDatabase(); await this.db.init(); const statements = generateSchemaStatements(this.schema); await this.db.createSchema(statements); this.resolve(); } } catch (error) { this.reject(error); } } async clear(): Promise<void> { await this.db.clear(); this.db = undefined; this.initPromise = undefined; } async save<T extends PersistentModel>( model: T, condition?: ModelPredicate<T> ): Promise<[T, OpType.INSERT | OpType.UPDATE][]> { const modelConstructor = Object.getPrototypeOf(model) .constructor as PersistentModelConstructor<T>; const { name: tableName } = modelConstructor; const connectedModels = traverseModel( modelConstructor.name, model, this.schema.namespaces[this.namespaceResolver(modelConstructor)], this.modelInstanceCreator, this.getModelConstructorByModelName ); const connectionStoreNames = Object.values(connectedModels).map( ({ modelName, item, instance }) => { return { modelName, item, instance }; } ); const [queryStatement, params] = queryByIdStatement(model.id, tableName); const fromDB = await this.db.get(queryStatement, params); if (condition && fromDB) { const predicates = ModelPredicateCreator.getPredicates(condition); const { predicates: predicateObjs, type } = predicates; const isValid = validatePredicate(fromDB, type, predicateObjs); if (!isValid) { const msg = 'Conditional update failed'; logger.error(msg, { model: fromDB, condition: predicateObjs }); throw new Error(msg); } } const result: [T, OpType.INSERT | OpType.UPDATE][] = []; const saveStatements = new Set<ParameterizedStatement>(); for await (const resItem of connectionStoreNames) { const { modelName, item, instance } = resItem; const { id } = item; const [queryStatement, params] = queryByIdStatement(id, modelName); const fromDB = await this.db.get(queryStatement, params); const opType: OpType = fromDB === undefined ? OpType.INSERT : OpType.UPDATE; const saveStatement = fromDB ? modelUpdateStatement(instance, modelName) : modelInsertStatement(instance, modelName); saveStatements.add(saveStatement); result.push([instance, opType]); } await this.db.batchSave(saveStatements); return result; } private async load<T>( namespaceName: string, srcModelName: string, records: T[] ): Promise<T[]> { const namespace = this.schema.namespaces[namespaceName]; const relations = namespace.relationships[srcModelName].relationTypes; const connectionTableNames = relations.map(({ modelName }) => modelName); const modelConstructor = this.getModelConstructorByModelName( namespaceName, srcModelName ); if (connectionTableNames.length === 0) { return records.map(record => this.modelInstanceCreator(modelConstructor, record) ); } for await (const relation of relations) { const { fieldName, modelName: tableName, targetName, relationType, } = relation; const modelConstructor = this.getModelConstructorByModelName( namespaceName, tableName ); // TODO: use SQL JOIN instead switch (relationType) { case 'HAS_ONE': for await (const recordItem of records) { if (recordItem[fieldName]) { const [queryStatement, params] = queryByIdStatement( recordItem[fieldName], tableName ); const connectionRecord = await this.db.get( queryStatement, params ); recordItem[fieldName] = connectionRecord && this.modelInstanceCreator(modelConstructor, connectionRecord); } } break; case 'BELONGS_TO': for await (const recordItem of records) { if (recordItem[targetName]) { const [queryStatement, params] = queryByIdStatement( recordItem[targetName], tableName ); const connectionRecord = await this.db.get( queryStatement, params ); recordItem[fieldName] = connectionRecord && this.modelInstanceCreator(modelConstructor, connectionRecord); delete recordItem[targetName]; } } break; case 'HAS_MANY': // TODO: Lazy loading break; default: const _: never = relationType; throw new Error(`invalid relation type ${relationType}`); break; } } return records.map(record => this.modelInstanceCreator(modelConstructor, record) ); } async query<T extends PersistentModel>( modelConstructor: PersistentModelConstructor<T>, predicate?: ModelPredicate<T>, pagination?: PaginationInput<T> ): Promise<T[]> { const { name: tableName } = modelConstructor; const namespaceName = this.namespaceResolver(modelConstructor); const predicates = predicate && ModelPredicateCreator.getPredicates(predicate); const sortPredicates = pagination && pagination.sort && ModelSortPredicateCreator.getPredicates(pagination.sort); const limit = pagination && pagination.limit; const page = limit && pagination.page; const queryById = predicates && this.idFromPredicate(predicates); const records: T[] = <T[]>await (async () => { if (queryById) { const record = await this.getById(tableName, queryById); return record ? [record] : []; } const [queryStatement, params] = queryAllStatement( tableName, predicates, sortPredicates, limit, page ); return await this.db.getAll(queryStatement, params); })(); return await this.load(namespaceName, modelConstructor.name, records); } private async getById<T extends PersistentModel>( tableName: string, id: string ): Promise<T> { const [queryStatement, params] = queryByIdStatement(id, tableName); const record = await this.db.get<T>(queryStatement, params); return record; } private idFromPredicate<T extends PersistentModel>( predicates: PredicatesGroup<T> ) { const { predicates: predicateObjs } = predicates; const idPredicate = predicateObjs.length === 1 && (predicateObjs.find( p => isPredicateObj(p) && p.field === 'id' && p.operator === 'eq' ) as PredicateObject<T>); return idPredicate && idPredicate.operand; } async queryOne<T extends PersistentModel>( modelConstructor: PersistentModelConstructor<T>, firstOrLast: QueryOne = QueryOne.FIRST ): Promise<T | undefined> { const { name: tableName } = modelConstructor; const [queryStatement, params] = queryOneStatement(firstOrLast, tableName); const result = await this.db.get<T>(queryStatement, params); const modelInstance = result && this.modelInstanceCreator(modelConstructor, result); return modelInstance; } // Currently does not cascade // TODO: use FKs in relations and have `ON DELETE CASCADE` set // For Has Many and Has One relations to have SQL handle cascades automatically async delete<T extends PersistentModel>( modelOrModelConstructor: T | PersistentModelConstructor<T>, condition?: ModelPredicate<T> ): Promise<[T[], T[]]> { if (isModelConstructor(modelOrModelConstructor)) { const modelConstructor = modelOrModelConstructor; const namespaceName = this.namespaceResolver(modelConstructor); const { name: tableName } = modelConstructor; const predicates = condition && ModelPredicateCreator.getPredicates(condition); const queryStatement = queryAllStatement(tableName, predicates); const deleteStatement = deleteByPredicateStatement(tableName, predicates); const models = await this.db.selectAndDelete( queryStatement, deleteStatement ); const modelInstances = await this.load( namespaceName, modelConstructor.name, models ); return [modelInstances, modelInstances]; } else { const model = modelOrModelConstructor as T; const modelConstructor = Object.getPrototypeOf(model) .constructor as PersistentModelConstructor<T>; const { name: tableName } = modelConstructor; if (condition) { const [queryStatement, params] = queryByIdStatement( model.id, tableName ); const fromDB = await this.db.get(queryStatement, params); if (fromDB === undefined) { const msg = 'Model instance not found in storage'; logger.warn(msg, { model }); return [[model], []]; } const predicates = ModelPredicateCreator.getPredicates(condition); const { predicates: predicateObjs, type } = predicates; const isValid = validatePredicate(fromDB, type, predicateObjs); if (!isValid) { const msg = 'Conditional update failed'; logger.error(msg, { model: fromDB, condition: predicateObjs }); throw new Error(msg); } const [deleteStatement, deleteParams] = deleteByIdStatement( model.id, tableName ); await this.db.save(deleteStatement, deleteParams); return [[model], [model]]; } else { const [deleteStatement, params] = deleteByIdStatement( model.id, tableName ); await this.db.save(deleteStatement, params); return [[model], [model]]; } } } async batchSave<T extends PersistentModel>( modelConstructor: PersistentModelConstructor<any>, items: ModelInstanceMetadata[] ): Promise<[T, OpType][]> { const { name: tableName } = modelConstructor; const result: [T, OpType][] = []; const itemsToSave: T[] = []; // To determine whether an item should result in an insert or update operation // We first need to query the local DB on the item id const queryStatements = new Set<ParameterizedStatement>(); // Deletes don't need to be queried first, because if the item doesn't exist, // the delete operation will be a no-op const deleteStatements = new Set<ParameterizedStatement>(); const saveStatements = new Set<ParameterizedStatement>(); for (const item of items) { const connectedModels = traverseModel( modelConstructor.name, this.modelInstanceCreator(modelConstructor, item), this.schema.namespaces[this.namespaceResolver(modelConstructor)], this.modelInstanceCreator, this.getModelConstructorByModelName ); const { id, _deleted } = item; const { instance } = connectedModels.find( ({ instance }) => instance.id === id ); if (_deleted) { // create the delete statements right away const deleteStatement = deleteByIdStatement(instance.id, tableName); deleteStatements.add(deleteStatement); result.push([<T>(<unknown>item), OpType.DELETE]); } else { // query statements for the saves at first const queryStatement = queryByIdStatement(id, tableName); queryStatements.add(queryStatement); // combination of insert and update items itemsToSave.push(instance); } } // returns the query results for each of the save items const queryResponses = await this.db.batchQuery(queryStatements); queryResponses.forEach((response, idx) => { if (response === undefined) { const insertStatement = modelInsertStatement( itemsToSave[idx], tableName ); saveStatements.add(insertStatement); result.push([<T>(<unknown>itemsToSave[idx]), OpType.INSERT]); } else { const updateStatement = modelUpdateStatement( itemsToSave[idx], tableName ); saveStatements.add(updateStatement); result.push([<T>(<unknown>itemsToSave[idx]), OpType.UPDATE]); } }); // perform all of the insert/update/delete operations in a single transaction await this.db.batchSave(saveStatements, deleteStatements); return result; } } export default new SQLiteAdapter();
the_stack
import * as fsExtra from 'fs-extra'; import * as webdriver from 'selenium-webdriver'; import ProgressBar = require('progress'); import ansi = require('ansi-escape-sequences'); import {jsonOutput, legacyJsonOutput} from './json-output'; import {browserSignature, makeDriver, openAndSwitchToNewTab} from './browser'; import {measure, measurementName} from './measure'; import {BenchmarkResult, BenchmarkSpec} from './types'; import {formatCsvStats, formatCsvRaw} from './csv'; import { ResultStatsWithDifferences, autoSampleConditionsResolved, summaryStats, computeDifferences, } from './stats'; import { verticalTermResultTable, horizontalTermResultTable, verticalHtmlResultTable, horizontalHtmlResultTable, automaticResultTable, spinner, benchmarkOneLiner, } from './format'; import {Config} from './config'; import * as github from './github'; import {Server, Session} from './server'; import {specUrl} from './specs'; import {wait} from './util'; import * as pathlib from 'path'; interface Browser { name: string; driver: webdriver.WebDriver; initialTabHandle: string; } export class Runner { private readonly config: Config; private readonly specs: BenchmarkSpec[]; private readonly servers: Map<BenchmarkSpec, Server>; private readonly browsers = new Map<string, Browser>(); private readonly bar: ProgressBar; private readonly results = new Map<BenchmarkSpec, BenchmarkResult[]>(); /** * How many times we will load a page and try to collect all measurements * before fully failing. */ private readonly maxAttempts = 3; /** * Maximum milliseconds we will wait for all measurements to be collected per * attempt before reloading and trying a new attempt. */ private readonly attemptTimeout = 10000; /** * How many milliseconds we will wait between each poll for measurements. */ private readonly pollTime = 50; private completeGithubCheck?: (markdown: string) => void; private hitTimeout = false; constructor(config: Config, servers: Map<BenchmarkSpec, Server>) { this.config = config; this.specs = config.benchmarks; this.servers = servers; this.bar = new ProgressBar('[:bar] :status', { total: this.specs.length * (config.sampleSize + /** warmup */ 1), width: 58, }); } async run(): Promise<Array<ResultStatsWithDifferences> | undefined> { await this.launchBrowsers(); if (this.config.githubCheck !== undefined) { this.completeGithubCheck = await github.createCheck( this.config.githubCheck ); } console.log('Running benchmarks\n'); await this.warmup(); await this.takeMinimumSamples(); await this.takeAdditionalSamples(); await this.closeBrowsers(); const results = this.makeResults(); await this.outputResults(results); return results; } private async launchBrowsers() { for (const {browser} of this.specs) { const sig = browserSignature(browser); if (this.browsers.has(sig)) { continue; } this.bar.tick(0, {status: `launching ${browser.name}`}); // It's important that we execute each benchmark iteration in a new tab. // At least in Chrome, each tab corresponds to process which shares some // amount of cached V8 state which can cause significant measurement // effects. There might even be additional interaction effects that // would require an entirely new browser to remove, but experience in // Chrome so far shows that new tabs are neccessary and sufficient. const driver = await makeDriver(browser); const tabs = await driver.getAllWindowHandles(); // We'll always launch new tabs from this initial blank tab. const initialTabHandle = tabs[0]; this.browsers.set(sig, {name: browser.name, driver, initialTabHandle}); } } private async closeBrowsers() { // Close the browsers by closing each of their last remaining tabs. await Promise.all( [...this.browsers.values()].map(({driver}) => driver.close()) ); } /** * Do one throw-away run per benchmark to warm up our server (especially * when expensive bare module resolution is enabled), and the browser. */ private async warmup() { const {specs, bar} = this; for (let i = 0; i < specs.length; i++) { const spec = specs[i]; if (spec.browser.trace !== undefined) { await fsExtra.mkdirp(spec.browser.trace.logDir); } bar.tick(0, { status: `warmup ${i + 1}/${specs.length} ${benchmarkOneLiner(spec)}`, }); await this.takeSamples(spec, 'warmup'); bar.tick(1); } } private recordSamples(spec: BenchmarkSpec, newResults: BenchmarkResult[]) { let specResults = this.results.get(spec); if (specResults === undefined) { specResults = []; this.results.set(spec, specResults); } // This function is called once per page per sample. The first time this // function is called for a page, that result object becomes our "primary" // one. On subsequent calls, we accrete the additional sample data into this // primary one. The other fields are always the same, so we can just ignore // them after the first call. // TODO(aomarks) The other fields (user agent, bytes sent, etc.) only need // to be collected on the first run of each page, so we could do that in the // warmup phase, and then function would only need to take sample data, // since it's a bit confusing how we throw away a bunch of fields after the // first call. for (const newResult of newResults) { const primary = specResults[newResult.measurementIndex]; if (primary === undefined) { specResults[newResult.measurementIndex] = newResult; } else { primary.millis.push(...newResult.millis); } } } private async takeMinimumSamples() { // Always collect our minimum number of samples. const {config, specs, bar} = this; const numRuns = specs.length * config.sampleSize; const maxLength = config.sampleSize.toString().length; let run = 0; for (let sample = 0; sample < config.sampleSize; sample++) { const sampleLabel = `sample-${sample .toString() .padStart(maxLength, '0')}`; for (const spec of specs) { bar.tick(0, { status: `${++run}/${numRuns} ${benchmarkOneLiner(spec)}`, }); this.recordSamples(spec, await this.takeSamples(spec, sampleLabel)); if (bar.curr === bar.total - 1) { // Note if we tick with 0 after we've completed, the status is // rendered on the next line for some reason. bar.tick(1, {status: 'done'}); } else { bar.tick(1); } } } } private async takeAdditionalSamples() { const {config, specs} = this; if (config.timeout <= 0) { return; } console.log(); const timeoutMs = config.timeout * 60 * 1000; // minutes -> millis const startMs = Date.now(); let run = 0; let sample = 0; let elapsed = 0; while (true) { if ( autoSampleConditionsResolved( this.makeResults(), config.autoSampleConditions ) ) { console.log(); break; } if (elapsed >= timeoutMs) { this.hitTimeout = true; break; } // Run batches of 10 additional samples at a time for more presentable // sample sizes, and to nudge sample sizes up a little. for (let i = 0; i < 10; i++) { sample++; for (const spec of specs) { run++; elapsed = Date.now() - startMs; const remainingSecs = Math.max( 0, Math.round((timeoutMs - elapsed) / 1000) ); const mins = Math.floor(remainingSecs / 60); const secs = remainingSecs % 60; process.stdout.write( `\r${spinner[run % spinner.length]} Auto-sample ${sample} ` + `(timeout in ${mins}m${secs}s)` + ansi.erase.inLine(0) ); const sampleLabel = `auto-sample-${sample .toString() .padStart(2, '0')}`; this.recordSamples(spec, await this.takeSamples(spec, sampleLabel)); } } } } private async takeSamples( spec: BenchmarkSpec, sampleLabel: string ): Promise<BenchmarkResult[]> { const {servers, config, browsers} = this; let server; if (spec.url.kind === 'local') { server = servers.get(spec); if (server === undefined) { throw new Error('Internal error: no server for spec'); } } const url = specUrl(spec, servers, config); const {driver, initialTabHandle} = browsers.get( browserSignature(spec.browser) )!; let session: Session; let pendingMeasurements; let measurementResults: number[]; // We'll try N attempts per page. Within each attempt, we'll try to collect // all of the measurements by polling. If we hit our per-attempt timeout // before collecting all measurements, we'll move onto the next attempt // where we reload the whole page and start from scratch. If we hit our max // attempts, we'll throw. for (let pageAttempt = 1; ; pageAttempt++) { // New attempt. Reset all measurements and results. pendingMeasurements = new Set(spec.measurement); measurementResults = []; await openAndSwitchToNewTab(driver, spec.browser); await driver.get(url); for ( let waited = 0; pendingMeasurements.size > 0 && waited <= this.attemptTimeout; waited += this.pollTime ) { // TODO(aomarks) You don't have to wait in callback mode! await wait(this.pollTime); for ( let measurementIndex = 0; measurementIndex < spec.measurement.length; measurementIndex++ ) { if (measurementResults[measurementIndex] !== undefined) { // Already collected this measurement on this attempt. continue; } const measurement = spec.measurement[measurementIndex]; const result = await measure(driver, measurement, server); if (result !== undefined) { measurementResults[measurementIndex] = result; pendingMeasurements.delete(measurement); } } } await this.capturePerfTraces(spec, driver, sampleLabel); // Close the active tab (but not the whole browser, since the // initial blank tab is still open). await driver.close(); await driver.switchTo().window(initialTabHandle); if (server !== undefined) { session = server.endSession(); } if (pendingMeasurements.size === 0 || pageAttempt >= this.maxAttempts) { break; } console.log( `\n\nFailed ${pageAttempt}/${this.maxAttempts} times ` + `to get measurement(s) ${spec.name}` + (spec.measurement.length > 1 ? ` [${[...pendingMeasurements].map(measurementName).join(', ')}]` : '') + ` in ${spec.browser.name} from ${url}. Retrying.` ); } if (pendingMeasurements.size > 0) { console.log(); throw new Error( `\n\nFailed ${this.maxAttempts}/${this.maxAttempts} times ` + `to get measurement(s) ${spec.name}` + (spec.measurement.length > 1 ? ` [${[...pendingMeasurements].map(measurementName).join(', ')}]` : '') + ` in ${spec.browser.name} from ${url}` ); } return spec.measurement.map((measurement, measurementIndex) => ({ name: spec.measurement.length === 1 ? spec.name : `${spec.name} [${measurementName(measurement)}]`, measurement, measurementIndex: measurementIndex, queryString: spec.url.kind === 'local' ? spec.url.queryString : '', version: spec.url.kind === 'local' && spec.url.version !== undefined ? spec.url.version.label : '', millis: [measurementResults[measurementIndex]], bytesSent: session ? session.bytesSent : 0, browser: spec.browser, userAgent: session ? session.userAgent : '', })); } async capturePerfTraces( spec: BenchmarkSpec, driver: webdriver.WebDriver, sampleLabel: string ) { if (spec.browser.trace === undefined) { return; } let perfEntries: webdriver.logging.Entry[] = []; let newPerfEntries: webdriver.logging.Entry[]; do { newPerfEntries = await driver.manage().logs().get('performance'); perfEntries = perfEntries.concat(newPerfEntries); } while (newPerfEntries.length > 0); const logDir = spec.browser.trace.logDir; await fsExtra.writeFile( pathlib.join(logDir, `log-${sampleLabel}.json`), // Convert perf logs into a format about:tracing can parse '[\n' + perfEntries .map((e) => JSON.parse(e.message).message) .filter((log) => log.method === 'Tracing.dataCollected') .map((log) => JSON.stringify(log.params)) .join(',\n') + '\n]', 'utf8' ); } makeResults() { const resultStats = []; for (const results of this.results.values()) { for (let r = 0; r < results.length; r++) { const result = results[r]; resultStats.push({result, stats: summaryStats(result.millis)}); } } return computeDifferences(resultStats); } private async outputResults(withDifferences: ResultStatsWithDifferences[]) { const {config, hitTimeout} = this; console.log(); const {fixed, unfixed} = automaticResultTable(withDifferences); console.log(horizontalTermResultTable(fixed)); console.log(verticalTermResultTable(unfixed)); if (hitTimeout === true) { console.log( ansi.format( `[bold red]{NOTE} Hit ${config.timeout} minute auto-sample timeout` + ` trying to resolve condition(s)` ) ); console.log( 'Consider a longer --timeout or different --auto-sample-conditions' ); } if (config.jsonFile) { const json = await jsonOutput(withDifferences); await fsExtra.writeJSON(config.jsonFile, json, {spaces: 2}); } // TOOD(aomarks) Remove this in next major version. if (config.legacyJsonFile) { const json = await legacyJsonOutput(withDifferences.map((s) => s.result)); await fsExtra.writeJSON(config.legacyJsonFile, json); } if (config.csvFileStats) { await fsExtra.writeFile( config.csvFileStats, formatCsvStats(withDifferences) ); } if (config.csvFileRaw) { await fsExtra.writeFile(config.csvFileRaw, formatCsvRaw(withDifferences)); } if (this.completeGithubCheck !== undefined) { const markdown = horizontalHtmlResultTable(fixed) + '\n' + verticalHtmlResultTable(unfixed); await this.completeGithubCheck(markdown); } } }
the_stack
import * as pulumi from "@pulumi/pulumi"; import * as arn from "../arn"; import * as iam from "../iam"; import * as utils from "../utils"; import { Function as LambdaFunction, FunctionArgs } from "./function"; import * as permission from "./permission"; import { Runtime } from "."; /** * Context is the shape of the context object passed to a Function callback. For more information, * see: https://docs.aws.amazon.com/lambda/latest/dg/nodejs-prog-model-context.html */ export interface Context { /** * The default value is true. This property is useful only to modify the default behavior of the * callback. By default, the callback will wait until the event loop is empty before freezing * the process and returning the results to the caller. You can set this property to false to * request AWS Lambda to freeze the process soon after the callback is called, even if there are * events in the event loop. AWS Lambda will freeze the process, any state data and the events * in the event loop (any remaining events in the event loop processed when the Lambda function * is called next and if AWS Lambda chooses to use the frozen process). */ callbackWaitsForEmptyEventLoop: boolean; /** * Name of the Lambda function that is executing. */ readonly functionName: string; /** * The Lambda function version that is executing. If an alias is used to invoke the function, * then function_version will be the version the alias points to. */ readonly functionVersion: string; /** * The ARN used to invoke this function. It can be a function ARN or an alias ARN. An * unqualified ARN executes the $LATEST version and aliases execute the function version it is * pointing to. */ readonly invokedFunctionArn: string; /** * Memory limit, in MB, you configured for the Lambda function. You set the memory limit at the * time you create a Lambda function and you can change it later. */ readonly memoryLimitInMB: string; /** * AWS request ID associated with the request. This is the ID returned to the client that called * the invoke method. * * If AWS Lambda retries the invocation (for example, in a situation where the Lambda function * that is processing Kinesis records throws an exception), the request ID remains the same. */ readonly awsRequestId: string; /** * The name of the CloudWatch log group where you can find logs written by your Lambda function. */ readonly logGroupName: string; /** * The name of the CloudWatch log group where you can find logs written by your Lambda function. * The log stream may or may not change for each invocation of the Lambda function. * * The value is null if your Lambda function is unable to create a log stream, which can happen * if the execution role that grants necessary permissions to the Lambda function does not * include permissions for the CloudWatch actions. */ readonly logStreamName: string; /** * Information about the Amazon Cognito identity provider when invoked through the AWS Mobile * SDK. It can be null. */ readonly identity: any; /** * Information about the client application and device when invoked through the AWS Mobile SDK. * It can be null. */ readonly clientContext: any; /** * Returns the approximate remaining execution time (before timeout occurs) of the Lambda * function that is currently executing. The timeout is one of the Lambda function * configuration. When the timeout reaches, AWS Lambda terminates your Lambda function. * * You can use this method to check the remaining time during your function execution and take * appropriate corrective action at run time. */ getRemainingTimeInMillis(): string; } /** * Callback is the signature for an AWS Lambda function entrypoint. * * [event] is the data passed in by specific services calling the Lambda (like s3, or kinesis). The * shape of it will be specific to individual services. * * [context] AWS Lambda uses this parameter to provide details of your Lambda function's execution. * For more information, see * https://docs.aws.amazon.com/lambda/latest/dg/nodejs-prog-model-context.html * * [callback] See https://docs.aws.amazon.com/lambda/latest/dg/nodejs-prog-model-handler.html#nodejs-prog-model-handler-callback * for details. * * This function can be synchronous or asynchronous function, though async is only supported with an * AWS Lambda runtime of 8.10 or higher. On those runtimes a Promise can be returned, 'callback' * parameter can be ignored, and AWS will appropriately handle things. For AWS lambda pre-8.10, a * synchronous function must be provided. The synchronous function should return nothing, and * should instead invoke 'callback' when complete. */ export type Callback<E, R> = (event: E, context: Context, callback: (error?: any, result?: R) => void) => Promise<R> | void; /** * CallbackFactory is the signature for a function that will be called once to produce the * entrypoint function that AWS Lambda will invoke. It can be used to initialize expensive state * once that can then be used across all invocations of the Lambda (as long as the Lambda is using * the same warm node instance). */ export type CallbackFactory<E, R> = () => Callback<E, R>; /** * An EventHandler is either a JavaScript callback or an aws.lambda.Function that can be used to * handle an event triggered by some resource. If just a JavaScript callback is provided the AWS * Lambda will be created by calling [createCallbackFunction] on it. If more control over the * resultant AWS Lambda is required, clients can call [createCallbackFunction] directly and pass the * result of that to any code that needs an EventHandler. */ export type EventHandler<E, R> = Callback<E, R> | LambdaFunction; /** * BaseCallbackFunctionArgs provides configuration options for the serverless Function. It is * effectively equivalent to [aws.lambda.FunctionArgs] except with a few important differences * documented at the property level. For example, [role] is an actual iam.Role instance, and not an * ARN. Properties like [runtime] are now optional. And some properties (like [code]) are entirely * disallowed. */ export type BaseCallbackFunctionArgs = utils.Overwrite<FunctionArgs, { /** * Not allowed when creating an aws.serverless.Function. The [code] will be generated from the * passed in JavaScript callback. */ code?: never; /** * Not allowed when creating an aws.serverless.Function. The [code] will be generated from the * passed in JavaScript callback. */ handler?: never; /** * A pre-created role to use for the Function. If not provided, [policies] will be used. */ role?: iam.Role; /** * A list of IAM policy ARNs to attach to the Function. Will be used if [role] is not provide. * If neither [role] nor [policies] is provided, a default policy of [iam.AWSLambda_FullAccess] * will be used instead. */ policies?: arn.ARN[]; /** * The Lambda runtime to use. If not provided, will default to [NodeJS8d10Runtime] */ runtime?: Runtime; /** * Options to control which paths/packages should be included or excluded in the zip file containing * the code for the AWS lambda. */ codePathOptions?: pulumi.runtime.CodePathOptions; }>; /** * CallbackFunctionArgs provides configuration options for the serverless Function. It is * effectively equivalent to [aws.lambda.FunctionArgs] except with a few important differences * documented at the property level. For example, [role] is an actual iam.Role instance, and not an * ARN. Properties like [runtime] are now optional. And some properties (like [code]) are entirely * disallowed. */ export interface CallbackFunctionArgs<E, R> extends BaseCallbackFunctionArgs { /** * The Javascript callback to use as the entrypoint for the AWS Lambda out of. Either * [callback] or [callbackFactory] must be provided. */ callback?: Callback<E, R>; /** * The Javascript function instance that will be called to produce the callback function that is * the entrypoint for the AWS Lambda. Either [callback] or [callbackFactory] must be * provided. * * This form is useful when there is expensive initialization work that should only be executed * once. The factory-function will be invoked once when the final AWS Lambda module is loaded. * It can run whatever code it needs, and will end by returning the actual function that Lambda * will call into each time the Lambda is invoked. */ callbackFactory?: CallbackFactory<E, R>; }; /** * Base type for all subscription types. An event subscription represents a connection between some * AWS resource and an AWS lambda that will be triggered when something happens to that resource. */ export class EventSubscription extends pulumi.ComponentResource { public permission!: permission.Permission; public func!: LambdaFunction; public constructor( type: string, name: string, opts?: pulumi.ComponentResourceOptions) { super(type, name, {}, opts); } } export function isEventHandler(obj: any): obj is EventHandler<any, any> { return LambdaFunction.isInstance(obj) || obj instanceof Function; } export function createFunctionFromEventHandler<E, R>( name: string, handler: EventHandler<E, R>, opts?: pulumi.ResourceOptions): LambdaFunction { if (handler instanceof Function) { return new CallbackFunction(name, { callback: handler }, opts); } else { return handler; } } /** * A CallbackFunction is a special type of aws.lambda.Function that can be created out of an actual * JavaScript function instance. The function instance will be analyzed and packaged up (including * dependencies) into a form that can be used by AWS Lambda. See * https://www.pulumi.com/docs/tutorials/aws/serializing-functions/ for additional * details on this process. * If no IAM Role is specified, CallbackFunction will automatically use the following managed policies: * `AWSLambda_FullAccess` * `CloudWatchFullAccess` * `CloudWatchEventsFullAccess` * `AmazonS3FullAccess` * `AmazonDynamoDBFullAccess` * `AmazonSQSFullAccess` * `AmazonKinesisFullAccess` * `AWSCloudFormationReadOnlyAccess` * `AmazonCognitoPowerUser` * `AWSXrayWriteOnlyAccess` */ export class CallbackFunction<E, R> extends LambdaFunction { public constructor(name: string, args: CallbackFunctionArgs<E, R>, opts: pulumi.CustomResourceOptions = {}) { if (!name) { throw new Error("Missing required resource name"); } if (args.callback && args.callbackFactory) { throw new pulumi.RunError("Cannot provide both [callback] and [callbackFactory]"); } const func = args.callback || args.callbackFactory; if (!func) { throw new Error("One of [callback] or [callbackFactory] must be provided."); } let role: iam.Role; if (args.role) { role = args.role; } else { // Attach a role and then, if there are policies, attach those too. role = new iam.Role(name, { assumeRolePolicy: JSON.stringify(lambdaRolePolicy), }, opts); if (!args.policies) { const policies = [iam.ManagedPolicy.LambdaFullAccess, iam.ManagedPolicy.CloudWatchFullAccess, iam.ManagedPolicy.CloudWatchEventsFullAccess, iam.ManagedPolicy.AmazonS3FullAccess, iam.ManagedPolicy.AmazonDynamoDBFullAccess, iam.ManagedPolicy.AmazonSQSFullAccess, iam.ManagedPolicy.AmazonKinesisFullAccess, iam.ManagedPolicy.AmazonCognitoPowerUser, iam.ManagedPolicy.AWSXrayWriteOnlyAccess, ] for (const policy of policies) { const attachment = new iam.RolePolicyAttachment(`${name}-${utils.sha1hash(policy)}`, { role: role, policyArn: policy, }, opts); } } if (args.policies) { for (const policy of args.policies) { // RolePolicyAttachment objects don't have a physical identity, and create/deletes are processed // structurally based on the `role` and `policyArn`. So we need to make sure our Pulumi name matches the // structural identity by using a name that includes the role name and policyArn. const attachment = new iam.RolePolicyAttachment(`${name}-${utils.sha1hash(policy)}`, { role: role, policyArn: policy, }, opts); } } } // Now compile the function text into an asset we can use to create the lambda. Note: to // prevent a circularity/deadlock, we list this Function object as something that the // serialized closure cannot reference. const handlerName = "handler"; const serializedFileNameNoExtension = "__index"; const closure = pulumi.runtime.serializeFunction(func, { serialize: _ => true, exportName: handlerName, isFactoryFunction: !!args.callbackFactory, allowSecrets: true, }); const codePaths = computeCodePaths( closure, serializedFileNameNoExtension, args.codePathOptions); const code = pulumi.output(new pulumi.asset.AssetArchive(codePaths)); (<any>code).isSecret = closure.then(c => c.containsSecrets); // Copy over all option values into the function args. Then overwrite anything we care // about with our own values. This ensures that clients can pass future supported // lambda options without us having to know about it. const functionArgs = { ...args, code: code, handler: serializedFileNameNoExtension + "." + handlerName, runtime: args.runtime || Runtime.NodeJS12dX, role: role.arn, timeout: args.timeout === undefined ? 180 : args.timeout, }; // If there is no custom Runtime argument being passed to the user // then we should add "runtime" to the ignoreChanges of the CustomResourceOptions // This is because as of 12/16/19, we upgraded the default NodeJS version from 8.x to 12.x as 12.x is latest LTS // We don't want to force recreation of user defined Lambdas because of this change if (!args.runtime) { pulumi.mergeOptions(opts, { ignoreChanges: ["runtime"] }) } super(name, functionArgs, opts); this.roleInstance = role; } } // computeCodePaths calculates an AssetMap of files to include in the Lambda package. async function computeCodePaths( closure: Promise<pulumi.runtime.SerializedFunction>, serializedFileNameNoExtension: string, codePathOptions: pulumi.runtime.CodePathOptions | undefined): Promise<pulumi.asset.AssetMap> { const serializedFunction = await closure; // Construct the set of paths to include in the archive for upload. let codePaths: pulumi.asset.AssetMap = { // Always include the serialized function. [serializedFileNameNoExtension + ".js"]: new pulumi.asset.StringAsset(serializedFunction.text), }; // AWS Lambda always provides `aws-sdk`, so skip this. Do this before processing user-provided // extraIncludePackages so that users can force aws-sdk to be included (if they need a specific // version). codePathOptions = codePathOptions || {}; codePathOptions.extraExcludePackages = codePathOptions.extraExcludePackages || []; codePathOptions.extraExcludePackages.push("aws-sdk"); const modulePaths = await pulumi.runtime.computeCodePaths(codePathOptions); for (const [path, asset] of modulePaths) { codePaths[path] = asset; } return codePaths; } const lambdaRolePolicy = { "Version": "2012-10-17", "Statement": [ { "Action": "sts:AssumeRole", "Principal": { "Service": "lambda.amazonaws.com", }, "Effect": "Allow", "Sid": "", }, ], }; // Mixin the Role we potentially create into the Function instances we return. declare module "./function" { interface Function { /** * Actual Role instance value for this Function. Will only be set if this function was * created from [createFunction] */ roleInstance?: iam.Role; } }
the_stack
import { Injectable } from '@angular/core'; import { Observable } from 'rxjs/Observable'; import { HttpClient, HttpHeaders, HttpParams, HttpErrorResponse } from '@angular/common/http'; import { CognitoUtil } from './cognito.service'; import { Device } from '../model/device'; import { DeviceType } from '../model/deviceType'; import { WidgetRequest } from '../model/widgetRequest'; import { LoggerService } from './logger.service'; import 'rxjs/add/operator/map'; import 'rxjs/add/operator/catch'; import 'rxjs/add/observable/throw'; import 'rxjs/add/operator/toPromise'; import * as _ from 'underscore'; declare var appVariables: any; @Injectable() export class DeviceService { constructor(private http: HttpClient, private cognito: CognitoUtil, private logger: LoggerService) { } public getAllDevices(page: number, filter: any) { const _self = this; const promise = new Promise((resolve, reject) => { this.cognito.getIdToken({ callback() { }, callbackWithParam(token: any) { _self.logger.info(token); let pg = 0; if (page) { pg = page; } let path = `widgets?page=${pg}&op=list`; if (filter) { path = `${path}&filter=${encodeURI(JSON.stringify(filter))}`; } console.log(path); _self.http .get<any>([appVariables.APIG_ENDPOINT, 'devices', path].join('/'), { headers: new HttpHeaders().set('Authorization', token) }) .toPromise() .then((data: any) => { let devices: Device[] = []; devices = data.map((device) => new Device(device)); resolve(devices); }, (err: HttpErrorResponse) => { if (err.error instanceof Error) { // A client-side or network error occurred. _self.logger.error('An error occurred:', err.error.message); } else { // The backend returned an unsuccessful response code. // The response body may contain clues as to what went wrong, _self.logger.error(`Backend returned code ${err.status}, body was: ${err.error}`); } reject(err); } ); } }); }); return promise; } public getDeviceStats(filter: any, op: string = 'stats') { const _self = this; const promise = new Promise((resolve, reject) => { let path = `widgets?op=${op}`; if (filter) { path = `${path}&filter=${encodeURI(JSON.stringify(filter))}`; } this.cognito.getIdToken({ callback() { }, callbackWithParam(token: any) { _self.http .get<any>([appVariables.APIG_ENDPOINT, 'devices', path].join('/'), { headers: new HttpHeaders().set('Authorization', token) }) .toPromise() .then((data: any) => { if (op === 'stats') { data.simulations = data.hydrated; } resolve(data); }, (err: HttpErrorResponse) => { if (err.error instanceof Error) { // A client-side or network error occurred. _self.logger.error('An error occurred:', err.error.message); } else { // The backend returned an unsuccessful response code. // The response body may contain clues as to what went wrong, _self.logger.error(`Backend returned code ${err.status}, body was: ${err.error}`); } reject(err); }); } }); }); return promise; } public getDevice(id: string) { const _self = this; const promise = new Promise((resolve, reject) => { this.cognito.getIdToken({ callback() { }, callbackWithParam(token: any) { _self.logger.info(token); const path = `widgets/${id}`; _self.http .get<any>([appVariables.APIG_ENDPOINT, 'devices', path].join('/'), { headers: new HttpHeaders().set('Authorization', token) }) .toPromise() .then((data: any) => { const device = new Device(data); resolve(device); }, (err: HttpErrorResponse) => { if (err.error instanceof Error) { // A client-side or network error occurred. _self.logger.error('An error occurred:', err.error.message); } else { // The backend returned an unsuccessful response code. // The response body may contain clues as to what went wrong, _self.logger.error(`Backend returned code ${err.status}, body was: ${err.error}`); } reject(err); } ); } }); }); return promise; } public bulkUpdateDevices(devices: Device[]) { const _self = this; const promise = new Promise((resolve, reject) => { const path = `widgets`; this.cognito.getIdToken({ callback() { }, callbackWithParam(token: any) { _self.http .put<any>([appVariables.APIG_ENDPOINT, 'devices', path].join('/'), devices, { headers: new HttpHeaders().set('Authorization', token) }) .toPromise() .then((data: any) => { resolve(data); }, (err: HttpErrorResponse) => { if (err.error instanceof Error) { // A client-side or network error occurred. _self.logger.error('An error occurred:', err.error.message); } else { // The backend returned an unsuccessful response code. // The response body may contain clues as to what went wrong, _self.logger.error(`Backend returned code ${err.status}, body was: ${err.error}`); } reject(err); }); } }); }); return promise; } public updateDevice(device: Device) { const _self = this; const promise = new Promise((resolve, reject) => { const path = `widgets/${device.id}`; this.cognito.getIdToken({ callback() { }, callbackWithParam(token: any) { _self.http .put<any>([appVariables.APIG_ENDPOINT, 'devices', path].join('/'), device, { headers: new HttpHeaders().set('Authorization', token) }) .toPromise() .then((data: any) => { resolve(data); }, (err: HttpErrorResponse) => { if (err.error instanceof Error) { // A client-side or network error occurred. _self.logger.error('An error occurred:', err.error.message); } else { // The backend returned an unsuccessful response code. // The response body may contain clues as to what went wrong, _self.logger.error(`Backend returned code ${err.status}, body was: ${err.error}`); } reject(err); }); } }); }); return promise; } public deleteDevice(deviceId: string) { const _self = this; const promise = new Promise((resolve, reject) => { const path = `widgets/${deviceId}`; this.cognito.getIdToken({ callback() { }, callbackWithParam(token: any) { _self.http .delete<any>([appVariables.APIG_ENDPOINT, 'devices', path].join('/'), { headers: new HttpHeaders().set('Authorization', token) }) .toPromise() .then((data: any) => { resolve(data); }, (err: HttpErrorResponse) => { if (err.error instanceof Error) { // A client-side or network error occurred. _self.logger.error('An error occurred:', err.error.message); } else { // The backend returned an unsuccessful response code. // The response body may contain clues as to what went wrong, _self.logger.error(`Backend returned code ${err.status}, body was: ${err.error}`); } reject(err); }); } }); }); return promise; } public createDevice(widget: WidgetRequest) { const _self = this; const promise = new Promise((resolve, reject) => { this.cognito.getIdToken({ callback() { }, callbackWithParam(token: any) { _self.logger.info(token); _self.http .post<any>([appVariables.APIG_ENDPOINT, 'devices', 'widgets'].join('/'), { typeId: widget.typeId, metadata: widget.metadata, count: widget.count }, { headers: new HttpHeaders().set('Authorization', token) }) .toPromise() .then((data: any) => { let device = new Device(data); resolve(device); }, (err: HttpErrorResponse) => { if (err.error instanceof Error) { // A client-side or network error occurred. _self.logger.error('An error occurred:', err.error.message); } else { // The backend returned an unsuccessful response code. // The response body may contain clues as to what went wrong, _self.logger.error(`Backend returned code ${err.status}, body was: ${err.error}`); } reject(err); } ); } }); }); return promise; } public getDeviceTypeStats() { const _self = this; const promise = new Promise((resolve, reject) => { const path = 'types?op=stats'; this.cognito.getIdToken({ callback() { }, callbackWithParam(token: any) { _self.http .get<any>([appVariables.APIG_ENDPOINT, 'devices', path].join('/'), { headers: new HttpHeaders().set('Authorization', token) }) .toPromise() .then((data: any) => { _self.logger.info(data); resolve(data); }, (err: HttpErrorResponse) => { if (err.error instanceof Error) { // A client-side or network error occurred. _self.logger.error('An error occurred:', err.error.message); } else { // The backend returned an unsuccessful response code. // The response body may contain clues as to what went wrong, _self.logger.error(`Backend returned code ${err.status}, body was: ${err.error}`); } reject(err); }); } }); }); return promise; } public getDeviceTypes(page: number) { const _self = this; const promise = new Promise((resolve, reject) => { this.cognito.getIdToken({ callback() { }, callbackWithParam(token: any) { _self.logger.info(token); let pg = 0; if (page) { pg = page; } const path = `types?page=${pg}&op=list`; _self.http .get<any>([appVariables.APIG_ENDPOINT, 'devices', path].join('/'), { headers: new HttpHeaders().set('Authorization', token) }) .toPromise() .then((data: any) => { let deviceTypes: DeviceType[] = []; deviceTypes = data.map((type) => new DeviceType(type)); resolve(deviceTypes); }, (err: HttpErrorResponse) => { if (err.error instanceof Error) { // A client-side or network error occurred. _self.logger.error('An error occurred:', err.error.message); } else { // The backend returned an unsuccessful response code. // The response body may contain clues as to what went wrong, _self.logger.error(`Backend returned code ${err.status}, body was: ${err.error}`); } reject(err); } ); } }); }); return promise; } public getDeviceType(id: string) { const _self = this; const promise = new Promise((resolve, reject) => { this.cognito.getIdToken({ callback() { }, callbackWithParam(token: any) { _self.logger.info(token); const path = `types/${id}`; _self.http .get<any>([appVariables.APIG_ENDPOINT, 'devices', path].join('/'), { headers: new HttpHeaders().set('Authorization', token) }) .toPromise() .then((data: any) => { const deviceType = new DeviceType(data); resolve(deviceType); }, (err: HttpErrorResponse) => { if (err.error instanceof Error) { // A client-side or network error occurred. _self.logger.error('An error occurred:', err.error.message); } else { // The backend returned an unsuccessful response code. // The response body may contain clues as to what went wrong, _self.logger.error(`Backend returned code ${err.status}, body was: ${err.error}`); } reject(err); } ); } }); }); return promise; } public updateDeviceType(type: DeviceType) { const _self = this; const promise = new Promise((resolve, reject) => { const path = `types/${type.typeId}`; this.cognito.getIdToken({ callback() { }, callbackWithParam(token: any) { _self.http .put<any>([appVariables.APIG_ENDPOINT, 'devices', path].join('/'), type, { headers: new HttpHeaders().set('Authorization', token) }) .toPromise() .then((data: any) => { _self.logger.info(data); resolve(data); }, (err: HttpErrorResponse) => { if (err.error instanceof Error) { // A client-side or network error occurred. _self.logger.error('An error occurred:', err.error.message); } else { // The backend returned an unsuccessful response code. // The response body may contain clues as to what went wrong, _self.logger.error(`Backend returned code ${err.status}, body was: ${err.error}`); } reject(err); }); } }); }); return promise; } public createDeviceType(dtype: DeviceType) { const _self = this; const promise = new Promise((resolve, reject) => { this.cognito.getIdToken({ callback() { }, callbackWithParam(token: any) { _self.logger.info(token); let payload = { spec: dtype.spec, name: dtype.name, custom: dtype.custom, visibility: dtype.visibility }; if (_.has(dtype, 'typeId')) { if (dtype.typeId !== 'new') { payload['typeId'] = dtype.typeId; } } _self.http .post<any>([appVariables.APIG_ENDPOINT, 'devices', 'types'].join('/'), payload, { headers: new HttpHeaders().set('Authorization', token) }) .toPromise() .then((data: any) => { let type = new DeviceType(data); resolve(type); }, (err: HttpErrorResponse) => { if (err.error instanceof Error) { // A client-side or network error occurred. _self.logger.error('An error occurred:', err.error.message); } else { // The backend returned an unsuccessful response code. // The response body may contain clues as to what went wrong, _self.logger.error(`Backend returned code ${err.status}, body was: ${err.error}`); } reject(err); } ); } }); }); return promise; } public getNextRouteStep(route: string, step: number) { const _self = this; const promise = new Promise((resolve, reject) => { _self.http .get<any>('/assets/routes.json', {}) .toPromise() .then( data => { resolve(data[route][step]); }, (err: HttpErrorResponse) => { if (err.error instanceof Error) { // A client-side or network error occurred. _self.logger.error('An error occurred:', err.error.message); } else { // The backend returned an unsuccessful response code. // The response body may contain clues as to what went wrong, _self.logger.error(`Backend returned code ${err.status}, body was: ${err.error}`); } reject(err); } ); }); return promise; } }
the_stack
import * as sinon from "sinon"; import {MockPdfDocument} from "../contentCapture/mockPdfDocument"; import {Constants} from "../../scripts/constants"; import {Clipper} from "../../scripts/clipperUI/frontEndGlobals"; import {StubSessionLogger} from "../../scripts/logging/stubSessionLogger"; import {SaveToOneNote} from "../../scripts/saveToOneNote/saveToOneNote"; import {OneNoteSaveablePage} from "../../scripts/saveToOneNote/oneNoteSaveablePage"; import {OneNoteSaveablePdf} from "../../scripts/saveToOneNote/oneNoteSaveablePdf"; import {OneNoteSaveablePdfSynchronousBatched} from "../../scripts/saveToOneNote/oneNoteSaveablePdfSynchronousBatched"; import {ClipperStorageKeys} from "../../scripts/storage/clipperStorageKeys"; import {AsyncUtils} from "../asyncUtils"; import {TestModule} from "../testModule"; export class SaveToOneNoteTests extends TestModule { private server: sinon.SinonFakeServer; private saveToOneNote: SaveToOneNote; protected module() { return "saveToOneNote"; } protected beforeEach() { AsyncUtils.mockSetTimeout(); this.server = sinon.fakeServer.create(); this.server.respondImmediately = true; this.saveToOneNote = new SaveToOneNote("userToken"); } protected afterEach() { AsyncUtils.restoreSetTimeout(); this.server.restore(); } protected tests() { test("When saving a 'just a page', save() should resolve with the parsed response and request in a responsePackage if the API call succeeds", (assert: QUnitAssert) => { let done = assert.async(); let saveLocation = "sectionId"; let responseJson = { key: "value" }; this.server.respondWith( "POST", "https://www.onenote.com/api/v1.0/me/notes/sections/" + saveLocation + "/pages", [200, { "Content-Type": "application/json" }, JSON.stringify(responseJson) ]); this.saveToOneNote.save({ page: this.getMockSaveablePage(), saveLocation: saveLocation }).then((responsePackage) => { deepEqual(responsePackage.parsedResponse, responseJson, "The parsedResponse field should be the response in json form"); ok(responsePackage.request, "The request field should be defined"); }, (error) => { ok(false, "reject should not be called"); }).then(() => { done(); }); }); test("When saving a 'just a page', save() should resolve with the parsed response and request in a responsePackage if the API call succeeds and no saveLocation is specified", (assert: QUnitAssert) => { let done = assert.async(); let responseJson = { key: "value" }; this.server.respondWith( "POST", "https://www.onenote.com/api/v1.0/me/notes/pages", [200, { "Content-Type": "application/json" }, JSON.stringify(responseJson) ]); this.saveToOneNote.save({ page: this.getMockSaveablePage() }).then((responsePackage) => { deepEqual(responsePackage.parsedResponse, responseJson, "The parsedResponse field should be the response in json form"); ok(responsePackage.request, "The request field should be defined"); }, (error) => { ok(false, "reject should not be called"); }).then(() => { done(); }); }); test("When saving a 'just a page', but the this.server returns an unexpected response code, reject should be called with the error object", (assert: QUnitAssert) => { let done = assert.async(); let responseJson = { key: "value" }; this.server.respondWith( "POST", "https://www.onenote.com/api/v1.0/me/notes/pages", [404, { "Content-Type": "application/json" }, JSON.stringify(responseJson) ]); this.saveToOneNote.save({ page: this.getMockSaveablePage() }).then((responsePackage) => { ok(false, "resolve should not be called"); }, (error) => { deepEqual(error, { error: "Unexpected response status", statusCode: 404, responseHeaders: { "Content-Type": "application/json" }, response: JSON.stringify(responseJson), timeout: 30000 }, "The error object should be returned in the reject"); }).then(() => { done(); }); }); // From this point, we now test cases where we hit multiple endpoints. For this to work, we need to declare the fakeServer // responses before the this.saveToOneNote call otherwise the fakeServer will respond with 404 test("When saving a pdf, save() should resolve with the parsed response and request in a responsePackage assuming the patch permissions call succeeds", (assert: QUnitAssert) => { let done = assert.async(); let saveLocation = "mySection"; let pageId = "abc"; let createPageJson = { id: pageId }; // Request patch permissions this.server.respondWith( "GET", "https://www.onenote.com/api/v1.0/me/notes/sections/" + saveLocation + "/pages?top=1", [200, { "Content-Type": "application/json" }, JSON.stringify({ getPages: "getPages" }) ]); // Create initial page this.server.respondWith( "POST", "https://www.onenote.com/api/v1.0/me/notes/sections/" + saveLocation + "/pages", [200, { "Content-Type": "application/json" }, JSON.stringify(createPageJson) ]); // Check that page exists before patching this.server.respondWith( "GET", "https://www.onenote.com/api/v1.0/me/notes/pages/" + pageId + "/content", [200, { "Content-Type": "application/json" }, JSON.stringify({ getPage: "getPage" }) ]); // Patch to the page this.server.respondWith( "PATCH", "https://www.onenote.com/api/v1.0/me/notes/pages/" + pageId + "/content", [200, { "Content-Type": "application/json" }, JSON.stringify({ updatePage: "updatePage" }) ]); this.saveToOneNote.save({ page: this.getMockSaveablePdf([0, 1]), saveLocation: saveLocation }).then((responsePackage) => { deepEqual(responsePackage.parsedResponse, createPageJson, "The parsedResponse field should be the create page response in json form"); ok(responsePackage.request, "The request field should be defined"); }, (error) => { ok(false, "reject should not be called"); }).then(() => { done(); }); }); test("When saving a pdf to the default location, save() should resolve with the parsed response and request in a responsePackage assuming the patch permissions call succeeds", (assert: QUnitAssert) => { let done = assert.async(); let pageId = "abc"; let createPageJson = { id: pageId }; // Request patch permissions this.server.respondWith( "GET", "https://www.onenote.com/api/v1.0/me/notes/pages?top=1", [200, { "Content-Type": "application/json" }, JSON.stringify({ getPages: "getPages" }) ]); // Create initial page this.server.respondWith( "POST", "https://www.onenote.com/api/v1.0/me/notes/pages", [200, { "Content-Type": "application/json" }, JSON.stringify(createPageJson) ]); // Check that page exists before patching this.server.respondWith( "GET", "https://www.onenote.com/api/v1.0/me/notes/pages/" + pageId + "/content", [200, { "Content-Type": "application/json" }, JSON.stringify({ getPage: "getPage" }) ]); // Patch to the page this.server.respondWith( "PATCH", "https://www.onenote.com/api/v1.0/me/notes/pages/" + pageId + "/content", [200, { "Content-Type": "application/json" }, JSON.stringify({ updatePage: "updatePage" }) ]); this.saveToOneNote.save({ page: this.getMockSaveablePdf([0, 1]) }).then((responsePackage) => { deepEqual(responsePackage.parsedResponse, createPageJson, "The parsedResponse field should be the create page response in json form"); ok(responsePackage.request, "The request field should be defined"); }, (error) => { ok(false, "reject should not be called"); }).then(() => { done(); }); }); test("When saving a pdf, save() should resolve with the parsed response and request in a responsePackage assuming the patch permission validity has been cached in localStorage", (assert: QUnitAssert) => { let done = assert.async(); Clipper.storeValue(ClipperStorageKeys.hasPatchPermissions, "true"); let pageId = "abc"; let createPageJson = { id: pageId }; // Create initial page this.server.respondWith( "POST", "https://www.onenote.com/api/v1.0/me/notes/pages", [200, { "Content-Type": "application/json" }, JSON.stringify(createPageJson) ]); // Check that page exists before patching this.server.respondWith( "GET", "https://www.onenote.com/api/v1.0/me/notes/pages/" + pageId + "/content", [200, { "Content-Type": "application/json" }, JSON.stringify({ getPage: "getPage" }) ]); // Update page with pdf pages this.server.respondWith( "PATCH", "https://www.onenote.com/api/v1.0/me/notes/pages/" + pageId + "/content", [200, { "Content-Type": "application/json" }, JSON.stringify({ updatePage: "updatePage" }) ]); this.saveToOneNote.save({ page: this.getMockSaveablePdf([0, 1]) }).then((responsePackage) => { deepEqual(responsePackage.parsedResponse, createPageJson, "The parsedResponse field should be the create page response in json form"); ok(responsePackage.request, "The request field should be defined"); }, (error) => { ok(false, "reject should not be called"); }).then(() => { done(); }); }); test("When saving a single page pdf in BATCH mode, save() should resolve with the first createPage response and request in a responsePackage, assuming all createPages succeeded", (assert: QUnitAssert) => { // Create initialPage let done = assert.async(); let saveLocation = "mySection"; let pageId = "abc"; let createPageJson = { id: pageId }; // Create initial page this.server.respondWith( "POST", "https://www.onenote.com/api/v1.0/me/notes/sections/" + saveLocation + "/pages", [200, { "Content-Type": "application/json" }, JSON.stringify(createPageJson) ]); this.saveToOneNote.save({ page: this.getMockSaveablePdfSynchronousBatch([]), saveLocation: saveLocation }).then((responsePackage) => { deepEqual(responsePackage.parsedResponse, createPageJson, "The parsedResponse field should be the create page response in json form"); ok(responsePackage.request, "The request field should be defined"); strictEqual(this.server.requests.length, 1, "A 1-page PDF that is distributing pages should make exactly 1 call to the API"); }, (error) => { ok(false, "reject should not be called: " + error); }).then(() => { done(); }); }); test("When saving a single page pdf in BATCH mode, save() should resolve with the first createPage response and request in a responsePackage, assuming all createPages succeeded and no saveLocation is specified", (assert: QUnitAssert) => { let done = assert.async(); let pageId = "abc"; let createPageJsonOne = { id: pageId }; // Create initial page this.server.respondWith( "POST", "https://www.onenote.com/api/v1.0/me/notes/pages", [200, { "Content-Type": "application/json" }, JSON.stringify(createPageJsonOne) ]); this.saveToOneNote.save({ page: this.getMockSaveablePdfSynchronousBatch([]) }).then((responsePackage) => { deepEqual(responsePackage.parsedResponse, createPageJsonOne, "The parsedResponse field should be the create page response in json form of the first createPage request"); ok(responsePackage.request, "The request field should be defined"); }, (error) => { ok(false, "reject should not be called"); }).then(() => { done(); }); }); test("When saving a multi-page pdf in BATCH mode, save() should resolve with the first createPage response and request in a responsePackage, assuming all createPages succeeded", (assert: QUnitAssert) => { let done = assert.async(); let saveLocation = "mySection"; let pageId = "abc"; let createPageJsonOne = { id: pageId }; let pageIdTwo = "def"; let createPageJsonTwo = { id: pageIdTwo }; let responses = [createPageJsonOne, createPageJsonTwo]; const responseClass = new class { private responses = responses; private count = 0; respond = (request) => { const response = this.responses[this.count]; this.count++; request.respond(201, { "Content-Type": "application/json" }, JSON.stringify(response)); } }; // Create initial page this.server.respondWith( "POST", "https://www.onenote.com/api/v1.0/me/notes/sections/" + saveLocation + "/pages", responseClass.respond ); this.saveToOneNote.save({ page: this.getMockSaveablePdfSynchronousBatch([1]), saveLocation: saveLocation }).then((responsePackage) => { deepEqual(responsePackage.parsedResponse, createPageJsonOne, "The parsedResponse field should be the create page response in json form of the first createPage request"); ok(responsePackage.request, "The request field should be defined"); strictEqual(this.server.requests.length, 2, "A 2-page PDF that is distributing pages should make exactly 2 calls to the API"); }, (error) => { ok(false, "reject should not be called"); }).then(() => { done(); }); }); test("When saving a multi-page pdf in BATCH mode, save() should resolve with the first createPage response and request in a responsePackage, assuming all createPages succeeded and no saveLocation is specified", (assert: QUnitAssert) => { let done = assert.async(); let pageId = "abc"; let createPageJsonOne = { id: pageId }; let pageIdTwo = "def"; let createPageJsonTwo = { id: pageIdTwo }; let responses = [createPageJsonOne, createPageJsonTwo]; const responseClass = new class { private responses = responses; private count = 0; respond = (request) => { const response = this.responses[this.count]; this.count++; request.respond(201, { "Content-Type": "application/json" }, JSON.stringify(response)); } }; // Create initial page this.server.respondWith( "POST", "https://www.onenote.com/api/v1.0/me/notes/pages", responseClass.respond ); this.saveToOneNote.save({ page: this.getMockSaveablePdfSynchronousBatch([1]) }).then((responsePackage) => { deepEqual(responsePackage.parsedResponse, createPageJsonOne, "The parsedResponse field should be the create page response in json form of the first createPage request"); ok(responsePackage.request, "The request field should be defined"); strictEqual(this.server.requests.length, 2, "A 2-page PDF that is distributing pages should make exactly 2 calls to the API"); }, (error) => { ok(false, "reject should not be called"); }).then(() => { done(); }); }); test("When saving a pdf that is distribued over many pages, if the first page creation fails, reject should be called with the error object", (assert: QUnitAssert) => { let done = assert.async(); let responseJson = { key: "value" }; this.server.respondWith( "POST", "https://www.onenote.com/api/v1.0/me/notes/pages", [404, { "Content-Type": "application/json" }, JSON.stringify(responseJson)] ); this.saveToOneNote.save({ page: this.getMockSaveablePdfSynchronousBatch([1]) }).then((responsePackage) => { ok(false, "resolve should not be called"); }, (error) => { deepEqual(error, { error: "Unexpected response status", statusCode: 404, responseHeaders: { "Content-Type": "application/json" }, response: JSON.stringify(responseJson), timeout: 30000 }, "The error object should be returned in the reject"); }).then(() => { done(); }); }); test("When saving a pdf that is distributed over many pages, if any of the createPage calls fail, the call should still resolve", (assert: QUnitAssert) => { let done = assert.async(); let pageId1 = "abc"; let createPageJson1 = { id: pageId1 }; let pageId2 = "def"; let createPageJson2 = { id: pageId2 }; let errorResponse = { key: "value" }; let pageId3 = "ghi"; let createPageJson3 = { id: pageId3 }; let headers = { "Content-Type": "application/json" }; let responses = [ { statusCode: 201, headers: headers, body: JSON.stringify(createPageJson1) }, { statusCode: 201, headers: headers, body: JSON.stringify(createPageJson2) }, { statusCode: 404, headers: headers, body: JSON.stringify(errorResponse) }, { statusCode: 201, headers: headers, body: JSON.stringify(createPageJson3) } ]; const responseClass = new class { private responses = responses; private count = 0; respond = (request) => { const response = this.responses[this.count]; this.count++; request.respond(response.statusCode, response.headers, response.body); } }; // Initial create page this.server.respondWith( "POST", "https://www.onenote.com/api/v1.0/me/notes/pages", responseClass.respond ); this.saveToOneNote.save({ page: this.getMockSaveablePdfSynchronousBatch([1]) }).then((responsePackage) => { deepEqual(responsePackage.parsedResponse, createPageJson1, "The parsedResponse field should be the create page response in json form of the first createPage request"); ok(responsePackage.request, "The request field should be defined"); }, (error) => { ok(false, "reject should not be called"); }).then(() => { done(); }); }); test("When saving a pdf and a PATCH permission check is needed, but that check returns an unexpected response code, reject should be called with the error object", (assert: QUnitAssert) => { let done = assert.async(); let responseJson = { getPages: "getPages" }; // Request patch permissions this.server.respondWith( "GET", "https://www.onenote.com/api/v1.0/me/notes/pages?top=1", [404, { "Content-Type": "application/json" }, JSON.stringify(responseJson) ]); this.saveToOneNote.save({ page: this.getMockSaveablePdf([0, 1]) }).then((responsePackage) => { ok(false, "resolve should not be called"); }, (error) => { deepEqual(error, { error: "Unexpected response status", statusCode: 404, responseHeaders: { "Content-Type": "application/json" }, response: JSON.stringify(responseJson), timeout: 30000 }, "The error object should be returned in the reject"); }).then(() => { done(); }); }); test("When saving a pdf, if the page creation fails, reject should be called with the error object", (assert: QUnitAssert) => { let done = assert.async(); Clipper.storeValue(ClipperStorageKeys.hasPatchPermissions, "true"); let responseJson = { getPages: "getPages" }; // Create initial page this.server.respondWith( "POST", "https://www.onenote.com/api/v1.0/me/notes/pages", [404, { "Content-Type": "application/json" }, JSON.stringify(responseJson) ]); this.saveToOneNote.save({ page: this.getMockSaveablePdf([0, 1]) }).then((responsePackage) => { ok(false, "resolve should not be called"); }, (error) => { deepEqual(error, { error: "Unexpected response status", statusCode: 404, responseHeaders: { "Content-Type": "application/json" }, response: JSON.stringify(responseJson), timeout: 30000 }, "The error object should be returned in the reject"); }).then(() => { done(); }); }); test("When saving a pdf, if the check for page existence fails, reject should be called with the error object", (assert: QUnitAssert) => { let done = assert.async(); Clipper.storeValue(ClipperStorageKeys.hasPatchPermissions, "true"); let pageId = "abc"; let createPageJson = { id: pageId }; let responseJson = { getPages: "getPages" }; // Create initial page this.server.respondWith( "POST", "https://www.onenote.com/api/v1.0/me/notes/pages", [200, { "Content-Type": "application/json" }, JSON.stringify(createPageJson) ]); // Check that page exists before patching this.server.respondWith( "GET", "https://www.onenote.com/api/v1.0/me/notes/pages/" + pageId + "/content", [404, { "Content-Type": "application/json" }, JSON.stringify(responseJson) ]); this.saveToOneNote.save({ page: this.getMockSaveablePdf([0, 1]) }).then((responsePackage) => { ok(false, "resolve should not be called"); }, (error) => { deepEqual(error, { error: "Unexpected response status", statusCode: 404, responseHeaders: { "Content-Type": "application/json" }, response: JSON.stringify(responseJson), timeout: 30000 }, "The error object should be returned in the reject"); }).then(() => { done(); }); }); test("When saving a pdf, if the PATCH call fails, reject should be called with the error object", (assert: QUnitAssert) => { let done = assert.async(); Clipper.storeValue(ClipperStorageKeys.hasPatchPermissions, "true"); let pageId = "abc"; let createPageJson = { id: pageId }; let responseJson = { getPages: "getPages" }; // Create initial page this.server.respondWith( "POST", "https://www.onenote.com/api/v1.0/me/notes/pages", [200, { "Content-Type": "application/json" }, JSON.stringify(createPageJson) ]); // Check that page exists before patching this.server.respondWith( "GET", "https://www.onenote.com/api/v1.0/me/notes/pages/" + pageId + "/content", [200, { "Content-Type": "application/json" }, JSON.stringify({ getPage: "getPage" }) ]); // Update page with pdf pages this.server.respondWith( "PATCH", "https://www.onenote.com/api/v1.0/me/notes/pages/" + pageId + "/content", [404, { "Content-Type": "application/json" }, JSON.stringify(responseJson) ]); this.saveToOneNote.save({ page: this.getMockSaveablePdf([0, 1]) }).then((responsePackage) => { ok(false, "resolve should not be called"); }, (error) => { deepEqual(error, { error: "Unexpected response status", statusCode: 404, responseHeaders: { "Content-Type": "application/json" }, response: JSON.stringify(responseJson), timeout: 30000 }, "The error object should be returned in the reject"); }).then(() => { done(); }); }); test("When saving a pdf and a save location is specified, if the PATCH call fails, reject should be called with the error object", (assert: QUnitAssert) => { let done = assert.async(); Clipper.storeValue(ClipperStorageKeys.hasPatchPermissions, "true"); let saveLocation = "sectionId"; let pageId = "abc"; let createPageJson = { id: pageId }; let responseJson = { getPages: "getPages" }; // Create initial page this.server.respondWith( "POST", "https://www.onenote.com/api/v1.0/me/notes/sections/" + saveLocation + "/pages", [200, { "Content-Type": "application/json" }, JSON.stringify(createPageJson) ]); // Check that page exists before patching this.server.respondWith( "GET", "https://www.onenote.com/api/v1.0/me/notes/pages/" + pageId + "/content", [200, { "Content-Type": "application/json" }, JSON.stringify({ getPage: "getPage" }) ]); // Update page with pdf pages this.server.respondWith( "PATCH", "https://www.onenote.com/api/v1.0/me/notes/pages/" + pageId + "/content", [404, { "Content-Type": "application/json" }, JSON.stringify(responseJson) ]); this.saveToOneNote.save({ page: this.getMockSaveablePdf([0, 1]), saveLocation: saveLocation }).then((responsePackage) => { ok(false, "resolve should not be called"); }, (error) => { deepEqual(error, { error: "Unexpected response status", statusCode: 404, responseHeaders: { "Content-Type": "application/json" }, response: JSON.stringify(responseJson), timeout: 30000 }, "The error object should be returned in the reject"); }).then(() => { done(); }); }); } private getMockSaveablePage(): OneNoteSaveablePage { let page = new OneNoteApi.OneNotePage(); return new OneNoteSaveablePage(page); } private getMockSaveablePdf(pageIndexes?: number[]): OneNoteSaveablePdf { let page = new OneNoteApi.OneNotePage(); let mockPdf = new MockPdfDocument(); return new OneNoteSaveablePdf(page, mockPdf, pageIndexes); } private getMockSaveablePdfSynchronousBatch(pageIndexes: number[]): OneNoteSaveablePdfSynchronousBatched { let page = new OneNoteApi.OneNotePage(); let mockPdf = new MockPdfDocument(); return new OneNoteSaveablePdfSynchronousBatched(page, mockPdf, pageIndexes, "en-US", "sample.pdf"); } } (new SaveToOneNoteTests()).runTests();
the_stack
'use strict' import { ethers } from 'ethers' import { encodeParams as encodeParamsHelper, encodeFunctionId, makeFullTypeDefinition } from './txHelper' import { eachOfSeries } from 'async' import { linkBytecode as linkBytecodeSolc } from 'solc/linker' import { isValidAddress, addHexPrefix } from 'ethereumjs-util' /** * build the transaction data * * @param {Object} function abi * @param {Object} values to encode * @param {String} contractbyteCode */ export function encodeData (funABI, values, contractbyteCode) { let encoded let encodedHex try { encoded = encodeParamsHelper(funABI, values) encodedHex = encoded.toString('hex') } catch (e) { return { error: 'cannot encode arguments' } } if (contractbyteCode) { return { data: '0x' + contractbyteCode + encodedHex.replace('0x', '') } } else { return { data: encodeFunctionId(funABI) + encodedHex.replace('0x', '') } } } /** * encode function / constructor parameters * * @param {Object} params - input paramater of the function to call * @param {Object} funAbi - abi definition of the function to call. null if building data for the ctor. * @param {Function} callback - callback */ export function encodeParams (params, funAbi, callback) { let data: Buffer | string = '' let dataHex: string = '' let funArgs if (params.indexOf('raw:0x') === 0) { // in that case we consider that the input is already encoded and *does not* contain the method signature dataHex = params.replace('raw:0x', '') data = Buffer.from(dataHex, 'hex') } else { try { params = params.replace(/(^|,\s+|,)(\d+)(\s+,|,|$)/g, '$1"$2"$3') // replace non quoted number by quoted number params = params.replace(/(^|,\s+|,)(0[xX][0-9a-fA-F]+)(\s+,|,|$)/g, '$1"$2"$3') // replace non quoted hex string by quoted hex string funArgs = JSON.parse('[' + params + ']') } catch (e) { return callback('Error encoding arguments: ' + e) } if (funArgs.length > 0) { try { data = encodeParamsHelper(funAbi, funArgs) dataHex = data.toString() } catch (e) { return callback('Error encoding arguments: ' + e) } } if (data.slice(0, 9) === 'undefined') { dataHex = data.slice(9) } if (data.slice(0, 2) === '0x') { dataHex = data.slice(2) } } callback(null, { data: data, dataHex: dataHex, funArgs: funArgs }) } /** * encode function call (function id + encoded parameters) * * @param {Object} params - input paramater of the function to call * @param {Object} funAbi - abi definition of the function to call. null if building data for the ctor. * @param {Function} callback - callback */ export function encodeFunctionCall (params, funAbi, callback) { encodeParams(params, funAbi, (error, encodedParam) => { if (error) return callback(error) callback(null, { dataHex: encodeFunctionId(funAbi) + encodedParam.dataHex, funAbi, funArgs: encodedParam.funArgs }) }) } /** * encode constructor creation and link with provided libraries if needed * * @param {Object} contract - input paramater of the function to call * @param {Object} params - input paramater of the function to call * @param {Object} funAbi - abi definition of the function to call. null if building data for the ctor. * @param {Object} linkLibraries - contains {linkReferences} object which list all the addresses to be linked * @param {Object} linkReferences - given by the compiler, contains the proper linkReferences * @param {Function} callback - callback */ export function encodeConstructorCallAndLinkLibraries (contract, params, funAbi, linkLibraries, linkReferences, callback) { encodeParams(params, funAbi, (error, encodedParam) => { if (error) return callback(error) let bytecodeToDeploy = contract.evm.bytecode.object if (bytecodeToDeploy.indexOf('_') >= 0) { if (linkLibraries && linkReferences) { for (const libFile in linkLibraries) { for (const lib in linkLibraries[libFile]) { const address = linkLibraries[libFile][lib] if (!isValidAddress(address)) return callback(address + ' is not a valid address. Please check the provided address is valid.') bytecodeToDeploy = linkLibraryStandardFromlinkReferences(lib, address.replace('0x', ''), bytecodeToDeploy, linkReferences) } } } } if (bytecodeToDeploy.indexOf('_') >= 0) { return callback('Failed to link some libraries') } return callback(null, { dataHex: bytecodeToDeploy + encodedParam.dataHex, funAbi, funArgs: encodedParam.funArgs, contractBytecode: contract.evm.bytecode.object }) }) } /** * encode constructor creation and deploy librairies if needed * * @param {String} contractName - current contract name * @param {Object} contract - input paramater of the function to call * @param {Object} contracts - map of all compiled contracts. * @param {Object} params - input paramater of the function to call * @param {Object} funAbi - abi definition of the function to call. null if building data for the ctor. * @param {Function} callback - callback * @param {Function} callbackStep - callbackStep * @param {Function} callbackDeployLibrary - callbackDeployLibrary * @param {Function} callback - callback */ export function encodeConstructorCallAndDeployLibraries (contractName, contract, contracts, params, funAbi, callback, callbackStep, callbackDeployLibrary) { encodeParams(params, funAbi, (error, encodedParam) => { if (error) return callback(error) let dataHex = '' const contractBytecode = contract.evm.bytecode.object let bytecodeToDeploy = contract.evm.bytecode.object if (bytecodeToDeploy.indexOf('_') >= 0) { linkBytecode(contract, contracts, (err, bytecode) => { if (err) { callback('Error deploying required libraries: ' + err) } else { bytecodeToDeploy = bytecode + dataHex return callback(null, { dataHex: bytecodeToDeploy, funAbi, funArgs: encodedParam.funArgs, contractBytecode, contractName: contractName }) } }, callbackStep, callbackDeployLibrary) return } else { dataHex = bytecodeToDeploy + encodedParam.dataHex } callback(null, { dataHex: bytecodeToDeploy, funAbi, funArgs: encodedParam.funArgs, contractBytecode, contractName: contractName }) }) } /** * (DEPRECATED) build the transaction data * * @param {String} contractName * @param {Object} contract - abi definition of the current contract. * @param {Object} contracts - map of all compiled contracts. * @param {Bool} isConstructor - isConstructor. * @param {Object} funAbi - abi definition of the function to call. null if building data for the ctor. * @param {Object} params - input paramater of the function to call * @param {Function} callback - callback * @param {Function} callbackStep - callbackStep * @param {Function} callbackDeployLibrary - callbackDeployLibrary */ export function buildData (contractName, contract, contracts, isConstructor, funAbi, params, callback, callbackStep, callbackDeployLibrary) { let funArgs = [] let data: Buffer | string = '' let dataHex: string = '' if (params.indexOf('raw:0x') === 0) { // in that case we consider that the input is already encoded and *does not* contain the method signature dataHex = params.replace('raw:0x', '') data = Buffer.from(dataHex, 'hex') } else { try { if (params.length > 0) { funArgs = parseFunctionParams(params) } } catch (e) { return callback('Error encoding arguments: ' + e) } try { data = encodeParamsHelper(funAbi, funArgs) dataHex = data.toString() } catch (e) { return callback('Error encoding arguments: ' + e) } if (data.slice(0, 9) === 'undefined') { dataHex = data.slice(9) } if (data.slice(0, 2) === '0x') { dataHex = data.slice(2) } } let contractBytecode if (isConstructor) { contractBytecode = contract.evm.bytecode.object let bytecodeToDeploy = contract.evm.bytecode.object if (bytecodeToDeploy.indexOf('_') >= 0) { linkBytecode(contract, contracts, (err, bytecode) => { if (err) { callback('Error deploying required libraries: ' + err) } else { bytecodeToDeploy = bytecode + dataHex return callback(null, { dataHex: bytecodeToDeploy, funAbi, funArgs, contractBytecode, contractName: contractName }) } }, callbackStep, callbackDeployLibrary) return } else { dataHex = bytecodeToDeploy + dataHex } } else { dataHex = encodeFunctionId(funAbi) + dataHex } callback(null, { dataHex, funAbi, funArgs, contractBytecode, contractName: contractName }) } export function atAddress () {} export function linkBytecodeStandard (contract, contracts, callback, callbackStep, callbackDeployLibrary) { let contractBytecode = contract.evm.bytecode.object eachOfSeries(contract.evm.bytecode.linkReferences, (libs, file, cbFile) => { eachOfSeries(contract.evm.bytecode.linkReferences[file], (libRef, libName, cbLibDeployed) => { const library = contracts[file][libName] if (library) { deployLibrary(file + ':' + libName, libName, library, contracts, (error, address) => { if (error) { return cbLibDeployed(error) } let hexAddress = address.toString('hex') if (hexAddress.slice(0, 2) === '0x') { hexAddress = hexAddress.slice(2) } contractBytecode = linkLibraryStandard(libName, hexAddress, contractBytecode, contract) cbLibDeployed() }, callbackStep, callbackDeployLibrary) } else { cbLibDeployed('Cannot find compilation data of library ' + libName) } }, (error) => { cbFile(error) }) }, (error) => { if (error) { callbackStep(error) } callback(error, contractBytecode) }) } export function linkBytecodeLegacy (contract, contracts, callback, callbackStep, callbackDeployLibrary) { const libraryRefMatch = contract.evm.bytecode.object.match(/__([^_]{1,36})__/) if (!libraryRefMatch) { return callback('Invalid bytecode format.') } const libraryName = libraryRefMatch[1] // file_name:library_name const libRef = libraryName.match(/(.*):(.*)/) if (!libRef) { return callback('Cannot extract library reference ' + libraryName) } if (!contracts[libRef[1]] || !contracts[libRef[1]][libRef[2]]) { return callback('Cannot find library reference ' + libraryName) } const libraryShortName = libRef[2] const library = contracts[libRef[1]][libraryShortName] if (!library) { return callback('Library ' + libraryName + ' not found.') } deployLibrary(libraryName, libraryShortName, library, contracts, (err, address) => { if (err) { return callback(err) } let hexAddress = address.toString('hex') if (hexAddress.slice(0, 2) === '0x') { hexAddress = hexAddress.slice(2) } contract.evm.bytecode.object = linkLibrary(libraryName, hexAddress, contract.evm.bytecode.object) linkBytecode(contract, contracts, callback, callbackStep, callbackDeployLibrary) }, callbackStep, callbackDeployLibrary) } export function linkBytecode (contract, contracts, callback?, callbackStep?, callbackDeployLibrary?) { if (contract.evm.bytecode.object.indexOf('_') < 0) { return callback(null, contract.evm.bytecode.object) } if (contract.evm.bytecode.linkReferences && Object.keys(contract.evm.bytecode.linkReferences).length) { linkBytecodeStandard(contract, contracts, callback, callbackStep, callbackDeployLibrary) } else { linkBytecodeLegacy(contract, contracts, callback, callbackStep, callbackDeployLibrary) } } export function deployLibrary (libraryName, libraryShortName, library, contracts, callback, callbackStep, callbackDeployLibrary) { const address = library.address if (address) { return callback(null, address) } const bytecode = library.evm.bytecode.object if (bytecode.indexOf('_') >= 0) { linkBytecode(library, contracts, (err, bytecode) => { if (err) callback(err) else { library.evm.bytecode.object = bytecode deployLibrary(libraryName, libraryShortName, library, contracts, callback, callbackStep, callbackDeployLibrary) } }, callbackStep, callbackDeployLibrary) } else { callbackStep(`creation of library ${libraryName} pending...`) const data = { dataHex: bytecode, funAbi: { type: 'constructor' }, funArgs: [], contractBytecode: bytecode, contractName: libraryShortName, contractABI: library.abi } callbackDeployLibrary({ data: data, useCall: false }, (err, txResult) => { if (err) { return callback(err) } const address = txResult.receipt.contractAddress library.address = address callback(err, address) }) } } export function linkLibraryStandardFromlinkReferences (libraryName, address, bytecode, linkReferences) { for (const file in linkReferences) { for (const libName in linkReferences[file]) { if (libraryName === libName) { bytecode = setLibraryAddress(address, bytecode, linkReferences[file][libName]) } } } return bytecode } export function linkLibraryStandard (libraryName, address, bytecode, contract) { return linkLibraryStandardFromlinkReferences(libraryName, address, bytecode, contract.evm.bytecode.linkReferences) } export function setLibraryAddress (address, bytecodeToLink, positions) { if (positions) { for (const pos of positions) { const regpos = bytecodeToLink.match(new RegExp(`(.{${2 * pos.start}})(.{${2 * pos.length}})(.*)`)) if (regpos) { bytecodeToLink = regpos[1] + address + regpos[3] } } } return bytecodeToLink } export function linkLibrary (libraryName, address, bytecodeToLink) { return linkBytecodeSolc(bytecodeToLink, { [libraryName]: addHexPrefix(address) }) } export function decodeResponse (response, fnabi) { // Only decode if there supposed to be fields if (fnabi.outputs && fnabi.outputs.length > 0) { try { let i const outputTypes = [] for (i = 0; i < fnabi.outputs.length; i++) { const type = fnabi.outputs[i].type outputTypes.push(type.indexOf('tuple') === 0 ? makeFullTypeDefinition(fnabi.outputs[i]) : type) } if (!response || !response.length) response = new Uint8Array(32 * fnabi.outputs.length) // ensuring the data is at least filled by 0 cause `AbiCoder` throws if there's not engouh data // decode data const abiCoder = new ethers.utils.AbiCoder() const decodedObj = abiCoder.decode(outputTypes, response) const json = {} for (i = 0; i < outputTypes.length; i++) { const name = fnabi.outputs[i].name json[i] = outputTypes[i] + ': ' + (name ? name + ' ' + decodedObj[i] : decodedObj[i]) } return json } catch (e) { return { error: 'Failed to decode output: ' + e } } } return {} } export function parseFunctionParams (params) { let args = [] // Check if parameter string starts with array or string let startIndex = isArrayOrStringStart(params, 0) ? -1 : 0 for (let i = 0; i < params.length; i++) { // If a quote is received if (params.charAt(i) === '"') { startIndex = -1 let endQuoteIndex = false // look for closing quote. On success, push the complete string in arguments list for (let j = i + 1; !endQuoteIndex; j++) { if (params.charAt(j) === '"') { args.push(params.substring(i + 1, j)) endQuoteIndex = true i = j } // Throw error if end of params string is arrived but couldn't get end quote if (!endQuoteIndex && j === params.length - 1) { throw new Error('invalid params') } } } else if (params.charAt(i) === '[') { // If an array/struct opening bracket is received startIndex = -1 let bracketCount = 1 let j for (j = i + 1; bracketCount !== 0; j++) { // Increase count if another array opening bracket is received (To handle nested array) if (params.charAt(j) === '[') { bracketCount++ } else if (params.charAt(j) === ']') { // // Decrease count if an array closing bracket is received (To handle nested array) bracketCount-- } // Throw error if end of params string is arrived but couldn't get end of tuple if (bracketCount !== 0 && j === params.length - 1) { throw new Error('invalid tuple params') } } // If bracketCount = 0, it means complete array/nested array parsed, push it to the arguments list args.push(JSON.parse(params.substring(i, j))) i = j - 1 } else if (params.charAt(i) === ',') { // if startIndex >= 0, it means a parameter was being parsed, it can be first or other parameter if (startIndex >= 0) { args.push(params.substring(startIndex, i)) } // Register start index of a parameter to parse startIndex = isArrayOrStringStart(params, i + 1) ? -1 : i + 1 } else if (startIndex >= 0 && i === params.length - 1) { // If start index is registered and string is completed (To handle last parameter) args.push(params.substring(startIndex, params.length)) } } args = args.map(e => { if (!Array.isArray(e)) { return e.trim() } else { return e } }) return args } export function isArrayOrStringStart (str, index) { return str.charAt(index) === '"' || str.charAt(index) === '[' }
the_stack
import * as pathlib from 'path'; import { promisify } from 'util'; import * as vscode from 'vscode'; import { AbstractRunnable } from './AbstractRunnable'; import * as c2fs from './util/FSWrapper'; import { getAbsolutePath, findURIs } from './Util'; import { resolveOSEnvironmentVariables, createPythonIndexerForPathVariable, createPythonIndexerForStringVariable, resolveVariablesAsync, ResolveRuleAsync, } from './util/ResolveRule'; import { RunnableFactory } from './RunnableFactory'; import { SharedVariables } from './SharedVariables'; import { GazeWrapper, VSCFSWatcherWrapper, FSWatcher } from './util/FSWatcher'; import { RootSuite } from './RootSuite'; import { readJSONSync } from 'fs-extra'; import { Spawner, DefaultSpawner, SpawnWithExecutor } from './Spawner'; import { RunTask, ExecutionWrapper, FrameworkSpecific } from './AdvancedExecutableInterface'; import { LoggerWrapper } from './LoggerWrapper'; /// export class ExecutableConfig implements vscode.Disposable { public constructor( private readonly _shared: SharedVariables, private readonly _pattern: string, private readonly _name: string | undefined, private readonly _description: string | undefined, private readonly _cwd: string, private readonly _env: { [prop: string]: string } | undefined, private readonly _envFile: string | undefined, private readonly _dependsOn: string[], private readonly _runTask: RunTask, private readonly _parallelizationLimit: number, private readonly _strictPattern: boolean | undefined, private readonly _markAsSkipped: boolean | undefined, private readonly _waitForBuildProcess: boolean | undefined, private readonly _executionWrapper: ExecutionWrapper | undefined, private readonly _sourceFileMap: Record<string, string>, private readonly _fsWatcher: string | undefined, private readonly _catch2: FrameworkSpecific, private readonly _gtest: FrameworkSpecific, private readonly _doctest: FrameworkSpecific, private readonly _gbenchmark: FrameworkSpecific, ) { const createUriSymbol: unique symbol = Symbol('createUri'); type CreateUri = { [createUriSymbol]: () => vscode.Uri }; this._disposables.push( vscode.languages.registerDocumentLinkProvider( { language: 'testMate.cpp.testOutput' }, { provideDocumentLinks: ( document: vscode.TextDocument, token: vscode.CancellationToken, // eslint-disable-line ): vscode.ProviderResult<vscode.DocumentLink[]> => { const text = document.getText(); const result: vscode.DocumentLink[] = []; const findLinks = (regexType: 'catch2' | 'gtest' | 'general', resolvePath: boolean): void => { const lines = text.split(/\r?\n/); for (let i = 0; i < lines.length; ++i) { if (token.isCancellationRequested) return; const matches = findURIs(lines[i], regexType); for (let j = 0; j < matches.length; ++j) { const match = matches[j]; const file = match.file; const col = match.column ? `:${match.column}` : ''; const fragment = match.line ? `${match.line}${col}` : undefined; const link: vscode.DocumentLink = new vscode.DocumentLink( new vscode.Range(i, match.index, i, match.index + match.full.length), ); if (resolvePath) { (link as unknown as CreateUri)[createUriSymbol] = (): vscode.Uri => { const dirs = new Set([...this._runnables.keys()].map(k => pathlib.dirname(k))); const resolvedFile = getAbsolutePath(file, dirs); return vscode.Uri.file(resolvedFile).with({ fragment }); }; } else { link.target = vscode.Uri.file(file).with({ fragment }); } result.push(link); } } }; if (text.startsWith('[ RUN ]')) { findLinks('gtest', true); } else if (text.startsWith('⏱Duration:')) { findLinks('catch2', true); } else { //https://github.com/matepek/vscode-catch2-test-adapter/issues/207 findLinks('general', false); } return result; }, resolveDocumentLink: (link: vscode.DocumentLink): vscode.ProviderResult<vscode.DocumentLink> => { link.target = (link as unknown as CreateUri)[createUriSymbol](); return link; }, }, ), ); } private _cancellationFlag = { isCancellationRequested: false }; private _disposables: vscode.Disposable[] = []; public dispose(): void { this._cancellationFlag.isCancellationRequested = true; this._disposables.forEach(d => d.dispose()); } private readonly _runnables: Map<string /*fsPath*/, AbstractRunnable> = new Map(); public async load(rootSuite: RootSuite): Promise<unknown[]> { const pattern = await this._pathProcessor(this._pattern); this._shared.log.info('pattern', this._pattern, this._shared.workspaceFolder.uri.fsPath, pattern); if (pattern.isAbsolute && pattern.isPartOfWs) this._shared.log.info('Absolute path is used for workspace directory. This is unnecessary, but it should work.'); if (this._pattern.indexOf('\\') != -1) this._shared.log.info('Pattern contains backslash character. Try to avoid that.'); const filePaths: string[] = []; let execWatcher: FSWatcher | undefined = undefined; try { switch (this._fsWatcher) { case 'disable': case 'disabled': this._shared.log.info('fswatcher: disabled', this._fsWatcher); break; default: this._shared.log.warn('fswatcher: unknown config value. falling back to default', this._fsWatcher); case undefined: if (pattern.isPartOfWs) { this._shared.log.info('fswatcher: using vscode', this._fsWatcher); execWatcher = new VSCFSWatcherWrapper(this._shared.workspaceFolder, pattern.relativeToWsPosix); } else { this._shared.log.info('fswatcher: using gaze', this._fsWatcher); execWatcher = new GazeWrapper([pattern.absPath]); } break; case 'vscode': this._shared.log.info('fswatcher: using vscode', this._fsWatcher); execWatcher = new VSCFSWatcherWrapper(this._shared.workspaceFolder, pattern.relativeToWsPosix); break; case 'custom': this._shared.log.info('fswatcher: using gaze', this._fsWatcher); execWatcher = new GazeWrapper([pattern.absPath]); break; } } catch (e) { execWatcher && execWatcher.dispose(); filePaths.push(this._pattern); this._shared.log.exceptionS(e, "Couldn't watch pattern"); } if (execWatcher) { filePaths.push(...(await execWatcher.watched())); execWatcher.onError((err: Error) => { // eslint-disable-next-line if ((err as any).code == 'ENOENT') this._shared.log.info('watcher error', err); else this._shared.log.error('watcher error', err); }); execWatcher.onAll(fsPath => { this._shared.log.info('watcher event:', fsPath); this._handleEverything(fsPath, rootSuite); }); this._disposables.push(execWatcher); } const suiteCreationAndLoadingTasks: Promise<void>[] = []; for (let i = 0; i < filePaths.length; i++) { const file = filePaths[i]; this._shared.log.debug('Checking file for tests:', file); if (this._shouldIgnorePath(file)) continue; if (this._isDuplicate(file)) continue; suiteCreationAndLoadingTasks.push( (async (): Promise<void> => { try { await c2fs.isNativeExecutableAsync(file); try { const factory = await this._createSuiteByUri(file, rootSuite); const suite = await factory.create(false); try { await suite.reloadTests(this._shared.taskPool, this._cancellationFlag); this._runnables.set(file, suite); } catch (reason) { this._shared.log.warn("Couldn't load executable", reason, suite); if ( this._strictPattern === true || (this._strictPattern === undefined && this._shared.enabledStrictPattern === true) ) throw Error( `Coudn\'t load executable while using "discovery.strictPattern" or "test.advancedExecutables:strictPattern": ${file}\n ${reason}`, ); } } catch (reason) { this._shared.log.debug('Not a test executable:', file, 'reason:', reason); if ( this._strictPattern === true || (this._strictPattern === undefined && this._shared.enabledStrictPattern === true) ) throw Error( `Coudn\'t load executable while using "discovery.strictPattern" or "test.advancedExecutables:strictPattern": ${file}\n ${reason}`, ); } } catch (reason) { this._shared.log.debug('Not an executable:', file, reason); } })(), ); } const errors: unknown[] = []; for (const task of suiteCreationAndLoadingTasks) { try { await task; } catch (e) { errors.push(e); } } if (errors.length > 0) return errors; if (this._dependsOn.length > 0) { try { // gaze can handle more patterns at once const absPatterns: string[] = []; for (const pattern of this._dependsOn) { const p = await this._pathProcessor(pattern); if (p.isPartOfWs) { const w = new VSCFSWatcherWrapper(this._shared.workspaceFolder, p.relativeToWsPosix); this._disposables.push(w); w.onError((e: Error): void => this._shared.log.error('dependsOn watcher:', e, p)); w.onAll((fsPath: string): void => { this._shared.log.info('dependsOn watcher event:', fsPath); this._shared.sendRetireEvent(this._runnables.values()); }); } else { absPatterns.push(p.absPath); } } if (absPatterns.length > 0) { const w = new GazeWrapper(absPatterns); this._disposables.push(w); w.onError((e: Error): void => this._shared.log.error('dependsOn watcher:', e, absPatterns)); w.onAll((fsPath: string): void => { this._shared.log.info('dependsOn watcher event:', fsPath); this._shared.sendRetireEvent(this._runnables.values()); }); } } catch (e) { this._shared.log.error('dependsOn error:', e); } } return []; } private async _pathProcessor( path: string, moreVarsToResolve?: readonly ResolveRuleAsync[], ): Promise<{ isAbsolute: boolean; absPath: string; isPartOfWs: boolean; relativeToWsPosix: string; }> { path = await this._resolveVariables(path, false, moreVarsToResolve); const normPattern = path.replace(/\\/g, '/'); const isAbsolute = pathlib.posix.isAbsolute(normPattern) || pathlib.win32.isAbsolute(normPattern); const absPath = isAbsolute ? vscode.Uri.file(pathlib.normalize(path)).fsPath : vscode.Uri.file(pathlib.join(this._shared.workspaceFolder.uri.fsPath, normPattern)).fsPath; const relativeToWs = pathlib.relative(this._shared.workspaceFolder.uri.fsPath, absPath); return { isAbsolute, absPath: absPath, isPartOfWs: !relativeToWs.startsWith('..') && relativeToWs !== absPath, // pathlib.relative('B:\wp', 'C:\a\b') == 'C:\a\b' relativeToWsPosix: relativeToWs.replace(/\\/g, '/'), }; } private async _createSuiteByUri(filePath: string, rootSuite: RootSuite): Promise<RunnableFactory> { const relPath = pathlib.relative(this._shared.workspaceFolder.uri.fsPath, filePath); let varToValue: ResolveRuleAsync[] = []; const subPath = createPythonIndexerForPathVariable; const subFilename = (valName: string, filename: string): ResolveRuleAsync => createPythonIndexerForStringVariable(valName, filename, '.', '.'); try { const filename = pathlib.basename(filePath); const extFilename = pathlib.extname(filename); const baseFilename = pathlib.basename(filename, extFilename); const relDirpath = pathlib.dirname(relPath); varToValue = [ { resolve: '${filename}', rule: filename }, // redundant but might faster { resolve: '${relDirpath}', rule: relDirpath }, // redundant but might faster subFilename('filename', filename), subPath('relPath', relPath), subPath('absPath', filePath), subPath('relDirpath', relDirpath), subPath('absDirpath', pathlib.dirname(filePath)), { resolve: '${extFilename}', rule: extFilename }, { resolve: '${baseFilename}', rule: baseFilename }, ...this._shared.varToValue, ]; } catch (e) { this._shared.log.exceptionS(e); } const variableRe = /\$\{[^ ]*\}/; let resolvedCwd = '.'; try { resolvedCwd = await this._resolveVariables(this._cwd, false, varToValue); if (resolvedCwd.match(variableRe)) this._shared.log.warn('Possibly unresolved variable', resolvedCwd); resolvedCwd = pathlib.resolve(this._shared.workspaceFolder.uri.fsPath, resolvedCwd); varToValue.push(subPath('cwd', resolvedCwd)); } catch (e) { this._shared.log.error('resolvedCwd', e); } let resolvedEnv: Record<string, string> = {}; try { if (this._env) Object.assign(resolvedEnv, this._env); resolvedEnv = await this._resolveVariables(resolvedEnv, true, varToValue); } catch (e) { this._shared.log.error('resolvedEnv', e); } if (this._envFile) { const resolvedEnvFile = await this._pathProcessor(this._envFile, varToValue); try { const envFromFile = readJSONSync(resolvedEnvFile.absPath); if (typeof envFromFile !== 'object') throw Error('envFile is not a JSON object'); const props = Object.getOwnPropertyNames(envFromFile); for (const p of props) if (typeof envFromFile[p] !== 'string') throw Error('property of envFile is not a string: ' + p); Object.assign(resolvedEnv, envFromFile); this._shared.log.info( 'Extra environment variables has been added from file', resolvedEnvFile.absPath, envFromFile, ); } catch (e) { this._shared.log.warn('Unable to parse envFile', `"${resolvedEnvFile.absPath}"`, e); } } checkEnvForPath(resolvedEnv, this._shared.log); let spawner: Spawner = new DefaultSpawner(); if (this._executionWrapper) { try { const resolvedPath = await this._pathProcessor(this._executionWrapper.path, varToValue); const resolvedArgs = await this._resolveVariables(this._executionWrapper.args, false, varToValue); spawner = new SpawnWithExecutor(resolvedPath.absPath, resolvedArgs); this._shared.log.info('executionWrapper was specified', resolvedPath, resolvedArgs); } catch (e) { this._shared.log.warn('Unable to apply executionWrapper', e); } } return new RunnableFactory( this._shared, this._name, this._description, rootSuite, filePath, { cwd: resolvedCwd, env: Object.assign({}, process.env, resolvedEnv), }, varToValue, this._catch2, this._gtest, this._doctest, this._gbenchmark, this._parallelizationLimit, this._markAsSkipped === true, this._runTask, spawner, this._sourceFileMap, ); } private readonly _lastEventArrivedAt: Map<string /*fsPath*/, number /*Date*/> = new Map(); private async _handleEverything(filePath: string, rootSuite: RootSuite): Promise<void> { if (this._cancellationFlag.isCancellationRequested) return; const isHandlerRunningForFile = this._lastEventArrivedAt.get(filePath) !== undefined; this._lastEventArrivedAt.set(filePath, Date.now()); if (isHandlerRunningForFile) return; await promisify(setTimeout)(1000); // just not to be hasty. no other reason for this const runnable = this._runnables.get(filePath); if (runnable !== undefined) { this._recursiveHandleRunnable(runnable) .catch(reject => { this._shared.log.errorS(`_recursiveHandleRunnable errors should be handled inside`, reject); }) .finally(() => { this._lastEventArrivedAt.delete(filePath); }); } else { if (this._shouldIgnorePath(filePath)) return; this._shared.log.info('possibly new suite: ' + filePath); this._recursiveHandleFile(filePath, rootSuite) .catch(reject => { this._shared.log.errorS(`_recursiveHandleFile errors should be handled inside`, reject); }) .finally(() => { this._lastEventArrivedAt.delete(filePath); }); } } private async _recursiveHandleFile( filePath: string, rootSuite: RootSuite, delay = 1024, tryCount = 1, ): Promise<void> { if (this._cancellationFlag.isCancellationRequested) return; const lastEventArrivedAt = this._lastEventArrivedAt.get(filePath); if (lastEventArrivedAt === undefined) { this._shared.log.errorS('_recursiveHandleFile: lastEventArrivedAt'); debugger; return; } if (Date.now() - lastEventArrivedAt > this._shared.execWatchTimeout) { this._shared.log.info('file refresh timeout:', filePath); return; } const isExec = await c2fs.isNativeExecutableAsync(filePath).then( () => true, () => false, ); if (isExec) { try { const factory = await this._createSuiteByUri(filePath, rootSuite); const runnable = await factory.create(true); return this._recursiveHandleRunnable(runnable).catch(reject => { this._shared.log.errorS(`_recursiveHandleFile._recursiveHandleFile errors should be handled inside`, reject); }); } catch (reason) { const nextDelay = Math.min(delay + 1000, 5000); if (tryCount > 20) { this._shared.log.info("couldn't add file", filePath, 'reason', reason, tryCount); return; } if (c2fs.isSpawnBusyError(reason)) { this._shared.log.debug('_recursiveHandleFile: busy, retrying... ' + filePath, 'reason:', reason); } else { this._shared.log.debug('_recursiveHandleFile: other error... ' + filePath, 'reason:', reason); } await promisify(setTimeout)(delay); return this._recursiveHandleFile(filePath, rootSuite, nextDelay, tryCount + 1); } } } private async _recursiveHandleRunnable( runnable: AbstractRunnable, isFileExistsAndExecutable = false, delay = 128, ): Promise<void> { if (this._cancellationFlag.isCancellationRequested) return; const filePath = runnable.properties.path; const lastEventArrivedAt = this._lastEventArrivedAt.get(filePath); if (lastEventArrivedAt === undefined) { this._shared.log.errorS('_recursiveHandleRunnable: lastEventArrivedAt'); debugger; return; } if (isFileExistsAndExecutable) { if (this._waitForBuildProcess) await this._shared.buildProcessChecker.resolveAtFinish(); try { await runnable.reloadTests(this._shared.taskPool, this._cancellationFlag); this._runnables.set(filePath, runnable); // it might be set already but we don't care this._shared.sendRetireEvent([runnable]); } catch (reason: any /*eslint-disable-line*/) { if (reason?.code === undefined) this._shared.log.debug('problem under reloading', { reason, filePath, runnable }); return this._recursiveHandleRunnable(runnable, false, Math.min(delay * 2, 2000)); } } else if (Date.now() - lastEventArrivedAt > this._shared.execWatchTimeout) { this._shared.log.info('refresh timeout:', filePath); const foundRunnable = this._runnables.get(filePath); if (foundRunnable) { return this._shared.loadWithTask(async (): Promise<void> => { foundRunnable.removeTests(); this._runnables.delete(filePath); }); } } else { await promisify(setTimeout)(delay); const isExec = await c2fs.isNativeExecutableAsync(filePath).then( () => true, () => false, ); return this._recursiveHandleRunnable(runnable, isExec, Math.min(delay * 2, 2000)); } } private _shouldIgnorePath(filePath: string): boolean { if (!this._pattern.match(/(\/|\\)_deps(\/|\\)/) && filePath.indexOf('/_deps/') !== -1) { // cmake fetches the dependencies here. we dont care about it 🤞 this._shared.log.info('skipping because it is under "/_deps/"', filePath); return true; } else if (!this._pattern.match(/(\/|\\)CMakeFiles(\/|\\)/) && filePath.indexOf('/CMakeFiles/') !== -1) { // cmake fetches the dependencies here. we dont care about it 🤞 this._shared.log.info('skipping because it is under "/CMakeFiles/"', filePath); return true; } else { return false; } } private _isDuplicate(filePath: string): boolean { return this._runnables.has(filePath); } private async _resolveVariables<T>( value: T, strictAllowed: boolean, moreVarsToResolve?: readonly ResolveRuleAsync[], ): Promise<T> { let resolved = resolveOSEnvironmentVariables(value, strictAllowed); resolved = await resolveVariablesAsync(resolved, this._shared.varToValue); if (moreVarsToResolve) resolved = await resolveVariablesAsync(resolved, moreVarsToResolve); this._shared.log.debug('ExecutableConfig.resolveVariable: ', { value, resolved, strictAllowed }); return resolved; } } function checkEnvForPath(env: Record<string, string>, log: LoggerWrapper): void { if (process.platform === 'win32') { checkPathVariance('PATH', env, log); checkPathVariance('Path', env, log); checkPathVariance('path', env, log); } } function checkPathVariance(variance: string, env: Record<string, string>, log: LoggerWrapper): void { if (variance in env) { if (env[variance].indexOf('/') != -1) log.warn(`Env variable ${variance} contains slash on Windows: "${env[variance]}". That won't really work.`); } }
the_stack
import * as msRest from "@azure/ms-rest-js"; import * as Models from "../models"; import * as Mappers from "../models/galleryImagesMappers"; import * as Parameters from "../models/parameters"; import { ManagedLabsClientContext } from "../managedLabsClientContext"; /** Class representing a GalleryImages. */ export class GalleryImages { private readonly client: ManagedLabsClientContext; /** * Create a GalleryImages. * @param {ManagedLabsClientContext} client Reference to the service client. */ constructor(client: ManagedLabsClientContext) { this.client = client; } /** * List gallery images in a given lab account. * @param resourceGroupName The name of the resource group. * @param labAccountName The name of the lab Account. * @param [options] The optional parameters * @returns Promise<Models.GalleryImagesListResponse> */ list(resourceGroupName: string, labAccountName: string, options?: Models.GalleryImagesListOptionalParams): Promise<Models.GalleryImagesListResponse>; /** * @param resourceGroupName The name of the resource group. * @param labAccountName The name of the lab Account. * @param callback The callback */ list(resourceGroupName: string, labAccountName: string, callback: msRest.ServiceCallback<Models.ResponseWithContinuationGalleryImage>): void; /** * @param resourceGroupName The name of the resource group. * @param labAccountName The name of the lab Account. * @param options The optional parameters * @param callback The callback */ list(resourceGroupName: string, labAccountName: string, options: Models.GalleryImagesListOptionalParams, callback: msRest.ServiceCallback<Models.ResponseWithContinuationGalleryImage>): void; list(resourceGroupName: string, labAccountName: string, options?: Models.GalleryImagesListOptionalParams | msRest.ServiceCallback<Models.ResponseWithContinuationGalleryImage>, callback?: msRest.ServiceCallback<Models.ResponseWithContinuationGalleryImage>): Promise<Models.GalleryImagesListResponse> { return this.client.sendOperationRequest( { resourceGroupName, labAccountName, options }, listOperationSpec, callback) as Promise<Models.GalleryImagesListResponse>; } /** * Get gallery image * @param resourceGroupName The name of the resource group. * @param labAccountName The name of the lab Account. * @param galleryImageName The name of the gallery Image. * @param [options] The optional parameters * @returns Promise<Models.GalleryImagesGetResponse> */ get(resourceGroupName: string, labAccountName: string, galleryImageName: string, options?: Models.GalleryImagesGetOptionalParams): Promise<Models.GalleryImagesGetResponse>; /** * @param resourceGroupName The name of the resource group. * @param labAccountName The name of the lab Account. * @param galleryImageName The name of the gallery Image. * @param callback The callback */ get(resourceGroupName: string, labAccountName: string, galleryImageName: string, callback: msRest.ServiceCallback<Models.GalleryImage>): void; /** * @param resourceGroupName The name of the resource group. * @param labAccountName The name of the lab Account. * @param galleryImageName The name of the gallery Image. * @param options The optional parameters * @param callback The callback */ get(resourceGroupName: string, labAccountName: string, galleryImageName: string, options: Models.GalleryImagesGetOptionalParams, callback: msRest.ServiceCallback<Models.GalleryImage>): void; get(resourceGroupName: string, labAccountName: string, galleryImageName: string, options?: Models.GalleryImagesGetOptionalParams | msRest.ServiceCallback<Models.GalleryImage>, callback?: msRest.ServiceCallback<Models.GalleryImage>): Promise<Models.GalleryImagesGetResponse> { return this.client.sendOperationRequest( { resourceGroupName, labAccountName, galleryImageName, options }, getOperationSpec, callback) as Promise<Models.GalleryImagesGetResponse>; } /** * Create or replace an existing Gallery Image. * @param resourceGroupName The name of the resource group. * @param labAccountName The name of the lab Account. * @param galleryImageName The name of the gallery Image. * @param galleryImage Represents an image from the Azure Marketplace * @param [options] The optional parameters * @returns Promise<Models.GalleryImagesCreateOrUpdateResponse> */ createOrUpdate(resourceGroupName: string, labAccountName: string, galleryImageName: string, galleryImage: Models.GalleryImage, options?: msRest.RequestOptionsBase): Promise<Models.GalleryImagesCreateOrUpdateResponse>; /** * @param resourceGroupName The name of the resource group. * @param labAccountName The name of the lab Account. * @param galleryImageName The name of the gallery Image. * @param galleryImage Represents an image from the Azure Marketplace * @param callback The callback */ createOrUpdate(resourceGroupName: string, labAccountName: string, galleryImageName: string, galleryImage: Models.GalleryImage, callback: msRest.ServiceCallback<Models.GalleryImage>): void; /** * @param resourceGroupName The name of the resource group. * @param labAccountName The name of the lab Account. * @param galleryImageName The name of the gallery Image. * @param galleryImage Represents an image from the Azure Marketplace * @param options The optional parameters * @param callback The callback */ createOrUpdate(resourceGroupName: string, labAccountName: string, galleryImageName: string, galleryImage: Models.GalleryImage, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.GalleryImage>): void; createOrUpdate(resourceGroupName: string, labAccountName: string, galleryImageName: string, galleryImage: Models.GalleryImage, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.GalleryImage>, callback?: msRest.ServiceCallback<Models.GalleryImage>): Promise<Models.GalleryImagesCreateOrUpdateResponse> { return this.client.sendOperationRequest( { resourceGroupName, labAccountName, galleryImageName, galleryImage, options }, createOrUpdateOperationSpec, callback) as Promise<Models.GalleryImagesCreateOrUpdateResponse>; } /** * Delete gallery image. * @param resourceGroupName The name of the resource group. * @param labAccountName The name of the lab Account. * @param galleryImageName The name of the gallery Image. * @param [options] The optional parameters * @returns Promise<msRest.RestResponse> */ deleteMethod(resourceGroupName: string, labAccountName: string, galleryImageName: string, options?: msRest.RequestOptionsBase): Promise<msRest.RestResponse>; /** * @param resourceGroupName The name of the resource group. * @param labAccountName The name of the lab Account. * @param galleryImageName The name of the gallery Image. * @param callback The callback */ deleteMethod(resourceGroupName: string, labAccountName: string, galleryImageName: string, callback: msRest.ServiceCallback<void>): void; /** * @param resourceGroupName The name of the resource group. * @param labAccountName The name of the lab Account. * @param galleryImageName The name of the gallery Image. * @param options The optional parameters * @param callback The callback */ deleteMethod(resourceGroupName: string, labAccountName: string, galleryImageName: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<void>): void; deleteMethod(resourceGroupName: string, labAccountName: string, galleryImageName: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<void>, callback?: msRest.ServiceCallback<void>): Promise<msRest.RestResponse> { return this.client.sendOperationRequest( { resourceGroupName, labAccountName, galleryImageName, options }, deleteMethodOperationSpec, callback); } /** * Modify properties of gallery images. * @param resourceGroupName The name of the resource group. * @param labAccountName The name of the lab Account. * @param galleryImageName The name of the gallery Image. * @param galleryImage Represents an image from the Azure Marketplace * @param [options] The optional parameters * @returns Promise<Models.GalleryImagesUpdateResponse> */ update(resourceGroupName: string, labAccountName: string, galleryImageName: string, galleryImage: Models.GalleryImageFragment, options?: msRest.RequestOptionsBase): Promise<Models.GalleryImagesUpdateResponse>; /** * @param resourceGroupName The name of the resource group. * @param labAccountName The name of the lab Account. * @param galleryImageName The name of the gallery Image. * @param galleryImage Represents an image from the Azure Marketplace * @param callback The callback */ update(resourceGroupName: string, labAccountName: string, galleryImageName: string, galleryImage: Models.GalleryImageFragment, callback: msRest.ServiceCallback<Models.GalleryImage>): void; /** * @param resourceGroupName The name of the resource group. * @param labAccountName The name of the lab Account. * @param galleryImageName The name of the gallery Image. * @param galleryImage Represents an image from the Azure Marketplace * @param options The optional parameters * @param callback The callback */ update(resourceGroupName: string, labAccountName: string, galleryImageName: string, galleryImage: Models.GalleryImageFragment, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.GalleryImage>): void; update(resourceGroupName: string, labAccountName: string, galleryImageName: string, galleryImage: Models.GalleryImageFragment, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.GalleryImage>, callback?: msRest.ServiceCallback<Models.GalleryImage>): Promise<Models.GalleryImagesUpdateResponse> { return this.client.sendOperationRequest( { resourceGroupName, labAccountName, galleryImageName, galleryImage, options }, updateOperationSpec, callback) as Promise<Models.GalleryImagesUpdateResponse>; } /** * List gallery images in a given lab account. * @param nextPageLink The NextLink from the previous successful call to List operation. * @param [options] The optional parameters * @returns Promise<Models.GalleryImagesListNextResponse> */ listNext(nextPageLink: string, options?: msRest.RequestOptionsBase): Promise<Models.GalleryImagesListNextResponse>; /** * @param nextPageLink The NextLink from the previous successful call to List operation. * @param callback The callback */ listNext(nextPageLink: string, callback: msRest.ServiceCallback<Models.ResponseWithContinuationGalleryImage>): void; /** * @param nextPageLink The NextLink from the previous successful call to List operation. * @param options The optional parameters * @param callback The callback */ listNext(nextPageLink: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.ResponseWithContinuationGalleryImage>): void; listNext(nextPageLink: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.ResponseWithContinuationGalleryImage>, callback?: msRest.ServiceCallback<Models.ResponseWithContinuationGalleryImage>): Promise<Models.GalleryImagesListNextResponse> { return this.client.sendOperationRequest( { nextPageLink, options }, listNextOperationSpec, callback) as Promise<Models.GalleryImagesListNextResponse>; } } // Operation Specifications const serializer = new msRest.Serializer(Mappers); const listOperationSpec: msRest.OperationSpec = { httpMethod: "GET", path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.LabServices/labaccounts/{labAccountName}/galleryimages", urlParameters: [ Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.labAccountName ], queryParameters: [ Parameters.expand, Parameters.filter, Parameters.top, Parameters.orderby, Parameters.apiVersion ], headerParameters: [ Parameters.acceptLanguage ], responses: { 200: { bodyMapper: Mappers.ResponseWithContinuationGalleryImage }, default: { bodyMapper: Mappers.CloudError } }, serializer }; const getOperationSpec: msRest.OperationSpec = { httpMethod: "GET", path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.LabServices/labaccounts/{labAccountName}/galleryimages/{galleryImageName}", urlParameters: [ Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.labAccountName, Parameters.galleryImageName ], queryParameters: [ Parameters.expand, Parameters.apiVersion ], headerParameters: [ Parameters.acceptLanguage ], responses: { 200: { bodyMapper: Mappers.GalleryImage }, default: { bodyMapper: Mappers.CloudError } }, serializer }; const createOrUpdateOperationSpec: msRest.OperationSpec = { httpMethod: "PUT", path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.LabServices/labaccounts/{labAccountName}/galleryimages/{galleryImageName}", urlParameters: [ Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.labAccountName, Parameters.galleryImageName ], queryParameters: [ Parameters.apiVersion ], headerParameters: [ Parameters.acceptLanguage ], requestBody: { parameterPath: "galleryImage", mapper: { ...Mappers.GalleryImage, required: true } }, responses: { 200: { bodyMapper: Mappers.GalleryImage }, 201: { bodyMapper: Mappers.GalleryImage }, default: { bodyMapper: Mappers.CloudError } }, serializer }; const deleteMethodOperationSpec: msRest.OperationSpec = { httpMethod: "DELETE", path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.LabServices/labaccounts/{labAccountName}/galleryimages/{galleryImageName}", urlParameters: [ Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.labAccountName, Parameters.galleryImageName ], queryParameters: [ Parameters.apiVersion ], headerParameters: [ Parameters.acceptLanguage ], responses: { 200: {}, 204: {}, default: { bodyMapper: Mappers.CloudError } }, serializer }; const updateOperationSpec: msRest.OperationSpec = { httpMethod: "PATCH", path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.LabServices/labaccounts/{labAccountName}/galleryimages/{galleryImageName}", urlParameters: [ Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.labAccountName, Parameters.galleryImageName ], queryParameters: [ Parameters.apiVersion ], headerParameters: [ Parameters.acceptLanguage ], requestBody: { parameterPath: "galleryImage", mapper: { ...Mappers.GalleryImageFragment, required: true } }, responses: { 200: { bodyMapper: Mappers.GalleryImage }, default: { bodyMapper: Mappers.CloudError } }, serializer }; const listNextOperationSpec: msRest.OperationSpec = { httpMethod: "GET", baseUrl: "https://management.azure.com", path: "{nextLink}", urlParameters: [ Parameters.nextPageLink ], headerParameters: [ Parameters.acceptLanguage ], responses: { 200: { bodyMapper: Mappers.ResponseWithContinuationGalleryImage }, default: { bodyMapper: Mappers.CloudError } }, serializer };
the_stack
export class PathRegionPrototype { CHUNK = 1000; path: string; start?: number; stop?: number; authorized?: boolean; // There is no rule whether stop is greater than start. constructor( path: string, start?: number, stop?: number, authorized: boolean = true ) { this.path = path; this.start = authorized ? start || 0 : start; this.stop = !authorized ? stop : start === stop || !stop ? Number(start) + this.CHUNK : stop; // FIXME() It prohibits stop === stop cooridanetes/ this.authorized = authorized; } canonicalPath() { return this.path.replace('chr', ''); } compare(target: PathRegionPrototype) { return ( this.path === target.path && this.start === target.start && this.stop === target.stop ); } rescale(padding: number) { this.start -= padding; if (this.start < 0) { this.start = 0; } this.stop += padding; return this; } flip() { const tmp = this.start; this.start = this.stop; this.stop = tmp; return this; } scaleUp() { if (this.stop !== null) { const diff = this.stop - this.start; this.start += Math.round(diff / 4) - 1; this.stop -= Math.round(diff / 4); if (this.stop < 0) { this.stop = 0; } } return this; } scaleDown() { if (this.stop !== null) { const diff = this.stop - this.start; this.start -= Math.round(diff / 2) + 1; if (this.start < 0) { this.start = 0; } this.stop += Math.round(diff / 2); } return this; } scaleLeft() { const diff = this.stop - this.start; this.start -= Math.round(diff / 2); if (this.start < 0) { this.start = 0; } this.stop -= Math.round(diff / 2); return this; } scaleRight() { const diff = this.stop - this.start; this.start += Math.round(diff / 2); this.stop += Math.round(diff / 2); return this; } chunkLeft() { this.stop = this.start + this.CHUNK; return this; } chunkRight() { this.start = this.stop - this.CHUNK; if (this.start < 0) { this.start = 0; } return this; } diff() { return Math.abs(this.stop - this.start); } toUnreadableString() { return this.stop ? this.path + ':' + this.start + '-' + this.stop : this.path + ':' + (this.start === null ? '' : this.start); } toString() { return this.stop ? this.path + ':' + Utils.formatPrettier(this.start) + '-' + Utils.formatPrettier(this.stop) : this.path + ':' + Utils.formatPrettier(this.start); } toQuery() { return this.stop ? this.path + ':' + this.start + '-' + this.stop : this.path + ':' + (this.start === null ? '' : this.start); } } export type TagItem = string; export class PathRegion extends PathRegionPrototype { name: TagItem[]; isLocked?: boolean; constructor( path: string, start?: number, stop?: number, authorized?: boolean, name?: TagItem[], isLocked?: boolean ) { super(path, start, stop, authorized); this.name = name || []; this.isLocked = isLocked; } toStringWithNames() { return this.stop ? this.path + ':' + this.start + '-' + this.stop + '-' + this.name.join('-') : this.path + ':' + (this.start === null ? '' : this.start); } compareExact(target: PathRegion) { return ( this.path === target.path && this.start === target.start && this.stop === target.stop && this.name.toString() === target.name.toString() ); } withPrevLen() { return new PathRegionWithPrevLen(this.path, this.start, this.stop); } } export class PathRegionWithPrevLen extends PathRegionPrototype { previous: number; startIndex: number; stopIndex: number; constructor( path: string, start?: number, stop?: number, previous?: number, startIndex?: number, stopIndex?: number ) { super(path, start, stop); this.previous = previous || 0; this.startIndex = startIndex || 0; this.stopIndex = stopIndex || startIndex || 0; } } export class PathRegionArray { paths: PathRegion[]; selectedIndex: number; } export interface OverViewProps { pos: PathRegion[]; posUpdate: (reg: PathRegion[], featureId: number) => void; closeModal: () => void; featureThreshold: number[]; featureSelection: boolean[]; features: any; chroms: any; width: number; reference?: string; } export interface PartialGraphProps { width: number; height: number; chroms: any; pos: PathRegion[]; nodesUpdate: (reg: number[]) => void; uuid: string; reference?: string; } export interface PathRegionProps { pos: PathRegion[]; posUpdate: ( reg: PathRegion[], featureId: number, updatedIndex?: number ) => void; posConcat: (reg: PathRegion[], featureId: number) => void; // It is useless; arrayMode: () => void; reference: string; chroms: any; } export class Wigs { max: number; min: number; values: any; constructor(max: number, min: number, values: any) { this.max = max; this.min = min; this.values = values; } } export class PackAnnotation { static offset: number = 0; static interval: number = 100; // static mergeOption: number = 0; static buildAnnotationRequest(pos: PathRegionPrototype) { return ('/api/v2/static/pack.json'); // + pos.toQuery()); } static buildAnnotationRequests(positions: PathRegionPrototype[]) { return ('/api/v2/static/pack.json'); // + positions.map(a => a.toQuery()).join(',')); } static divide(n: number, ary: any[]) { var idx = 0; var results = []; var length = ary.length; while (idx + n < length) { var result = ary.slice(idx, idx + n); results.push(result); idx = idx + n; } var rest = ary.slice(idx, length + 1); results.push(rest); return results; } static convertToAnnotations(res: any, positions: PathRegionWithPrevLen[]): Wigs[] { // let hash = {}; let key_length = Object.keys(res[0]).length; let temporal = new Array(key_length); for (let i = 0; i < key_length; i++ ) { temporal[i] = new Wigs(0, 100000, {}); } res.forEach((response, index) => { Object.keys(response).forEach((key, temp_index) => { let wigs = response[key]; // TODO() let array = []; wigs.forEach(wig => { for (let step = wig.start_offset; step < wig.stop_offset; step++) { if (positions[index].start <= step && step < positions[index].stop) { if (wig.value > temporal[temp_index].max) { temporal[temp_index].max = wig.value; } if (wig.value < temporal[temp_index].min) { temporal[temp_index].min = wig.value; } array.push(wig.value); } } }); // Convolution with interval // temporal.forEach(arrayMaxMin => { let arrayMaxMin = temporal[temp_index]; array = array.reduce((table, item) => { const last = table[table.length - 1]; if (last.length >= array.length / PackAnnotation.interval) { table.push([item]); return table; } last.push(item); return table; }, [[]]); array = array.map(item => item.reduce((a, b) => a > b ? a : b, 0)); // Select Max coverage // array = array.filter((a, i) => i % WigAnnotation.interval === 0); if (array.length === 1) { // Since single-length lane cannot visualize array = [array[0], array[0]]; } arrayMaxMin.values[positions[index].startIndex] = array; // console.log(hash); // }); }); }); return temporal; } static convertToAnnotation(res: any, pos: PathRegionWithPrevLen) { // res = WIGTest; let max = res[0][0].value; let min = res[0][0].value; let hash = []; res.forEach(wigs => { // TODO() wigs.forEach(wig => { for (let step = wig.start_offset; step < wig.stop_offset; step++) { if (pos.start <= step && step < pos.stop) { if (wig.value > max) { max = wig.value; } if (wig.value < min) { min = wig.value; } hash.push(wig.value); } } }); }); return { max, min, values: hash, }; } } export class WigAnnotation { static offset: number = 0; static interval: number = 100; // static mergeOption: number = 0; static buildAnnotationRequest(pos: PathRegionPrototype) { return ('/api/v2/region?format=wig&path=' + pos.toQuery()); } static buildAnnotationRequests(positions: PathRegionPrototype[]) { return ('/api/v2/region?format=wig&multiple=true&path=' + positions.map(a => a.toQuery()).join(',')); } static divide(n: number, ary: any[]) { var idx = 0; var results = []; var length = ary.length; while (idx + n < length) { var result = ary.slice(idx, idx + n); results.push(result); idx = idx + n; } var rest = ary.slice(idx, length + 1); results.push(rest); return results; } static convertToAnnotations(res: any, positions: PathRegionWithPrevLen[]): Wigs[] { // let hash = {}; let key_length = Object.keys(res[0]).length; let temporal = new Array(key_length); for (let i = 0; i < key_length; i++ ) { temporal[i] = new Wigs(0, 100000, {}); } res.forEach((response, index) => { Object.keys(response).forEach((key, temp_index) => { let wigs = response[key]; // TODO() let array = []; wigs.forEach(wig => { for (let step = wig.start_offset; step < wig.stop_offset; step++) { if (positions[index].start <= step && step < positions[index].stop) { if (wig.value > temporal[temp_index].max) { temporal[temp_index].max = wig.value; } if (wig.value < temporal[temp_index].min) { temporal[temp_index].min = wig.value; } array.push(wig.value); } } }); // Convolution with interval // temporal.forEach(arrayMaxMin => { let arrayMaxMin = temporal[temp_index]; array = array.reduce((table, item) => { const last = table[table.length - 1]; if (last.length >= array.length / WigAnnotation.interval) { table.push([item]); return table; } last.push(item); return table; }, [[]]); array = array.map(item => item.reduce((a, b) => a > b ? a : b, 0)); // Select Max coverage // array = array.filter((a, i) => i % WigAnnotation.interval === 0); if (array.length === 1) { // Since single-length lane cannot visualize array = [array[0], array[0]]; } arrayMaxMin.values[positions[index].startIndex] = array; // console.log(hash); // }); }); }); return temporal; } static convertToAnnotation(res: any, pos: PathRegionWithPrevLen) { // res = WIGTest; let max = res[0][0].value; let min = res[0][0].value; let hash = []; res.forEach(wigs => { // TODO() wigs.forEach(wig => { for (let step = wig.start_offset; step < wig.stop_offset; step++) { if (pos.start <= step && step < pos.stop) { if (wig.value > max) { max = wig.value; } if (wig.value < min) { min = wig.value; } hash.push(wig.value); } } }); }); return { max, min, values: hash, }; } } export class BedAnnotation { static offset: number = 0; static buildBedAnnotationRequest(pos: PathRegionPrototype) { /* const seq = pos.canonicalPath(); const start = (pos.start - this.offset > 0 ? pos.start - this.offset : 0); const end = (pos.stop + this.offset);*/ return ('/api/v2/region?format=bed&path=' + pos.toQuery()); } static convertToAnnotation(res: any, pos: PathRegionWithPrevLen) { // res = BEDTest; let hash = {}; Object.keys(res).forEach((key) => { let annotations = res[key]; // TODO() annotations.forEach(annotation => { if (hash[annotation.id] === undefined) { hash[annotation.id] = []; } hash[annotation.id].push(annotation); }); }); const isoform = Object.keys(hash) .map(key => { const coordinate = [ hash[key][0].start_offset, hash[key][0].stop_offset, ] .map(a => Number(a)) .sort(); return { track: hash[key][0].attributes[0] + '_' + hash[key][0].id, path: pos.path, type: 'bed', // repeat mrna_start: coordinate[0], mrna_end: coordinate[1], strand: hash[key][0].attributes[2], name: hash[key][0].attributes[0], description: hash[key][0].attributes.join(',') }; }); // .filter(track => track.track.startsWith('NM')); // Limit annotations only NM return { isoform }; } } export class SPARQList { static offset: number = 0; // 5000; static buildSparqlistRequest(pos: PathRegionPrototype, ref: string = 'hg19') { const seq = pos.canonicalPath(); const url = ref === 'hg19' ? '_grch37/' : '/'; return ( 'http://biohackathon.org/rest/api/vg_gene_annotation' + url + '?seq=' + seq + '&start=' + (pos.start - this.offset > 0 ? pos.start - this.offset : 0) + '&end=' + (pos.stop + this.offset) ); } static strandToString(strand: string) { switch (strand) { case '1': return '+'; case '-1': return '-'; default: return '?'; } } static convertToAnnotationFromSparqlist( res: any, pos: PathRegionWithPrevLen ) { var hash = {}; res.forEach(item => { // TODO() if (hash[item.mrna.value] === undefined) { hash[item.mrna.value] = []; } hash[item.mrna.value].push(item); }); const isoform = Object.keys(hash) .map(key => { const mrnaCoordinate = [ hash[key][0].mrna_start.value, hash[key][0].mrna_end.value ] .map(a => Number(a)) .sort(); return { track: hash[key][0].transcript_id.value, path: pos.path, type: 'gene', mrna_start: mrnaCoordinate[0], mrna_end: mrnaCoordinate[1], strand: hash[key][0].strand.value, name: hash[key][0].name.value + ' / ' + hash[key][0].transcript_id.value + ' (' + this.strandToString(hash[key][0].strand.value) + ')', description: hash[key][0].description.value }; }) .filter(track => track.track.startsWith('NM')); // Limit annotations only NM const exon = res .map(item => { const exonCoordinate = [item.exon_start.value, item.exon_end.value] .map(a => Number(a)) .sort(); const mrnaCoordinate = [item.mrna_start.value, item.mrna_end.value] .map(a => Number(a)) .sort(); const startPosition = Math.max(mrnaCoordinate[0], pos.start); if ( exonCoordinate[0] > pos.stop || exonCoordinate[1] < pos.start || !item.transcript_id.value.startsWith('NM') ) { return null; } return { track: item.name.value + ' / ' + item.transcript_id.value + ' (' + this.strandToString(item.strand.value) + ')', start: exonCoordinate[0] - startPosition + pos.previous, end: exonCoordinate[1] - startPosition - 1 + pos.previous, type: 'exon', name: item.transcript_id.value }; }) .filter(a => a); return { isoform: isoform, exon: exon }; } } export class Utils { static refToGRC(ref: string) { switch (ref) { case 'hg19': return 'GRCh37'; case 'hg38': return 'GRCh38'; default: return 'GRCh37'; } } static refToNumber(ref: string) { switch (ref) { case 'hg19': return 0; case 'hg38': return 1; default: return 0; } } static numToReference(ref: number) { switch (Number(ref)) { case 0: return 'hg19'; case 1: return 'hg38'; default: return 'hg19'; } } static arrayUniqueByName(array: any[]) { let hash = {}; return array.filter((a, index, self) => { if (a === null || a.name in hash) { return false; } else { hash[a.name] = 1; return true; } }); } static applyMixins(derivedCtor: any, baseCtors: any[]) { baseCtors.forEach(baseCtor => { Object.getOwnPropertyNames(baseCtor.prototype).forEach(name => { derivedCtor.prototype[name] = baseCtor.prototype[name]; }); }); } static formatPrettier(d?: number) { return d === null ? '' : String(d).replace(/(\d)(?=(\d\d\d)+(?!\d))/g, '$1,'); } static formatResetter(d: string) { return Number(d.replace(',', '')); } static checkValid(d: PathRegion[]) { return d.filter(a => a).length !== 0; } static strToRegion(item: string) { const items = item.split('&'); return Utils.strsToRegion(items); } static strsToRegion(items: any, auth: boolean = true) { if (items[0] === '') { return []; } if (!Array.isArray(items)) { items = [items]; } return items.map(item => { const name = item.split(':'); if (name[0].match(/^[0-9]/)) { name[0] = name[0]; // FIXME() Does it make sense? all path incluing not reference path will be prefixed "chr"? } if (name[1] === '' || name[1] === undefined) { if (item.indexOf(':', item.length - 1) === item.length - 1) { return new PathRegion(name[0], null, null, auth); } return null; } var start = name[1].split(/-|—|–|\.\./); start[0] = start[0].replace(/[^0-9^\.]/g, ''); if (start.length === 1) { return new PathRegion(name[0], parseInt(start[0], 10), null, auth); } else { start[1] = start[1].replace(/[^0-9^\.]/g, ''); return new PathRegion( name[0], parseInt(start[0], 10), parseInt(start[1], 10), auth, start.slice(2) ); } }); } static strToLength(d: string, chroms: any) { var length = 0; chroms.forEach(chr => { if (chr.id === d) { length = chr.len; } }); return length; } static strToColor(d: string, chroms: any) { var color = ''; chroms.forEach(chr => { if (chr.id === d) { color = chr.color; } }); return color; } static svTypeToColor(type: string) { switch (type) { case 'INS': return 'rgb(255,40,0)'; // RED case 'INV': return 'rgb(250,245,0)'; // Yellow case 'DEL': return 'rgb(0,65,255)'; // Blue case 'TRA': return 'black'; case 'BND': return 'black'; case 'UNK': return 'black'; case 'DUP': return 'rgb(255,40,0)'; // RED default: return 'black'; } } } export interface Helpable { link: () => string; help: () => React.ReactElement<null>; }
the_stack
import * as React from "react"; import { WebPartContext } from "@microsoft/sp-webpart-base"; import commonServices from "../Common/CommonServices"; import * as stringsConstants from "../constants/strings"; import styles from "../scss/TOTCreateTournament.module.scss"; //React Boot Strap import Row from "react-bootstrap/Row"; import Col from "react-bootstrap/Col"; //FluentUI controls import { TextField } from "@fluentui/react/lib/TextField"; import { IButtonStyles, PrimaryButton } from "@fluentui/react"; import { Label } from "@fluentui/react/lib/Label"; import { Icon, IIconProps } from '@fluentui/react/lib/Icon'; import { mergeStyleSets } from '@fluentui/react/lib/Styling'; import { TooltipHost, ITooltipHostStyles } from '@fluentui/react/lib/Tooltip'; //PNP import { TreeView, ITreeItem, TreeViewSelectionMode, } from "@pnp/spfx-controls-react/lib/TreeView"; import { ITextFieldStyles } from "office-ui-fabric-react/lib/components/TextField/TextField.types"; export interface ICreateTournamentProps { context?: WebPartContext; siteUrl: string; onClickCancel: Function; } interface ICreateTournamentState { actionsList: ITreeItem[]; tournamentName: string; tournamentDescription: string; selectedActionsList: ITreeItem[]; tournamentError: Boolean; actionsError: Boolean; showForm: Boolean; showSuccess: Boolean; showError: Boolean; errorMessage: string; } const calloutProps = { gapSpace: 0 }; const hostStyles: Partial<ITooltipHostStyles> = { root: { display: 'inline-block', cursor: 'pointer' } }; const classes = mergeStyleSets({ icon: { fontSize: '16px', paddingLeft: '10px', paddingTop: '6px', fontWeight: 'bolder', color: '#1d0f62' } }); const labelStyles: Partial<ITextFieldStyles> = { subComponentStyles: { label: { root: { textAlign: "left", font: "normal normal 600 18px/24px Segoe UI", letterSpacing: "0px", color: "#000000", opacity: 1 } } } }; const backBtnStyles: Partial<IButtonStyles> = { root: { borderColor: "#33344A", backgroundColor: "white", }, rootHovered: { borderColor: "#33344A", backgroundColor: "white", color: "#000003" }, rootPressed: { borderColor: "#33344A", backgroundColor: "white", color: "#000003" }, icon: { fontSize: "17px", fontWeight: "bolder", color: "#000003", opacity: 1 }, label: { font: "normal normal bold 14px/24px Segoe UI", letterSpacing: "0px", color: "#000003", opacity: 1, marginTop: "-3px" } }; const addIcon: IIconProps = { iconName: 'Add' }; const backIcon: IIconProps = { iconName: 'NavigateBack' }; export default class TOTCreateTournament extends React.Component< ICreateTournamentProps, ICreateTournamentState > { constructor(props: ICreateTournamentProps, state: ICreateTournamentState) { super(props); //Set default values for state this.state = { actionsList: [], tournamentName: "", tournamentDescription: "", selectedActionsList: [], tournamentError: false, actionsError: false, showForm: true, showSuccess: false, showError: false, errorMessage: "", }; //Bind Methods this.getActions = this.getActions.bind(this); this.handleInput = this.handleInput.bind(this); this.onActionSelected = this.onActionSelected.bind(this); this.saveTournament = this.saveTournament.bind(this); } //Get Actions from Master list and bind it to treeview on app load public componentDidMount() { //Get Actions from Master list and bind it to Treeview this.getActions(); } //Get Actions from Master list and bind it to Treeview private async getActions() { console.log(stringsConstants.TotLog + "Getting actions from master list."); try { //Get all actions from 'Actions List' to bind it to Treeview let commonServiceManager: commonServices = new commonServices( this.props.context, this.props.siteUrl ); const allActionsArray: any[] = await commonServiceManager.getAllListItems( stringsConstants.ActionsMasterList ); var treeItemsArray: ITreeItem[] = []; //Loop through all actions and build parent nodes(Categories) for Treeview await allActionsArray.forEach((vAction) => { const tree: ITreeItem = { key: vAction["Category"], label: vAction["Category"], children: [], }; //Check if Category is already added to the Treeview. If yes, skip adding. var found = treeItemsArray.some((value) => { return value.label === vAction["Category"]; }); //Add category to Treeview only if it doesnt exists already. if (!found) treeItemsArray.push(tree); }); //Loop through all actions and build child nodes(Actions) to the Treeview await allActionsArray.forEach((vAction) => { const tree: ITreeItem = { key: vAction.Id, label: vAction["Title"], data: vAction["Category"] + stringsConstants.StringSeperator + vAction["HelpURL"], subLabel: vAction["Points"] + stringsConstants.PointsDisplayString + vAction["Description"], }; var treeCol: Array<ITreeItem> = treeItemsArray.filter((value) => { return value.label == vAction["Category"]; }); if (treeCol.length != 0) { treeCol[0].children.push(tree); } }); this.setState({ actionsList: treeItemsArray }); } catch (error) { console.error("TOT_TOTCreateTournament_getActions \n", error); this.setState({ showError: true, errorMessage: stringsConstants.TOTErrorMessage + " while retrieving actions list. Below are the details: \n" + JSON.stringify(error), }); } } //Handle state values for form fields private handleInput(event: any, key: string) { switch (key) { case "tournamentName": this.setState({ tournamentName: event.target.value }); break; case "tournamentDescription": this.setState({ tournamentDescription: event.target.value }); break; default: break; } } //On select of a tree node change the state of selected actions private onActionSelected(items: ITreeItem[]) { this.setState({ selectedActionsList: items }); } //Validate fields on the form and set a flag private ValidateFields(): Boolean { let validateFlag: Boolean = true; try { //clear previous error messages on the form this.setState({ showError: false }); if (this.state.tournamentName == "") { validateFlag = false; this.setState({ tournamentError: true }); } else this.setState({ tournamentError: false }); if (this.state.selectedActionsList.length == 0) { validateFlag = false; this.setState({ actionsError: true }); } else this.setState({ actionsError: false }); } catch (error) { console.error("TOT_TOTCreateTournament_validateFields \n", error); this.setState({ showError: true, errorMessage: stringsConstants.TOTErrorMessage + "while validating the form. Below are the details: \n" + JSON.stringify(error), }); } return validateFlag; } // Save Tournament Details to SP Lists 'Tournaments' and 'Tournament Actions' private async saveTournament() { try { console.log(stringsConstants.TotLog + "saving tournament details."); let filter: string = "Title eq '" + this.state.tournamentName.trim().replace(/'/g, "''") + "'"; if (this.ValidateFields()) { let commonServiceManager: commonServices = new commonServices( this.props.context, this.props.siteUrl ); const allItems: any[] = await commonServiceManager.getItemsWithOnlyFilter( stringsConstants.TournamentsMasterList, filter ); if (allItems.length == 0) { let submitTournamentsObject: any = { Title: this.state.tournamentName.trim(), Description: this.state.tournamentDescription, Status: stringsConstants.TournamentStatusNotStarted, }; //Create item in 'Tournaments' list await commonServiceManager .createListItem( stringsConstants.TournamentsMasterList, submitTournamentsObject ) .then((response) => { var selectedTreeArray: ITreeItem[] = this.state.selectedActionsList; //Loop through actions selected and create a list item for each treeview selection selectedTreeArray.forEach((c) => { //Skip parent node for treeview which is not an action if (c.data != undefined) { let submitObject: any = { Title: this.state.tournamentName.trim(), Action: c.label, Category: c.data.split(stringsConstants.StringSeperator)[0], HelpURL: c.data.split(stringsConstants.StringSeperator)[1], Points: c.subLabel .split(stringsConstants.StringSeperatorPoints)[0] .replace(stringsConstants.PointsReplaceString, ""), Description: c.subLabel .split(stringsConstants.StringSeperatorPoints)[1] .replace(stringsConstants.PointsReplaceString, ""), }; //Create an item in 'Tournament Actions' list for each selected action in tree view commonServiceManager .createListItem( stringsConstants.TournamentActionsMasterList, submitObject ) .then((responseObj) => { }) .catch((error) => { //Log error to console and display on the form console.error( "TOT_TOTCreateTournament_saveTournament \n", JSON.stringify(error) ); this.setState({ showError: true, errorMessage: stringsConstants.TOTErrorMessage + "while saving the tournament action details to list. Below are the details: \n" + JSON.stringify(error), showForm: true, showSuccess: false, }); }); } }); this.setState({ showForm: false, showSuccess: true }); }) .catch((error) => { //Log error to console and display on the form console.error( "TOT_TOTCreateTournament_saveTournament \n", JSON.stringify(error) ); this.setState({ showError: true, errorMessage: stringsConstants.TOTErrorMessage + "while saving the tournament details to list. Below are the details: \n" + JSON.stringify(error), }); }); } else { this.setState({ showError: true, errorMessage: "Tournament name already exists. Enter another name for tournament.", }); } } } catch (error) { console.error("TOT_TOTCreateTournament_saveTournament \n", error); this.setState({ showError: true, errorMessage: stringsConstants.TOTErrorMessage + "while saving the tournament. Below are the details: \n" + JSON.stringify(error), }); } } //Render Method public render(): React.ReactElement<ICreateTournamentProps> { return ( <div className={styles.container}> <div className={styles.createTournamentPath}> <img src={require("../assets/CMPImages/BackIcon.png")} className={styles.backImg} /> <span className={styles.backLabel} onClick={() => this.props.onClickCancel()} title="Tournament of Teams" > Tournament of Teams </span> <span className={styles.border}></span> <span className={styles.createTournamentLabel}>Create Tournament</span> </div> <div> {this.state.showSuccess && ( <Label className={styles.successMessage}> <img src={require('../assets/TOTImages/tickIcon.png')} alt="tickIcon" className={styles.tickImage} /> Tournament created successfully. </Label> )} {this.state.showError && ( <Label className={styles.errorMessage}> {this.state.errorMessage} </Label> )} </div> {this.state.showForm && ( <div> <Row> <Col md={6}> <TextField label="Tournament Name" required placeholder="Tournament Name" maxLength={255} value={this.state.tournamentName} onChange={(evt) => this.handleInput(evt, "tournamentName")} styles={labelStyles} /> {this.state.tournamentError && ( <Label className={styles.errorMessage}> Tournament Name is required. </Label> )} </Col> </Row> <br /> <Row> <Col md={6}> <TextField label="Tournament Description" multiline maxLength={500} placeholder="Tournament Description(Max 500 characters)" value={this.state.tournamentDescription} onChange={(evt) => this.handleInput(evt, "tournamentDescription") } styles={labelStyles} /> </Col> </Row> <br /> <Row> <Col className={styles.treeViewContent}> <div className={styles.selectTeamActionArea}> <Label className={styles.selectTeamActionLabel}> Select Teams Actions:{" "} <span className={styles.asteriskStyle}>*</span> </Label> <TooltipHost content="Select from the below available Teams actions to include in the new tournament. To add new tournament actions to choose from, visit the Manage Tournament Actions from the Admin Tools." calloutProps={calloutProps} styles={hostStyles} > <Icon aria-label="Info" iconName="Info" className={classes.icon} /> </TooltipHost> </div> <TreeView items={this.state.actionsList} showCheckboxes={true} selectChildrenIfParentSelected={true} selectionMode={TreeViewSelectionMode.Multiple} defaultExpanded={true} onSelect={this.onActionSelected} /> {this.state.actionsError && ( <Label className={styles.errorMessage}> Select atleast one action to create a tournament. </Label> )} </Col> </Row> </div> )} <div> <Row> <Col> {this.state.showForm && ( <PrimaryButton text="Create Tournament" title="Create Tournament" iconProps={addIcon} onClick={this.saveTournament} className={styles.createBtn} ></PrimaryButton> )} &nbsp; &nbsp; <PrimaryButton text="Back" title="Back" iconProps={backIcon} onClick={() => this.props.onClickCancel()} styles={backBtnStyles} ></PrimaryButton> </Col> </Row> </div> </div> //Final DIV ); } }
the_stack
import * as gt from 'gosling-theme'; import { assign } from 'lodash-es'; import { CHANNEL_DEFAULTS } from '../channel'; /* ----------------------------- THEME ----------------------------- */ export type Theme = ThemeType | ThemeDeep; export type ThemeType = keyof typeof gt.Themes; export enum Themes { light = 'light', dark = 'dark' } export interface ThemeDeep { base: ThemeType; root?: RootStyle; track?: TrackStyle; legend?: LegendStyle; axis?: AxisStyle; // Mark-Specific Styles markCommon?: MarkStyle; point?: MarkStyle; rect?: MarkStyle; triangle?: MarkStyle; area?: MarkStyle; line?: MarkStyle; bar?: MarkStyle; rule?: MarkStyle; link?: MarkStyle; brush?: MarkStyle; text?: MarkStyle & { textFontWeight?: 'bold' | 'normal'; textAnchor?: 'start' | 'middle' | 'end'; }; } // TODO: Better way to implement deep `Required` type instead of having two separate interfaces, i.e., CompleteThemeDeep and ThemeDeep export interface CompleteThemeDeep { base: Required<ThemeType>; root: Required<RootStyle>; track: Required<TrackStyle>; legend: Required<LegendStyle>; axis: Required<AxisStyle>; // Mark-Specific markCommon: Required<MarkStyle>; point: Required<MarkStyle>; rect: Required<MarkStyle>; triangle: Required<MarkStyle>; area: Required<MarkStyle>; line: Required<MarkStyle>; bar: Required<MarkStyle>; rule: Required<MarkStyle>; link: Required<MarkStyle>; brush: Required<MarkStyle>; text: Required<MarkStyle> & Required<{ textFontWeight?: 'bold' | 'normal'; textAnchor?: 'start' | 'middle' | 'end'; }>; } export interface RootStyle { background?: string; titleColor?: string; titleFontSize?: number; titleFontFamily?: string; titleAlign?: 'left' | 'middle' | 'right'; titleFontWeight?: 'bold' | 'normal' | 'light'; titleBackgroundColor?: string; subtitleColor?: string; subtitleFontSize?: number; subtitleFontFamily?: string; subtitleAlign?: 'left' | 'middle' | 'right'; subtitleFontWeight?: 'bold' | 'normal' | 'light'; subtitleBackgroundColor?: string; showMousePosition?: boolean; mousePositionColor?: string; } export interface TrackStyle { background?: string; alternatingBackground?: string; // used to fill all even rows titleColor?: string; titleBackground?: string; titleFontSize?: number; titleAlign?: 'left' | 'middle' | 'right'; outline?: string; outlineWidth?: number; // ... } export interface LegendStyle { position?: 'top' | 'right'; // TODO: support bottom and left, and even all corners (e.g., top-left, bottom-right, etc) tickColor?: string; labelColor?: string; labelFontSize?: number; labelFontWeight?: 'bold' | 'normal' | 'light'; labelFontFamily?: string; background?: string; backgroundOpacity?: number; backgroundStroke?: string; // ... } export interface AxisStyle { tickColor?: string; labelColor?: string; labelFontSize?: number; labelFontWeight?: 'bold' | 'normal' | 'light'; labelFontFamily?: string; baselineColor?: string; gridColor?: string; gridStrokeWidth?: number; gridStrokeType?: 'solid' | 'dashed'; gridStrokeDash?: [number, number]; // ... } export interface MarkStyle { color?: string; size?: number; stroke?: string; strokeWidth?: number; opacity?: number; nominalColorRange?: string[]; quantitativeSizeRange?: [number, number]; // ... } // TODO: Instead of calling this function everytime, create a JSON object and use it throughout the project. export function getTheme(theme: Theme = 'light'): Required<CompleteThemeDeep> { if (typeof theme === 'string') { if (gt.isThereTheme(theme)) { return gt.getTheme(theme); } else if (theme === 'dark' || theme === 'light') { return THEMES[theme]; } else { return THEMES['light']; } } else { // Iterate all keys to override from base let baseSpec = JSON.parse(JSON.stringify(THEMES['light'])); if (gt.isThereTheme(theme.base)) { baseSpec = gt.getTheme(theme.base); } else if (theme.base === 'light' || theme.base === 'dark') { baseSpec = JSON.parse(JSON.stringify(THEMES[theme.base])); } // Override defaults from `base` Object.keys(baseSpec).forEach(k => { if ((theme as any)[k] && k !== 'base') { baseSpec[k] = assign( JSON.parse(JSON.stringify(baseSpec[k])), JSON.parse(JSON.stringify((theme as any)[k])) ); } }); return baseSpec; } } const LightThemeMarkCommonStyle: Required<MarkStyle> = { color: CHANNEL_DEFAULTS.NOMINAL_COLOR[0], size: 1, stroke: 'black', strokeWidth: 0, opacity: 1, nominalColorRange: CHANNEL_DEFAULTS.NOMINAL_COLOR, quantitativeSizeRange: [2, 6] }; const DarkThemeMarkCommonStyle: Required<MarkStyle> = { ...LightThemeMarkCommonStyle, stroke: 'white' }; /* ----------------------------- THEME PRESETS ----------------------------- */ export const THEMES: { [key in Themes]: Required<CompleteThemeDeep> } = { light: { base: 'light', root: { background: 'white', titleColor: 'black', titleBackgroundColor: 'transparent', titleFontSize: 18, titleFontFamily: 'Arial', titleAlign: 'left', titleFontWeight: 'bold', subtitleColor: 'gray', subtitleBackgroundColor: 'transparent', subtitleFontSize: 16, subtitleFontFamily: 'Arial', subtitleFontWeight: 'normal', subtitleAlign: 'left', showMousePosition: true, mousePositionColor: '#000000' }, track: { background: 'transparent', alternatingBackground: 'transparent', titleColor: 'black', titleBackground: 'white', titleFontSize: 24, titleAlign: 'left', outline: 'black', outlineWidth: 1 }, legend: { position: 'top', background: 'white', backgroundOpacity: 0.7, labelColor: 'black', labelFontSize: 12, labelFontWeight: 'normal', labelFontFamily: 'Arial', backgroundStroke: '#DBDBDB', tickColor: 'black' }, axis: { tickColor: 'black', labelColor: 'black', labelFontSize: 12, labelFontWeight: 'normal', labelFontFamily: 'Arial', baselineColor: 'black', gridColor: '#E3E3E3', gridStrokeWidth: 1, gridStrokeType: 'solid', gridStrokeDash: [4, 4] }, markCommon: { ...LightThemeMarkCommonStyle }, point: { ...LightThemeMarkCommonStyle, size: 3 }, rect: { ...LightThemeMarkCommonStyle }, triangle: { ...LightThemeMarkCommonStyle }, area: { ...LightThemeMarkCommonStyle }, line: { ...LightThemeMarkCommonStyle }, bar: { ...LightThemeMarkCommonStyle }, rule: { ...LightThemeMarkCommonStyle, strokeWidth: 1 }, link: { ...LightThemeMarkCommonStyle, strokeWidth: 1 }, text: { ...LightThemeMarkCommonStyle, textAnchor: 'middle', textFontWeight: 'normal' }, brush: { ...LightThemeMarkCommonStyle, color: 'gray', opacity: 0.3, stroke: 'black', strokeWidth: 1 } }, dark: { base: 'dark', root: { background: 'black', titleColor: 'white', titleBackgroundColor: 'transparent', titleFontSize: 18, titleFontFamily: 'Arial', titleAlign: 'middle', titleFontWeight: 'bold', subtitleColor: 'lightgray', subtitleBackgroundColor: 'transparent', subtitleFontSize: 16, subtitleFontFamily: 'Arial', subtitleAlign: 'middle', subtitleFontWeight: 'normal', showMousePosition: true, mousePositionColor: '#FFFFFF' }, track: { background: 'transparent', alternatingBackground: 'transparent', titleColor: 'white', titleBackground: 'black', titleFontSize: 18, titleAlign: 'left', outline: 'white', outlineWidth: 1 }, legend: { position: 'right', background: 'black', backgroundOpacity: 0.7, labelColor: 'white', labelFontSize: 12, labelFontWeight: 'normal', labelFontFamily: 'Arial', backgroundStroke: '#DBDBDB', tickColor: 'white' }, axis: { tickColor: 'white', labelColor: 'white', labelFontSize: 10, labelFontWeight: 'normal', labelFontFamily: 'Arial', baselineColor: 'white', gridColor: 'gray', gridStrokeWidth: 1, gridStrokeType: 'solid', gridStrokeDash: [4, 4] }, markCommon: { ...DarkThemeMarkCommonStyle }, point: { ...DarkThemeMarkCommonStyle, size: 3 }, rect: { ...DarkThemeMarkCommonStyle }, triangle: { ...DarkThemeMarkCommonStyle }, area: { ...DarkThemeMarkCommonStyle }, line: { ...DarkThemeMarkCommonStyle }, bar: { ...DarkThemeMarkCommonStyle }, rule: { ...DarkThemeMarkCommonStyle, strokeWidth: 1 }, link: { ...DarkThemeMarkCommonStyle, strokeWidth: 1 }, text: { ...DarkThemeMarkCommonStyle, textAnchor: 'middle', textFontWeight: 'normal' }, brush: { ...DarkThemeMarkCommonStyle, color: 'lightgray', opacity: 0.3, stroke: 'white', strokeWidth: 1 } } };
the_stack
{ // Validator test program.(socket.io client) const io = require("socket.io-client"); const config = require("config"); // Specify the server (Validator) of the communication destination const validatorUrl = config.validatorUrl; console.log("validatorUrl: " + validatorUrl); const options = { rejectUnauthorized: false, // temporary avoidance since self-signed certificates are used reconnection: false, timeout: 20000, }; const socket = io(validatorUrl, options); // For reading keys and certificates const fs = require("fs"); const path = require("path"); //Constant definition //Fabric node-sdk const FabricCAService = require("fabric-ca-client"); const Client = require("fabric-client"); //Cryptographic const hash = require("fabric-client/lib/hash"); const jsrsa = require("jsrsasign"); const { KEYUTIL } = jsrsa; const elliptic = require("elliptic"); const EC = elliptic.ec; // Keys and certificates issued by Fabric-CA (STM administrator, general user) const privateKeyPem = "-----BEGIN PRIVATE KEY-----\nMIGHAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBG0wawIBAQQgQ3pbxM94ZzHPEHW7\n5TQ1N/WfCLSgqY97dfyF34WiJz2hRANCAATROM5gNB8NsA5TfBg2/GB5pMT+vzwG\nJ47lXjK7/oQmTjIEexzJpEKestn16rIVrn7cblXSYDuFtPDjyZ14wCuw\n-----END PRIVATE KEY-----\n"; const certPem = "-----BEGIN CERTIFICATE-----\nMIICAjCCAaigAwIBAgIUYcAcX63XaN2Omym6hEXF+Kxzx2QwCgYIKoZIzj0EAwIw\nczELMAkGA1UEBhMCVVMxEzARBgNVBAgTCkNhbGlmb3JuaWExFjAUBgNVBAcTDVNh\nbiBGcmFuY2lzY28xGTAXBgNVBAoTEG9yZzEuZXhhbXBsZS5jb20xHDAaBgNVBAMT\nE2NhLm9yZzEuZXhhbXBsZS5jb20wHhcNMjAwNzI3MTAzNDAwWhcNMjEwNzI3MTAz\nOTAwWjAhMQ8wDQYDVQQLEwZjbGllbnQxDjAMBgNVBAMTBWFkbWluMFkwEwYHKoZI\nzj0CAQYIKoZIzj0DAQcDQgAE0TjOYDQfDbAOU3wYNvxgeaTE/r88BieO5V4yu/6E\nJk4yBHscyaRCnrLZ9eqyFa5+3G5V0mA7hbTw48mdeMArsKNsMGowDgYDVR0PAQH/\nBAQDAgeAMAwGA1UdEwEB/wQCMAAwHQYDVR0OBBYEFBMOvw1wPpaBeZIpqc3AFbGs\nY0KMMCsGA1UdIwQkMCKAIEI5qg3NdtruuLoM2nAYUdFFBNMarRst3dusalc2Xkl8\nMAoGCCqGSM49BAMCA0gAMEUCIQDXvckX5bZ5mGPHpQ49aKSFsGJkwrX1BnW7DwA+\n4suQPQIgVGKIiQBQDGlOQHkt9lqno/yFiFZSjzZSS24LFIJNKU4=\n-----END CERTIFICATE-----\n"; const mspId = config.fabric.mspid; // ## Request for "changeCarOwner" const carId = "CAR11"; const newOwner = "Charlie"; const contract = { channelName: "mychannel" }; const method = { type: "sendSignedTransaction" }; //const args = {"args": [carID]}; const func = "changeCarOwner"; const args = { carId: carId, newOwner: newOwner, }; // function param const requestData = { func: func, args: args, }; const json2str = (jsonObj) => { try { return JSON.stringify(jsonObj); } catch (error) { return null; } }; // BEGIN Signature process===================================================================================== // this ordersForCurve comes from CryptoSuite_ECDSA_AES.js and will be part of the // stand alone fabric-sig package in future. const ordersForCurve = { secp256r1: { halfOrder: elliptic.curves.p256.n.shrn(1), order: elliptic.curves.p256.n, }, secp384r1: { halfOrder: elliptic.curves.p384.n.shrn(1), order: elliptic.curves.p384.n, }, }; // this function comes from CryptoSuite_ECDSA_AES.js and will be part of the // stand alone fabric-sig package in future. const _preventMalleability = (sig, curveParams) => { const halfOrder = ordersForCurve[curveParams.name].halfOrder; if (!halfOrder) { throw new Error( 'Can not find the half order needed to calculate "s" value for immalleable signatures. Unsupported curve name: ' + curveParams.name, ); } // in order to guarantee 's' falls in the lower range of the order, as explained in the above link, // first see if 's' is larger than half of the order, if so, it needs to be specially treated if (sig.s.cmp(halfOrder) === 1) { // module 'bn.js', file lib/bn.js, method cmp() // convert from BigInteger used by jsrsasign Key objects and bn.js used by elliptic Signature objects const bigNum = ordersForCurve[curveParams.name].order; sig.s = bigNum.sub(sig.s); } return sig; }; /** * this method is used for test at this moment. In future this * would be a stand alone package that running at the browser/cellphone/PAD * * @param {string} privateKey PEM encoded private key * @param {Buffer} proposalBytes proposal bytes */ const sign = (privateKey, proposalBytes, algorithm, keySize) => { const hashAlgorithm = algorithm.toUpperCase(); const hashFunction = hash[`${hashAlgorithm}_${keySize}`]; const ecdsaCurve = elliptic.curves[`p${keySize}`]; const ecdsa = new EC(ecdsaCurve); const key = KEYUTIL.getKey(privateKey); const signKey = ecdsa.keyFromPrivate(key.prvKeyHex, "hex"); const digest = hashFunction(proposalBytes); let sig = ecdsa.sign(Buffer.from(digest, "hex"), signKey); sig = _preventMalleability(sig, key.ecparams); return Buffer.from(sig.toDER()); }; const signProposal = (proposalBytes, paramPrivateKeyPem) => { console.log("signProposal start"); const signature = sign(paramPrivateKeyPem, proposalBytes, "sha2", 256); const signedProposal = { signature, proposal_bytes: proposalBytes }; return signedProposal; }; // END Signature process========================================================================================= // setup TLS for this client const TLSSetup = async (client, enrollmentID, secret) => { const tlsOptions = { trustedRoots: [], verify: false, }; console.log("tlssetup start"); const caService = new FabricCAService( config.fabric.ca.url, tlsOptions, config.fabric.ca.name, ); const req = { enrollmentID: enrollmentID, enrollmentSecret: secret, profile: "tls", }; const enrollment = await caService.enroll(req); client.setTlsClientCertAndKey( enrollment.certificate, enrollment.key.toBytes(), ); }; //Creating a channel object const setupChannel = async (channelName) => { console.log("setupChannel start"); const client = new Client(); await TLSSetup( client, config.fabric.submitter.name, config.fabric.submitter.secret, ); const channel = client.newChannel(channelName); //add peer to channel //const peerTLSCertPath = path.resolve(__dirname, './crypto-config/peerOrganizations/org1.example.com/peers/peer0.org1.example.com/tlscacerts/org1.example.com-cert.pem'); //const peerPEMCert = fs.readFileSync(peerTLSCertPath, 'utf8'); for (let i = 0; i < config.fabric.peers.length; i++) { const peer = client.newPeer( config.fabric.peers[i].requests, /*{ pem: peerPEMCert, 'ssl-target-name-override': 'peer0.org1.example.com', } */ ); channel.addPeer(peer); } //add orderer to channel /* const ordererTLSCertPath = path.resolve(__dirname, './crypto-config/ordererOrganizations/example.com/orderers/orderer.example.com/tlscacerts/example.com-cert.pem'); const ordererPEMCert = fs.readFileSync(ordererTLSCertPath, 'utf8'); */ const orderer = client.newOrderer( config.fabric.orderer.url, /*{ pem: ordererPEMCert, 'ssl-target-name-override': 'orderer.example.com', } */ ); channel.addOrderer(orderer); // TODO: channel.initialize() should not require an signning identity // await channel.initialize(); return channel; }; // The following three signatures are required when sending transactions and monitoring block commits. // Endorsement, Commit -> Signed by STM user. Request a signature from the authorization/signature server. // RegisterChannelEventHub -> Signed by msp user (User1@example.com) const Invoke = async (reqBody, isWait) => { // exports.Invoke = async function(reqBody, isWait){ //var eventhubs = []; //For the time being, give up the eventhub connection of multiple peers. let invokeResponse; //Return value from chain code let channel; let eh; //EventHub return new Promise(async function (resolve, reject) { try { //channel object generation if (channel == undefined) { channel = await setupChannel(config.fabric.channelName); } /* * Endorse step */ const transactionProposalReq = { fcn: reqBody.func, //Chain code function name args: [reqBody.args.carId, reqBody.args.newOwner], //Chaincode argument chaincodeId: "fabcar", channelId: config.fabric.channelName, }; console.log(transactionProposalReq); const { proposal, txId } = channel.generateUnsignedProposal( transactionProposalReq, config.fabric.mspid, certPem, ); console.log("proposal end"); console.log(`##txId: ${txId.getTransactionID()}`); const signedProposal = signProposal(proposal.toBuffer(), privateKeyPem); const targets = []; for (let i = 0; i < config.fabric.peers.length; i++) { const peer = channel.getPeer( config.fabric.peers[i].requests.split("//")[1], ); targets.push(peer); } const sendSignedProposalReq = { signedProposal, targets }; const proposalResponses = await channel.sendSignedProposal( sendSignedProposalReq, ); console.log("successfully send signedProposal"); let allGood = true; for (const i in proposalResponses) { let oneGood = false; if ( proposalResponses && proposalResponses[i].response && proposalResponses[i].response.status === 200 ) { if (proposalResponses[i].response.payload) { invokeResponse = new String( proposalResponses[i].response.payload, ); } oneGood = true; } else { console.log("transaction proposal was bad"); const resStr = proposalResponses[0].toString(); const errMsg = resStr.replace("Error: ", ""); return reject(errMsg); } allGood = allGood && oneGood; } //If the return value of invoke is an empty string, store txID if (invokeResponse == "") { invokeResponse = txId.getTransactionID(); } //Error if all peers do not return status 200 if (!allGood) { throw new Error( "Failed to send Proposal or receive valid response. Response null or status is not 200. exiting...", ); } /** * End the endorse step. * Start to commit the tx. */ const commitReq = { proposalResponses, proposal, }; const commitProposal = channel.generateUnsignedTransaction(commitReq); console.log("Successfully build commit transaction proposal"); // sign this commit proposal at local const signedCommitProposal = signProposal( commitProposal.toBuffer(), privateKeyPem, ); console.log("Successfully build endorse transaction proposal"); const retRequestData = { contract: contract, method: method, args: { args: [ { signedCommitProposal: signedCommitProposal, commitReq: commitReq, }, ], }, }; return resolve(retRequestData); } catch (e) { console.log(`error at Invoke: err=${e}`); return reject(e); } }); }; socket.on("connect_error", (err) => { console.log("####connect_error:", err); // end communication socket.disconnect(); process.exit(0); }); socket.on("connect_timeout", (err) => { console.log("####Error:", err); // end communication socket.disconnect(); process.exit(0); }); socket.on("error", (err) => { console.log("####Error:", err); }); socket.on("eventReceived", function (res) { // output the data received from the client console.log("#[recv]eventReceived, res: " + json2str(res)); }); const requestStopMonitor = () => { console.log("##exec requestStopMonitor()"); socket.emit("stopMonitor"); setTimeout(function () { // end communication socket.disconnect(); process.exit(0); }, 5000); }; // request StartMonitor const requestStartMonitor = () => { console.log("##exec requestStartMonitor()"); socket.emit("startMonitor"); setTimeout(requestStopMonitor, 15000); }; const sendRequest = () => { // console.log("exec sendRequest()"); console.log("#[send]requestData: " + json2str(requestData)); Invoke(requestData, true) .then((returnvalue) => { //console.log('success : ' + json2str(returnvalue)); console.log(`emit request2`); socket.emit("request2", returnvalue); }) .catch((err) => { console.log("failed : " + err); }); }; setTimeout(requestStartMonitor, 2000); // TODO: setTimeout(sendRequest, 4000); }
the_stack
import * as React from 'react'; import * as Handlebars from "handlebars"; import * as strings from 'contentQueryStrings'; import { Spinner } from 'office-ui-fabric-react'; import { isEmpty } from '@microsoft/sp-lodash-subset'; import { Text } from '@microsoft/sp-core-library'; import { IContentQueryProps } from './IContentQueryProps'; import { IContentQueryState } from './IContentQueryState'; import { IContentQueryTemplateContext } from './IContentQueryTemplateContext'; import { SPComponentLoader } from '@microsoft/sp-loader'; import styles from './ContentQuery.module.scss'; import { Placeholder } from "@pnp/spfx-controls-react/lib/Placeholder"; import { Icon } from 'office-ui-fabric-react/lib/components/Icon'; import { IMandatoryFieldsStatus } from './IMandatoryFieldsStatus'; import { IReadonlyTheme } from '@microsoft/sp-component-base'; export default class ContentQuery extends React.Component<IContentQueryProps, IContentQueryState> { /************************************************************************************* * Constants *************************************************************************************/ private readonly logSource = "ContentQuery.tsx"; private readonly nsReactContentQuery = "ReactContentQuery"; private readonly nsExternalScripts = "ExternalScripts"; private readonly callbackOnPreRenderName = "onPreRender"; private readonly callbackOnPostRenderName = "onPostRender"; /************************************************************************************* * Stores the timestamps of each async calls in order to wait for the last call in * case multiple calls have been fired in a short lapse of time by updaing the * toolpane too fast *************************************************************************************/ private onGoingAsyncCalls: number[]; /************************************************************************************* * Component's constructor * @param props * @param state *************************************************************************************/ constructor(props: IContentQueryProps, state: IContentQueryState) { super(props); // Imports the handlebars-helpers let helpers = require<any>('handlebars-helpers')({ handlebars: Handlebars }); // Ensures the WebPart's namespace for external scripts window[this.nsReactContentQuery] = window[this.nsReactContentQuery] || {}; window[this.nsReactContentQuery][this.nsExternalScripts] = window[this.nsReactContentQuery][this.nsExternalScripts] || {}; this.onGoingAsyncCalls = []; this.state = { loading: true, processedTemplateResult: null, error: null }; } /************************************************************************************* * Returns whether the specified call is the LAST executed call within the stored calls *************************************************************************************/ private isLastExecutedCall(timeStamp: number) { return (this.onGoingAsyncCalls.length > 0 && this.onGoingAsyncCalls.filter((t: number) => { return t > timeStamp; }).length == 0); } /************************************************************************************* * Loads the external scritps sequentially (one after the other) if any *************************************************************************************/ private loadExternalScriptsSequentially(scriptUrls: string[]): Promise<{}> { var index = 0; var _this_ = this; return new Promise((resolve, reject) => { function next() { if (scriptUrls && index < scriptUrls.length) { SPComponentLoader.loadScript(scriptUrls[index++]) .then(next) .catch((error) => { // As of August 12th 2017, Log.error doesn't seem to do anything, so I use a console.log on top of it for now. //Log.error(_this_.logSource, error, _this_.props.wpContext.serviceScope); console.log(error); next(); }); } else { resolve(); } } next(); }); } /************************************************************************************* * Loads the items asynchronously and wraps them into a context object for handlebars *************************************************************************************/ private loadTemplateContext() { if (this.getMandatoryFieldsStatus().allConfigured) { // Stores the current call timestamp locally let currentCallTimeStamp = new Date().valueOf(); this.onGoingAsyncCalls.push(currentCallTimeStamp); // Sets the state to "loading" only if it's the only async call going on (otherwise it's already loading) if (this.onGoingAsyncCalls.length == 1) { this.setState({ loading: true, processedTemplateResult: null, error: null }); } // Fires the async call with its associated timestamp this.props.onLoadTemplateContext(this.props.querySettings, currentCallTimeStamp).then((templateContext: IContentQueryTemplateContext) => { // Loads the handlebars template this.loadTemplate().then((templateContent: string) => { // Only process the result of the current async call if it's the last in the ordered queue if (this.isLastExecutedCall(templateContext.callTimeStamp)) { // Resets the onGoingAsyncCalls this.onGoingAsyncCalls = []; // Process the handlebars template this.processTemplate(templateContent, templateContext); } }) .catch((error: string) => { this.setState({ loading: false, processedTemplateResult: null, error: Text.format(this.props.strings.errorLoadingTemplate, error) }); }); }) .catch((error) => { this.setState({ loading: false, processedTemplateResult: null, error: Text.format(this.props.strings.errorLoadingQuery, error) }); }); } else { this.setState({ loading: false, processedTemplateResult: null, error: null }); } } /************************************************************************************* * Loads the template from url if available, otherwise returns the inline template *************************************************************************************/ private loadTemplate(): Promise<string> { // Resolves the template content if no template url if (isEmpty(this.props.templateUrl)) { return Promise.resolve(this.props.templateText); } return new Promise<string>((resolve, reject) => { this.props.onLoadTemplate(this.props.templateUrl).then((templateContent: string) => { resolve(templateContent); }) .catch((error: string) => { reject(error); }); }); } /************************************************************************************* * Process the specified handlebars template with the given template context * @param templateContent : The handlebars template that needs to be compiled * @param templateContext : The context that must be applied to the compiled template *************************************************************************************/ private processTemplate(templateContent: string, templateContext: IContentQueryTemplateContext) { try { // Calls the external OnPreRender callbacks if any this.executeExternalCallbacks(this.callbackOnPreRenderName); // Processes the template let template = Handlebars.compile(templateContent); let result = template(templateContext); // Updates the state only if the stored calls are still empty (just in case they get updated during the processing of the handlebars template) if (this.onGoingAsyncCalls.length == 0) { this.setState({ loading: false, processedTemplateResult: result, error: null }); } // Calls the external OnPostRender callbacks if any this.executeExternalCallbacks(this.callbackOnPostRenderName); // Bind any item selector control in the template this.bindItemSelectors(); } catch (error) { this.setState({ loading: false, processedTemplateResult: null, error: Text.format(this.props.strings.errorProcessingTemplate, error) }); } } /************************************************************************************* * Executes the specified callback for every external script, if available *************************************************************************************/ private executeExternalCallbacks(callbackName: string) { if (this.props.externalScripts) { // Gets the ReactContentQuery namespace previously created in the constructor var ReactContentQuery = window[this.nsReactContentQuery]; // Loops through all the external scripts of the current WebPart for (let scriptUrl of this.props.externalScripts) { // Generates a valid namespace suffix based on the current file name var namespaceSuffix = this.generateNamespaceFromScriptUrl(scriptUrl); // Checks if the current file's namespace is available within the page var scriptNamespace = ReactContentQuery[this.nsExternalScripts][namespaceSuffix]; if (scriptNamespace) { // Checks if the needed callback is available in the script's namespace var callback = scriptNamespace[callbackName]; if (callback) { callback(this.props.wpContext, Handlebars); } } } } } /************************************************************************************* * Extracts the file name out of the specified url and normalizes it for a namespace *************************************************************************************/ private generateNamespaceFromScriptUrl(scriptUrl: string): string { return scriptUrl.substring(scriptUrl.lastIndexOf('/') + 1).replace('.js', '').replace(/[^a-zA-Z0-9]/g, ""); } /************************************************************************************* * Returns whether all mandatory fields are configured or not *************************************************************************************/ private getMandatoryFieldsStatus(): IMandatoryFieldsStatus { const needsSiteUrl: boolean = isEmpty(this.props.siteUrl); const needsWebUrl: boolean = isEmpty(this.props.querySettings.webUrl); const needsListId: boolean = isEmpty(this.props.querySettings.listId); const needsViewFields: boolean = isEmpty(this.props.querySettings.viewFields); const hasTemplate: boolean = (!isEmpty(this.props.templateUrl) || !isEmpty(this.props.templateText)); const result: IMandatoryFieldsStatus = { needsSiteUrl, needsWebUrl, needsListId, needsViewFields, hasTemplate, needsTemplate: !hasTemplate, allConfigured: !needsSiteUrl && !needsWebUrl && !needsListId && !needsViewFields && hasTemplate }; return result; } /************************************************************************************* * Converts the specified HTML by an object required for dangerouslySetInnerHTML * @param html *************************************************************************************/ private createMarkup(html: string) { return { __html: this._processTheme(html) }; } /************************************************************************************* * Selects all the item selector controls, if any, in the template and binds the * onclick event in order to process the selection logic for Dynamic Data consumers *************************************************************************************/ private bindItemSelectors() { // An item selector can be something like the following HTML in the Handlebars template // // <button class="selectItem" data-itemId="{{ID.textValue}}">Select</button> // // mind the 'selectItem' CSS class name and the data-itemId attributes, which are mandatory const itemSelectorElements = document.querySelectorAll(`.${styles.cqwp} .selectItem`); if (itemSelectorElements) { [].forEach.call(itemSelectorElements, itemSelector => { itemSelector.addEventListener("click", this.itemSelectorClick); }); } } /************************************************************************************* * Handles the click event on an item selector in the rendered template *************************************************************************************/ private itemSelectorClick = (e) => { e.preventDefault(); const webUrl : string = this.props.querySettings.webUrl; const listId : string = this.props.querySettings.listId; const itemId : number = e.target.getAttribute('data-itemId'); this.props.onSelectedItem({ webUrl: webUrl, listId: listId, itemId: itemId }); } /************************************************************************************* * Called once after initial rendering *************************************************************************************/ public componentDidMount(): void { this.loadExternalScriptsSequentially(this.props.externalScripts).then(() => { this.loadTemplateContext(); }); } /************************************************************************************* * Gets called when the WebPart refreshes (because of the reactive mode for instance) *************************************************************************************/ public componentDidUpdate(prevProps: IContentQueryProps, prevState: IContentQueryState): void { if (prevProps.stateKey !== this.props.stateKey) { this.loadExternalScriptsSequentially(this.props.externalScripts).then(() => { this.loadTemplateContext(); }); } } /************************************************************************************* * Renders the Content by Query WebPart *************************************************************************************/ public render(): React.ReactElement<IContentQueryProps> { const { semanticColors }: IReadonlyTheme = this.props.themeVariant; const loading: JSX.Element = this.state.loading ? <Spinner label={this.props.strings.loadingItems} /> : <div />; const error: JSX.Element = this.state.error ? <div className={styles.cqwpError}>{this.state.error}</div> : <div />; const mandatoryFieldsConfigured: IMandatoryFieldsStatus = this.getMandatoryFieldsStatus(); const { needsSiteUrl, needsWebUrl, needsListId, needsViewFields, hasTemplate, needsTemplate, allConfigured, } = mandatoryFieldsConfigured; return ( <div className={styles.cqwp} style={{backgroundColor: semanticColors.bodyBackground}}> {loading} {error} {/* Shows the validation checklist if mandatory properties aren't all configured */} {/* UPDATE 1.0.12: Changed to placeholder and removed use of checkboxes due to accessibility reasons */} {!allConfigured && !this.state.loading && !this.state.error && <Placeholder iconName='Edit' iconText={strings.PlaceholderIconText} description={this.props.strings.mandatoryProperties} buttonLabel={strings.PlaceholderButtonLabel} onConfigure={this._onConfigure} > <div className={styles.cqwpValidations}> <Icon iconName={needsSiteUrl ? 'Cancel' : 'CheckMark'} className={needsSiteUrl ? styles.incomplete : styles.complete} title={needsSiteUrl ? strings.IncompleteLabel : strings.CompleteLabel} /> {strings.SiteUrlChecklistLabel}<br /> <Icon iconName={needsWebUrl ? 'Cancel' : 'CheckMark'} className={needsWebUrl ? styles.incomplete : styles.complete} title={needsWebUrl ? strings.IncompleteLabel : strings.CompleteLabel} /> {strings.WebUrlChecklistLabel}<br /> <Icon iconName={needsListId ? 'Cancel' : 'CheckMark'} className={needsListId ? styles.incomplete : styles.complete} title={needsListId ? strings.IncompleteLabel : strings.CompleteLabel} /> {strings.ListIdChecklistLabel}<br /> <Icon iconName={needsViewFields ? 'Cancel' : 'CheckMark'} className={needsViewFields ? styles.incomplete : styles.complete} title={needsViewFields ? strings.IncompleteLabel : strings.CompleteLabel} /> {strings.ViewFieldsChecklistLabel}<br /> <Icon iconName={needsTemplate ? 'Cancel': 'CheckMark'} className={needsTemplate ? styles.incomplete : styles.complete} title={needsTemplate ? strings.IncompleteLabel : strings.CompleteLabel} /> {strings.TemplateChecklistLabel}<br /> </div> </Placeholder> } {/* Shows the query results once loaded */} {mandatoryFieldsConfigured && !this.state.loading && !this.state.error && <div dangerouslySetInnerHTML={this.createMarkup(this.state.processedTemplateResult)}></div> } </div> ); } private _processTheme = (html: string): string => { const { semanticColors, palette } = this.props.themeVariant; // Find themable colors const expression = /"\[theme:\s?(\w*),\s?default:\s?(.*)]"/; let result; // For every "[theme:themeVariable, default:defaultColor]" in the template while ((result = expression.exec(html)) !== null) { // Find the theme variable they're asking for const themeVariable: string = result[1]; // Find the theme equivalent or default value const themeColor = (semanticColors[themeVariable] ? semanticColors[themeVariable] : palette[themeVariable] ? palette[themeVariable] : result[2]); // Replace the color html = html.replace(result[0], themeColor); } return html; } private _onConfigure = () => { // Context of the web part this.props.wpContext.propertyPane.open(); } }
the_stack
import * as Common from '../../core/common/common.js'; import * as Root from '../../core/root/root.js'; import * as SDK from '../../core/sdk/sdk.js'; import * as Workspace from '../../models/workspace/workspace.js'; import * as NetworkForward from '../../panels/network/forward/forward.js'; import * as UI from '../../ui/legacy/legacy.js'; // eslint-disable-next-line rulesdir/es_modules_import import type * as Network from './network.js'; import * as i18n from '../../core/i18n/i18n.js'; const UIStrings = { /** *@description Command for showing the 'Network' tool */ showNetwork: 'Show Network', /** *@description Title of the Network tool */ network: 'Network', /** *@description Command for showing the 'Network request blocking' tool */ showNetworkRequestBlocking: 'Show Network request blocking', /** *@description Title of the 'Network request blocking' tool in the bottom drawer */ networkRequestBlocking: 'Network request blocking', /** *@description Command for showing the 'Network conditions' tool */ showNetworkConditions: 'Show Network conditions', /** *@description Title of the 'Network conditions' tool in the bottom drawer */ networkConditions: 'Network conditions', /** *@description A tag of Network Conditions tool that can be searched in the command menu */ diskCache: 'disk cache', /** *@description A tag of Network Conditions tool that can be searched in the command menu */ networkThrottling: 'network throttling', /** *@description Command for showing the 'Search' tool */ showSearch: 'Show Search', /** *@description Title of a search bar or tool */ search: 'Search', /** *@description Title of an action in the network tool to toggle recording */ recordNetworkLog: 'Record network log', /** *@description Title of an action in the network tool to toggle recording */ stopRecordingNetworkLog: 'Stop recording network log', /** *@description Title of an action that hides network request details */ hideRequestDetails: 'Hide request details', /** *@description Title of a setting under the Network category in Settings */ colorcodeResourceTypes: 'Color-code resource types', /** *@description A tag of Network color-code resource types that can be searched in the command menu */ colorCode: 'color code', /** *@description A tag of Network color-code resource types that can be searched in the command menu */ resourceType: 'resource type', /** *@description Title of a setting under the Network category that can be invoked through the Command Menu */ colorCodeByResourceType: 'Color code by resource type', /** *@description Title of a setting under the Network category that can be invoked through the Command Menu */ useDefaultColors: 'Use default colors', /** *@description Title of a setting under the Network category in Settings */ groupNetworkLogByFrame: 'Group network log by frame', /** *@description A tag of Group Network by frame setting that can be searched in the command menu */ netWork: 'network', /** *@description A tag of Group Network by frame setting that can be searched in the command menu */ frame: 'frame', /** *@description A tag of Group Network by frame setting that can be searched in the command menu */ group: 'group', /** *@description Title of a setting under the Network category that can be invoked through the Command Menu */ groupNetworkLogItemsByFrame: 'Group network log items by frame', /** *@description Title of a setting under the Network category that can be invoked through the Command Menu */ dontGroupNetworkLogItemsByFrame: 'Don\'t group network log items by frame', }; const str_ = i18n.i18n.registerUIStrings('panels/network/network-meta.ts', UIStrings); const i18nLazyString = i18n.i18n.getLazilyComputedLocalizedString.bind(undefined, str_); let loadedNetworkModule: (typeof Network|undefined); async function loadNetworkModule(): Promise<typeof Network> { if (!loadedNetworkModule) { // Side-effect import resources in module.json await Root.Runtime.Runtime.instance().loadModulePromise('panels/network'); loadedNetworkModule = await import('./network.js'); } return loadedNetworkModule; } function maybeRetrieveContextTypes<T = unknown>(getClassCallBack: (loadedNetworkModule: typeof Network) => T[]): T[] { if (loadedNetworkModule === undefined) { return []; } return getClassCallBack(loadedNetworkModule); } UI.ViewManager.registerViewExtension({ location: UI.ViewManager.ViewLocationValues.PANEL, id: 'network', commandPrompt: i18nLazyString(UIStrings.showNetwork), title: i18nLazyString(UIStrings.network), order: 40, async loadView() { const Network = await loadNetworkModule(); return Network.NetworkPanel.NetworkPanel.instance(); }, }); UI.ViewManager.registerViewExtension({ location: UI.ViewManager.ViewLocationValues.DRAWER_VIEW, id: 'network.blocked-urls', commandPrompt: i18nLazyString(UIStrings.showNetworkRequestBlocking), title: i18nLazyString(UIStrings.networkRequestBlocking), persistence: UI.ViewManager.ViewPersistence.CLOSEABLE, order: 60, async loadView() { const Network = await loadNetworkModule(); return Network.BlockedURLsPane.BlockedURLsPane.instance(); }, }); UI.ViewManager.registerViewExtension({ location: UI.ViewManager.ViewLocationValues.DRAWER_VIEW, id: 'network.config', commandPrompt: i18nLazyString(UIStrings.showNetworkConditions), title: i18nLazyString(UIStrings.networkConditions), persistence: UI.ViewManager.ViewPersistence.CLOSEABLE, order: 40, tags: [ i18nLazyString(UIStrings.diskCache), i18nLazyString(UIStrings.networkThrottling), i18n.i18n.lockedLazyString('useragent'), i18n.i18n.lockedLazyString('user agent'), i18n.i18n.lockedLazyString('user-agent'), ], async loadView() { const Network = await loadNetworkModule(); return Network.NetworkConfigView.NetworkConfigView.instance(); }, }); UI.ViewManager.registerViewExtension({ location: UI.ViewManager.ViewLocationValues.NETWORK_SIDEBAR, id: 'network.search-network-tab', commandPrompt: i18nLazyString(UIStrings.showSearch), title: i18nLazyString(UIStrings.search), persistence: UI.ViewManager.ViewPersistence.PERMANENT, async loadView() { const Network = await loadNetworkModule(); return Network.NetworkPanel.SearchNetworkView.instance(); }, }); UI.ActionRegistration.registerActionExtension({ actionId: 'network.toggle-recording', category: UI.ActionRegistration.ActionCategory.NETWORK, iconClass: UI.ActionRegistration.IconClass.LARGEICON_START_RECORDING, toggleable: true, toggledIconClass: UI.ActionRegistration.IconClass.LARGEICON_STOP_RECORDING, toggleWithRedColor: true, contextTypes() { return maybeRetrieveContextTypes(Network => [Network.NetworkPanel.NetworkPanel]); }, async loadActionDelegate() { const Network = await loadNetworkModule(); return Network.NetworkPanel.ActionDelegate.instance(); }, options: [ { value: true, title: i18nLazyString(UIStrings.recordNetworkLog), }, { value: false, title: i18nLazyString(UIStrings.stopRecordingNetworkLog), }, ], bindings: [ { shortcut: 'Ctrl+E', platform: UI.ActionRegistration.Platforms.WindowsLinux, }, { shortcut: 'Meta+E', platform: UI.ActionRegistration.Platforms.Mac, }, ], }); UI.ActionRegistration.registerActionExtension({ actionId: 'network.hide-request-details', category: UI.ActionRegistration.ActionCategory.NETWORK, title: i18nLazyString(UIStrings.hideRequestDetails), contextTypes() { return maybeRetrieveContextTypes(Network => [Network.NetworkPanel.NetworkPanel]); }, async loadActionDelegate() { const Network = await loadNetworkModule(); return Network.NetworkPanel.ActionDelegate.instance(); }, bindings: [ { shortcut: 'Esc', }, ], }); UI.ActionRegistration.registerActionExtension({ actionId: 'network.search', category: UI.ActionRegistration.ActionCategory.NETWORK, title: i18nLazyString(UIStrings.search), contextTypes() { return maybeRetrieveContextTypes(Network => [Network.NetworkPanel.NetworkPanel]); }, async loadActionDelegate() { const Network = await loadNetworkModule(); return Network.NetworkPanel.ActionDelegate.instance(); }, bindings: [ { platform: UI.ActionRegistration.Platforms.Mac, shortcut: 'Meta+F', keybindSets: [ UI.ActionRegistration.KeybindSet.DEVTOOLS_DEFAULT, UI.ActionRegistration.KeybindSet.VS_CODE, ], }, { platform: UI.ActionRegistration.Platforms.WindowsLinux, shortcut: 'Ctrl+F', keybindSets: [ UI.ActionRegistration.KeybindSet.DEVTOOLS_DEFAULT, UI.ActionRegistration.KeybindSet.VS_CODE, ], }, ], }); Common.Settings.registerSettingExtension({ category: Common.Settings.SettingCategory.NETWORK, title: i18nLazyString(UIStrings.colorcodeResourceTypes), settingName: 'networkColorCodeResourceTypes', settingType: Common.Settings.SettingType.BOOLEAN, defaultValue: false, tags: [ i18nLazyString(UIStrings.colorCode), i18nLazyString(UIStrings.resourceType), ], options: [ { value: true, title: i18nLazyString(UIStrings.colorCodeByResourceType), }, { value: false, title: i18nLazyString(UIStrings.useDefaultColors), }, ], }); Common.Settings.registerSettingExtension({ category: Common.Settings.SettingCategory.NETWORK, title: i18nLazyString(UIStrings.groupNetworkLogByFrame), settingName: 'network.group-by-frame', settingType: Common.Settings.SettingType.BOOLEAN, defaultValue: false, tags: [ i18nLazyString(UIStrings.netWork), i18nLazyString(UIStrings.frame), i18nLazyString(UIStrings.group), ], options: [ { value: true, title: i18nLazyString(UIStrings.groupNetworkLogItemsByFrame), }, { value: false, title: i18nLazyString(UIStrings.dontGroupNetworkLogItemsByFrame), }, ], }); UI.ViewManager.registerLocationResolver({ name: UI.ViewManager.ViewLocationValues.NETWORK_SIDEBAR, category: UI.ViewManager.ViewLocationCategoryValues.NETWORK, async loadResolver() { const Network = await loadNetworkModule(); return Network.NetworkPanel.NetworkPanel.instance(); }, }); UI.ContextMenu.registerProvider({ contextTypes() { return [ SDK.NetworkRequest.NetworkRequest, SDK.Resource.Resource, Workspace.UISourceCode.UISourceCode, ]; }, async loadProvider() { const Network = await loadNetworkModule(); return Network.NetworkPanel.ContextMenuProvider.instance(); }, experiment: undefined, }); Common.Revealer.registerRevealer({ contextTypes() { return [ SDK.NetworkRequest.NetworkRequest, ]; }, destination: Common.Revealer.RevealerDestination.NETWORK_PANEL, async loadRevealer() { const Network = await loadNetworkModule(); return Network.NetworkPanel.RequestRevealer.instance(); }, }); Common.Revealer.registerRevealer({ contextTypes() { return [NetworkForward.UIRequestLocation.UIRequestLocation]; }, async loadRevealer() { const Network = await loadNetworkModule(); return Network.NetworkPanel.RequestLocationRevealer.instance(); }, destination: undefined, }); Common.Revealer.registerRevealer({ contextTypes() { return [NetworkForward.NetworkRequestId.NetworkRequestId]; }, destination: Common.Revealer.RevealerDestination.NETWORK_PANEL, async loadRevealer() { const Network = await loadNetworkModule(); return Network.NetworkPanel.RequestIdRevealer.instance(); }, }); Common.Revealer.registerRevealer({ contextTypes() { return [ NetworkForward.UIFilter.UIRequestFilter, ]; }, destination: Common.Revealer.RevealerDestination.NETWORK_PANEL, async loadRevealer() { const Network = await loadNetworkModule(); return Network.NetworkPanel.NetworkLogWithFilterRevealer.instance(); }, });
the_stack
import { expect } from "chai"; import React from "react"; import { PropertyRecord } from "@itwin/appui-abstract"; import { Orientation } from "@itwin/core-react"; import { render } from "@testing-library/react"; import { HighlightingComponentProps } from "../../../components-react/common/HighlightingComponentProps"; import { CommonPropertyRenderer } from "../../../components-react/properties/renderers/CommonPropertyRenderer"; describe("CommonPropertyRenderer", () => { describe("createNewDisplayValue", () => { it("should create a value which is highlighted if highlighProps are provided, applyOnLabel is set to true and highlightedText matches part of propertyRecord", () => { const propertyRecord = PropertyRecord.fromString("asdtestasd"); const highlight: HighlightingComponentProps & { applyOnLabel: boolean, applyOnValue: boolean } = { highlightedText: "test", applyOnLabel: false, applyOnValue: true, }; const displayValue = CommonPropertyRenderer.createNewDisplayValue(Orientation.Vertical, propertyRecord, 10, undefined, undefined, undefined, undefined, highlight); const { container } = render(<div>{displayValue}</div>); const element = container.querySelector("mark"); expect(element?.textContent).to.equal("test"); }); it("should create a value which is not highlighted if highlighProps are provided, applyOnLabel is set to true but highlightedText does not match any part of propertyRecord", () => { const propertyRecord = PropertyRecord.fromString("asdtestasd"); const highlight: HighlightingComponentProps & { applyOnLabel: boolean, applyOnValue: boolean } = { highlightedText: "gav", applyOnLabel: false, applyOnValue: true, }; const displayValue = CommonPropertyRenderer.createNewDisplayValue(Orientation.Vertical, propertyRecord, 10, undefined, undefined, undefined, undefined, highlight); const { container } = render(<div>{displayValue}</div>); const element = container.querySelector("mark"); expect(element?.textContent).to.be.undefined; }); it("should create a value which is not highlighted if highlighProps are not provided", () => { const propertyRecord = PropertyRecord.fromString("asdtestasd"); const displayValue = CommonPropertyRenderer.createNewDisplayValue(Orientation.Vertical, propertyRecord, 10, undefined); const { container } = render(<div>{displayValue}</div>); const element = container.querySelector("mark"); expect(element?.textContent).to.be.undefined; }); it("should create a value which is actively highlighted if highlighProps are provided, highlightedText matches part of propertyRecord and property name matches highlight activeMatch propertyName", () => { const propertyRecord = PropertyRecord.fromString("asdtestasd"); propertyRecord.property.name = "testName"; const highlight: HighlightingComponentProps & { applyOnLabel: boolean, applyOnValue: boolean } = { highlightedText: "test", activeHighlight: { highlightedItemIdentifier: "testName", highlightIndex: 0, }, applyOnLabel: false, applyOnValue: true, }; const displayValue = CommonPropertyRenderer.createNewDisplayValue(Orientation.Vertical, propertyRecord, 10, undefined, undefined, undefined, undefined, highlight); const { container } = render(<div>{displayValue}</div>); const element = container.querySelector("mark"); expect(element?.textContent).to.equal("test"); expect(element?.classList.contains("components-activehighlight")).to.be.true; }); it("should not create a value which is actively highlighted if highlighProps are provided, highlightedText matches part of propertyRecord but property name does not match highlight activeMatch propertyName", () => { const propertyRecord = PropertyRecord.fromString("asdtestasd"); propertyRecord.property.name = "testName2"; const highlight: HighlightingComponentProps & { applyOnLabel: boolean, applyOnValue: boolean } = { highlightedText: "test", activeHighlight: { highlightedItemIdentifier: "testName", highlightIndex: 0, }, applyOnLabel: false, applyOnValue: true, }; const displayValue = CommonPropertyRenderer.createNewDisplayValue(Orientation.Vertical, propertyRecord, 10, undefined, undefined, undefined, undefined, highlight); const { container } = render(<div>{displayValue}</div>); const element = container.querySelector("mark"); expect(element?.textContent).to.equal("test"); expect(element?.classList.contains("components-activehighlight")).to.be.false; }); it("should not create a value which is actively highlighted if highlighProps are provided, highlightedText matches part of propertyRecord, property name matches highlight activeMatch propertyName but applyOnLabel is true and matchIndex is in the label scope", () => { const propertyRecord = PropertyRecord.fromString("asdtestasd"); propertyRecord.property.name = "testName"; propertyRecord.property.displayLabel = "tesTtest"; const highlight: HighlightingComponentProps & { applyOnLabel: boolean, applyOnValue: boolean } = { highlightedText: "test", activeHighlight: { highlightedItemIdentifier: "testName", highlightIndex: 1, }, applyOnLabel: true, applyOnValue: true, }; const displayValue = CommonPropertyRenderer.createNewDisplayValue(Orientation.Vertical, propertyRecord, 10, undefined, undefined, undefined, undefined, highlight); const { container } = render(<div>{displayValue}</div>); const element = container.querySelector("mark"); expect(element?.textContent).to.equal("test"); expect(element?.classList.contains("components-activehighlight")).to.be.false; }); it("should create a value which is actively highlighted if highlighProps are provided, highlightedText matches part of propertyRecord, property name matches highlight activeMatch propertyName, applyOnLabel is true and matchIndex is bigger than label matchCount and is in the value scope", () => { const propertyRecord = PropertyRecord.fromString("asdtestasd"); propertyRecord.property.name = "testName"; propertyRecord.property.displayLabel = "tesTtest"; const highlight: HighlightingComponentProps & { applyOnLabel: boolean, applyOnValue: boolean } = { highlightedText: "test", activeHighlight: { highlightedItemIdentifier: "testName", highlightIndex: 2, }, applyOnLabel: true, applyOnValue: true, }; const displayValue = CommonPropertyRenderer.createNewDisplayValue(Orientation.Vertical, propertyRecord, 10, undefined, undefined, undefined, undefined, highlight); const { container } = render(<div>{displayValue}</div>); const element = container.querySelector("mark"); expect(element?.textContent).to.equal("test"); expect(element?.classList.contains("components-activehighlight")).to.be.true; }); it("should not create a value which is highlighted if applyOnValue is false", () => { const propertyRecord = PropertyRecord.fromString("asdtestasd"); const highlight: HighlightingComponentProps & { applyOnLabel: boolean, applyOnValue: boolean } = { highlightedText: "gav", applyOnLabel: false, applyOnValue: true, }; const displayValue = CommonPropertyRenderer.createNewDisplayValue(Orientation.Vertical, propertyRecord, 10, undefined, undefined, undefined, undefined, highlight); const { container } = render(<div>{displayValue}</div>); const element = container.querySelector("mark"); expect(element?.textContent).to.be.undefined; }); }); describe("getLabelOffset", () => { const maxIndent = 17; const minIndent = 6; function setupStaticIndentationTests(orientation: Orientation) { describe("Static indentation", () => { it("returns 0 when indentation is undefined or 0", () => { expect(CommonPropertyRenderer.getLabelOffset(undefined, orientation)).to.be.eq(0); expect(CommonPropertyRenderer.getLabelOffset(0, orientation)).to.be.eq(0); }); it("returns maxIndent when indentation is 1", () => { expect(CommonPropertyRenderer.getLabelOffset(1, orientation)).to.be.equal(maxIndent); }); it("returns maxIndent * 2 when indentation is 2", () => { expect(CommonPropertyRenderer.getLabelOffset(2, orientation)).to.be.equal(maxIndent * 2); }); }); } describe("Vertical orientation", () => { const orientation = Orientation.Vertical; setupStaticIndentationTests(orientation); it("should not shrink indentation in Vertical mode", () => { expect(CommonPropertyRenderer.getLabelOffset(1, orientation, 100, 0.2, 20)).to.be.equal(maxIndent); }); }); describe("Horizontal orientation", () => { const orientation = Orientation.Horizontal; setupStaticIndentationTests(orientation); describe("Shrinking indentation", () => { it("returns 0 when indentation is undefined or 0", () => { expect(CommonPropertyRenderer.getLabelOffset(undefined, orientation, 100, 0.2, 20)).to.be.eq(0); expect(CommonPropertyRenderer.getLabelOffset(0, orientation, 100, 0.1, 20)).to.be.eq(0); }); it("returns maxIndent when indentation is 1 and current label size is bigger than shrink threshold", () => { expect(CommonPropertyRenderer.getLabelOffset(1, orientation, 100, 0.4, 20)).to.be.equal(maxIndent); }); it("returns minIndent when indentation is 1 and current label size is same as minimum label size", () => { expect(CommonPropertyRenderer.getLabelOffset(1, orientation, 100, 0.2, 20)).to.be.equal(minIndent); }); it("returns intermediate value between min and max when indentation is 1 and current label size is between threshold and minimum shrink", () => { expect(CommonPropertyRenderer.getLabelOffset(1, orientation, 100, 0.3, 20)).to.be.equal(10); }); it("returns maxIndent * 4 when indentation is 4 and current label size is larger than shrink threshold", () => { expect(CommonPropertyRenderer.getLabelOffset(4, orientation, 100, 0.9, 20)).to.be.equal(maxIndent * 4); }); it("returns minIndent * 4 when indentation is 4 and current label size is same as minimum label size", () => { expect(CommonPropertyRenderer.getLabelOffset(4, orientation, 100, 0.2, 20)).to.be.equal(minIndent * 4); }); it("returns (maxIndent * 3) + intermediate when indentation is 4 and current label size is between indentation 4 min shrink and threshold", () => { const intermediateSize = 9; const minimumLabelSize = 20; const width = 100; const currentLabelSizeRatio = (minimumLabelSize + (maxIndent * 3) + intermediateSize) / width; expect(CommonPropertyRenderer.getLabelOffset(4, orientation, width, currentLabelSizeRatio, minimumLabelSize)).to.be.equal((maxIndent * 3) + intermediateSize); }); it("returns (maxIndent) + intermediate + (minIndent * 2) when when indentation is 4 and current label size is between indentation 2 threshold and minimum shrink", () => { const intermediateSize = 13; const minimumLabelSize = 20; const width = 100; const currentLabelSizeRatio = (minimumLabelSize + maxIndent + intermediateSize) / width; expect(CommonPropertyRenderer.getLabelOffset(4, orientation, width, currentLabelSizeRatio, minimumLabelSize)).to.be.equal(maxIndent + intermediateSize + (minIndent * 2)); }); }); }); }); });
the_stack
// NOTE: This file is only partially ported and is a work in progress /* eslint-disable */ export default class Tile3DStyle { constructor(styleJson = {}) { this._style = {}; this._ready = false; this._show = undefined; this._color = undefined; this._pointSize = undefined; this._pointOutlineColor = undefined; this._pointOutlineWidth = undefined; this._labelColor = undefined; this._labelOutlineColor = undefined; this._labelOutlineWidth = undefined; this._font = undefined; this._labelStyle = undefined; this._labelText = undefined; this._backgroundColor = undefined; this._backgroundPadding = undefined; this._backgroundEnabled = undefined; this._scaleByDistance = undefined; this._translucencyByDistance = undefined; this._distanceDisplayCondition = undefined; this._heightOffset = undefined; this._anchorLineEnabled = undefined; this._anchorLineColor = undefined; this._image = undefined; this._disableDepthTestDistance = undefined; this._horizontalOrigin = undefined; this._verticalOrigin = undefined; this._labelHorizontalOrigin = undefined; this._labelVerticalOrigin = undefined; this._meta = undefined; this._colorShaderFunction = undefined; this._showShaderFunction = undefined; this._pointSizeShaderFunction = undefined; this._colorShaderFunctionReady = false; this._showShaderFunctionReady = false; this._pointSizeShaderFunctionReady = false; this._colorShaderTranslucent = false; setup(this, styleJson); } // Gets the object defining the style using the get style() { return this._style; } // get show() { return this._show; } set show(value) { this._show = getExpression(this, value); this._style.show = getJsonFromExpression(this._show); this._showShaderFunctionReady = false; } get color() { return this._color; } set color(value) { this._color = getExpression(this, value); this._style.color = getJsonFromExpression(this._color); this._colorShaderFunctionReady = false; } get pointSize() { return this._pointSize; } set pointSize(value) { this._pointSize = getExpression(this, value); this._style.pointSize = getJsonFromExpression(this._pointSize); this._pointSizeShaderFunctionReady = false; } get pointOutlineColor() { return this._pointOutlineColor; } set pointOutlineColor(value) { this._pointOutlineColor = getExpression(this, value); this._style.pointOutlineColor = getJsonFromExpression(this._pointOutlineColor); } get pointOutlineWidth() { return this._pointOutlineWidth; } set pointOutlineWidth(value) { this._pointOutlineWidth = getExpression(this, value); this._style.pointOutlineWidth = getJsonFromExpression(this._pointOutlineWidth); } // Gets or sets the {@link StyleExpression} object used to evaluate the style's <code>labelColor</code> property. get labelColor() { return this._labelColor; } set labelColor(value) { this._labelColor = getExpression(this, value); this._style.labelColor = getJsonFromExpression(this._labelColor); } // Gets or sets the {@link StyleExpression} object used to evaluate the style's <code>labelOutlineColor</code> property. get labelOutlineColor() { return this._labelOutlineColor; } set labelOutlineColor(value) { this._labelOutlineColor = getExpression(this, value); this._style.labelOutlineColor = getJsonFromExpression(this._labelOutlineColor); } // Gets or sets the {@link StyleExpression} object used to evaluate the style's <code>labelOutlineWidth</code> property. get labelOutlineWidth() { return this._labelOutlineWidth; } set labelOutlineWidth(value) { this._labelOutlineWidth = getExpression(this, value); this._style.labelOutlineWidth = getJsonFromExpression(this._labelOutlineWidth); } // Gets or sets the {@link StyleExpression} object used to evaluate the style's <code>font</code> property. get font() { return this._font; } set font(value) { this._font = getExpression(this, value); this._style.font = getJsonFromExpression(this._font); } // Gets or sets the {@link StyleExpression} object used to evaluate the style's <code>label style</code> property. get labelStyle() { return this._labelStyle; } set labelStyle(value) { this._labelStyle = getExpression(this, value); this._style.labelStyle = getJsonFromExpression(this._labelStyle); } // Gets or sets the {@link StyleExpression} object used to evaluate the style's <code>labelText</code> property. get labelText() { return this._labelText; } set labelText(value) { this._labelText = getExpression(this, value); this._style.labelText = getJsonFromExpression(this._labelText); } // Gets or sets the {@link StyleExpression} object used to evaluate the style's <code>backgroundColor</code> property. get backgroundColor() { return this._backgroundColor; } set backgroundColor(value) { this._backgroundColor = getExpression(this, value); this._style.backgroundColor = getJsonFromExpression(this._backgroundColor); } // Gets or sets the {@link StyleExpression} object used to evaluate the style's <code>backgroundPadding</code> property. get backgroundPadding() { return this._backgroundPadding; } set backgroundPadding(value) { this._backgroundPadding = getExpression(this, value); this._style.backgroundPadding = getJsonFromExpression(this._backgroundPadding); } // Gets or sets the {@link StyleExpression} object used to evaluate the style's <code>backgroundEnabled</code> property. get distanceDisplayCondition() { return this._distanceDisplayCondition; } set distanceDisplayCondition(value) { this._distanceDisplayCondition = getExpression(this, value); this._style.distanceDisplayCondition = getJsonFromExpression(this._distanceDisplayCondition); } // Gets or sets the {@link StyleExpression} object used to evaluate the style's <code>heightOffset</code> property. get heightOffset() { return this._heightOffset; } set heightOffset(value) { this._heightOffset = getExpression(this, value); this._style.heightOffset = getJsonFromExpression(this._heightOffset); } // Gets or sets the {@link StyleExpression} object used to evaluate the style's <code>anchorLineEnabled</code> property. get anchorLineEnabled() { return this._anchorLineEnabled; } set anchorLineEnabled(value) { this._anchorLineEnabled = getExpression(this, value); this._style.anchorLineEnabled = getJsonFromExpression(this._anchorLineEnabled); } // Gets or sets the {@link StyleExpression} object used to evaluate the style's <code>anchorLineColor</code> property. get anchorLineColor() { return this._anchorLineColor; } set anchorLineColor(value) { this._anchorLineColor = getExpression(this, value); this._style.anchorLineColor = getJsonFromExpression(this._anchorLineColor); } // Gets or sets the {@link StyleExpression} object used to evaluate the style's <code>image</code> property. get image() { return this._image; } set image(value) { this._image = getExpression(this, value); this._style.image = getJsonFromExpression(this._image); } // Gets or sets the {@link StyleExpression} object used to evaluate the style's <code>disableDepthTestDistance</code> property. get disableDepthTestDistance() { return this._disableDepthTestDistance; } set disableDepthTestDistance(value) { this._disableDepthTestDistance = getExpression(this, value); this._style.disableDepthTestDistance = getJsonFromExpression(this._disableDepthTestDistance); } // Gets or sets the {@link StyleExpression} object used to evaluate the style's <code>horizontalOrigin</code> property. get horizontalOrigin() { return this._horizontalOrigin; } set horizontalOrigin(value) { this._horizontalOrigin = getExpression(this, value); this._style.horizontalOrigin = getJsonFromExpression(this._horizontalOrigin); } // Gets or sets the {@link StyleExpression} object used to evaluate the style's <code>verticalOrigin</code> property. get verticalOrigin() { return this._verticalOrigin; } set verticalOrigin(value) { this._verticalOrigin = getExpression(this, value); this._style.verticalOrigin = getJsonFromExpression(this._verticalOrigin); } // Gets or sets the {@link StyleExpression} object used to evaluate the style's <code>labelHorizontalOrigin</code> property. get labelHorizontalOrigin() { return this._labelHorizontalOrigin; } set labelHorizontalOrigin(value) { this._labelHorizontalOrigin = getExpression(this, value); this._style.labelHorizontalOrigin = getJsonFromExpression(this._labelHorizontalOrigin); } // Gets or sets the {@link StyleExpression} object used to evaluate the style's <code>labelVerticalOrigin</code> property. get labelVerticalOrigin() { return this._labelVerticalOrigin; } set labelVerticalOrigin(value) { this._labelVerticalOrigin = getExpression(this, value); this._style.labelVerticalOrigin = getJsonFromExpression(this._labelVerticalOrigin); } // Gets or sets the object containing application-specific expression that can be explicitly evaluated, e.g., for display in a UI. get meta() { return this._meta; } set meta(value) { this._meta = value; } /** * Gets the color shader function for this style. * * @param {String} functionName Name to give to the generated function. * @param {String} attributePrefix Prefix that is added to any variable names to access vertex attributes. * @param {Object} shaderState Stores information about the generated shader function, including whether it is translucent. * * @returns {String} The shader function. * * @private */ getColorShaderFunction(functionName, attributePrefix, shaderState) { if (this._colorShaderFunctionReady) { shaderState.translucent = this._colorShaderTranslucent; // Return the cached result, may be undefined return this._colorShaderFunction; } this._colorShaderFunctionReady = true; this._colorShaderFunction = defined(this.color) ? this.color.getShaderFunction(functionName, attributePrefix, shaderState, 'vec4') : undefined; this._colorShaderTranslucent = shaderState.translucent; return this._colorShaderFunction; } /** * Gets the show shader function for this style. * * @param {String} functionName Name to give to the generated function. * @param {String} attributePrefix Prefix that is added to any variable names to access vertex attributes. * @param {Object} shaderState Stores information about the generated shader function, including whether it is translucent. * * @returns {String} The shader function. * * @private */ getShowShaderFunction(functionName, attributePrefix, shaderState) { if (this._showShaderFunctionReady) { // Return the cached result, may be undefined return this._showShaderFunction; } this._showShaderFunctionReady = true; this._showShaderFunction = defined(this.show) ? this.show.getShaderFunction(functionName, attributePrefix, shaderState, 'bool') : undefined; return this._showShaderFunction; } /** * Gets the pointSize shader function for this style. * * @param {String} functionName Name to give to the generated function. * @param {String} attributePrefix Prefix that is added to any variable names to access vertex attributes. * @param {Object} shaderState Stores information about the generated shader function, including whether it is translucent. * * @returns {String} The shader function. * * @private */ getPointSizeShaderFunction(functionName, attributePrefix, shaderState) { if (this._pointSizeShaderFunctionReady) { // Return the cached result, may be undefined return this._pointSizeShaderFunction; } this._pointSizeShaderFunctionReady = true; this._pointSizeShaderFunction = defined(this.pointSize) ? this.pointSize.getShaderFunction(functionName, attributePrefix, shaderState, 'float') : undefined; return this._pointSizeShaderFunction; } } function setup(that, styleJson) { // styleJson = defaultValue(clone(styleJson, true), that._style); that._style = styleJson; that.show = styleJson.show; that.color = styleJson.color; that.pointSize = styleJson.pointSize; that.pointOutlineColor = styleJson.pointOutlineColor; that.pointOutlineWidth = styleJson.pointOutlineWidth; that.labelColor = styleJson.labelColor; that.labelOutlineColor = styleJson.labelOutlineColor; that.labelOutlineWidth = styleJson.labelOutlineWidth; that.labelStyle = styleJson.labelStyle; that.font = styleJson.font; that.labelText = styleJson.labelText; that.backgroundColor = styleJson.backgroundColor; that.backgroundPadding = styleJson.backgroundPadding; that.backgroundEnabled = styleJson.backgroundEnabled; that.scaleByDistance = styleJson.scaleByDistance; that.translucencyByDistance = styleJson.translucencyByDistance; that.distanceDisplayCondition = styleJson.distanceDisplayCondition; that.heightOffset = styleJson.heightOffset; that.anchorLineEnabled = styleJson.anchorLineEnabled; that.anchorLineColor = styleJson.anchorLineColor; that.image = styleJson.image; that.disableDepthTestDistance = styleJson.disableDepthTestDistance; that.horizontalOrigin = styleJson.horizontalOrigin; that.verticalOrigin = styleJson.verticalOrigin; that.labelHorizontalOrigin = styleJson.labelHorizontalOrigin; that.labelVerticalOrigin = styleJson.labelVerticalOrigin; var meta = {}; if (defined(styleJson.meta)) { var defines = styleJson.defines; var metaJson = defaultValue(styleJson.meta, defaultValue.EMPTY_OBJECT); for (var property in metaJson) { if (metaJson.hasOwnProperty(property)) { meta[property] = new Expression(metaJson[property], defines); } } } that._meta = meta; that._ready = true; } function getExpression(tileStyle, value) { var defines = defaultValue(tileStyle._style, defaultValue.EMPTY_OBJECT).defines; if (!defined(value)) { return undefined; } else if (typeof value === 'boolean' || typeof value === 'number') { return new Expression(String(value)); } else if (typeof value === 'string') { return new Expression(value, defines); } else if (defined(value.conditions)) { return new ConditionsExpression(value, defines); } return value; } function getJsonFromExpression(expression) { if (!defined(expression)) { return undefined; } else if (defined(expression.expression)) { return expression.expression; } else if (defined(expression.conditionsExpression)) { return clone(expression.conditionsExpression, true); } return expression; }
the_stack
import * as vscode from 'vscode'; import * as fs from 'fs'; import Interpreter from './interpreter'; import JsImport from './jsImport'; import { kebab2camel, base2camel } from './help'; import { WorkspaceFolder, RelativePattern } from 'vscode'; const path = require('path'); export interface ImportObj { path: string; module: { /** * identifier name */ name: string; /** * is default identifier */ default: boolean; /** * is plain file */ isPlainFile?: boolean; /** * should add member to import statement like import 'file.less' */ isNotMember?: boolean; }; isNodeModule: boolean; } export interface RootOptions { emptyMemberPlainFiles: Array<string>, defaultMemberPlainFiles : Array<string>, plainFilesGlob: string, filesToScan: string; excludeFilesToScan: string; } export default class RootScanner { private interpreter = new Interpreter(); private workspaceFolder: WorkspaceFolder; private options: RootOptions; public cache = {}; public nodeModuleCache = {}; public nodeModuleVersion = {}; constructor(workspaceFolder: WorkspaceFolder, options) { this.workspaceFolder = workspaceFolder; this.options = options; } public scanAllImport() { const relativePattern = new RelativePattern(this.workspaceFolder, this.options.filesToScan); // TODO: filter file not in src vscode.workspace.findFiles(relativePattern, this.options.excludeFilesToScan, 99999) .then((files) => this.processFiles(files)); this.findModulesInPackageJson(); this.processPlainFiles(); } public scanFileImport(file: vscode.Uri) { this.deleteFile(file); this.processFile(file); } public deleteFile(file: vscode.Uri) { const keys = Object.keys(this.cache); for (const key of keys) { if (key.startsWith(file.fsPath)) { delete this.cache[key]; } } } private processPlainFiles() { const relativePattern = new vscode.RelativePattern(this.workspaceFolder, this.options.plainFilesGlob); vscode.workspace.findFiles(relativePattern, this.options.excludeFilesToScan, 99999) .then((files) => { files.filter((f) => { return f.fsPath.indexOf('node_modules') === -1 }).map((url) => { this.processPlainFile(url); }) }); } public processPlainFile(url: vscode.Uri) { const parsedFile = path.parse(url.fsPath); const name = base2camel(parsedFile.name); if (this.options.emptyMemberPlainFiles.includes(parsedFile.ext.replace('\.', ''))) { this.cache[`${url.fsPath}-${name}`] = { path: url.fsPath, module: { default: true, name, isPlainFile: true, isNotMember: true, }, isNodeModule: false, }; } else { this.cache[`${url.fsPath}-${name}`] = { path: url.fsPath, module: { default: true, name, isPlainFile: true, }, isNodeModule: false, }; } JsImport.setStatusBar(); } private processFiles(files: vscode.Uri[]) { files.forEach(file => { this.processFile(file); }); return; } private processFile(file: vscode.Uri) { fs.readFile(file.fsPath, 'utf8', (err, data) => { if (err) { return console.log(err); } const fileName = path.parse(file.fsPath).name; // use for unnamed identifier const moduleName = path.basename(path.dirname(file.fsPath)); const isIndex = fileName === 'index'; const modules = this.interpreter.run(data, isIndex, moduleName, fileName); let defaultModule = null; let shouldParse = false; modules.forEach(m => { if (m.parse) { shouldParse = true; return; } this.cache[`${file.fsPath}-${m.name}`] = { path: file.fsPath, module: m, isNodeModule: false, }; if (m.default) { defaultModule = m; } }); if (shouldParse) { // only complex export should be parsed const parsedModules = this.interpreter.runMainFile(data, moduleName, file.fsPath); parsedModules.forEach(m => { if (this.cache[`${file.fsPath}-${m.name}`] == null) { if (m.default && defaultModule != null) { return; } this.cache[`${file.fsPath}-${m.name}`] = { path: file.fsPath, module: m, isNodeModule: false, }; } }); } JsImport.setStatusBar(); }); } public findModulesInPackageJson() { const modules = []; const packageJsonPath = path.join(this.workspaceFolder.uri.fsPath, 'package.json'); if (fs.existsSync(packageJsonPath)) { fs.readFile(packageJsonPath, 'utf8', (err, data) => { if (err) { return console.log(err); } const packageJson = JSON.parse(data); [ "dependencies", "devDependencies", "peerDependencies", "optionalDependencies" ].forEach(key => { if (packageJson.hasOwnProperty(key)) { modules.push(...Object.keys(packageJson[key])); } }) this.deleteUnusedModules(modules); this.cacheModules(modules); }) } } private deleteUnusedModules(modules: Array<string>) { const keys = Object.keys(this.nodeModuleCache); const notexists = keys.filter(key => !modules.includes(this.nodeModuleCache[key].path)); notexists.forEach(name => { if (this.nodeModuleCache[name] != null) { delete this.nodeModuleVersion[this.nodeModuleCache[name].path]; delete this.nodeModuleCache[name]; } }) JsImport.setStatusBar(); } private cacheModules(modules) { modules.forEach((moduleName) => { const modulePath = path.join(this.workspaceFolder.uri.fsPath, 'node_modules', moduleName); const packageJsonPath = path.join(modulePath, 'package.json'); if (fs.existsSync(packageJsonPath)) { fs.readFile(packageJsonPath, 'utf-8', (err, data) => { if (err) { return console.log(err); } const packageJson = JSON.parse(data); if (!this.isCachedByVersion(moduleName, packageJson)) { this.cacheModulesFromMain(moduleName, modulePath, packageJson); } }) } }) } private cacheModulesFromMain(moduleName, modulePath, packageJson) { if (!packageJson.hasOwnProperty('main')) return; let mainFilePath = path.join(modulePath, packageJson.main); if (!fs.existsSync(mainFilePath)) { mainFilePath += '.js'; } if (fs.existsSync(mainFilePath)) { fs.readFile(mainFilePath, 'utf-8', (err, data) => { if (err) { return console.log(err); } const moduleKebabName = kebab2camel(moduleName) const modules = this.interpreter.run(data, true, moduleKebabName, '') let defaultModule = null; modules.forEach(m => { if (m.parse) { return; } this.nodeModuleCache[`${moduleName}-${m.name}`] = { path: moduleName, module: m, isNodeModule: true, }; if (m.default) { defaultModule = m; } }); const parsedModules = this.interpreter.runMainFile(data, moduleKebabName, mainFilePath); parsedModules.forEach(m => { if (this.nodeModuleCache[`${moduleName}-${m.name}`] == null) { if (m.default && defaultModule != null) { return; } this.nodeModuleCache[`${moduleName}-${m.name}`] = { path: moduleName, module: m, isNodeModule: true, }; } }); JsImport.setStatusBar(); }); } } public isCachedByVersion(moduleName, packageJson) { if (packageJson.hasOwnProperty('version')) { if (this.nodeModuleVersion[moduleName] != null) { if (this.nodeModuleVersion[moduleName] === packageJson.version) { return true } else { this.nodeModuleVersion[moduleName] = packageJson.version; return false; } } else { this.nodeModuleVersion[moduleName] = packageJson.version; return false; } } return false; } }
the_stack
module fng.services { /*@ngInject*/ export function formMarkupHelper(cssFrameworkService, inputSizeHelper, addAllService, $filter) { function generateNgShow(showWhen, model) { function evaluateSide(side) { var result = side; if (typeof side === 'string') { if (side.slice(0, 1) === '$') { result = (model || 'record') + '.'; var parts = side.slice(1).split('.'); if (parts.length > 1) { var lastBit = parts.pop(); result += parts.join('.') + '[$index].' + lastBit; } else { result += side.slice(1); } } else { result = '\'' + side + '\''; } } return result; } var conditionText = ['eq', 'ne', 'gt', 'gte', 'lt', 'lte'], conditionSymbols = ['===', '!==', '>', '>=', '<', '<='], conditionPos = conditionText.indexOf(showWhen.comp); if (conditionPos === -1) { throw new Error('Invalid comparison in showWhen'); } return evaluateSide(showWhen.lhs) + conditionSymbols[conditionPos] + evaluateSide(showWhen.rhs); } var isHorizontalStyle = function isHorizontalStyle(formStyle, includeStacked: boolean) { let exclude = ['vertical', 'inline']; if (!includeStacked) { exclude.push('stacked'); } return (!formStyle || formStyle === 'undefined' || !exclude.includes(formStyle)); }; function glyphClass() { return (cssFrameworkService.framework() === 'bs2' ? 'icon' : 'glyphicon glyphicon'); } return { isHorizontalStyle: isHorizontalStyle, fieldChrome: function fieldChrome(scope, info, options) { var classes = info.classes || ''; var template = ''; var closeTag = ''; var insert = ''; info.showWhen = info.showWhen || info.showwhen; // deal with use within a directive if (info.showWhen) { if (typeof info.showWhen === 'string') { insert += 'ng-show="' + info.showWhen + '"'; } else { insert += 'ng-show="' + generateNgShow(info.showWhen, options.model) + '"'; } } if (info.id && typeof info.id.replace === "function") { insert += ' id="cg_' + info.id.replace(/\./g, '-') + '"'; } if (cssFrameworkService.framework() === 'bs3') { classes += ' form-group'; if (options.formstyle === 'vertical' && info.size !== 'block-level') { template += '<div class="row">'; classes += ' col-sm-' + inputSizeHelper.sizeAsNumber(info.size); closeTag += '</div>'; } var modelControllerName; var formName = null; var parts = info.name.split('.'); if (options && typeof options.subkeyno !== 'undefined') { modelControllerName = options.subschemaroot.replace(/\./g, '-') + '-subkey' + options.subkeyno + '-' + parts[parts.length - 1]; } else if (options.subschema) { formName = 'form_' + parts.slice(0, -1).join('_') + '$index'; modelControllerName = info.name.replace(/\./g, '-'); } else { modelControllerName = 'f_' + info.name.replace(/\./g, '_'); } template += '<div' + addAllService.addAll(scope, 'Group', classes, options) + ' ng-class="{\'has-error\': hasError(\'' + formName + '\',\'' + modelControllerName + '\', $index)}"'; closeTag += '</div>'; } else { if (isHorizontalStyle(options.formstyle, true)) { template += '<div' + addAllService.addAll(scope, 'Group', 'control-group', options); closeTag = '</div>'; } else { template += '<span '; closeTag = '</span>'; } } template += (insert || '') + '>'; return {template: template, closeTag: closeTag}; }, label: function label(scope, fieldInfo, addButtonMarkup, options) { var labelHTML = ''; if ((cssFrameworkService.framework() === 'bs3' || (!['inline','stacked'].includes(options.formstyle) && fieldInfo.label !== '')) || addButtonMarkup) { labelHTML = '<label'; var classes = 'control-label'; if (isHorizontalStyle(options.formstyle, false)) { if (!fieldInfo.linklabel) { labelHTML += ' for="' + fieldInfo.id + '"'; } if (typeof fieldInfo.labelDefaultClass !== 'undefined') { // Override default label class (can be empty) classes += ' ' + fieldInfo.labelDefaultClass; } else if (cssFrameworkService.framework() === 'bs3') { classes += ' col-sm-3'; } } else if (['inline','stacked'].includes(options.formstyle)) { labelHTML += ' for="' + fieldInfo.id + '"'; classes += ' sr-only'; } labelHTML += addAllService.addAll(scope, 'Label', null, options) + ' class="' + classes + '">' + fieldInfo.label; if (addButtonMarkup) { labelHTML += ' <i id="add_' + fieldInfo.id + '" ng-click="add(\'' + fieldInfo.name + '\',$event)" class="' + glyphClass() + '-plus-sign"></i>'; } labelHTML += '</label>'; if (fieldInfo.linklabel) { let value: string = '<fng-link fld="' + fieldInfo.name + '" ref="' + fieldInfo.ref + '" text="' + escape(labelHTML) + '"' ; if (fieldInfo.form) { value += ' form="' + fieldInfo.form + '"'; } if (fieldInfo.linktab) { value += ' linktab="' + fieldInfo.linktab + '"'; } value += '></fng-link>'; labelHTML = value; } } return labelHTML; }, glyphClass: glyphClass, allInputsVars: function allInputsVars(scope, fieldInfo, options, modelString, idString, nameString) { var placeHolder = fieldInfo.placeHolder; var common; var compactClass = ''; var sizeClassBS3 = ''; var sizeClassBS2 = ''; var formControl = ''; if (cssFrameworkService.framework() === 'bs3') { compactClass = (['horizontal', 'vertical', 'inline'].indexOf(options.formstyle) === -1) ? ' input-sm' : ''; sizeClassBS3 = 'col-sm-' + inputSizeHelper.sizeAsNumber(fieldInfo.size); formControl = ' form-control'; } else { sizeClassBS2 = (fieldInfo.size ? ' input-' + fieldInfo.size : ''); } if (['inline','stacked'].includes(options.formstyle)) { placeHolder = placeHolder || fieldInfo.label; } common = 'data-ng-model="' + modelString + '"' + (idString ? ' id="' + idString + '" name="' + idString + '" ' : ' name="' + nameString + '" '); common += (placeHolder ? ('placeholder="' + placeHolder + '" ') : ''); if (fieldInfo.popup) { common += 'title="' + fieldInfo.popup + '" '; } if (fieldInfo.ariaLabel) { common += 'aria-label="' + fieldInfo.ariaLabel + '" '; } common += addAllService.addAll(scope, 'Field', null, options); return { common: common, sizeClassBS3: sizeClassBS3, sizeClassBS2: sizeClassBS2, compactClass: compactClass, formControl: formControl }; }, inputChrome: function inputChrome(value, fieldInfo, options: fng.IFormOptions, markupVars) { if (cssFrameworkService.framework() === 'bs3' && isHorizontalStyle(options.formstyle, true) && fieldInfo.type !== 'checkbox') { value = '<div class="bs3-input ' + markupVars.sizeClassBS3 + '">' + value + '</div>'; } // Hack to cope with inline help in directives var inlineHelp = (fieldInfo.helpInline || '') + (fieldInfo.helpinline || ''); if (inlineHelp.length > 0) { let helpMarkup = cssFrameworkService.framework() === 'bs2' ? { el: 'span', cl: 'help-inline'} : {el: 'div', cl: 'help-block'}; value += `<${helpMarkup.el} class="${helpMarkup.cl}">${inlineHelp}</${helpMarkup.el}>`; } if (!options.noid) { value += `<div ng-if="${(options.name || 'myForm')}['${fieldInfo.id}'].$dirty" class="help-block">` + ` <div ng-messages="${(options.name || 'myForm')}['${fieldInfo.id}'].$error">` + ' <div ng-messages-include="error-messages.html">' + ' </div>' + ' </div>' + '</div>'; } if (fieldInfo.help) { value += '<div class="help-block">' + fieldInfo.help + '</div>'; } return value; }, generateSimpleInput: function generateSimpleInput(common, fieldInfo, options) { var result = '<input ' + common + 'type="' + fieldInfo.type + '" '; if (!fieldInfo.label && !fieldInfo.ariaLabel) { result += `aria-label="${fieldInfo.name.replace(/\./g,' ')}" ` } else if (options.subschema) { result += `aria-label="${fieldInfo.label ? ($filter('titleCase')(options.subschemaroot) + ' ' + fieldInfo.label) : (fieldInfo.popup || fieldInfo.name.replace(/\./g,' '))}" ` } if (options.formstyle === 'inline' && cssFrameworkService.framework() === 'bs2' && !fieldInfo.size) { result += 'class="input-small"'; } result += ' />'; return result; }, controlDivClasses: function controlDivClasses(options) { var result = []; if (isHorizontalStyle(options.formstyle, false)) { result.push(cssFrameworkService.framework() === 'bs2' ? 'controls' : 'col-sm-9'); } return result; }, handleInputAndControlDiv: function handleInputAndControlDiv(inputMarkup, controlDivClasses) { if (controlDivClasses.length > 0) { inputMarkup = '<div class="' + controlDivClasses.join(' ') + '">' + inputMarkup + '</div>'; } return inputMarkup; }, handleArrayInputAndControlDiv: function handleArrayInputAndControlDiv(inputMarkup, controlDivClasses, info, options: fng.IFormOptions) { var result = '<div '; if (cssFrameworkService.framework() === 'bs3') { result += 'ng-class="skipCols($index)" '; } result += 'class="' + controlDivClasses.join(' ') + '" id="' + info.id + 'List" '; result += 'ng-repeat="arrayItem in ' + (options.model || 'record') + '.' + info.name + ' track by $index">'; result += inputMarkup; if (info.type !== 'link') { result += '<i ng-click="remove(\'' + info.name + '\',$index,$event)" id="remove_' + info.id + '_{{$index}}" class="' + glyphClass() + '-minus-sign"></i>'; } result += '</div>'; return result; }, addTextInputMarkup: function addTextInputMarkup(allInputsVars, fieldInfo, requiredStr) { var result = ''; var setClass = allInputsVars.formControl.trim() + allInputsVars.compactClass + allInputsVars.sizeClassBS2 + (fieldInfo.class ? ' ' + fieldInfo.class : ''); if (setClass.length !== 0) { result += 'class="' + setClass + '"'; } if (fieldInfo.add) { result += ' ' + fieldInfo.add + ' '; } result += requiredStr; if (fieldInfo.readonly) { result += ` ${typeof fieldInfo.readOnly === 'boolean' ? 'readonly' : 'ng-readonly="' + fieldInfo.readonly + '"'} `; } else { result += ' '; } return result; } } } }
the_stack
import React, { Component } from 'react'; import { View, Animated, Easing, StyleSheet, PanResponder, PanResponderInstance, NativeModules, } from 'react-native'; import { Utils } from 'tuya-panel-utils'; import { FRICTION_LEVEL, DECELERATION } from './constant'; import { Center, StyledTab, StyledTabBtn, StyledTabText, AnimatedView, AnimatedUnderline, } from './styled'; import { getTabWidth, getIndexByDeltaX, getNearestIndexByDeltaX, getCenteredScrollIndex, isValidPress, isValidSwipe, reduceTabLayoutLeft, } from './utils'; import TabMask from './tab-mask'; import TabPanel from './tab-panel'; import TabContent from './tab-content'; import TabScrollView from './tab-scroll-view'; import { TabsProps, ITabsState } from './interface'; const { get } = Utils.CoreUtils; const { winWidth } = Utils.RatioUtils; export default class Tabs extends Component<TabsProps, ITabsState> { static defaultProps = { accessibilityLabel: 'Tabs', style: null, wrapperStyle: null, tabStyle: null, tabActiveStyle: null, tabTextStyle: null, tabActiveTextStyle: null, tabContentStyle: null, underlineStyle: null, underlineWidth: undefined, defaultActiveKey: 0, activeKey: undefined, disabled: false, maxItem: 4, tabPosition: 'top', swipeable: true, activeColor: undefined, // 默认跟随主题色 background: '#fff', onChange: undefined, preload: true, preloadTimeout: 375, velocityThreshold: 0.5, renderPlaceholder: undefined, children: undefined, extraSpace: 0, animationConfig: { duration: 200, easing: Easing.linear, delay: 0, isInteraction: true, useNativeDriver: false, }, isVibration: true, }; constructor(props) { super(props); if ( Array.isArray(props.dataSource) && Array.isArray(props.children) && props.dataSource.length !== props.children.length ) { console.warn('Tabs: 数据源与children数量不匹配,请检查是否配置错误'); } this.state = { activeIndex: this.getCurActiveIndex(props), scrollX: new Animated.Value(0), // 只在tabs数量超过maxItem时使用到 underlineLeft: new Animated.Value(0), underlineWidth: new Animated.Value(0), }; const styleObj = StyleSheet.flatten([props.wrapperStyle, props.style]); this._tabsWidth = (styleObj.width || winWidth) - props.extraSpace; this._tabWidth = getTabWidth(props.maxItem, this._tabsWidth); this._bounds = [0, -this._tabWidth * props.dataSource.length + this._tabsWidth]; // x轴左右边界坐标 this._curDeltaX = 0; // 当前的x轴偏移量 this._tabIsReady = false; this._tabLayouts = []; this._cachedChildren = Array.isArray(props.children) ? new Array(props.children.length).fill(0) : []; this._panResponder = PanResponder.create({ onStartShouldSetPanResponder: () => !this.props.disabled, onStartShouldSetPanResponderCapture: () => !this.props.disabled, onMoveShouldSetPanResponder: () => !this.props.disabled, onMoveShouldSetPanResponderCapture: () => !this.props.disabled, // TODO: 确认是否能被终止 onPanResponderTerminationRequest: () => !this.props.disabled, // 上层的responder是否能中断当前的responder onPanResponderGrant: () => true, onPanResponderMove: this._handleMove, onPanResponderRelease: this._handleRelease, onPanResponderTerminate: this._handleRelease, }); } componentWillReceiveProps(nextProps) { if (this._tabIsReady && typeof nextProps.activeKey !== 'undefined') { this.setState({ activeIndex: this.getCurActiveIndex(nextProps) }, () => { this._startUnderlineAnimation(this.state.activeIndex); }); } } componentWillUnmount() { this._stopAllAnimations(); } get isMultiScreen() { return this.props.dataSource.length > this.props.maxItem; } /** * @desc 根据当前的`activeKey`获取当前激活的索引 * @param {Object} props - 当前 */ getCurActiveIndex = props => { const { activeKey, defaultActiveKey } = props; const { dataSource } = this.props; const activeIndex = dataSource.findIndex( d => d.value === activeKey || d.value === defaultActiveKey ); return activeIndex === -1 ? 0 : activeIndex; }; /** * @desc 获取对应索引对应的tab布局属性 * @param {Number} idx - 索引 */ getCurTabLayout = idx => { const curTabLayout = get(this._tabLayouts, `${idx}`, {}); return curTabLayout; }; static TabPanel = TabPanel; static TabContent = TabContent; static TabScrollView = TabScrollView; _panResponder: PanResponderInstance; _tabsWidth: number; _tabWidth: number; _bounds: number[]; _curDeltaX: number; _tabIsReady: boolean; _tabLayouts: number[]; _cachedChildren: number[]; animationFn: any; /** * @desc 滚动tabs到对应索引的位置 * @param {Number} idx - 滚动到哪个索引的位置 * @param {Function} cb - 滚动动画结束回调 */ scrollToIndex = (idx, cb?: () => void) => { const { animationConfig, dataSource } = this.props; if (idx > dataSource.length - 1) { return; } const toValue = -this._tabWidth * idx; this._stopAllAnimations(); this._curDeltaX = toValue; Animated.timing(this.state.scrollX, { toValue, ...animationConfig, useNativeDriver: false, }).start(cb); }; /** * @desc 滚动下划线到对应索引的位置 * @param {Number} idx - 要滚动到下划线的索引 * @param {Function} cb - 滚动动画结束回调 */ _startUnderlineAnimation = (idx: number, cb?: () => void) => { const { animationConfig, dataSource, maxItem } = this.props; if (idx > dataSource.length - 1) { return; } const curTabLayout = this.getCurTabLayout(idx); this._stopAllAnimations(); this.animationFn = Animated.parallel([ Animated.timing(this.state.underlineLeft, { toValue: curTabLayout.left, ...animationConfig, useNativeDriver: false, }), Animated.timing(this.state.underlineWidth, { toValue: curTabLayout.width, ...animationConfig, useNativeDriver: false, }), ]); this.animationFn.start(() => { const scrollIdx = getCenteredScrollIndex(idx, maxItem, dataSource.length); this.scrollToIndex(scrollIdx); typeof cb === 'function' && cb(); }); }; _stopAllAnimations = () => { this.state.scrollX.stopAnimation(); this.state.underlineLeft.stopAnimation(); this.state.underlineWidth.stopAnimation(); }; /** * @desc 根据x轴偏移量计算出tabs滑动的位置 * @param {Number} dx - x轴偏移量 */ _moveTo(dx) { let deltaX = this._curDeltaX + dx; const [leftBound, rightBound] = this._bounds; if (dx > 0 && deltaX >= leftBound) { // 超出左边界 deltaX = leftBound + (deltaX - leftBound) * FRICTION_LEVEL; } else if (dx < 0 && deltaX <= rightBound) { // 超出右边界 deltaX = rightBound + (deltaX - rightBound) * FRICTION_LEVEL; } this.state.scrollX.setValue(deltaX); return deltaX; } _handleMove = (e, { dx }) => { if (this.isMultiScreen) { this._moveTo(dx); } }; _handleRelease = ({ nativeEvent }, { dx, dy, vx }) => { const isPress = isValidPress(dx, dy); if (isPress) { const { locationX } = nativeEvent; const deltaX = Math.abs(this._curDeltaX) + Math.abs(locationX); const idx = getIndexByDeltaX(deltaX, this._tabWidth); this._handleTabChange(this.props.dataSource[idx], idx); } else if (this.isMultiScreen) { const [leftBound, rightBound] = this._bounds; const { dataSource, maxItem } = this.props; const deltaX = this._moveTo(dx); const maxIdx = Math.max(dataSource.length - maxItem, 0); if ((dx > 0 && deltaX >= leftBound) || (dx < 0 && deltaX <= rightBound)) { const idx = getNearestIndexByDeltaX(deltaX, this._tabWidth, maxIdx); this.scrollToIndex(idx); } else if (isValidSwipe(vx, dx)) { this.state.scrollX.addListener(({ value }) => { if (value > leftBound) { this._curDeltaX = leftBound; this.state.scrollX.stopAnimation(); this.state.scrollX.setValue(leftBound); } else if (value < rightBound) { this._curDeltaX = rightBound; this.state.scrollX.stopAnimation(); this.state.scrollX.setValue(rightBound); } else { this._curDeltaX = value; } }); Animated.decay(this.state.scrollX, { velocity: vx, deceleration: DECELERATION, useNativeDriver: false, }).start(() => { // @ts-ignore this._curDeltaX = this.state.scrollX._value; this.state.scrollX.removeAllListeners(); }); } else { this._curDeltaX = deltaX; } } }; _handleTabLayout = ({ nativeEvent: { layout } }, idx) => { const { dataSource } = this.props; this._tabLayouts[idx] = layout; this._tabIsReady = this._tabLayouts.filter(d => !!d).length === dataSource.length; if (this._tabIsReady) { this._tabLayouts = reduceTabLayoutLeft(this._tabLayouts); this._startUnderlineAnimation(this.state.activeIndex); } }; _handleTabChange = (tab, idx) => { const { dataSource, activeKey, onChange, isVibration } = this.props; if (idx > dataSource.length - 1 || (tab && tab.disabled)) { return; } if (typeof activeKey === 'undefined') { this.setState({ activeIndex: idx }, () => { this._startUnderlineAnimation(idx); }); } if (NativeModules.TYRCTHapticsManager && isVibration) { NativeModules.TYRCTHapticsManager.selection(); } typeof onChange === 'function' && this.props.onChange(tab, idx); }; /** * @desc 根据tabContent滑动的位置动态计算`下划线`的`宽度`和`偏移量`,仿原生动效 * @param {Object} gestureState * @param {Number} idx - 距离当前滑动偏移量最近的索引 * @param {Number} percent - 当前滑动偏移量相对content宽度的百分比 */ _handleTabContentMove = (gestureState, idx, percent) => { const { dataSource } = this.props; const { dx } = gestureState; const minIdx = 0; const maxIdx = dataSource.length - 1; const isToRight = dx < 0; const rPercent = isToRight ? percent : 1 - percent; const isNextPage = rPercent >= 0.5; if (isToRight) { const nextIdx = Math.min(isNextPage ? idx : idx + 1, maxIdx); if (this.state.activeIndex === maxIdx && nextIdx === maxIdx) { return; } const curTabLayout = this.getCurTabLayout(this.state.activeIndex); const nextTabLayout = this.getCurTabLayout(nextIdx); const { left: curLeft, width: curWidth } = curTabLayout; const { left: nextLeft, width: nextWidth } = nextTabLayout; const moveDelta = curWidth * 0.666667; const totalLen = nextLeft + nextWidth * 0.5 - curLeft - curWidth; let newWidth = curTabLayout.width + (totalLen - moveDelta) * Math.min(rPercent * 2, 1); let newLeft = curLeft + moveDelta * Math.min(rPercent * 2, 1); if (isNextPage) { const extraWidth = nextLeft - curLeft; newWidth -= extraWidth * Math.min((rPercent - 0.5) * 2, 1); newLeft += extraWidth * Math.min((rPercent - 0.5) * 2, 1); } this.state.underlineWidth.setValue(newWidth); this.state.underlineLeft.setValue(newLeft); } else { const nextIdx = Math.max(isNextPage ? idx : idx - 1, minIdx); if (this.state.activeIndex === minIdx && nextIdx === minIdx) { return; } const curTabLayout = this.getCurTabLayout(this.state.activeIndex); const nextTabLayout = this.getCurTabLayout(nextIdx); const { left: curLeft, width: curWidth } = curTabLayout; const { left: nextLeft, width: nextWidth } = nextTabLayout; const moveDelta = curWidth * 0.333333; const totalLen = curLeft - nextLeft - nextWidth * 0.5; let newWidth = curTabLayout.width + (totalLen - moveDelta) * Math.min(rPercent * 2, 1); let newLeft = curLeft - moveDelta * Math.min(rPercent * 2, 1); if (isNextPage) { const extraWidth = curLeft - nextLeft; newWidth -= extraWidth * Math.min((rPercent - 0.5) * 2, 1); newLeft -= extraWidth * Math.min((rPercent - 0.5) * 2, 1); } this.state.underlineWidth.setValue(newWidth); this.state.underlineLeft.setValue(newLeft - (newWidth - curWidth)); } }; _handleTabContentRelease = (gestureState, idx) => { const { dataSource } = this.props; this._handleTabChange(dataSource[idx], idx); this._startUnderlineAnimation(idx); }; _renderTab = (tab, idx) => { const { accessibilityLabel, tabStyle, tabActiveStyle, tabTextStyle, tabActiveTextStyle, activeColor, underlineWidth, } = this.props; const { label, renderTab, ...rest } = tab; const isActive = idx === this.state.activeIndex; const isFixedWidth = typeof underlineWidth === 'number'; const TabText = ( <StyledTabText style={[tabTextStyle, isActive && tabActiveTextStyle]} color={activeColor} text={label} isActive={isActive} /> ); return ( <Center key={idx} {...rest} accessibilityLabel={`${accessibilityLabel}_${idx}`} style={[{ width: this._tabWidth }, tab.disabled && { opacity: 0.3 }]} > <StyledTabBtn style={[isFixedWidth && { width: underlineWidth }, tabStyle, isActive && tabActiveStyle]} onLayout={evt => this._handleTabLayout(evt, idx)} > {!isFixedWidth ? typeof renderTab === 'function' ? renderTab(isActive, this.state, this.props) : TabText : null} </StyledTabBtn> {isFixedWidth ? typeof renderTab === 'function' ? renderTab(isActive, this.state, this.props) : TabText : null} </Center> ); }; _renderTabs = () => { const { dataSource } = this.props; if (this.isMultiScreen) { const width = dataSource.length * this._tabWidth; return ( <AnimatedView style={{ width, transform: [ { translateX: this.state.scrollX, }, ], }} > {dataSource.map(this._renderTab)} </AnimatedView> ); } return dataSource.map(this._renderTab); }; _renderUnderline = () => { const { activeColor, underlineStyle, dataSource } = this.props; const { activeIndex } = this.state; const { backgroundColor } = StyleSheet.flatten([underlineStyle]); const disabled = get(dataSource, `${activeIndex}.disabled`, false); return ( <AnimatedUnderline style={[ underlineStyle, disabled && { opacity: 0.3 }, { width: this.state.underlineWidth, transform: [{ translateX: Animated.add(this.state.scrollX, this.state.underlineLeft) }], }, ]} color={backgroundColor || activeColor} /> ); }; render() { const { accessibilityLabel, style, wrapperStyle, tabContentStyle, dataSource, tabPosition, swipeable, maxItem, background, preload, preloadTimeout, velocityThreshold, renderPlaceholder, children, } = this.props; const showMask = this.state.activeIndex <= dataSource.length - maxItem; const tabsComponent = ( <StyledTab key="Tabs" style={[style, { width: this._tabsWidth, backgroundColor: background }]} pointerEvents="box-only" {...this._panResponder.panHandlers} > {this._renderTabs()} {this._renderUnderline()} <TabMask visible={this.isMultiScreen && showMask} color={background} /> </StyledTab> ); if (React.Children.count(children) > 0) { const content = [ tabsComponent, <TabContent key="TabContent" accessibilityLabel={accessibilityLabel} style={[tabContentStyle, { width: this._tabsWidth }]} activeIndex={this.state.activeIndex} disabled={!swipeable} preload={preload} preloadTimeout={preloadTimeout} velocityThreshold={velocityThreshold} renderPlaceholder={renderPlaceholder} onMove={this._handleTabContentMove} onRelease={this._handleTabContentRelease} > {this.props.children} </TabContent>, ]; if (tabPosition === 'bottom') content.reverse(); return ( <View style={[{ flex: 1, overflow: 'hidden', backgroundColor: 'transparent' }, wrapperStyle]} > {content} </View> ); } return tabsComponent; } }
the_stack
import { hooks } from 'botframework-webchat-api'; import classNames from 'classnames'; import PropTypes from 'prop-types'; import React, { MutableRefObject, useCallback, useEffect, useRef } from 'react'; import { ie11 } from '../Utils/detectBrowser'; import AccessibleInputText from '../Utils/AccessibleInputText'; import AutoResizeTextArea from './AutoResizeTextArea'; import connectToWebChat from '../connectToWebChat'; import navigableEvent from '../Utils/TypeFocusSink/navigableEvent'; import useFocus from '../hooks/useFocus'; import useRegisterFocusSendBox from '../hooks/internal/useRegisterFocusSendBox'; import useReplaceEmoticon from '../hooks/internal/useReplaceEmoticon'; import useScrollDown from '../hooks/useScrollDown'; import useScrollToEnd from '../hooks/useScrollToEnd'; import useScrollUp from '../hooks/useScrollUp'; import useStyleSet from '../hooks/useStyleSet'; import useStyleToEmotionObject from '../hooks/internal/useStyleToEmotionObject'; const { useDisabled, useLocalizer, useSendBoxValue, useStopDictate, useStyleOptions, useSubmitSendBox } = hooks; const ROOT_STYLE = { '&.webchat__send-box-text-box': { display: 'flex', '& .webchat__send-box-text-box__input, & .webchat__send-box-text-box__text-area': { flex: 1 } } }; const connectSendTextBox = (...selectors) => connectToWebChat( ({ disabled, focusSendBox, language, scrollToEnd, sendBoxValue, setSendBox, stopDictate, submitSendBox }) => ({ disabled, language, onChange: ({ target: { value } }) => { setSendBox(value); stopDictate(); }, onKeyPress: event => { const { key, shiftKey } = event; if (key === 'Enter' && !shiftKey) { event.preventDefault(); if (sendBoxValue) { scrollToEnd(); submitSendBox(); focusSendBox(); } } }, onSubmit: event => { event.preventDefault(); // Consider clearing the send box only after we received POST_ACTIVITY_PENDING // E.g. if the connection is bad, sending the message essentially do nothing but just clearing the send box if (sendBoxValue) { scrollToEnd(); submitSendBox(); } }, value: sendBoxValue }), ...selectors ); function useTextBoxSubmit(): (setFocus?: boolean | 'sendBox') => void { const [sendBoxValue] = useSendBoxValue(); const focus = useFocus(); const scrollToEnd = useScrollToEnd(); const submitSendBox = useSubmitSendBox(); return useCallback( setFocus => { if (sendBoxValue) { scrollToEnd(); submitSendBox(); if (setFocus) { if (setFocus === true) { console.warn( `"botframework-webchat: Passing "true" to "useTextBoxSubmit" is deprecated and will be removed on or after 2022-04-23. Please pass "sendBox" instead."` ); focus('sendBox'); } else { focus(setFocus); } } } return !!sendBoxValue; }, [focus, scrollToEnd, sendBoxValue, submitSendBox] ); } function useTextBoxValue(): [ string, ( textBoxValue: string, options: { selectionEnd: number; selectionStart: number } ) => { selectionEnd: number; selectionStart: number; value: string } ] { const [value, setValue] = useSendBoxValue(); const replaceEmoticon = useReplaceEmoticon(); const stopDictate = useStopDictate(); const setter = useCallback( (nextValue, { selectionEnd, selectionStart } = {}) => { if (typeof nextValue !== 'string') { throw new Error('botframework-webchat: First argument passed to useTextBoxValue() must be a string.'); } // Currently, we cannot detect whether the change is due to clipboard paste or pressing a key on the keyboard. // We should not change to emoji when the user is pasting text. // We would assume, for a single character addition, the user must be pressing a key. if (nextValue.length === value.length + 1) { const { selectionEnd: nextSelectionEnd, selectionStart: nextSelectionStart, value: nextValueWithEmoji } = replaceEmoticon({ selectionEnd, selectionStart, value: nextValue }); selectionEnd = nextSelectionEnd; selectionStart = nextSelectionStart; nextValue = nextValueWithEmoji; } setValue(nextValue); stopDictate(); return { selectionEnd, selectionStart, value: nextValue }; }, [replaceEmoticon, setValue, stopDictate, value] ); return [value, setter]; } const PREVENT_DEFAULT_HANDLER = event => event.preventDefault(); const TextBox = ({ className }) => { const [, setSendBox] = useSendBoxValue(); const [{ sendBoxTextBox: sendBoxTextBoxStyleSet }] = useStyleSet(); const [{ sendBoxTextWrap }] = useStyleOptions(); const [disabled] = useDisabled(); const [textBoxValue, setTextBoxValue] = useTextBoxValue(); const inputElementRef: MutableRefObject<HTMLInputElement & HTMLTextAreaElement> = useRef(); const localize = useLocalizer(); const placeCheckpointOnChangeRef = useRef(false); const prevInputStateRef: MutableRefObject<{ selectionEnd: number; selectionStart: number; value: string; }> = useRef(); const rootClassName = useStyleToEmotionObject()(ROOT_STYLE) + ''; const scrollDown = useScrollDown(); const scrollUp = useScrollUp(); const submitTextBox = useTextBoxSubmit(); const undoStackRef = useRef([]); const sendBoxString = localize('TEXT_INPUT_ALT'); const typeYourMessageString = localize('TEXT_INPUT_PLACEHOLDER'); const rememberInputState = useCallback(() => { const { current: { selectionEnd, selectionStart, value } } = inputElementRef; prevInputStateRef.current = { selectionEnd, selectionStart, value }; }, [inputElementRef, prevInputStateRef]); // This is for TypeFocusSink. When the focus in on the script, then starting press "a", without this line, it would cause errors. // We call rememberInputState() when "onFocus" event is fired, but since this is from TypeFocusSink, we are not able to receive "onFocus" event before it happen. useEffect(rememberInputState, [rememberInputState]); // This is for moving the selection while setting the send box value. // If we only use setSendBox, we will need to wait for the next render cycle to get the value in, before we can set selectionEnd/Start. const setSelectionRangeAndValue = useCallback( ({ selectionEnd, selectionStart, value }) => { if (inputElementRef.current) { // We need to set the value, before selectionStart/selectionEnd. inputElementRef.current.value = value; inputElementRef.current.selectionStart = selectionStart; inputElementRef.current.selectionEnd = selectionEnd; } setSendBox(value); }, [inputElementRef, setSendBox] ); const handleChange = useCallback( event => { const { target: { selectionEnd, selectionStart, value } } = event; if (placeCheckpointOnChangeRef.current) { undoStackRef.current.push({ ...prevInputStateRef.current }); placeCheckpointOnChangeRef.current = false; } const nextInputState = setTextBoxValue(value, { selectionEnd, selectionStart }); // If an emoticon is converted to emoji, place another checkpoint. if (nextInputState.value !== value) { undoStackRef.current.push({ selectionEnd, selectionStart, value }); placeCheckpointOnChangeRef.current = true; setSelectionRangeAndValue(nextInputState); } }, [placeCheckpointOnChangeRef, prevInputStateRef, setSelectionRangeAndValue, setTextBoxValue, undoStackRef] ); const handleFocus = useCallback(() => { rememberInputState(); placeCheckpointOnChangeRef.current = true; }, [placeCheckpointOnChangeRef, rememberInputState]); const handleKeyDown = useCallback( event => { const { ctrlKey, key, metaKey } = event; if ((ctrlKey || metaKey) && (key === 'Z' || key === 'z')) { event.preventDefault(); const poppedInputState = undoStackRef.current.pop(); if (poppedInputState) { prevInputStateRef.current = { ...poppedInputState }; } else { prevInputStateRef.current = { selectionEnd: 0, selectionStart: 0, value: '' }; } setSelectionRangeAndValue(prevInputStateRef.current); } }, [prevInputStateRef, setSelectionRangeAndValue, undoStackRef] ); const handleKeyPress = useCallback( event => { const { key, shiftKey } = event; if (key === 'Enter' && !shiftKey) { event.preventDefault(); // If text box is submitted, focus on the send box submitTextBox('sendBox'); // After submit, we will clear the undo stack. undoStackRef.current = []; } }, [submitTextBox, undoStackRef] ); const handleSelect = useCallback( ({ target: { selectionEnd, selectionStart, value } }) => { if (value === prevInputStateRef.current.value) { // When caret move, we should push to undo stack on change. placeCheckpointOnChangeRef.current = true; } prevInputStateRef.current = { selectionEnd, selectionStart, value }; }, [placeCheckpointOnChangeRef, prevInputStateRef] ); const handleSubmit = useCallback( event => { event.preventDefault(); // Consider clearing the send box only after we received POST_ACTIVITY_PENDING // E.g. if the connection is bad, sending the message essentially do nothing but just clearing the send box submitTextBox(); // After submit, we will clear the undo stack. undoStackRef.current = []; }, [submitTextBox, undoStackRef] ); const handleKeyDownCapture = useCallback( event => { const { ctrlKey, metaKey, shiftKey } = event; if (ctrlKey || metaKey || shiftKey) { return; } // Navigable event means the end-user is focusing on an inputtable element, but it is okay to capture the arrow keys. if (navigableEvent(event)) { let handled = true; switch (event.key) { case 'End': scrollDown({ displacement: Infinity }); break; case 'Home': scrollUp({ displacement: Infinity }); break; case 'PageDown': scrollDown(); break; case 'PageUp': scrollUp(); break; default: handled = false; break; } if (handled) { event.preventDefault(); event.stopPropagation(); } } }, [scrollDown, scrollUp] ); const focusCallback = useCallback( ({ noKeyboard } = {}) => { const { current } = inputElementRef; if (current) { // The "disable soft keyboard on mobile devices" logic will not work on IE11. It will cause the <input> to become read-only until next focus. // Thus, no mobile devices carry IE11 so we don't need to explicitly disable soft keyboard on IE11. // See #3757 for repro and details. if (noKeyboard && !ie11) { // To not activate the virtual keyboard while changing focus to an input, we will temporarily set it as read-only and flip it back. // https://stackoverflow.com/questions/7610758/prevent-iphone-default-keyboard-when-focusing-an-input/7610923 const readOnly = current.getAttribute('readonly'); current.setAttribute('readonly', 'readonly'); setTimeout(() => { const { current } = inputElementRef; if (current) { current.focus(); readOnly ? current.setAttribute('readonly', readOnly) : current.removeAttribute('readonly'); } }, 0); } else { current.focus(); } } }, [inputElementRef] ); useRegisterFocusSendBox(focusCallback); return ( <form aria-disabled={disabled} className={classNames( 'webchat__send-box-text-box', rootClassName, sendBoxTextBoxStyleSet + '', (className || '') + '' )} onSubmit={disabled ? PREVENT_DEFAULT_HANDLER : handleSubmit} > {!sendBoxTextWrap ? ( <AccessibleInputText aria-label={sendBoxString} className="webchat__send-box-text-box__input" data-id="webchat-sendbox-input" disabled={disabled} enterKeyHint="send" inputMode="text" onChange={disabled ? undefined : handleChange} onFocus={disabled ? undefined : handleFocus} onKeyDown={disabled ? undefined : handleKeyDown} onKeyDownCapture={disabled ? undefined : handleKeyDownCapture} onKeyPress={disabled ? undefined : handleKeyPress} onSelect={disabled ? undefined : handleSelect} placeholder={typeYourMessageString} readOnly={disabled} ref={inputElementRef} type="text" value={textBoxValue} /> ) : ( <AutoResizeTextArea aria-label={sendBoxString} className="webchat__send-box-text-box__text-area" data-id="webchat-sendbox-input" disabled={disabled} enterKeyHint="send" inputMode="text" onChange={disabled ? undefined : handleChange} onFocus={disabled ? undefined : handleFocus} onKeyDown={disabled ? undefined : handleKeyDown} onKeyDownCapture={disabled ? undefined : handleKeyDownCapture} onKeyPress={disabled ? undefined : handleKeyPress} onSelect={disabled ? undefined : handleSelect} placeholder={typeYourMessageString} readOnly={disabled} ref={inputElementRef} rows={1} textAreaClassName="webchat__send-box-text-box__html-text-area" value={textBoxValue} /> )} {disabled && <div className="webchat__send-box-text-box__glass" />} </form> ); }; TextBox.defaultProps = { className: '' }; TextBox.propTypes = { className: PropTypes.string }; export default TextBox; export { connectSendTextBox, useTextBoxSubmit, useTextBoxValue };
the_stack
declare module '@opentrons/app/src/logger' { export type LogLevel = | 'error' | 'warn' | 'info' | 'http' | 'verbose' | 'debug' | 'silly' export type Log = (message: string, meta?: Record<string, unknown>) => void export type Logger = Record<LogLevel, Log> } declare module '@opentrons/app/src/__mocks__/logger' { import type { Logger } from '@opentrons/app/src/logger' export function createLogger(filename: string): Logger export function useLogger(filename: string): Logger } declare module '@opentrons/app/src/redux/types' { export interface Action { type: string payload?: unknown | Record<string, unknown> meta?: Record<string, unknown> } export interface Error { name?: string message?: string } } declare module '@opentrons/app/src/redux/buildroot/types' { import type { Action } from '@opentrons/app/src/redux/types' export interface BuildrootUpdateInfo { releaseNotes: string } export type BuildrootAction = Action } declare module '@opentrons/app/src/redux/config/types' { import type { LogLevel } from '@opentrons/app/src/logger' import type { Action } from '@opentrons/app/src/redux/types' export interface ConfigValueChangeAction extends Action { payload: { path: string; value?: unknown } } export type UrlProtocol = 'file:' | 'http:' export type UpdateChannel = 'latest' | 'beta' | 'alpha' export type DiscoveryCandidates = string | string[] export type ConfigV0 = Record<string, unknown> & { version: number } export type ConfigV1 = Record<string, unknown> & { version: number } export type ConfigV2 = Record<string, unknown> & { version: number } export type ConfigV3 = Record<string, unknown> & { version: number } export interface Config { version: number devtools: boolean reinstallDevtools?: boolean buildroot: { manifestUrl: string } log: { level: { file: LogLevel console: LogLevel } } ui: { width: number height: number url: { protocol: UrlProtocol path: string } webPreferences: { webSecurity: boolean } } discovery: { candidates: DiscoveryCandidates disableCache: boolean } labware: { directory: string } alerts: { ignored: string[] } devInternal?: { [featureFlag: string]: boolean | undefined } } } declare module '@opentrons/app/src/redux/custom-labware/types' { import type { LabwareDefinition2 } from '@opentrons/shared-data' interface LabwareFileProps { filename: string modified: number } interface ValidatedLabwareProps extends LabwareFileProps { definition: LabwareDefinition2 } export interface UncheckedLabwareFile extends LabwareFileProps { data: Record<string, unknown> | null } export interface InvalidLabwareFile extends LabwareFileProps { type: 'INVALID_LABWARE_FILE' } export interface DuplicateLabwareFile extends ValidatedLabwareProps { type: 'DUPLICATE_LABWARE_FILE' } export interface OpentronsLabwareFile extends ValidatedLabwareProps { type: 'OPENTRONS_LABWARE_FILE' } export interface ValidLabwareFile extends ValidatedLabwareProps { type: 'VALID_LABWARE_FILE' } export type CheckedLabwareFile = | InvalidLabwareFile | DuplicateLabwareFile | OpentronsLabwareFile | ValidLabwareFile export type FailedLabwareFile = | InvalidLabwareFile | DuplicateLabwareFile | OpentronsLabwareFile export type CustomLabwareListActionSource = | 'poll' | 'initial' | 'addLabware' | 'overwriteLabware' | 'changeDirectory' } declare module '@opentrons/app/src/redux/robot-api/types' { export interface RobotHost { name: string ip: string port: number } } declare module '@opentrons/app/src/redux/shell/types' { export interface UpdateInfo { version: string files: Array<{ sha512: string; url: string }> releaseDate: string releaseNotes?: string } } declare module '@opentrons/app/src/redux/system-info/types' { import type { NetworkInterfaceInfo } from 'os' export interface UsbDevice { locationId: number vendorId: number productId: number deviceName: string manufacturer: string serialNumber: string deviceAddress: number windowsDriverVersion?: string | null } export type NetworkInterface = NetworkInterfaceInfo } declare module '@opentrons/app/src/redux/config' { import type { Action } from '@opentrons/app/src/redux/types' import type { Config, ConfigValueChangeAction, } from '@opentrons/app/src/redux/config/types' export const CONFIG_VERSION_LATEST: number export const INITIALIZED: 'config:INITIALIZED' export const VALUE_UPDATED: 'config:VALUE_UPDATED' export const UPDATE_VALUE: 'config:UPDATE_VALUE' export const RESET_VALUE: 'config:RESET_VALUE' export const TOGGLE_VALUE: 'config:TOGGLE_VALUE' export const ADD_UNIQUE_VALUE: 'config:ADD_UNIQUE_VALUE' export const SUBTRACT_VALUE: 'config:SUBTRACT_VALUE' export function configInitialized(config: Config): Action export function configValueUpdated(path: string, value: unknown): Action export function updateConfigValue( path: string, value: unknown ): ConfigValueChangeAction export function resetConfigValue(path: string): ConfigValueChangeAction export function toggleConfigValue(path: string): ConfigValueChangeAction export function addUniqueConfigValue( path: string, value: unknown ): ConfigValueChangeAction export function subtractConfigValue( path: string, value: unknown ): ConfigValueChangeAction } // NOTE(mc, 2021-02-17): intentionally duplicated to avoid correcting a // too-deep import in app-shell declare module '@opentrons/app/src/redux/custom-labware/selectors' { export const INVALID_LABWARE_FILE: 'INVALID_LABWARE_FILE' export const DUPLICATE_LABWARE_FILE: 'DUPLICATE_LABWARE_FILE' export const OPENTRONS_LABWARE_FILE: 'OPENTRONS_LABWARE_FILE' export const VALID_LABWARE_FILE: 'VALID_LABWARE_FILE' } declare module '@opentrons/app/src/redux/custom-labware' { import type { Action } from '@opentrons/app/src/redux/types' import type { DuplicateLabwareFile, FailedLabwareFile, CheckedLabwareFile, CustomLabwareListActionSource, } from '@opentrons/app/src/redux/custom-labware/types' export const INVALID_LABWARE_FILE: 'INVALID_LABWARE_FILE' export const DUPLICATE_LABWARE_FILE: 'DUPLICATE_LABWARE_FILE' export const OPENTRONS_LABWARE_FILE: 'OPENTRONS_LABWARE_FILE' export const VALID_LABWARE_FILE: 'VALID_LABWARE_FILE' export const POLL: 'poll' export const INITIAL: 'initial' export const ADD_LABWARE: 'addLabware' export const OVERWRITE_LABWARE: 'overwriteLabware' export const CHANGE_DIRECTORY: 'changeDirectory' export const FETCH_CUSTOM_LABWARE: 'labware:FETCH_CUSTOM_LABWARE' export const CHANGE_CUSTOM_LABWARE_DIRECTORY: 'labware:CHANGE_CUSTOM_LABWARE_DIRECTORY' export const ADD_CUSTOM_LABWARE: 'labware:ADD_CUSTOM_LABWARE' export const OPEN_CUSTOM_LABWARE_DIRECTORY: 'labware:OPEN_CUSTOM_LABWARE_DIRECTORY' export const LABWARE_DIRECTORY_CONFIG_PATH: string export function addCustomLabwareFailure( labware?: FailedLabwareFile | null, message?: string | null ): Action export function customLabwareList( payload: CheckedLabwareFile[], source?: CustomLabwareListActionSource ): Action export function customLabwareListFailure( message: string, source?: CustomLabwareListActionSource ): Action export function fetchCustomLabware(): Action export function changeCustomLabwareDirectory(): Action export function openCustomLabwareDirectory(): Action export function addCustomLabware( overwrite?: DuplicateLabwareFile | null ): Action } declare module '@opentrons/app/src/redux/custom-labware/__fixtures__' { import type { LabwareDefinition2 } from '@opentrons/shared-data' import { ValidLabwareFile, InvalidLabwareFile, OpentronsLabwareFile, DuplicateLabwareFile, } from '@opentrons/app/src/redux/custom-labware/types' export const mockDefinition: LabwareDefinition2 export const mockValidLabware: ValidLabwareFile export const mockInvalidLabware: InvalidLabwareFile export const mockOpentronsLabware: OpentronsLabwareFile export const mockDuplicateLabware: DuplicateLabwareFile export const mockTipRackDefinition: LabwareDefinition2 } declare module '@opentrons/app/src/redux/robot-api/constants' { export const HTTP_API_VERSION: number } declare module '@opentrons/app/src/redux/system-info' { import type { Action } from '@opentrons/app/src/redux/types' import type { UsbDevice, NetworkInterface, } from '@opentrons/app/src/redux/system-info/types' export function initialized( devices: UsbDevice[], interfaces: NetworkInterface[] ): Action export function usbDeviceAdded(device: UsbDevice): Action export function usbDeviceRemoved(device: UsbDevice): Action export function networkInterfacesChanged( interfaces: NetworkInterface[] ): Action } declare module '@opentrons/app/src/redux/system-info/__fixtures__' { import type { UsbDevice, NetworkInterface, } from '@opentrons/app/src/redux/system-info/types' export const mockUsbDevice: UsbDevice export const mockRealtekDevice: UsbDevice export const mockWindowsRealtekDevice: UsbDevice export const mockNetworkInterface: NetworkInterface export const mockNetworkInterfaceV6: NetworkInterface } declare module '@opentrons/app/src/redux/discovery' { import type { Action } from '@opentrons/app/src/redux/types' export function startDiscovery(): Action export function finishDiscovery(): Action } declare module '@opentrons/app/src/redux/discovery/actions' { export const DISCOVERY_START: 'discovery:START' export const DISCOVERY_FINISH: 'discovery:FINISH' export const DISCOVERY_REMOVE: 'discovery:REMOVE' export const CLEAR_CACHE: 'discovery:CLEAR_CACHE' } declare module '@opentrons/app/src/redux/shell/actions' { import type { Action } from '@opentrons/app/src/redux/types' export const UI_INITIALIZED: 'shell:UI_INITIALIZED' export function uiInitialized(): Action }
the_stack
var __reflect = (this && this.__reflect) || function (p, c, t) { p.__class__ = c, t ? t.push(c) : t = [c], p.__types__ = p.__types__ ? t.concat(p.__types__) : t; }; var __extends = this && this.__extends || function __extends(t, e) { function r() { this.constructor = t; } for (var i in e) e.hasOwnProperty(i) && (t[i] = e[i]); r.prototype = e.prototype, t.prototype = new r(); }; declare let window; declare let generateEUI2; declare namespace egret { function getDefinitionByName(name: string): any; export class Rectangle { constructor(a, b, c, d); } } declare namespace eui { export class SetProperty { constructor(a, b, c); } export class SetStateProperty { constructor(a, b, c, d, e); } export class Binding { static $bindProperties(a, b, c, d, e); static bindProperty(a, b, c, d) } export class State { constructor(a, b); } export class AddItems { constructor(a, b, c, d); } } class JSONParseClass { private json; private skinClass = {}; private target; private skinName: string;//一个skin可能包含多个 private euiNormalizeNames = { "$eBL": "eui.BitmapLabel", "$eB": "eui.Button", "$eCB": "eui.CheckBox", "$eC": "eui.Component", "$eDG": "eui.DataGroup", "$eET": "eui.EditableText", "$eG": "eui.Group", "$eHL": "eui.HorizontalLayout", "$eHSB": "eui.HScrollBar", "$eHS": "eui.HSlider", "$eI": "eui.Image", "$eL": "eui.Label", "$eLs": "eui.List", "$eP": "eui.Panel", "$ePB": "eui.ProgressBar", "$eRB": "eui.RadioButton", "$eRBG": "eui.RadioButtonGroup", "$eRa": "eui.Range", "$eR": "eui.Rect", "$eRAl": "eui.RowAlign", "$eS": "eui.Scroller", "$eT": "eui.TabBar", "$eTI": "eui.TextInput", "$eTL": "eui.TileLayout", "$eTB": "eui.ToggleButton", "$eTS": "eui.ToggleSwitch", "$eVL": "eui.VerticalLayout", "$eV": "eui.ViewStack", "$eVSB": "eui.VScrollBar", "$eVS": "eui.VSlider", "$eSk": "eui.Skin" } setData(data: any) { if (!this.json) { this.json = data; this.parseSkinMap(this.json); } else { this.parseSkinMap(data); for (let a in data) { this.json[a] = data[a]; } } } private generateSkinClass(skinData: any, className: string, superName: string): any { if (!skinData) return null; let paths = superName.split("."); let target = window; for (let p of paths) { target = target[p]; } function __SkinClass() { target.call(this); window["JSONParseClass"].create(className, this); } (<any>__extends)(__SkinClass, target); (<any>__reflect)(__SkinClass, className, [superName]); return __SkinClass; } parseSkinMap(skinMap): any { let skinResult = {}; for (let exml in skinMap) { let skinData = skinMap[exml]; if (!skinData) continue; let paths = exml.split("."); let target = window; for (let p of paths) { let parent = target; if (p !== paths[paths.length - 1]) { target = target[p]; if (target == undefined) { target = {}; parent[p] = target; } } } let superName = this.euiNormalizeNames[skinData["$sC"]] == undefined ? skinData["$sC"] : this.euiNormalizeNames[skinData["$sC"]]; skinResult[exml] = target[paths[paths.length - 1]] = this.generateSkinClass(skinData, exml, superName); if (skinMap[exml]["$path"]) { generateEUI2["paths"][skinMap[exml]["$path"]] = skinResult[exml]; } } return skinResult; } create(skinName: string, target: any) { if (!this.json) { console.log("Missing json defined by eui resource, please modify the theme adapter"); console.log("缺少eui资源定义的json,请修改主题适配器"); return; } /** 先解析对应名字的的 */ this.target = target; this.skinName = skinName; this.skinClass = this.json[skinName]; //开始生成 this.applyBase(); this.applySkinParts(); this.applyState(); this.applyBinding(); //skinParts 只能最后赋值,在comp中引用问题 if (this.skinClass["$sP"] == undefined) this.target["skinParts"] = []; else this.target["skinParts"] = this.skinClass["$sP"] } private applySkinParts() { if (this.skinClass["$sP"] == undefined) return; for (let component of this.skinClass["$sP"]) { if (this.target[component] == undefined) this.createElementContentOrViewport(component); } } private applyBase() { if (this.skinClass["$bs"] == undefined) return; this.addCommonProperty("$bs", this.target); } private createElementContentOrViewport(component: string) { let result; const typeStr = this.getNormalizeEuiName(this.skinClass[component].$t); if (typeStr == "egret.tween.TweenGroup") { result = this.creatsEgretTweenGroup(component); } else { /** 有可能对象是从外面一定义的皮肤 */ const type = egret.getDefinitionByName(typeStr); this.$createNewObject(() => { result = new type(); }) this.addCommonProperty(component, result); } this.target[component] = result; return result; } /** * 生成单位,有可能会跳出当前皮肤,所以统一维护target和skin * @param callback 创建对象的真实逻辑 */ private $createNewObject(callback: Function) { const skinName = this.skinName; const target = this.target; callback(); this.skinName = skinName; this.skinClass = this.json[this.skinName]; this.target = target; } /** * 生成对应的缓动组 * @param component 名字索引 */ private creatsEgretTweenGroup(component: string) { let result = this.createTypeObject(component); let items = []; for (let item of this.skinClass[component]["items"]) { items.push(this.createEgretTweenItem(item)); } result["items"] = items; return result; } /** * 生成对应的缓动单位 * @param tweenItem 名字索引 */ private createEgretTweenItem(tweenItem: string) { let result = this.createTypeObject(tweenItem); let paths = []; for (let prop in this.skinClass[tweenItem]) { const property = this.skinClass[tweenItem][prop]; if (prop == "$t" || prop == "target") { } else if (prop == "paths") { for (let path of property) paths.push(this.createSetOrTo(path)); } else if (prop == "target") { this.$createNewObject(() => { result[prop] = this.createElementContentOrViewport(property); this.target[property] = result[prop]; }) } else { result[prop] = property; } } result["paths"] = paths; this.target[tweenItem] = result; return result; } private createSetOrTo(key: string) { let result = this.createTypeObject(key); for (let prop in this.skinClass[key]) { const property = this.skinClass[key][prop]; if (prop == "$t" || prop == "target") { } else if (prop == "props") { result[prop] = this.createObject(property); this.target[property] = result[prop]; } else { result[prop] = property; } } return result; } private createObject(name: string) { let result = {}; for (let prop in this.skinClass[name]) { if (prop == "$t" || prop == "target") { } else { result[prop] = this.skinClass[name][prop]; } } return result; } private addCommonProperty(componentName: string, target: any) { let eleC: string[]; let sId: string[]; for (let prop in this.skinClass[componentName]) { let property = this.skinClass[componentName][prop]; if (prop == "$t") { } else if (prop == "layout") { target[prop] = this.createLayout(property); } else if (prop == "$eleC") { eleC = property; } else if (prop == "$sId") { sId = property; } else if (prop == "scale9Grid") { target[prop] = this.getScale9Grid(property); } else if (prop == "skinName") { this.$createNewObject(() => { target[prop] = property; }); } else if (prop == "itemRendererSkinName") { this.$createNewObject(() => { let dirPath = property.split("."); let t = window; for (let p of dirPath) { t = t[p]; } target[prop] = t; }); } else if (prop == "itemRenderer") { target[prop] = egret.getDefinitionByName(property); } else if (prop == "dataProvider") { target[prop] = this.createDataProvider(property); } else if (prop == "viewport") { target[prop] = this.createElementContentOrViewport(property); } else { target[prop] = property; } } let ele = [] if (eleC && eleC.length > 0) { for (let element of eleC) { let e = this.createElementContentOrViewport(element); ele.push(e); } } target["elementsContent"] = ele; if (sId && sId.length > 0) { for (let element of sId) { this.createElementContentOrViewport(element); } } return target; } private createLayout(componentName: string) { let result = this.createTypeObject(componentName); const component = this.skinClass[componentName]; for (let property in component) { if (property !== "$t") { result[property] = component[property]; } } this.target[componentName] = result; return result; } private applyState() { if (this.skinClass["$s"] == undefined) return; let states = []; for (let state in this.skinClass["$s"]) { let setProperty = []; let tempState = this.skinClass["$s"][state]; if (tempState["$saI"]) { for (let property of tempState["$saI"]) { setProperty.push(new eui.AddItems(property["target"], property["property"], property["position"], property["relativeTo"])); } } if (tempState["$ssP"]) { for (let property of tempState["$ssP"]) { if (property["name"]) { let value = property["value"]; if (property["name"] == "scale9Grid") { value = this.getScale9Grid(property["value"]) } setProperty.push(new eui.SetProperty(property["target"], property["name"], value)); } else { setProperty.push(new eui.SetStateProperty(this.target, property["templates"], property["chainIndex"], this.target[property["target"]], property["property"])); } } } states.push(new eui.State(state, setProperty)) } this.target["states"] = states; } private applyBinding() { if (this.skinClass["$b"] == undefined) return; for (let bindingDate of this.skinClass["$b"]) { if (bindingDate["$bc"] !== undefined) { eui.Binding.$bindProperties(this.target, bindingDate["$bd"], bindingDate["$bc"], this.target[bindingDate["$bt"]], bindingDate["$bp"]); } else { eui.Binding.bindProperty(this.target, bindingDate["$bd"][0].split("."), this.target[bindingDate["$bt"]], bindingDate["$bp"]) } } } private createDataProvider(component: string) { if (component == "") return undefined; let result = this.createTypeObject(component); let source = []; for (let sour of this.skinClass[component]["source"]) { source.push(this.createItemRender(sour)); } result["source"] = source; return result; } private createItemRender(itemName: string) { let result = this.createTypeObject(itemName); for (let property in this.skinClass[itemName]) { if (property != "$t") { result[property] = this.skinClass[itemName][property]; } } return result; } private getNormalizeEuiName(str: string): string { return this.euiNormalizeNames[str] ? this.euiNormalizeNames[str] : str; } private createTypeObject(component: string) { const typestr = this.getNormalizeEuiName(this.skinClass[component].$t); const type = egret.getDefinitionByName(typestr); return new type(); } private getScale9Grid(data: string) { const datalist = data.split(","); return new egret.Rectangle(parseFloat(datalist[0]), parseFloat(datalist[1]), parseFloat(datalist[2]), parseFloat(datalist[3])); } } window["JSONParseClass"] = new JSONParseClass();
the_stack
import { EventEmitter } from "events"; import { CharStreams, CommonTokenStream, CommonToken, ParserRuleContext, Token } from "antlr4ts"; import { ParseTree, ErrorNode, TerminalNode } from "antlr4ts/tree"; import { ScopedSymbol, VariableSymbol } from "antlr4-c3"; import { InterpreterData } from "./InterpreterDataReader"; import { LexerToken, ParseTreeNode, ParseTreeNodeType, LexicalRange, PredicateFunction, } from "./facade"; import { RuleSymbol } from "./ContextSymbolTable"; import { SourceContext } from "./SourceContext"; import { GrammarLexerInterpreter, InterpreterLexerErrorListener, GrammarParserInterpreter, InterpreterParserErrorListener, RunMode, } from "./GrammarInterpreters"; import * as vm from "vm"; import * as fs from "fs"; export interface GrammarBreakPoint { source: string; validated: boolean; line: number; id: number; } export interface GrammarStackFrame { name: string; source: string; next: LexicalRange[]; } /** * This class provides debugging support for a grammar. */ export class GrammarDebugger extends EventEmitter { // Interpreter data for the main grammar as well as all imported grammars. private lexerData: InterpreterData | undefined; private parserData: InterpreterData | undefined; private lexer: GrammarLexerInterpreter; private tokenStream: CommonTokenStream; private parser: GrammarParserInterpreter | undefined; private parseTree: ParserRuleContext | undefined; private breakPoints = new Map<number, GrammarBreakPoint>(); private nextBreakPointId = 0; public constructor(private contexts: SourceContext[], actionFile: string) { super(); if (this.contexts.length === 0) { return; } let predicateFunction; if (actionFile) { const code = fs.readFileSync(actionFile, { encoding: "utf-8" }) + ` const runPredicate = (predicate) => eval(predicate); runPredicate; `; predicateFunction = vm.runInThisContext(code) as PredicateFunction; } // The context list contains all dependencies of the main grammar (which is the first entry). // There can be only one context with lexer data (either the main context if that represents a combined // grammar) or a dedicated lexer context. Parser data is merged into one set (by ANTLR4) even if there // are sub grammars. We need sub grammar contexts for breakpoint validation and call stacks. if (this.isValid) { // Set up the required structures with an empty input stream. // On start we will replace that with the actual input. let lexerName = ""; for (const context of this.contexts) { const [lexerData, parserData] = context.interpreterData; if (!this.lexerData && lexerData) { this.lexerData = lexerData; lexerName = context.fileName; } if (!this.parserData && parserData) { this.parserData = parserData; } } const eventSink = (event: string | symbol, ...args: any[]): void => { setImmediate((_) => this.emit(event, args)); }; if (this.lexerData) { const stream = CharStreams.fromString(""); this.lexer = new GrammarLexerInterpreter(predicateFunction, this.contexts[0], lexerName, this.lexerData, stream); this.lexer.removeErrorListeners(); this.lexer.addErrorListener(new InterpreterLexerErrorListener(eventSink)); this.tokenStream = new CommonTokenStream(this.lexer); } if (this.parserData) { this.parser = new GrammarParserInterpreter(eventSink, predicateFunction, this.contexts[0], this.parserData, this.tokenStream); this.parser.buildParseTree = true; this.parser.removeErrorListeners(); this.parser.addErrorListener(new InterpreterParserErrorListener(eventSink)); } } } public get isValid(): boolean { return this.contexts.find((context) => !context.isInterpreterDataLoaded) === undefined; } public start(startRuleIndex: number, input: string, noDebug: boolean): void { const stream = CharStreams.fromString(input); this.lexer.inputStream = stream; if (!this.parser) { this.sendEvent("end"); return; } this.parseTree = undefined; this.parser.breakPoints.clear(); if (noDebug) { void this.parser.setProfile(false).then(() => { this.parseTree = this.parser!.parse(startRuleIndex); this.sendEvent("end"); }); } else { for (const bp of this.breakPoints) { this.validateBreakPoint(bp[1]); } this.parser.start(startRuleIndex); this.continue(); } } public continue(): void { if (this.parser) { this.parseTree = this.parser.continue(RunMode.Normal); } } public stepIn(): void { if (this.parser) { this.parseTree = this.parser.continue(RunMode.StepIn); } } public stepOut(): void { if (this.parser) { this.parseTree = this.parser.continue(RunMode.StepOut); } } public stepOver(): void { if (this.parser) { this.parseTree = this.parser.continue(RunMode.StepOver); } } public stop(): void { // no-op } public pause(): void { // no-op } public clearBreakPoints(): void { this.breakPoints.clear(); if (this.parser) { this.parser.breakPoints.clear(); } } public addBreakPoint(path: string, line: number): GrammarBreakPoint { const breakPoint = <GrammarBreakPoint>{ source: path, validated: false, line, id: this.nextBreakPointId++ }; this.breakPoints.set(breakPoint.id, breakPoint); this.validateBreakPoint(breakPoint); return breakPoint; } /** * @returns the list of tokens in the test input. */ public get tokenList(): Token[] { this.tokenStream.fill(); return this.tokenStream.getTokens(); } public get errorCount(): number { if (!this.parser) { return 0; } return this.parser.numberOfSyntaxErrors; } public get inputSize(): number { if (!this.parser) { return 0; } return this.parser.inputStream.size; } public ruleNameFromIndex(ruleIndex: number): string | undefined { if (!this.parser) { return; } if (ruleIndex < 0 || ruleIndex >= this.parser.ruleNames.length) { return; } return this.parser.ruleNames[ruleIndex]; } public ruleIndexFromName(ruleName: string): number { if (!this.parser) { return -1; } return this.parser.ruleNames.findIndex((entry) => entry === ruleName); } public get currentParseTree(): ParseTreeNode | undefined { if (!this.parseTree) { return undefined; } return this.parseContextToNode(this.parseTree); } public get currentStackTrace(): GrammarStackFrame[] { const result: GrammarStackFrame[] = []; if (this.parser) { for (const frame of this.parser.callStack) { const externalFrame = <GrammarStackFrame>{ name: frame.name, source: frame.source, next: [], }; for (const next of frame.next) { if (next.context instanceof ParserRuleContext) { const start = next.context.start; const stop = next.context.stop; externalFrame.next.push({ start: { column: start.charPositionInLine, row: start.line }, end: { column: stop ? stop.charPositionInLine : 0, row: stop ? stop.line : start.line }, }); } else { const terminal = (next.context as TerminalNode).symbol; const length = terminal.stopIndex - terminal.startIndex + 1; externalFrame.next.push({ start: { column: terminal.charPositionInLine, row: terminal.line }, end: { column: terminal.charPositionInLine + length, row: terminal.line }, }); } } result.push(externalFrame); } } return result.reverse(); } public get currentTokenIndex(): number { return this.tokenStream.index; } /** * Return a string describing the stack frame at the given index. * Note: we return the stack trace reverted, so we have to account for that here. * * @param index The index of the entry to return info for. * * @returns A string representation of the stack frame. */ public getStackInfo(index: number): string { if (!this.parser || index < 0 || index > this.parser.callStack.length) { return "Invalid Stack Frame"; } const frame = this.parser.callStack[this.parser.callStack.length - index - 1]; return "Context " + frame.name; } public getVariables(index: number): Array<[string, string]> { const result: Array<[string, string]> = []; if (!this.parser || index < 0 || index > this.parser.callStack.length) { return []; } const frame = this.parser.callStack[this.parser.callStack.length - index - 1]; // There's always at least one current symbol in the given frame. // Go up the parent chain to find the rule symbol which contains this current symbol. let run = frame.current[0]; while (run && !(run instanceof RuleSymbol)) { run = run.parent as ScopedSymbol; } if (run) { // Walk up the parent chain of the current parser rule context to find the // corresponding context for our stack frame. let context = this.parser.context; while (index-- > 0) { context = context.parent!; } const symbols = (run as ScopedSymbol).getNestedSymbolsOfType(VariableSymbol); // Coalesce variable names and look up the value. const variables: Set<string> = new Set<string>(); for (const symbol of symbols) { variables.add(symbol.name); } /* for (const variable of variables) { // TODO: there are no variables stored in the interpreter. // Possible solution: handle that manually with the help of the symbol table. }*/ } return result; } public tokenTypeName(token: CommonToken): string { // For implicit tokens we use the same approach like ANTLR4 does for the naming. return this.lexer.vocabulary.getSymbolicName(token.type) || "T__" + token.type; } private sendEvent(event: string, ...args: any[]) { setImmediate((_) => { this.emit(event, ...args); }); } private parseContextToNode(tree: ParseTree): ParseTreeNode { if (tree instanceof ParserRuleContext) { const children: ParseTreeNode[] = []; if (tree.children) { for (const child of tree.children) { if ((child instanceof TerminalNode) && (child.symbol.type === Token.EOF)) { continue; } children.push(this.parseContextToNode(child)); } } return { type: ParseTreeNodeType.Rule, ruleIndex: tree.ruleIndex, name: this.parser!.ruleNames[tree.ruleIndex], start: this.convertToken(tree.start as CommonToken), stop: this.convertToken(tree.stop as CommonToken), id: this.computeHash(tree), range: { startIndex: tree.sourceInterval.a, stopIndex: tree.sourceInterval.b, length: tree.sourceInterval.length, }, children, }; } else if (tree instanceof ErrorNode) { const symbol = this.convertToken(tree.symbol as CommonToken); return { type: ParseTreeNodeType.Error, symbol, id: this.computeHash(tree.symbol as CommonToken), name: symbol ? symbol.name : "<no name>", children: [], }; } else { // Must be a terminal node then. const token = (tree as TerminalNode).symbol as CommonToken; const symbol = this.convertToken((tree as TerminalNode).symbol as CommonToken); return { type: ParseTreeNodeType.Terminal, symbol, id: this.computeHash(token), name: symbol ? symbol.name : "<no name>", children: [], }; } } /** * A simple hash function for rule contexts and common tokens. * * @param input The value to create the hash for. * * @returns The computed hash. */ private computeHash(input: ParserRuleContext | CommonToken): number { let hash = 0; if (input instanceof ParserRuleContext) { hash = (31 * hash) + input.start.inputStream!.size; // Seed with a value that for sure goes beyond any possible token index. if (input.parent) { // Multiple invocations of the same rule which matches nothing appear as nodes in the parse tree with the same // start token, so we need an additional property to tell them apart: the child index. hash = (31 * hash) + input.parent.children!.findIndex((element) => element === input); } hash = (31 * hash) + input.depth(); hash = (31 * hash) + input.ruleIndex; hash = (31 * hash) + input.start.type >>> 0; hash = (31 * hash) + input.start.tokenIndex >>> 0; hash = (31 * hash) + input.start.channel >>> 0; } else if (input instanceof CommonToken) { hash = (31 * hash) + input.tokenIndex >>> 0; hash = (31 * hash) + input.type >>> 0; hash = (31 * hash) + input.channel >>> 0; } return hash; } private convertToken(token: CommonToken): LexerToken | undefined { if (!token) { return; } return { text: token.text ? token.text : "", type: token.type, name: this.tokenTypeName(token), line: token.line, offset: token.charPositionInLine, channel: token.channel, tokenIndex: token.tokenIndex, startIndex: token.startIndex, stopIndex: token.stopIndex, }; } /** * Validates a breakpoint's position. * Breakpoints are aligned either to the first or the last rule line, hence the debugger * can only break on enter or on exit of the rule. * * @param breakPoint The breakpoint to validate. */ private validateBreakPoint(breakPoint: GrammarBreakPoint) { const context = this.contexts.find((entry) => entry.fileName === breakPoint.source); if (!context || !this.parserData) { return; } // Assuming here a rule always starts in column 0. const rule = context.enclosingSymbolAtPosition(0, breakPoint.line, true); if (rule) { breakPoint.validated = true; // Main and sub grammars are combined in the ATN (and interpreter data), which means // the rule index must be looked up in the main context, regardless of the source file. const index = this.ruleIndexFromName(rule.name); if (breakPoint.line === rule.definition!.range.end.row) { // If the breakpoint's line is on the rule's end (the semicolon) then // use the rule's end state for break. const stop = this.parserData.atn.ruleToStopState[index]; this.parser!.breakPoints.add(stop); } else { const start = this.parserData.atn.ruleToStartState[index]; this.parser!.breakPoints.add(start); breakPoint.line = rule.definition!.range.start.row; } this.sendEvent("breakpointValidated", breakPoint); } } }
the_stack
import { createComposer, DefineLocaleMessage } from './composer' import { I18nWarnCodes, getWarnMessage } from './warnings' import { createI18nError, I18nErrorCodes } from './errors' import { EnableEmitter, DisableEmitter, __VUE_I18N_BRIDGE__ } from './symbols' import { DEFAULT_LOCALE } from '@intlify/core-base' import { isString, isArray, isPlainObject, isNumber, isBoolean, isFunction, isRegExp, assign, warn } from '@intlify/shared' import type { Path, MessageResolver, PluralizationRule, PluralizationRules, LinkedModifiers, NamedValue, Locale, LocaleMessage, LocaleMessages, LocaleMessageDictionary, PostTranslationHandler, FallbackLocale, LocaleMessageValue, TranslateOptions, DateTimeFormats as DateTimeFormatsType, NumberFormats as NumberFormatsType, DateTimeFormat, NumberFormat, PickupKeys, PickupFormatKeys, PickupLocales, SchemaParams, LocaleParams, RemoveIndexSignature, FallbackLocales, PickupPaths, PickupFormatPathKeys, IsEmptyObject, IsNever } from '@intlify/core-base' import type { VueDevToolsEmitter } from '@intlify/vue-devtools' import type { VueMessageType, RemovedIndexResources, DefaultLocaleMessageSchema, DefineDateTimeFormat, DefaultDateTimeFormatSchema, DefineNumberFormat, DefaultNumberFormatSchema, MissingHandler, Composer, ComposerOptions, ComposerInternalOptions, ComposerResolveLocaleMessageTranslation } from './composer' /** @VueI18nLegacy */ export type TranslateResult = string export type Choice = number /** @VueI18nLegacy */ export type LocaleMessageObject<Message = string> = LocaleMessageDictionary<Message> export type PluralizationRulesMap = { [locale: string]: PluralizationRule } export type WarnHtmlInMessageLevel = 'off' | 'warn' | 'error' /** @VueI18nLegacy */ export type DateTimeFormatResult = string /** @VueI18nLegacy */ export type NumberFormatResult = string export interface Formatter { // eslint-disable-next-line @typescript-eslint/no-explicit-any interpolate(message: string, values: any, path: string): Array<any> | null } export type ComponentInstanceCreatedListener = <Messages>( target: VueI18n<Messages>, global: VueI18n<Messages> ) => void /** * VueI18n Options * * @remarks * This option is compatible with `VueI18n` class constructor options (offered with Vue I18n v8.x) * * @VueI18nLegacy */ export interface VueI18nOptions< Schema extends { message?: unknown datetime?: unknown number?: unknown } = { message: DefaultLocaleMessageSchema datetime: DefaultDateTimeFormatSchema number: DefaultNumberFormatSchema }, Locales extends | { messages: unknown datetimeFormats: unknown numberFormats: unknown } | string = Locale, Options extends ComposerOptions<Schema, Locales> = ComposerOptions< Schema, Locales > > { /** * @remarks * The locale of localization. * * If the locale contains a territory and a dialect, this locale contains an implicit fallback. * * @VueI18nSee [Scope and Locale Changing](../guide/essentials/scope) * * @defaultValue `'en-US'` */ locale?: Options['locale'] /** * @remarks * The locale of fallback localization. * * For more complex fallback definitions see fallback. * * @VueI18nSee [Fallbacking](../guide/essentials/fallback) * * @defaultValue The default `'en-US'` for the `locale` if it's not specified, or it's `locale` value */ fallbackLocale?: Options['fallbackLocale'] /** * @remarks * The locale messages of localization. * * @VueI18nSee [Getting Started](../guide/) * * @defaultValue `{}` */ messages?: Options['messages'] /** * @remarks * Allow use flat json messages or not * * @defaultValue `false` */ flatJson?: Options['flatJson'] /** * @remarks * The datetime formats of localization. * * @VueI18nSee [Datetime Formatting](../guide/essentials/datetime) * * @defaultValue `{}` */ datetimeFormats?: Options['datetimeFormats'] /** * @remarks * The number formats of localization. * * @VueI18nSee [Number Formatting](../guide/essentials/number) * * @defaultValue `{}` */ numberFormats?: Options['numberFormats'] /** * @remarks * The list of available locales in messages in lexical order. * * @defaultValue `[]` */ availableLocales?: Locale[] /** * @remarks * Custom Modifiers for linked messages. * * @VueI18nSee [Custom Modifiers](../guide/essentials/syntax#custom-modifiers) */ modifiers?: Options['modifiers'] /** * @remarks * The formatter that implemented with Formatter interface. * * @deprecated See the [here](../guide/migration/breaking#remove-custom-formatter) */ formatter?: Formatter /** * @remarks * A handler for localization missing. * * The handler gets called with the localization target locale, localization path key, the Vue instance and values. * * If missing handler is assigned, and occurred localization missing, it's not warned. * * @defaultValue `null` */ missing?: Options['missing'] /** * @remarks * In the component localization, whether to fall back to root level (global scope) localization when localization fails. * * If `false`, it's not fallback to root. * * @VueI18nSee [Fallbacking](../guide/essentials/fallback) * * @defaultValue `true` */ fallbackRoot?: Options['fallbackRoot'] /** * @remarks * Whether suppress warnings outputted when localization fails. * * If `true`, suppress localization fail warnings. * * If you use regular expression, you can suppress localization fail warnings that it match with translation key (e.g. `t`). * * @VueI18nSee [Fallbacking](../guide/essentials/fallback) * * @defaultValue `false` */ silentTranslationWarn?: Options['missingWarn'] /** * @remarks * Whether do template interpolation on translation keys when your language lacks a translation for a key. * * If `true`, skip writing templates for your "base" language; the keys are your templates. * * @VueI18nSee [Fallbacking](../guide/essentials/fallback) * * @defaultValue `false` */ silentFallbackWarn?: Options['fallbackWarn'] /** * @remarks * Whether suppress warnings when falling back to either `fallbackLocale` or root. * * @VueI18nSee [Fallbacking](../guide/essentials/fallback) * * @defaultValue `false` */ formatFallbackMessages?: Options['fallbackFormat'] /** * @remarks * Whether `v-t` directive's element should preserve `textContent` after directive is unbinded. * * @VueI18nSee [Custom Directive](../guide/advanced/directive) * @VueI18nSee [Remove `preserveDirectiveContent` option](../guide/migration/breaking#remove-preservedirectivecontent-option) * * @defaultValue `false` * * @deprecated The `v-t` directive for Vue 3 now preserves the default content. Therefore, this option and its properties have been removed from the VueI18n instance. */ preserveDirectiveContent?: boolean /** * @remarks * Whether to allow the use locale messages of HTML formatting. * * See the warnHtmlInMessage property. * * @VueI18nSee [HTML Message](../guide/essentials/syntax#html-message) * @VueI18nSee [Change `warnHtmlInMessage` option default value](../guide/migration/breaking#change-warnhtmlinmessage-option-default-value) * * @defaultValue `'off'` */ warnHtmlInMessage?: WarnHtmlInMessageLevel /** * @remarks * If `escapeParameterHtml` is configured as true then interpolation parameters are escaped before the message is translated. * * This is useful when translation output is used in `v-html` and the translation resource contains html markup (e.g. <b> around a user provided value). * * This usage pattern mostly occurs when passing precomputed text strings into UI components. * * The escape process involves replacing the following symbols with their respective HTML character entities: `<`, `>`, `"`, `'`. * * Setting `escapeParameterHtml` as true should not break existing functionality but provides a safeguard against a subtle type of XSS attack vectors. * * @VueI18nSee [HTML Message](../guide/essentials/syntax#html-message) * * @defaultValue `false` */ escapeParameterHtml?: Options['escapeParameter'] /** * @remarks * The shared locale messages of localization for components. More detail see Component based localization. * * @VueI18nSee [Shared locale messages for components](../guide/essentials/local#shared-locale-messages-for-components) * * @defaultValue `undefined` */ sharedMessages?: LocaleMessages<VueMessageType> /** * @remarks * A set of rules for word pluralization * * @VueI18nSee [Custom Pluralization](../guide/essentials/pluralization#custom-pluralization) * * @defaultValue `{}` */ pluralizationRules?: Options['pluralRules'] /** * @remarks * A handler for post processing of translation. The handler gets after being called with the `$t`, `t`, `$tc`, and `tc`. * * This handler is useful if you want to filter on translated text such as space trimming. * * @defaultValue `null` */ postTranslation?: Options['postTranslation'] /** * @remarks * Whether synchronize the root level locale to the component localization locale. * * If `false`, regardless of the root level locale, localize for each component locale. * * @VueI18nSee [Local Scope](../guide/essentials/scope#local-scope-2) * * @defaultValue `true` */ sync?: boolean /** * @remarks * A handler for getting notified when component-local instance was created. * * The handler gets called with new and old (root) VueI18n instances. * * This handler is useful when extending the root VueI18n instance and wanting to also apply those extensions to component-local instance. * * @defaultValue `null` */ componentInstanceCreatedListener?: ComponentInstanceCreatedListener /** * @remarks * A message resolver to resolve [`messages`](legacy#messages). * * If not specified, the vue-i18n internal message resolver will be used by default. * * You need to implement a message resolver yourself that supports the following requirements: * * - Resolve the message using the locale message of [`locale`](legacy#locale) passed as the first argument of the message resolver, and the path passed as the second argument. * * - If the message could not be resolved, you need to return `null`. * * - If you will be returned `null`, the message resolver will also be called on fallback if [`fallbackLocale`](legacy#fallbacklocale-2) is enabled, so the message will need to be resolved as well. * * The message resolver is called indirectly by the following APIs: * * - [`t`](legacy#t-key) * * - [`tc`](legacy#tc-key) * * - [`te`](legacy#te-key-locale) * * - [`tm`](legacy#tm-key) * * - [Translation component](component#translation) * * @example * Here is an example of how to set it up using your `createI18n`: * ```js * import { createI18n } from 'vue-i18n' * * // your message resolver * function messageResolver(obj, path) { * // simple message resolving! * const msg = obj[path] * return msg != null ? msg : null * } * * // call with I18n option * const i18n = createI18n({ * locale: 'ja', * messageResolver, // set your message resolver * messages: { * en: { ... }, * ja: { ... } * } * }) * * // the below your something to do ... * // ... * ``` * * @VueI18nTip * :new: v9.2+ * * @VueI18nWarning * If you use the message resolver, the [`flatJson`](legacy#flatjson) setting will be ignored. That is, you need to resolve the flat JSON by yourself. * * @VueI18nSee [Fallbacking](../guide/essentials/fallback) * * @defaultValue `undefined` */ messageResolver?: MessageResolver } /** * Locale message translation functions for VueI18n legacy interfaces * * @remarks * This is the interface for {@link VueI18n} * * @VueI18nLegacy */ export interface VueI18nTranslation< Messages = {}, Locales = 'en-US', DefinedLocaleMessage extends RemovedIndexResources<DefineLocaleMessage> = RemovedIndexResources<DefineLocaleMessage>, C = IsEmptyObject<DefinedLocaleMessage> extends false ? PickupPaths<{ [K in keyof DefinedLocaleMessage]: DefinedLocaleMessage[K] }> : never, M = IsEmptyObject<Messages> extends false ? PickupKeys<Messages> : never, ResourceKeys extends C | M = IsNever<C> extends false ? IsNever<M> extends false ? C | M : C : IsNever<M> extends false ? M : never > { /** * Locale message translation. * * @remarks * If this is used in a reactive context, it will re-evaluate once the locale changes. * * If [i18n component options](injection#i18n) is specified, it’s translated in preferentially local scope locale messages than global scope locale messages. * * If [i18n component options](injection#i18n) isn't specified, it’s translated with global scope locale messages. * * @param key - A target locale message key * * @returns Translated message * * @VueI18nSee [Scope and Locale Changing](../guide/essentials/scope) */ <Key extends string>(key: Key | ResourceKeys): TranslateResult /** * Locale message translation. * * @remarks * Overloaded `t`. About details, see the [call signature](legacy#key-key-resourcekeys-translateresult) details. * * @param key - A target locale message key * @param locale - A locale, it will be used over than global scope or local scope. * * @returns Translated message */ <Key extends string>( key: Key | ResourceKeys, locale: Locales | Locale ): TranslateResult /** * Locale message translation. * * @remarks * Overloaded `t`. About details, see the [call signature](legacy#key-key-resourcekeys-translateresult) details. * * @param key - A target locale message key * @param locale - A locale, it will be used over than global scope or local scope. * @param list - A values of list interpolation * * @returns Translated message * * @VueI18nSee [List interpolation](../guide/essentials/syntax#list-interpolation) */ <Key extends string>( key: Key | ResourceKeys, locale: Locales | Locale, list: unknown[] ): TranslateResult /** * Locale message translation. * * @remarks * Overloaded `t`. About details, see the [call signature](legacy#key-key-resourcekeys-translateresult) details. * * @param key - A target locale message key * @param locale - A locale, it will be used over than global scope or local scope. * @param named - A values of named interpolation * * @returns Translated message * * @VueI18nSee [Named interpolation](../guide/essentials/syntax#named-interpolation) */ <Key extends string>( key: Key | ResourceKeys, locale: Locales | Locale, named: Record<string, unknown> ): TranslateResult /** * Locale message translation. * * @remarks * Overloaded `t`. About details, see the [call signature](legacy#key-key-resourcekeys-translateresult) details. * * @param key - A target locale message key * @param list - A values of list interpolation * * @returns Translated message * * @VueI18nSee [List interpolation](../guide/essentials/syntax#list-interpolation) */ <Key extends string>( key: Key | ResourceKeys, list: unknown[] ): TranslateResult /** * Locale message translation. * * @remarks * Overloaded `t`. About details, see the [call signature](legacy#key-key-resourcekeys-translateresult) details. * * @param key - A target locale message key * @param named - A values of named interpolation * * @returns Translated message * * @VueI18nSee [Named interpolation](../guide/essentials/syntax#named-interpolation) */ <Key extends string>( key: Key | ResourceKeys, named: Record<string, unknown> ): TranslateResult } /** * Resolve locale message translation functions for VueI18n legacy interfaces * * @remarks * This is the interface for {@link VueI18n}. This interfce is an alias of {@link ComposerResolveLocaleMessageTranslation}. * * @VueI18nLegacy */ export type VueI18nResolveLocaleMessageTranslation<Locales = 'en-US'> = ComposerResolveLocaleMessageTranslation<Locales> /** * Locale message pluralization functions for VueI18n legacy interfaces * * @remarks * This is the interface for {@link VueI18n} * * @VueI18nLegacy */ export interface VueI18nTranslationChoice< Messages = {}, Locales = 'en-US', DefinedLocaleMessage extends RemovedIndexResources<DefineLocaleMessage> = RemovedIndexResources<DefineLocaleMessage>, C = IsEmptyObject<DefinedLocaleMessage> extends false ? PickupPaths<{ [K in keyof DefinedLocaleMessage]: DefinedLocaleMessage[K] }> : never, M = IsEmptyObject<Messages> extends false ? PickupKeys<Messages> : never, ResourceKeys extends C | M = IsNever<C> extends false ? IsNever<M> extends false ? C | M : C : IsNever<M> extends false ? M : never > { /** * Locale message pluralization * * @remarks * If this is used in a reactive context, it will re-evaluate once the locale changes. * * If [i18n component options](injection#i18n) is specified, it’s pluraled in preferentially local scope locale messages than global scope locale messages. * * If [i18n component options](injection#i18n) isn't specified, it’s pluraled with global scope locale messages. * * The plural choice number is handled with default `1`. * * @param key - A target locale message key * * @returns Pluraled message * * @VueI18nSee [Pluralization](../guide/essentials/pluralization) */ <Key extends string = string>(key: Key | ResourceKeys): TranslateResult /** * Locale message pluralization * * @remarks * Overloaded `tc`. About details, see the [call signature](legacy#key-key-resourcekeys-translateresult-2) details. * * @param key - A target locale message key * @param locale - A locale, it will be used over than global scope or local scope. * * @returns Pluraled message */ <Key extends string = string>( key: Key | ResourceKeys, locale: Locales | Locale ): TranslateResult /** * Locale message pluralization * * @remarks * Overloaded `tc`. About details, see the [call signature](legacy#key-key-resourcekeys-translateresult-2) details. * * @param key - A target locale message key * @param list - A values of list interpolation * * @returns Pluraled message */ <Key extends string>( key: Key | ResourceKeys, list: unknown[] ): TranslateResult /** * Locale message pluralization * * @remarks * Overloaded `tc`. About details, see the [call signature](legacy#key-key-resourcekeys-translateresult-2) details. * * @param key - A target locale message key * @param named - A values of named interpolation * * @returns Pluraled message */ <Key extends string>( key: Key | ResourceKeys, named: Record<string, unknown> ): TranslateResult /** * Locale message pluralization * * @remarks * Overloaded `tc`. About details, see the [call signature](legacy#key-key-resourcekeys-translateresult-2) details. * * @param key - A target locale message key * @param choice - Which plural string to get. 1 returns the first one. * * @returns Pluraled message */ <Key extends string>(key: Key | ResourceKeys, choice: number): TranslateResult /** * Locale message pluralization * * @remarks * Overloaded `tc`. About details, see the [call signature](legacy#key-key-resourcekeys-translateresult-2) details. * * @param key - A target locale message key * @param choice - Which plural string to get. 1 returns the first one. * @param locale - A locale, it will be used over than global scope or local scope. * * @returns Pluraled message */ <Key extends string>( key: Key | ResourceKeys, choice: number, locale: Locales | Locale ): TranslateResult /** * Locale message pluralization * * @remarks * Overloaded `tc`. About details, see the [call signature](legacy#key-key-resourcekeys-translateresult-2) details. * * @param key - A target locale message key * @param choice - Which plural string to get. 1 returns the first one. * @param list - A values of list interpolation * * @returns Pluraled message */ <Key extends string>( key: Key | ResourceKeys, choice: number, list: unknown[] ): TranslateResult /** * Locale message pluralization * * @remarks * Overloaded `tc`. About details, see the [call signature](legacy#key-key-resourcekeys-translateresult-2) details. * * @param key - A target locale message key * @param choice - Which plural string to get. 1 returns the first one. * @param named - A values of named interpolation * * @returns Pluraled message */ <Key extends string>( key: Key | ResourceKeys, choice: number, named: Record<string, unknown> ): TranslateResult } /** * Datetime formatting functions for VueI18n legacy interfaces * * @remarks * This is the interface for {@link VueI18n} * * @VueI18nLegacy */ export interface VueI18nDateTimeFormatting< DateTimeFormats = {}, Locales = 'en-US', DefinedDateTimeFormat extends RemovedIndexResources<DefineDateTimeFormat> = RemovedIndexResources<DefineDateTimeFormat>, C = IsEmptyObject<DefinedDateTimeFormat> extends false ? PickupFormatPathKeys<{ [K in keyof DefinedDateTimeFormat]: DefinedDateTimeFormat[K] }> : never, M = IsEmptyObject<DateTimeFormats> extends false ? PickupFormatKeys<DateTimeFormats> : never, ResourceKeys extends C | M = IsNever<C> extends false ? IsNever<M> extends false ? C | M : C : IsNever<M> extends false ? M : never > { /** * Datetime formatting * * @remarks * If this is used in a reactive context, it will re-evaluate once the locale changes. * * If [i18n component options](injection#i18n) is specified, it’s formatted in preferentially local scope datetime formats than global scope locale messages. * * If [i18n component options](injection#i18n) isn't specified, it’s formatted with global scope datetime formats. * * @param value - A value, timestamp number or `Date` instance * * @returns Formatted value * * @VueI18nSee [Datetime formatting](../guide/essentials/datetime) */ (value: number | Date): DateTimeFormatResult /** * Datetime formatting * * @remarks * Overloaded `d`. About details, see the [call signature](legacy#value-number-date-datetimeformatresult) details. * * @param value - A value, timestamp number or `Date` instance * @param key - A key of datetime formats * * @returns Formatted value */ <Value extends number | Date = number, Key extends string = string>( value: Value, key: Key | ResourceKeys ): DateTimeFormatResult /** * Datetime formatting * * @remarks * Overloaded `d`. About details, see the [call signature](legacy#value-number-date-datetimeformatresult) details. * * @param value - A value, timestamp number or `Date` instance * @param key - A key of datetime formats * @param locale - A locale, it will be used over than global scope or local scope. * * @returns Formatted value */ <Value extends number | Date = number, Key extends string = string>( value: Value, key: Key | ResourceKeys, locale: Locales ): DateTimeFormatResult /** * Datetime formatting * * @remarks * Overloaded `d`. About details, see the [call signature](legacy#value-number-date-datetimeformatresult) details. * * @param value - A value, timestamp number or `Date` instance * @param args - An argument values * * @returns Formatted value */ ( value: number | Date, args: { [key: string]: string | boolean | number } ): DateTimeFormatResult } /** * Number formatting functions for VueI18n legacy interfaces * * @remarks * This is the interface for {@link VueI18n} * * @VueI18nLegacy */ export interface VueI18nNumberFormatting< NumberFormats = {}, Locales = 'en-US', DefinedNumberFormat extends RemovedIndexResources<DefineNumberFormat> = RemovedIndexResources<DefineNumberFormat>, C = IsEmptyObject<DefinedNumberFormat> extends false ? PickupFormatPathKeys<{ [K in keyof DefinedNumberFormat]: DefinedNumberFormat[K] }> : never, M = IsEmptyObject<NumberFormats> extends false ? PickupFormatKeys<NumberFormats> : never, ResourceKeys extends C | M = IsNever<C> extends false ? IsNever<M> extends false ? C | M : C : IsNever<M> extends false ? M : never > { /** * Number formatting * * @remarks * If this is used in a reactive context, it will re-evaluate once the locale changes. * * If [i18n component options](injection#i18n) is specified, it’s formatted in preferentially local scope number formats than global scope locale messages. * * If [i18n component options](injection#i18n) isn't specified, it’s formatted with global scope number formats. * * @param value - A number value * * @returns Formatted value * * @VueI18nSee [Number formatting](../guide/essentials/number) */ (value: number): NumberFormatResult /** * Number formatting * * @remarks * Overloaded `n`. About details, see the [call signature](legacy#value-number-numberformatresult) details. * * @param value - A number value * @param key - A key of number formats * * @returns Formatted value */ <Key extends string = string>( value: number, key: Key | ResourceKeys ): NumberFormatResult /** * Number formatting * * @remarks * Overloaded `n`. About details, see the [call signature](legacy#value-number-numberformatresult) details. * * @param value - A number value * @param key - A key of number formats * @param locale - A locale, it will be used over than global scope or local scope. * * @returns Formatted value */ <Key extends string = string>( value: number, key: Key | ResourceKeys, locale: Locales ): NumberFormatResult /** * Number formatting * * @remarks * Overloaded `n`. About details, see the [call signature](legacy#value-number-numberformatresult) details. * * @param value - A number value * @param args - An argument values * * @returns Formatted value */ ( value: number, args: { [key: string]: string | boolean | number } ): NumberFormatResult } /** * VueI18n legacy interfaces * * @remarks * This interface is compatible with interface of `VueI18n` class (offered with Vue I18n v8.x). * * @VueI18nLegacy */ export interface VueI18n< Messages = {}, DateTimeFormats = {}, NumberFormats = {}, OptionLocale = Locale, ResourceLocales = | PickupLocales<NonNullable<Messages>> | PickupLocales<NonNullable<DateTimeFormats>> | PickupLocales<NonNullable<NumberFormats>>, Locales = OptionLocale extends string ? [ResourceLocales] extends [never] ? Locale : ResourceLocales : OptionLocale | ResourceLocales, Composition extends Composer< Messages, DateTimeFormats, NumberFormats, OptionLocale > = Composer<Messages, DateTimeFormats, NumberFormats, OptionLocale> > { /** * @remarks * Instance ID. */ id: number /** * @remarks * The current locale this VueI18n instance is using. * * If the locale contains a territory and a dialect, this locale contains an implicit fallback. * * @VueI18nSee [Scope and Locale Changing](../guide/essentials/scope) */ // locale: Locales locale: Locales /** * @remarks * The current fallback locales this VueI18n instance is using. * * @VueI18nSee [Fallbacking](../guide/essentials/fallback) */ fallbackLocale: FallbackLocales<Locales> /** * @remarks * The list of available locales in `messages` in lexical order. */ readonly availableLocales: Composition['availableLocales'] /** * @remarks * The locale messages of localization. * * @VueI18nSee [Getting Started](../guide/) */ readonly messages: { [K in keyof Messages]: Messages[K] } /** * @remarks * The datetime formats of localization. * * @VueI18nSee [Datetime Formatting](../guide/essentials/datetime) */ readonly datetimeFormats: { [K in keyof DateTimeFormats]: DateTimeFormats[K] } /** * @remarks * The number formats of localization. * * @VueI18nSee [Number Formatting](../guide/essentials/number) */ readonly numberFormats: { [K in keyof NumberFormats]: NumberFormats[K] } /** * @remarks * Custom Modifiers for linked messages. * * @VueI18nSee [Custom Modifiers](../guide/essentials/syntax#custom-modifiers) */ readonly modifiers: Composition['modifiers'] /** * @remarks * The formatter that implemented with Formatter interface. * * @deprecated See the [here](../guide/migration/breaking#remove-custom-formatter) */ formatter: Formatter /** * @remarks * A handler for localization missing. */ missing: MissingHandler | null /** * @remarks * A handler for post processing of translation. */ postTranslation: PostTranslationHandler<VueMessageType> | null /** * @remarks * Whether suppress warnings outputted when localization fails. * * @VueI18nSee [Fallbacking](../guide/essentials/fallback) */ silentTranslationWarn: Composition['missingWarn'] /** * @remarks * Whether suppress fallback warnings when localization fails. */ silentFallbackWarn: Composition['fallbackWarn'] /** * @remarks * Whether suppress warnings when falling back to either `fallbackLocale` or root. * * @VueI18nSee [Fallbacking](../guide/essentials/fallback) */ formatFallbackMessages: Composition['fallbackFormat'] /** * @remarks * Whether synchronize the root level locale to the component localization locale. * * @VueI18nSee [Local Scope](../guide/essentials/scope#local-scope-2) */ sync: Composition['inheritLocale'] /** * @remarks * Whether to allow the use locale messages of HTML formatting. * * If you set `warn` or` error`, will check the locale messages on the VueI18n instance. * * If you are specified `warn`, a warning will be output at console. * * If you are specified `error` will occurred an Error. * * @VueI18nSee [HTML Message](../guide/essentials/syntax#html-message) * @VueI18nSee [Change `warnHtmlInMessage` option default value](../guide/migration/breaking#change-warnhtmlinmessage-option-default-value) */ warnHtmlInMessage: WarnHtmlInMessageLevel /** * @remarks * Whether interpolation parameters are escaped before the message is translated. * * @VueI18nSee [HTML Message](../guide/essentials/syntax#html-message) */ escapeParameterHtml: Composition['escapeParameter'] /** * @remarks * Whether `v-t` directive's element should preserve `textContent` after directive is unbinded. * * @VueI18nSee [Custom Directive](../guide/advanced/directive) * @VueI18nSee [Remove preserveDirectiveContent option](../guide/migration/breaking#remove-preservedirectivecontent-option) * * @deprecated The `v-t` directive for Vue 3 now preserves the default content. Therefore, this option and its properties have been removed from the VueI18n instance. */ preserveDirectiveContent: boolean /** * A set of rules for word pluralization * * @VueI18nSee [Custom Pluralization](../guide/essentials/pluralization#custom-pluralization) */ pluralizationRules: Composition['pluralRules'] /** * Locale message translation * * @remarks * About details functions, See the {@link VueI18nTranslation} */ t: VueI18nTranslation< Messages, Locales, RemoveIndexSignature<{ [K in keyof DefineLocaleMessage]: DefineLocaleMessage[K] }> > /** * Resolve locale message translation * * @remarks * About details functions, See the {@link VueI18nResolveLocaleMessageTranslation} */ rt: VueI18nResolveLocaleMessageTranslation<Locales> /** * Locale message pluralization * * @remarks * About details functions, See the {@link VueI18nTranslationChoice} */ tc: VueI18nTranslationChoice< Messages, Locales, RemoveIndexSignature<{ [K in keyof DefineLocaleMessage]: DefineLocaleMessage[K] }> > /** * Translation locale message exist * * @remarks * whether do exist locale message on VueI18n instance [messages](legacy#messages). * * If you specified `locale`, check the locale messages of `locale`. * * @param key - A target locale message key * @param locale - A target locale * * @returns If found locale message, `true`, else `false` */ te< Str extends string, Key extends PickupKeys<Messages> = PickupKeys<Messages> >( key: Str | Key, locale?: Locales ): boolean /** * Locale messages getter * * @remarks * If [i18n component options](injection#i18n) is specified, it’s get in preferentially local scope locale messages than global scope locale messages. * * If [i18n component options](injection#i18n) isn't specified, it’s get with global scope locale messages. * * Based on the current `locale`, locale messages will be returned from Composer instance messages. * * If you change the `locale`, the locale messages returned will also correspond to the locale. * * If there are no locale messages for the given `key` in the composer instance messages, they will be returned with [fallbacking](../guide/essentials/fallback). * * @VueI18nWarning * You need to use `rt` for the locale message returned by `tm`. see the [rt](legacy#rt-message) details. * * @example * template: * ```html * <div class="container"> * <template v-for="content in $tm('contents')"> * <h2>{{ $rt(content.title) }}</h2> * <p v-for="paragraph in content.paragraphs"> * {{ $rt(paragraph) }} * </p> * </template> * </div> * ``` * * ```js * import { createI18n } from 'vue-i18n' * * const i18n = createI18n({ * messages: { * en: { * contents: [ * { * title: 'Title1', * // ... * paragraphs: [ * // ... * ] * } * ] * } * } * // ... * }) * ``` * @param key - A target locale message key * * @return Locale messages */ tm: Composition['tm'] /** * Get locale message * * @remarks * get locale message from VueI18n instance [messages](legacy#messages). * * @param locale - A target locale * * @returns Locale messages */ getLocaleMessage: Composition['getLocaleMessage'] /** * Set locale message * * @remarks * Set locale message to VueI18n instance [messages](legacy#messages). * * @param locale - A target locale * @param message - A message */ setLocaleMessage: Composition['setLocaleMessage'] /** * Merge locale message * * @remarks * Merge locale message to VueI18n instance [messages](legacy#messages). * * @param locale - A target locale * @param message - A message */ mergeLocaleMessage: Composition['mergeLocaleMessage'] /** * Datetime formatting * * @remarks * About details functions, See the {@link VueI18nDateTimeFormatting} */ d: VueI18nDateTimeFormatting< DateTimeFormats, Locales, RemoveIndexSignature<{ [K in keyof DefineDateTimeFormat]: DefineDateTimeFormat[K] }> > /** * Get datetime format * * @remarks * get datetime format from VueI18n instance [datetimeFormats](legacy#datetimeformats). * * @param locale - A target locale * * @returns Datetime format */ getDateTimeFormat: Composition['getDateTimeFormat'] /** * Set datetime format * * @remarks * Set datetime format to VueI18n instance [datetimeFormats](legacy#datetimeformats). * * @param locale - A target locale * @param format - A target datetime format */ setDateTimeFormat: Composition['setDateTimeFormat'] /** * Merge datetime format * * @remarks * Merge datetime format to VueI18n instance [datetimeFormats](legacy#datetimeformats). * * @param locale - A target locale * @param format - A target datetime format */ mergeDateTimeFormat: Composition['mergeDateTimeFormat'] /** * Number Formatting * * @remarks * About details functions, See the {@link VueI18nNumberFormatting} */ n: VueI18nNumberFormatting< NumberFormats, Locales, RemoveIndexSignature<{ [K in keyof DefineNumberFormat]: DefineNumberFormat[K] }> > /** * Get number format * * @remarks * get number format from VueI18n instance [numberFormats](legacy#numberFormats). * * @param locale - A target locale * * @returns Number format */ getNumberFormat: Composition['getNumberFormat'] /** * Set number format * * @remarks * Set number format to VueI18n instance [numberFormats](legacy#numberFormats). * * @param locale - A target locale * @param format - A target number format */ setNumberFormat: Composition['setNumberFormat'] /** * Merge number format * * @remarks * Merge number format to VueI18n instance [numberFormats](legacy#numberFormats). * * @param locale - A target locale * @param format - A target number format */ mergeNumberFormat: Composition['mergeNumberFormat'] /** * Get choice index * * @remarks * Get pluralization index for current pluralizing number and a given amount of choices. * * @deprecated Use `pluralizationRules` option instead of `getChoiceIndex`. */ getChoiceIndex: (choice: Choice, choicesLength: number) => number } /** * @internal */ export interface VueI18nInternal< Messages = {}, DateTimeFormats = {}, NumberFormats = {} > { __composer: Composer<Messages, DateTimeFormats, NumberFormats> __onComponentInstanceCreated( target: VueI18n<Messages, DateTimeFormats, NumberFormats> ): void __enableEmitter?: (emitter: VueDevToolsEmitter) => void __disableEmitter?: () => void } /** * Convert to I18n Composer Options from VueI18n Options * * @internal */ function convertComposerOptions< Messages = {}, DateTimeFormats = {}, NumberFormats = {} >( options: VueI18nOptions & ComposerInternalOptions<Messages, DateTimeFormats, NumberFormats> ): ComposerOptions & ComposerInternalOptions<Messages, DateTimeFormats, NumberFormats> { const locale = isString(options.locale) ? options.locale : DEFAULT_LOCALE const fallbackLocale = isString(options.fallbackLocale) || isArray(options.fallbackLocale) || isPlainObject(options.fallbackLocale) || options.fallbackLocale === false ? options.fallbackLocale : locale const missing = isFunction(options.missing) ? options.missing : undefined const missingWarn = isBoolean(options.silentTranslationWarn) || isRegExp(options.silentTranslationWarn) ? !options.silentTranslationWarn : true const fallbackWarn = isBoolean(options.silentFallbackWarn) || isRegExp(options.silentFallbackWarn) ? !options.silentFallbackWarn : true const fallbackRoot = isBoolean(options.fallbackRoot) ? options.fallbackRoot : true const fallbackFormat = !!options.formatFallbackMessages const modifiers = isPlainObject(options.modifiers) ? options.modifiers : {} const pluralizationRules = options.pluralizationRules const postTranslation = isFunction(options.postTranslation) ? options.postTranslation : undefined const warnHtmlMessage = isString(options.warnHtmlInMessage) ? options.warnHtmlInMessage !== 'off' : true const escapeParameter = !!options.escapeParameterHtml const inheritLocale = isBoolean(options.sync) ? options.sync : true if (__DEV__ && options.formatter) { warn(getWarnMessage(I18nWarnCodes.NOT_SUPPORTED_FORMATTER)) } if (__DEV__ && options.preserveDirectiveContent) { warn(getWarnMessage(I18nWarnCodes.NOT_SUPPORTED_PRESERVE_DIRECTIVE)) } let messages = options.messages if (isPlainObject(options.sharedMessages)) { const sharedMessages = options.sharedMessages const locales: Locale[] = Object.keys(sharedMessages) messages = locales.reduce((messages, locale) => { const message = messages[locale] || (messages[locale] = {}) assign(message, sharedMessages[locale]) return messages }, (messages || {}) as LocaleMessages<LocaleMessage<VueMessageType>>) } const { __i18n, __root, __injectWithOption } = options const datetimeFormats = options.datetimeFormats const numberFormats = options.numberFormats const flatJson = options.flatJson return { locale, fallbackLocale, messages, flatJson, datetimeFormats, numberFormats, missing, missingWarn, fallbackWarn, fallbackRoot, fallbackFormat, modifiers, pluralRules: pluralizationRules, postTranslation, warnHtmlMessage, escapeParameter, messageResolver: options.messageResolver, inheritLocale, __i18n, __root, __injectWithOption } } export function createVueI18n< Options extends VueI18nOptions = VueI18nOptions, Messages = Options['messages'] extends object ? Options['messages'] : {}, DateTimeFormats = Options['datetimeFormats'] extends object ? Options['datetimeFormats'] : {}, NumberFormats = Options['numberFormats'] extends object ? Options['numberFormats'] : {} >( options?: Options, VueI18nLegacy?: any ): VueI18n<Messages, DateTimeFormats, NumberFormats> export function createVueI18n< Schema extends object = DefaultLocaleMessageSchema, Locales extends string | object = 'en-US', Options extends VueI18nOptions< SchemaParams<Schema, VueMessageType>, LocaleParams<Locales> > = VueI18nOptions< SchemaParams<Schema, VueMessageType>, LocaleParams<Locales> >, Messages = Options['messages'] extends object ? Options['messages'] : {}, DateTimeFormats = Options['datetimeFormats'] extends object ? Options['datetimeFormats'] : {}, NumberFormats = Options['numberFormats'] extends object ? Options['numberFormats'] : {} >( options?: Options, VueI18nLegacy?: any ): VueI18n<Messages, DateTimeFormats, NumberFormats> /** * create VueI18n interface factory * * @internal */ // eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types export function createVueI18n(options: any = {}, VueI18nLegacy?: any): any { type Message = VueMessageType if (__BRIDGE__) { options[__VUE_I18N_BRIDGE__] = __VUE_I18N_BRIDGE__ // marking return new VueI18nLegacy(options) } else { const composer = createComposer(convertComposerOptions(options)) as Composer // defines VueI18n const vueI18n = { // id id: composer.id, // locale get locale(): Locale { return composer.locale.value as Locale }, set locale(val: Locale) { composer.locale.value = val as any }, // fallbackLocale get fallbackLocale(): FallbackLocale { return composer.fallbackLocale.value as FallbackLocale }, set fallbackLocale(val: FallbackLocale) { composer.fallbackLocale.value = val as any }, // messages get messages(): LocaleMessages<Message> { return composer.messages.value }, // datetimeFormats get datetimeFormats(): DateTimeFormatsType { return composer.datetimeFormats.value }, // numberFormats get numberFormats(): NumberFormatsType { return composer.numberFormats.value }, // availableLocales get availableLocales(): Locale[] { return composer.availableLocales as Locale[] }, // formatter get formatter(): Formatter { __DEV__ && warn(getWarnMessage(I18nWarnCodes.NOT_SUPPORTED_FORMATTER)) // dummy return { interpolate() { return [] } } }, set formatter(val: Formatter) { __DEV__ && warn(getWarnMessage(I18nWarnCodes.NOT_SUPPORTED_FORMATTER)) }, // missing get missing(): MissingHandler | null { return composer.getMissingHandler() }, set missing(handler: MissingHandler | null) { composer.setMissingHandler(handler) }, // silentTranslationWarn get silentTranslationWarn(): boolean | RegExp { return isBoolean(composer.missingWarn) ? !composer.missingWarn : composer.missingWarn }, set silentTranslationWarn(val: boolean | RegExp) { composer.missingWarn = isBoolean(val) ? !val : val }, // silentFallbackWarn get silentFallbackWarn(): boolean | RegExp { return isBoolean(composer.fallbackWarn) ? !composer.fallbackWarn : composer.fallbackWarn }, set silentFallbackWarn(val: boolean | RegExp) { composer.fallbackWarn = isBoolean(val) ? !val : val }, // modifiers get modifiers(): LinkedModifiers<Message> { return composer.modifiers }, // formatFallbackMessages get formatFallbackMessages(): boolean { return composer.fallbackFormat }, set formatFallbackMessages(val: boolean) { composer.fallbackFormat = val }, // postTranslation get postTranslation(): PostTranslationHandler<Message> | null { return composer.getPostTranslationHandler() }, set postTranslation(handler: PostTranslationHandler<Message> | null) { composer.setPostTranslationHandler(handler) }, // sync get sync(): boolean { return composer.inheritLocale }, set sync(val: boolean) { composer.inheritLocale = val }, // warnInHtmlMessage get warnHtmlInMessage(): WarnHtmlInMessageLevel { return composer.warnHtmlMessage ? 'warn' : 'off' }, set warnHtmlInMessage(val: WarnHtmlInMessageLevel) { composer.warnHtmlMessage = val !== 'off' }, // escapeParameterHtml get escapeParameterHtml(): boolean { return composer.escapeParameter }, set escapeParameterHtml(val: boolean) { composer.escapeParameter = val }, // preserveDirectiveContent get preserveDirectiveContent(): boolean { __DEV__ && warn(getWarnMessage(I18nWarnCodes.NOT_SUPPORTED_PRESERVE_DIRECTIVE)) return true }, set preserveDirectiveContent(val: boolean) { __DEV__ && warn(getWarnMessage(I18nWarnCodes.NOT_SUPPORTED_PRESERVE_DIRECTIVE)) }, // pluralizationRules get pluralizationRules(): PluralizationRules { return composer.pluralRules || {} }, // for internal __composer: composer, // t t(...args: unknown[]): TranslateResult { const [arg1, arg2, arg3] = args const options = {} as TranslateOptions let list: unknown[] | null = null let named: NamedValue | null = null if (!isString(arg1)) { throw createI18nError(I18nErrorCodes.INVALID_ARGUMENT) } const key = arg1 if (isString(arg2)) { options.locale = arg2 } else if (isArray(arg2)) { list = arg2 } else if (isPlainObject(arg2)) { named = arg2 as NamedValue } if (isArray(arg3)) { list = arg3 } else if (isPlainObject(arg3)) { named = arg3 as NamedValue } // return composer.t(key, (list || named || {}) as any, options) return Reflect.apply(composer.t, composer, [ key, (list || named || {}) as any, options ]) }, rt(...args: unknown[]): TranslateResult { return Reflect.apply(composer.rt, composer, [...args]) }, // tc tc(...args: unknown[]): TranslateResult { const [arg1, arg2, arg3] = args const options = { plural: 1 } as TranslateOptions let list: unknown[] | null = null let named: NamedValue | null = null if (!isString(arg1)) { throw createI18nError(I18nErrorCodes.INVALID_ARGUMENT) } const key = arg1 if (isString(arg2)) { options.locale = arg2 } else if (isNumber(arg2)) { options.plural = arg2 } else if (isArray(arg2)) { list = arg2 } else if (isPlainObject(arg2)) { named = arg2 as NamedValue } if (isString(arg3)) { options.locale = arg3 } else if (isArray(arg3)) { list = arg3 } else if (isPlainObject(arg3)) { named = arg3 as NamedValue } // return composer.t(key, (list || named || {}) as any, options) return Reflect.apply(composer.t, composer, [ key, (list || named || {}) as any, options ]) }, // te te(key: Path, locale?: Locale): boolean { return composer.te(key, locale) }, // tm tm(key: Path): LocaleMessageValue<VueMessageType> | {} { return composer.tm(key) }, // getLocaleMessage getLocaleMessage( locale: Locale ): LocaleMessageDictionary<VueMessageType> { return composer.getLocaleMessage(locale) }, // setLocaleMessage setLocaleMessage( locale: Locale, message: LocaleMessageDictionary<VueMessageType> ): void { composer.setLocaleMessage(locale, message) }, // mergeLocaleMessage mergeLocaleMessage( locale: Locale, message: LocaleMessageDictionary<VueMessageType> ): void { composer.mergeLocaleMessage(locale, message as any) }, // d d(...args: unknown[]): DateTimeFormatResult { return Reflect.apply(composer.d, composer, [...args]) }, // getDateTimeFormat getDateTimeFormat(locale: Locale): DateTimeFormat { return composer.getDateTimeFormat(locale) }, // setDateTimeFormat setDateTimeFormat(locale: Locale, format: DateTimeFormat): void { composer.setDateTimeFormat(locale, format) }, // mergeDateTimeFormat mergeDateTimeFormat(locale: Locale, format: DateTimeFormat): void { composer.mergeDateTimeFormat(locale, format) }, // n n(...args: unknown[]): NumberFormatResult { return Reflect.apply(composer.n, composer, [...args]) }, // getNumberFormat getNumberFormat(locale: Locale): NumberFormat { return composer.getNumberFormat(locale) }, // setNumberFormat setNumberFormat(locale: Locale, format: NumberFormat): void { composer.setNumberFormat(locale, format) }, // mergeNumberFormat mergeNumberFormat(locale: Locale, format: NumberFormat): void { composer.mergeNumberFormat(locale, format) }, // getChoiceIndex // eslint-disable-next-line @typescript-eslint/no-unused-vars getChoiceIndex(choice: Choice, choicesLength: number): number { __DEV__ && warn(getWarnMessage(I18nWarnCodes.NOT_SUPPORTED_GET_CHOICE_INDEX)) return -1 }, // for internal __onComponentInstanceCreated(target: VueI18n<Message>): void { const { componentInstanceCreatedListener } = options if (componentInstanceCreatedListener) { componentInstanceCreatedListener(target, vueI18n) } } } // for vue-devtools timeline event if (!__BRIDGE__ && __DEV__) { ;(vueI18n as unknown as VueI18nInternal).__enableEmitter = ( emitter: VueDevToolsEmitter ): void => { const __composer = composer as any __composer[EnableEmitter] && __composer[EnableEmitter](emitter) } ;(vueI18n as unknown as VueI18nInternal).__disableEmitter = (): void => { const __composer = composer as any __composer[DisableEmitter] && __composer[DisableEmitter]() } } return vueI18n } } /* eslint-enable @typescript-eslint/no-explicit-any */
the_stack
import { ConditionalTransferCreatedPayload, ConditionalTransferResolvedPayload, EngineEvents, FullTransferState, WithdrawalResolvedPayload, } from '@connext/vector-types' import { Address, formatGRT, Logger, Metrics, NetworkContracts, timer, toAddress, } from '@graphprotocol/common-ts' import { Allocation, AllocationSummary, createVectorClient, indexerError, IndexerErrorCode, QueryFeeModels, Transfer, TransferStatus, VectorClient, } from '@graphprotocol/indexer-common' import { BigNumber, providers, utils, Wallet } from 'ethers' import { EventCallbackConfig } from '@connext/vector-utils' import { Evt } from 'evt' import { DHeap } from '@thi.ng/heaps' import pRetry from 'p-retry' import { Transaction, Op, Sequelize } from 'sequelize' import { ReceiptCollector } from '.' // Transfers that can be resolved are resolved with a delay of 10 minutes const TRANSFER_RESOLVE_DELAY = 600_000 export interface VectorOptions { nodeUrl: string routerIdentifier: string transferDefinition: Address eventServer: { url: string port: string } } export interface TransferManagerCreateOptions { logger: Logger ethereum: providers.StaticJsonRpcProvider contracts: NetworkContracts wallet: Wallet vector: VectorOptions models: QueryFeeModels metrics: Metrics } interface TransferManagerOptions { logger: Logger vector: VectorClient contracts: NetworkContracts models: QueryFeeModels vectorTransferDefinition: Address } interface TransferToResolve { transfer: Transfer timeout: number } interface WithdrawableAllocation { allocation: Address collectedFees: string withdrawnFees: string } export class TransferReceiptCollector implements ReceiptCollector { private logger: Logger private contracts: NetworkContracts private vector: VectorClient private vectorTransferDefinition: Address private models: QueryFeeModels // Priority queue that orders transfers by the timeout after which // they should be resolved private transfersToResolve!: DHeap<TransferToResolve> private constructor(options: TransferManagerOptions) { this.logger = options.logger this.contracts = options.contracts this.vector = options.vector this.models = options.models this.vectorTransferDefinition = options.vectorTransferDefinition this.startTransferResolutionProcessing() this.startWithdrawalProcessing() this.vector.node.on( EngineEvents.CONDITIONAL_TRANSFER_CREATED, this.handleTransferCreated.bind(this), undefined, this.vector.node.publicIdentifier, ) this.vector.node.on( EngineEvents.CONDITIONAL_TRANSFER_RESOLVED, this.handleTransferResolved.bind(this), undefined, this.vector.node.publicIdentifier, ) this.vector.node.on( EngineEvents.WITHDRAWAL_RESOLVED, this.handleWithdrawalResolved.bind(this), undefined, this.vector.node.publicIdentifier, ) } static async create( options: TransferManagerCreateOptions, ): Promise<TransferReceiptCollector> { const logger = options.logger.child({ component: 'TransferQueryFeeCollector', }) // Connect to the vector node const evts: Partial<EventCallbackConfig> = { [EngineEvents.CONDITIONAL_TRANSFER_CREATED]: { evt: Evt.create<ConditionalTransferCreatedPayload>(), url: new URL( `/${EngineEvents.CONDITIONAL_TRANSFER_CREATED}`, options.vector.eventServer.url, ).toString(), }, [EngineEvents.CONDITIONAL_TRANSFER_RESOLVED]: { evt: Evt.create<ConditionalTransferResolvedPayload>(), url: new URL( `/${EngineEvents.CONDITIONAL_TRANSFER_RESOLVED}`, options.vector.eventServer.url, ).toString(), }, [EngineEvents.WITHDRAWAL_RESOLVED]: { evt: Evt.create<WithdrawalResolvedPayload>(), url: new URL( `/${EngineEvents.WITHDRAWAL_RESOLVED}`, options.vector.eventServer.url, ).toString(), }, } // Connect to the vector node for withdrawing query fees into the // rebate pool when allocations are closed const vector = await createVectorClient({ logger, metrics: options.metrics, ethereum: options.ethereum, contracts: options.contracts, wallet: options.wallet, nodeUrl: options.vector.nodeUrl, routerIdentifier: options.vector.routerIdentifier, eventServer: { ...options.vector.eventServer, evts, }, }) return new TransferReceiptCollector({ logger, vector, contracts: options.contracts, models: options.models, vectorTransferDefinition: options.vector.transferDefinition, }) } async rememberAllocations(allocations: Allocation[]): Promise<boolean> { const logger = this.logger.child({ allocations: allocations.map(allocation => allocation.id), }) try { // eslint-disable-next-line @typescript-eslint/no-non-null-assertion await this.models.allocationSummaries.sequelize!.transaction( async transaction => { for (const allocation of allocations) { await this.ensureAllocationSummary(allocation.id, transaction) } }, ) return true } catch (err) { logger.error( `Failed to remember allocations for collecting receipts later`, { err: indexerError(IndexerErrorCode.IE056, err), }, ) return false } } // Queue transfers of the allocation for resolving async collectReceipts(allocation: Allocation): Promise<boolean> { try { const now = new Date() const unresolvedTransfers = // eslint-disable-next-line @typescript-eslint/no-non-null-assertion await this.models.transfers.sequelize!.transaction( async transaction => { // Mark all transfers for the allocation as closed await this.models.transfers.update( { status: TransferStatus.ALLOCATION_CLOSED, allocationClosedAt: now, }, { where: { allocation: allocation.id, status: [TransferStatus.OPEN], }, transaction, }, ) // Update the allocation summary await this.models.allocationSummaries.update( { closedAt: now }, { where: { allocation: allocation.id }, transaction }, ) // Fetch all transfers for the allocation that have the status // OPEN or ALLOCATION_CLOSED and still need to be resolved return await this.unresolvedTransfersWithReceipts( allocation, transaction, ) }, ) // Resolve transfers with a delay for (const transfer of unresolvedTransfers) { this.transfersToResolve.push({ transfer, timeout: now.valueOf() + TRANSFER_RESOLVE_DELAY, }) } return true } catch (err) { this.logger.error(`Failed to queue transfers for resolving`, { allocation: allocation.id, deployment: allocation.subgraphDeployment.id.display, err: indexerError(IndexerErrorCode.IE045, err), }) return false } } private startTransferResolutionProcessing() { this.transfersToResolve = new DHeap<TransferToResolve>(null, { compare: (t1, t2) => t1.timeout - t2.timeout, }) // Check if there's another transfer to resolve every 10s timer(10_000).pipe(async () => { while (this.transfersToResolve.length > 0) { // Check whether the next transfer's timeout has expired let transfer = this.transfersToResolve.peek() if (transfer && transfer.timeout <= Date.now()) { // Remove the transfer from the processing queue // eslint-disable-next-line @typescript-eslint/no-non-null-assertion transfer = this.transfersToResolve.pop()! // Resolve the transfer now await this.resolveTransfer(transfer.transfer) } } }) } private startWithdrawalProcessing() { timer(30_000).pipe(async () => { const withdrawableAllocations = await this.withdrawableAllocations() for (const withdrawableAllocation of withdrawableAllocations) { await this.withdrawAllocation(withdrawableAllocation) } }) } public async queuePendingTransfersFromDatabase(): Promise<void> { let transfers try { // Fetch all resolvable transfers from the db and put them into the // processing queue transfers = await this.models.transfers.findAll({ where: { status: TransferStatus.ALLOCATION_CLOSED }, }) } catch (err) { this.logger.error(`Failed to query transfers to resolve`, { err: indexerError(IndexerErrorCode.IE041, err), }) return } for (const transfer of transfers) { this.transfersToResolve.push({ transfer, timeout: // eslint-disable-next-line @typescript-eslint/no-non-null-assertion transfer.allocationClosedAt!.valueOf() + TRANSFER_RESOLVE_DELAY, }) } } private isGraphTransfer(transfer: FullTransferState): boolean { const eventTransferDefinition = toAddress(transfer.transferDefinition) if (eventTransferDefinition !== this.vectorTransferDefinition) { this.logger.warn(`Non-Graph transfer detected`, { eventTransferDefinition, expectedTransferDefinition: this.vectorTransferDefinition, }) return false } return true } private async ensureAllocationSummary( allocation: Address, transaction: Transaction, ): Promise<AllocationSummary> { const [summary] = await this.models.allocationSummaries.findOrBuild({ where: { allocation }, defaults: { allocation, closedAt: null, createdTransfers: 0, resolvedTransfers: 0, failedTransfers: 0, openTransfers: 0, collectedFees: '0', withdrawnFees: '0', }, transaction, }) return summary } private async handleTransferCreated( payload: ConditionalTransferCreatedPayload, ) { // Ignore non-Graph transfers if (!this.isGraphTransfer(payload.transfer)) { return } // eslint-disable-next-line @typescript-eslint/no-non-null-assertion const { routingId, allocation } = payload.transfer.meta! const signer = payload.transfer.transferState.signer this.logger.info(`Add transfer to the database`, { routingId, allocation, signer, }) const transact = () => // eslint-disable-next-line @typescript-eslint/no-non-null-assertion this.models.transfers.sequelize!.transaction( { isolationLevel: Transaction.ISOLATION_LEVELS.REPEATABLE_READ }, async transaction => { // Update the allocation summary const summary = await this.ensureAllocationSummary( allocation, transaction, ) summary.createdTransfers += 1 summary.openTransfers += 1 await summary.save({ transaction }) // Add the transfer itself await this.models.transfers.create( { signer, allocation, routingId: routingId, status: TransferStatus.OPEN, allocationClosedAt: null, }, { transaction }, ) }, ) try { await pRetry( async () => { try { await transact() } catch (err) { // Only retry if the error is: // 40001: 'could not serialize access due to concurrent update' // This happens when 2 transfer creations write to the allocation summary at the same time. // 23505: 'duplicate key value violates unique constraint "allocation_summaries_pkey"', // This happens for the same as above, except that it creates the allocation summary. const code = err.parent.code if (!['40001', '23505'].includes(code)) { throw new pRetry.AbortError(err) } } }, { retries: 20 }, ) } catch (err) { this.logger.error(`Failed to add transfer to the database`, { routingId, allocation, signer, err: indexerError(IndexerErrorCode.IE042, err), }) return } } private async handleTransferResolved( payload: ConditionalTransferResolvedPayload, ) { // Ignore non-Graph transfers if (!this.isGraphTransfer(payload.transfer)) { return } // eslint-disable-next-line @typescript-eslint/no-non-null-assertion const { routingId, allocation } = payload.transfer.meta! const signer = payload.transfer.transferState.signer this.logger.info(`Mark transfer as resolved`, { routingId, allocation, }) try { // eslint-disable-next-line @typescript-eslint/no-non-null-assertion await this.models.transfers.sequelize!.transaction(async transaction => { // Mark the transfer as resolved await this.models.transfers.update( { status: TransferStatus.RESOLVED }, { where: { routingId }, transaction }, ) // Remove all its receipts (cleanup) await this.models.transferReceipts.destroy({ where: { signer }, transaction, }) // Update allocation summary const summary = await this.ensureAllocationSummary( allocation, transaction, ) summary.resolvedTransfers += 1 summary.openTransfers -= 1 summary.collectedFees = BigNumber.from(summary.collectedFees) .add(payload.transfer.balance.amount[1]) .toString() await summary.save({ transaction }) }) } catch (err) { this.logger.error(`Failed to mark transfer as resolved`, { routingId, err: indexerError(IndexerErrorCode.IE043, err), }) } } private async handleWithdrawalResolved(payload: WithdrawalResolvedPayload) { // eslint-disable-next-line @typescript-eslint/no-non-null-assertion const { allocation, collectedFees } = payload.transfer.meta! let success = false try { success = await pRetry( async () => { this.logger.debug(`Collecting query fees via the rebate pool`, { allocation, collectedFees: formatGRT(collectedFees), }) // Estimate gas and add some buffer (like we do in network.ts) const gasLimit = await this.vector.wallet.estimateGas( payload.transaction, ) const gasLimitWithBuffer = Math.ceil(gasLimit.toNumber() * 1.5) // Submit the transaction and wait for 2 confirmations // TODO: Use the robust transaction management from // https://github.com/graphprotocol/indexer/pull/212 // when it is ready const tx = await this.vector.wallet.sendTransaction({ ...payload.transaction, value: 0, // We're not sending any ETH gasLimit: gasLimitWithBuffer, }) await tx.wait(2) return true }, { retries: 2 }, ) } catch (err) { this.logger.error(`Failed to collect query fees on chain`, { allocation, collectedFees, err: indexerError(IndexerErrorCode.IE044, err), }) } if (success) { try { // Delete all transfers for the allocation (cleanup) await this.models.transfers.destroy({ where: { allocation, status: { [Op.not]: TransferStatus.OPEN } }, }) } catch (err) { this.logger.error(`Failed to clean up transfers for allocation`, { allocation, err: indexerError(IndexerErrorCode.IE049), }) } } } async withdrawableAllocations(): Promise<WithdrawableAllocation[]> { return await this.models.allocationSummaries.findAll({ where: { // In order to be withdrawable, allocations must be closed... closedAt: { [Op.not]: null }, // ...they must have some unwithdrawn query fees... collectedFees: { [Op.gt]: Sequelize.col('withdrawnFees') }, // ...they must have seen at least one transfer... createdTransfers: { [Op.gt]: 0 }, // ...and all transfers must have been resolved or failed. openTransfers: { [Op.lte]: 0 }, }, // Return and start withdrawing the most valuable allocations first order: [['collectedFees', 'DESC']], }) } async hasUnresolvedTransfers(allocation: Allocation): Promise<boolean> { const unresolvedTransfers = await this.models.transfers.count({ include: [this.models.transfers.associations.receipts], where: { allocation: allocation.id, status: [TransferStatus.OPEN, TransferStatus.ALLOCATION_CLOSED], }, }) return unresolvedTransfers > 0 } async unresolvedTransfersWithReceipts( allocation: Allocation, transaction: Transaction, ): Promise<Transfer[]> { return await this.models.transfers.findAll({ include: [this.models.transfers.associations.receipts], where: { allocation: allocation.id, status: [TransferStatus.OPEN, TransferStatus.ALLOCATION_CLOSED], }, order: [[this.models.transfers.associations.receipts, 'id', 'ASC']], transaction, }) } async resolveTransfer(transfer: Transfer): Promise<void> { const { routingId, allocation } = transfer this.logger.info(`Resolve transfer`, { routingId, allocation }) let failed = false try { const transferResult = await this.vector.node.getTransferByRoutingId({ channelAddress: this.vector.channelAddress, routingId: transfer.routingId, }) if (transferResult.isError) { throw transferResult.getError() } const vectorTransfer = transferResult.getValue() if (!vectorTransfer) { throw new Error(`Transfer not found`) } const result = await this.vector.node.resolveTransfer({ channelAddress: this.vector.channelAddress, transferId: vectorTransfer.transferId, transferResolver: { receipts: (transfer.receipts || []).map(receipt => ({ id: receipt.id, amount: receipt.fees.toString(), signature: receipt.signature, })), }, }) if (result.isError) { throw result.getError() } } catch (err) { this.logger.error(`Failed to resolve transfer`, { routingId, allocation, err: indexerError(IndexerErrorCode.IE046, err), }) failed = true } if (failed) { try { // eslint-disable-next-line @typescript-eslint/no-non-null-assertion await this.models.transfers.sequelize!.transaction( async transaction => { // Update transfer in the db await this.models.transfers.update( { status: TransferStatus.FAILED }, { where: { routingId }, transaction }, ) // Update allocation summary // eslint-disable-next-line @typescript-eslint/no-non-null-assertion const summary = (await this.models.allocationSummaries.findOne({ where: { allocation }, }))! summary.failedTransfers += 1 summary.openTransfers -= 1 await summary.save({ transaction }) }, ) } catch (err) { this.logger.critical(`Failed to mark transfer as failed`, { routingId, allocation, err: indexerError(IndexerErrorCode.IE047, err), }) } } } public async withdrawAllocation( withdrawal: WithdrawableAllocation, ): Promise<void> { const withdrawnFees = BigNumber.from(withdrawal.withdrawnFees) const feesToWithdraw = BigNumber.from(withdrawal.collectedFees).sub( withdrawal.withdrawnFees, ) this.logger.info(`Withdraw query fees for allocation`, { allocation: withdrawal.allocation, collectedFees: withdrawal.collectedFees, withdrawnFees: withdrawal.withdrawnFees.toString(), feesToWithdraw: feesToWithdraw.toString(), }) try { // Update the withdrawn fees await this.models.allocationSummaries.update( { withdrawnFees: withdrawnFees.add(feesToWithdraw).toString() }, { where: { allocation: withdrawal.allocation } }, ) const encoding = 'tuple(address staking,address allocationID)' const data = { staking: this.contracts.staking.address, allocationID: withdrawal.allocation, } const callData = utils.defaultAbiCoder.encode([encoding], [data]) const result = await this.vector.node.withdraw({ channelAddress: this.vector.channelAddress, assetId: this.contracts.token.address, amount: feesToWithdraw.toString(), recipient: '0xE5Fa88135c992A385aAa1C65A0c1b8ff3FdE1FD4', callTo: '0xE5Fa88135c992A385aAa1C65A0c1b8ff3FdE1FD4', callData, initiatorSubmits: true, meta: { allocation: withdrawal.allocation, collectedFees: feesToWithdraw, }, }) if (result.isError) { const err = result.getError() this.logger.error(`Failed to withdraw`, { channelAddress: this.vector.channelAddress, amount: withdrawal.collectedFees.toString(), callTo: '0xE5Fa88135c992A385aAa1C65A0c1b8ff3FdE1FD4', callData, err, }) throw err } } catch (err) { this.logger.error(`Failed to withdraw query fees for allocation`, { allocation: withdrawal.allocation, collectedFees: withdrawal.collectedFees.toString(), err: indexerError(IndexerErrorCode.IE048, err), }) } } }
the_stack
import { AfterViewInit, ApplicationRef, ChangeDetectorRef, Component, Directive, ElementRef, EventEmitter, HostBinding, HostListener, Injector, Input, OnChanges, OnDestroy, OnInit, Optional, Output, SkipSelf } from '@angular/core'; import { WindowComponent } from '../window/window.component'; import { WindowState } from '../window/window-state'; import { FormComponent } from '../form/form.component'; import { ngValueAccessor, ValueAccessorBase } from '../../core/form'; @Component({ selector: 'dui-button', template: ` <dui-icon *ngIf="icon && iconRight === false" [color]="iconColor" [name]="icon" [size]="iconSize"></dui-icon> <ng-content></ng-content> <dui-icon *ngIf="icon && iconRight !== false" [color]="iconColor" [name]="icon" [size]="iconSize"></dui-icon> `, host: { '[attr.tabindex]': '1', '[class.icon]': '!!icon', '[class.small]': 'small !== false', '[class.tight]': 'tight !== false', '[class.active]': 'active !== false', '[class.highlighted]': 'highlighted !== false', '[class.primary]': 'primary !== false', '[class.icon-left]': 'iconRight === false', '[class.icon-right]': 'iconRight !== false', '[class.with-text]': 'hasText()', }, styleUrls: ['./button.component.scss'], }) export class ButtonComponent implements OnInit, AfterViewInit { /** * The icon for this button. Either a icon name same as for dui-icon, or an image path. */ @Input() icon?: string; /** * Change in the icon size. Should not be necessary usually. */ @Input() iconSize?: number; @Input() iconRight?: boolean | '' = false; @Input() iconColor?: string; /** * Whether the button is active (pressed) */ @Input() active: boolean | '' = false; /** * Whether the button has no padding and smaller font size */ @Input() small: boolean | '' = false; /** * Whether the button has smaller padding. Better for button with icons. */ @Input() tight: boolean | '' = false; /** * Whether the button is highlighted. */ @Input() highlighted: boolean | '' = false; /** * Whether the button is primary. */ @Input() primary: boolean | '' = false; /** * Whether the button is focused on initial loading. */ @Input() focused: boolean | '' = false; /** * Whether the button is focused on initial loading. */ @Input() submitForm?: FormComponent; /** * Auto-detected but could be set manually as well. * Necessary for correct icon placement. */ withText?: boolean; protected detectedText: boolean = false; constructor( public element: ElementRef, @SkipSelf() public cdParent: ChangeDetectorRef, @Optional() public formComponent: FormComponent, ) { this.element.nativeElement.removeAttribute('tabindex'); } hasText() { return this.withText === undefined ? this.detectedText : this.withText; } @Input() disabled: boolean | '' = false; @HostBinding('class.disabled') get isDisabled() { if (this.formComponent && this.formComponent.disabled) return true; if (this.submitForm && (this.submitForm.invalid || this.submitForm.disabled || this.submitForm.submitting)) { return true; } return false !== this.disabled; } @Input() square: boolean | '' = false; @HostBinding('class.square') get isRound() { return false !== this.square; } @Input() textured: boolean | '' = false; @HostBinding('class.textured') get isTextured() { return false !== this.textured; } ngOnInit() { if (this.focused !== false) { setTimeout(() => { this.element.nativeElement.focus(); }, 10); } } ngAfterViewInit() { if (this.icon) { const content = this.element.nativeElement.innerText.trim(); const hasText = content !== this.icon && content.length > 0; if (hasText) { this.detectedText = true; this.cdParent.detectChanges(); } } } @HostListener('click') async onClick() { if (this.isDisabled) return; if (this.submitForm) { this.submitForm.submitForm(); } } } /** * Used to group buttons together. */ @Component({ selector: 'dui-button-group', template: '<ng-content></ng-content>', host: { '[class.float-right]': 'float===\'right\'', '(transitionend)': 'transitionEnded()' }, styleUrls: ['./button-group.component.scss'] }) export class ButtonGroupComponent implements AfterViewInit, OnDestroy { /** * How the button should behave. * `sidebar` means it aligns with the sidebar. Is the sidebar open, this button-group has a left margin. * Is it closed, the margin is gone. */ @Input() float: 'static' | 'sidebar' | 'float' | 'right' = 'static'; @Input() padding: 'normal' | 'none' = 'normal'; @HostBinding('class.padding-none') get isPaddingNone() { return this.padding === 'none'; } // @HostBinding('class.ready') // protected init = false; constructor( private windowState: WindowState, private windowComponent: WindowComponent, private element: ElementRef<HTMLElement>, @SkipSelf() protected cd: ChangeDetectorRef, ) { } public activateOneTimeAnimation() { (this.element.nativeElement as HTMLElement).classList.add('with-animation'); } public sidebarMoved() { this.updatePaddingLeft(); } ngOnDestroy(): void { } transitionEnded() { (this.element.nativeElement as HTMLElement).classList.remove('with-animation'); } ngAfterViewInit(): void { if (this.float === 'sidebar') { this.windowState.buttonGroupAlignedToSidebar = this; } this.updatePaddingLeft(); } updatePaddingLeft() { if (this.float === 'sidebar') { if (this.windowComponent.content) { if (this.windowComponent.content!.isSidebarVisible()) { const newLeft = Math.max(0, this.windowComponent.content!.getSidebarWidth() - this.element.nativeElement.offsetLeft) + 'px'; if (this.element.nativeElement.style.paddingLeft == newLeft) { //no transition change, doesn't trigger transitionEnd (this.element.nativeElement as HTMLElement).classList.remove('with-animation'); return; } this.element.nativeElement.style.paddingLeft = newLeft; return; } } } this.element.nativeElement.style.paddingLeft = '0px'; } } @Component({ selector: 'dui-button-groups', template: ` <ng-content></ng-content> `, host: { '[class.align-left]': `align === 'left'`, '[class.align-center]': `align === 'center'`, '[class.align-right]': `align === 'right'`, }, styleUrls: ['./button-groups.component.scss'], }) export class ButtonGroupsComponent { @Input() align: 'left' | 'center' | 'right' = 'left'; } @Directive({ selector: '[duiFileChooser]', providers: [ngValueAccessor(FileChooserDirective)] }) export class FileChooserDirective extends ValueAccessorBase<any> implements OnDestroy, OnChanges { @Input() duiFileMultiple?: boolean | '' = false; @Input() duiFileDirectory?: boolean | '' = false; // @Input() duiFileChooser?: string | string[]; @Output() duiFileChooserChange = new EventEmitter<string | string[]>(); protected input: HTMLInputElement; constructor( protected injector: Injector, public readonly cd: ChangeDetectorRef, @SkipSelf() public readonly cdParent: ChangeDetectorRef, private app: ApplicationRef, ) { super(injector, cd, cdParent); const input = document.createElement('input'); input.setAttribute('type', 'file'); this.input = input; this.input.addEventListener('change', (event: any) => { const files = event.target.files as FileList; if (files.length) { if (this.duiFileMultiple !== false) { const paths: string[] = []; for (let i = 0; i < files.length; i++) { const file = files.item(i) as any as { path: string, name: string }; paths.push(file.path); } this.innerValue = paths; } else { const file = files.item(0) as any as { path: string, name: string }; this.innerValue = file.path; } this.duiFileChooserChange.emit(this.innerValue); this.app.tick(); } }); } ngOnDestroy() { } ngOnChanges(): void { (this.input as any).webkitdirectory = this.duiFileDirectory !== false; this.input.multiple = this.duiFileMultiple !== false; } @HostListener('click') onClick() { this.input.click(); } } export interface FilePickerItem { data: Uint8Array; name: string; } function readFile(file: File): Promise<Uint8Array | undefined> { return new Promise((resolve, reject) => { const reader = new FileReader(); reader.onload = () => { if (reader.result) { if (reader.result instanceof ArrayBuffer) { resolve(new Uint8Array(reader.result)); } else { resolve(undefined); } } }; reader.onerror = (error) => { console.log('Error: ', error); reject(); }; reader.readAsArrayBuffer(file); }); } @Directive({ selector: '[duiFilePicker]', providers: [ngValueAccessor(FileChooserDirective)] }) export class FilePickerDirective extends ValueAccessorBase<any> implements OnDestroy, AfterViewInit { @Input() duiFileMultiple?: boolean | '' = false; @Input() duiFileAutoOpen: boolean = false; @Output() duiFilePickerChange = new EventEmitter<FilePickerItem | FilePickerItem[]>(); protected input: HTMLInputElement; constructor( protected injector: Injector, public readonly cd: ChangeDetectorRef, @SkipSelf() public readonly cdParent: ChangeDetectorRef, private app: ApplicationRef, ) { super(injector, cd, cdParent); const input = document.createElement('input'); input.setAttribute('type', 'file'); this.input = input; this.input.addEventListener('change', async (event: any) => { const files = event.target.files as FileList; if (files.length) { if (this.duiFileMultiple !== false) { const res: FilePickerItem[] = []; for (let i = 0; i < files.length; i++) { const file = files.item(i); if (file) { const uint8Array = await readFile(file); if (uint8Array) { res.push({ data: uint8Array, name: file.name }); } } } this.innerValue = res; } else { const file = files.item(0); if (file) { this.innerValue = { data: await readFile(file), name: file.name }; } } this.duiFilePickerChange.emit(this.innerValue); this.app.tick(); } }); } ngOnDestroy() { } ngAfterViewInit() { if (this.duiFileAutoOpen) this.onClick(); } @HostListener('click') onClick() { this.input.multiple = this.duiFileMultiple !== false; this.input.click(); } } @Directive({ selector: '[duiFileDrop]', host: { '[class.hover]': 'hover', }, providers: [ngValueAccessor(FileChooserDirective)] }) export class FileDropDirective extends ValueAccessorBase<any> implements OnDestroy { @Input() duiFileDropMultiple?: boolean | '' = false; @Output() duiFileDropChange = new EventEmitter<FilePickerItem | FilePickerItem[]>(); hover = false; constructor( protected injector: Injector, public readonly cd: ChangeDetectorRef, @SkipSelf() public readonly cdParent: ChangeDetectorRef, private app: ApplicationRef, ) { super(injector, cd, cdParent); } @HostListener('dragenter', ['$event']) onDragEnter(ev: any) { // Prevent default behavior (Prevent file from being opened) ev.preventDefault(); this.hover = true; this.cdParent.detectChanges(); } @HostListener('dragover', ['$event']) onDragOver(ev: any) { // Prevent default behavior (Prevent file from being opened) ev.preventDefault(); } @HostListener('dragleave', ['$event']) onDragLeave(ev: any) { // Prevent default behavior (Prevent file from being opened) ev.preventDefault(); this.hover = false; this.cdParent.detectChanges(); } @HostListener('drop', ['$event']) async onDrop(ev: any) { // Prevent default behavior (Prevent file from being opened) ev.preventDefault(); const res: FilePickerItem[] = []; if (ev.dataTransfer.items) { // Use DataTransferItemList interface to access the file(s) for (let i = 0; i < ev.dataTransfer.items.length; i++) { // If dropped items aren't files, reject them if (ev.dataTransfer.items[i].kind === 'file') { const file = ev.dataTransfer.items[i].getAsFile(); if (file) { const uint8Array = await readFile(file); if (uint8Array) { res.push({ data: uint8Array, name: file.name }); } } } } } else { // Use DataTransfer interface to access the file(s) for (let i = 0; i < ev.dataTransfer.files.length; i++) { const file = ev.dataTransfer.files.item(i); if (file) { const uint8Array = await readFile(file); if (uint8Array) { res.push({ data: uint8Array, name: file.name }); } } } } if (this.duiFileDropMultiple !== false) { this.innerValue = res; } else { if (res.length) { this.innerValue = res[0]; } else { this.innerValue = undefined; } } this.duiFileDropChange.emit(this.innerValue); this.hover = false; this.cdParent.detectChanges(); } ngOnDestroy() { } }
the_stack
declare var NFCErrorDomain: string; declare const enum NFCFeliCaEncryptionId { NFCFeliCaEncryptionIdAES = 79, NFCFeliCaEncryptionIdAES_DES = 65, EncryptionIdAES = 79, EncryptionIdAES_DES = 65 } declare const enum NFCFeliCaPollingRequestCode { NFCFeliCaPollingRequestCodeNoRequest = 0, NFCFeliCaPollingRequestCodeSystemCode = 1, NFCFeliCaPollingRequestCodeCommunicationPerformance = 2, PollingRequestCodeNoRequest = 0, PollingRequestCodeSystemCode = 1, PollingRequestCodeCommunicationPerformance = 2 } declare const enum NFCFeliCaPollingTimeSlot { NFCFeliCaPollingTimeSlotMax1 = 0, NFCFeliCaPollingTimeSlotMax2 = 1, NFCFeliCaPollingTimeSlotMax4 = 3, NFCFeliCaPollingTimeSlotMax8 = 7, NFCFeliCaPollingTimeSlotMax16 = 15, PollingTimeSlotMax1 = 0, PollingTimeSlotMax2 = 1, PollingTimeSlotMax4 = 3, PollingTimeSlotMax8 = 7, PollingTimeSlotMax16 = 15 } interface NFCFeliCaTag extends NFCNDEFTag, NFCTag { currentIDm: NSData; currentSystemCode: NSData; pollingWithSystemCodeRequestCodeTimeSlotCompletionHandler(systemCode: NSData, requestCode: NFCFeliCaPollingRequestCode, timeSlot: NFCFeliCaPollingTimeSlot, completionHandler: (p1: NSData, p2: NSData, p3: NSError) => void): void; readWithoutEncryptionWithServiceCodeListBlockListCompletionHandler(serviceCodeList: NSArray<NSData> | NSData[], blockList: NSArray<NSData> | NSData[], completionHandler: (p1: number, p2: number, p3: NSArray<NSData>, p4: NSError) => void): void; requestResponseWithCompletionHandler(completionHandler: (p1: number, p2: NSError) => void): void; requestServiceV2WithNodeCodeListCompletionHandler(nodeCodeList: NSArray<NSData> | NSData[], completionHandler: (p1: number, p2: number, p3: NFCFeliCaEncryptionId, p4: NSArray<NSData>, p5: NSArray<NSData>, p6: NSError) => void): void; requestServiceWithNodeCodeListCompletionHandler(nodeCodeList: NSArray<NSData> | NSData[], completionHandler: (p1: NSArray<NSData>, p2: NSError) => void): void; requestSpecificationVersionWithCompletionHandler(completionHandler: (p1: number, p2: number, p3: NSData, p4: NSData, p5: NSError) => void): void; requestSystemCodeWithCompletionHandler(completionHandler: (p1: NSArray<NSData>, p2: NSError) => void): void; resetModeWithCompletionHandler(completionHandler: (p1: number, p2: number, p3: NSError) => void): void; sendFeliCaCommandPacketCompletionHandler(commandPacket: NSData, completionHandler: (p1: NSData, p2: NSError) => void): void; writeWithoutEncryptionWithServiceCodeListBlockListBlockDataCompletionHandler(serviceCodeList: NSArray<NSData> | NSData[], blockList: NSArray<NSData> | NSData[], blockData: NSArray<NSData> | NSData[], completionHandler: (p1: number, p2: number, p3: NSError) => void): void; } declare var NFCFeliCaTag: { prototype: NFCFeliCaTag; }; declare class NFCISO15693CustomCommandConfiguration extends NFCTagCommandConfiguration { static alloc(): NFCISO15693CustomCommandConfiguration; // inherited from NSObject static new(): NFCISO15693CustomCommandConfiguration; // inherited from NSObject customCommandCode: number; manufacturerCode: number; requestParameters: NSData; constructor(o: { manufacturerCode: number; customCommandCode: number; requestParameters: NSData; }); constructor(o: { manufacturerCode: number; customCommandCode: number; requestParameters: NSData; maximumRetries: number; retryInterval: number; }); initWithManufacturerCodeCustomCommandCodeRequestParameters(manufacturerCode: number, customCommandCode: number, requestParameters: NSData): this; initWithManufacturerCodeCustomCommandCodeRequestParametersMaximumRetriesRetryInterval(manufacturerCode: number, customCommandCode: number, requestParameters: NSData, maximumRetries: number, retryInterval: number): this; } declare class NFCISO15693ReadMultipleBlocksConfiguration extends NFCTagCommandConfiguration { static alloc(): NFCISO15693ReadMultipleBlocksConfiguration; // inherited from NSObject static new(): NFCISO15693ReadMultipleBlocksConfiguration; // inherited from NSObject chunkSize: number; range: NSRange; constructor(o: { range: NSRange; chunkSize: number; }); constructor(o: { range: NSRange; chunkSize: number; maximumRetries: number; retryInterval: number; }); initWithRangeChunkSize(range: NSRange, chunkSize: number): this; initWithRangeChunkSizeMaximumRetriesRetryInterval(range: NSRange, chunkSize: number, maximumRetries: number, retryInterval: number): this; } declare class NFCISO15693ReaderSession extends NFCReaderSession { static alloc(): NFCISO15693ReaderSession; // inherited from NSObject static new(): NFCISO15693ReaderSession; // inherited from NSObject constructor(o: { delegate: NFCReaderSessionDelegate; queue: NSObject; }); initWithDelegateQueue(delegate: NFCReaderSessionDelegate, queue: NSObject): this; restartPolling(): void; } declare const enum NFCISO15693RequestFlag { NFCISO15693RequestFlagDualSubCarriers = 1, NFCISO15693RequestFlagHighDataRate = 2, NFCISO15693RequestFlagProtocolExtension = 8, NFCISO15693RequestFlagSelect = 16, NFCISO15693RequestFlagAddress = 32, NFCISO15693RequestFlagOption = 64, NFCISO15693RequestFlagCommandSpecificBit8 = 128, RequestFlagDualSubCarriers = 1, RequestFlagHighDataRate = 2, RequestFlagProtocolExtension = 8, RequestFlagSelect = 16, RequestFlagAddress = 32, RequestFlagOption = 64 } declare const enum NFCISO15693ResponseFlag { Error = 1, ResponseBufferValid = 2, FinalResponse = 4, ProtocolExtension = 8, BlockSecurityStatusBit5 = 16, BlockSecurityStatusBit6 = 32, WaitTimeExtension = 64 } interface NFCISO15693Tag extends NFCNDEFTag, NFCTag { icManufacturerCode: number; icSerialNumber: NSData; identifier: NSData; authenticateWithRequestFlagsCryptoSuiteIdentifierMessageCompletionHandler(flags: NFCISO15693RequestFlag, cryptoSuiteIdentifier: number, message: NSData, completionHandler: (p1: NFCISO15693ResponseFlag, p2: NSData, p3: NSError) => void): void; challengeWithRequestFlagsCryptoSuiteIdentifierMessageCompletionHandler(flags: NFCISO15693RequestFlag, cryptoSuiteIdentifier: number, message: NSData, completionHandler: (p1: NSError) => void): void; customCommandWithRequestFlagCustomCommandCodeCustomRequestParametersCompletionHandler(flags: NFCISO15693RequestFlag, customCommandCode: number, customRequestParameters: NSData, completionHandler: (p1: NSData, p2: NSError) => void): void; extendedFastReadMultipleBlocksWithRequestFlagBlockRangeCompletionHandler(flags: NFCISO15693RequestFlag, blockRange: NSRange, completionHandler: (p1: NSArray<NSData>, p2: NSError) => void): void; extendedGetMultipleBlockSecurityStatusWithRequestFlagBlockRangeCompletionHandler(flags: NFCISO15693RequestFlag, blockRange: NSRange, completionHandler: (p1: NSArray<number>, p2: NSError) => void): void; extendedLockBlockWithRequestFlagsBlockNumberCompletionHandler(flags: NFCISO15693RequestFlag, blockNumber: number, completionHandler: (p1: NSError) => void): void; extendedReadMultipleBlocksWithRequestFlagsBlockRangeCompletionHandler(flags: NFCISO15693RequestFlag, blockRange: NSRange, completionHandler: (p1: NSArray<NSData>, p2: NSError) => void): void; extendedReadSingleBlockWithRequestFlagsBlockNumberCompletionHandler(flags: NFCISO15693RequestFlag, blockNumber: number, completionHandler: (p1: NSData, p2: NSError) => void): void; extendedWriteMultipleBlocksWithRequestFlagsBlockRangeDataBlocksCompletionHandler(flags: NFCISO15693RequestFlag, blockRange: NSRange, dataBlocks: NSArray<NSData> | NSData[], completionHandler: (p1: NSError) => void): void; extendedWriteSingleBlockWithRequestFlagsBlockNumberDataBlockCompletionHandler(flags: NFCISO15693RequestFlag, blockNumber: number, dataBlock: NSData, completionHandler: (p1: NSError) => void): void; fastReadMultipleBlocksWithRequestFlagBlockRangeCompletionHandler(flags: NFCISO15693RequestFlag, blockRange: NSRange, completionHandler: (p1: NSArray<NSData>, p2: NSError) => void): void; getMultipleBlockSecurityStatusWithRequestFlagBlockRangeCompletionHandler(flags: NFCISO15693RequestFlag, blockRange: NSRange, completionHandler: (p1: NSArray<number>, p2: NSError) => void): void; getSystemInfoAndUIDWithRequestFlagCompletionHandler(flags: NFCISO15693RequestFlag, completionHandler: (p1: NSData, p2: number, p3: number, p4: number, p5: number, p6: number, p7: NSError) => void): void; getSystemInfoWithRequestFlagCompletionHandler(flags: NFCISO15693RequestFlag, completionHandler: (p1: number, p2: number, p3: number, p4: number, p5: number, p6: NSError) => void): void; keyUpdateWithRequestFlagsKeyIdentifierMessageCompletionHandler(flags: NFCISO15693RequestFlag, keyIdentifier: number, message: NSData, completionHandler: (p1: NFCISO15693ResponseFlag, p2: NSData, p3: NSError) => void): void; lockAFIWithRequestFlagCompletionHandler(flags: NFCISO15693RequestFlag, completionHandler: (p1: NSError) => void): void; lockBlockWithRequestFlagsBlockNumberCompletionHandler(flags: NFCISO15693RequestFlag, blockNumber: number, completionHandler: (p1: NSError) => void): void; lockDFSIDWithRequestFlagCompletionHandler(flags: NFCISO15693RequestFlag, completionHandler: (p1: NSError) => void): void; lockDSFIDWithRequestFlagCompletionHandler(flags: NFCISO15693RequestFlag, completionHandler: (p1: NSError) => void): void; readBufferWithRequestFlagsCompletionHandler(flags: NFCISO15693RequestFlag, completionHandler: (p1: NFCISO15693ResponseFlag, p2: NSData, p3: NSError) => void): void; readMultipleBlocksWithConfigurationCompletionHandler(readConfiguration: NFCISO15693ReadMultipleBlocksConfiguration, completionHandler: (p1: NSData, p2: NSError) => void): void; readMultipleBlocksWithRequestFlagsBlockRangeCompletionHandler(flags: NFCISO15693RequestFlag, blockRange: NSRange, completionHandler: (p1: NSArray<NSData>, p2: NSError) => void): void; readSingleBlockWithRequestFlagsBlockNumberCompletionHandler(flags: NFCISO15693RequestFlag, blockNumber: number, completionHandler: (p1: NSData, p2: NSError) => void): void; resetToReadyWithRequestFlagsCompletionHandler(flags: NFCISO15693RequestFlag, completionHandler: (p1: NSError) => void): void; selectWithRequestFlagsCompletionHandler(flags: NFCISO15693RequestFlag, completionHandler: (p1: NSError) => void): void; sendCustomCommandWithConfigurationCompletionHandler(commandConfiguration: NFCISO15693CustomCommandConfiguration, completionHandler: (p1: NSData, p2: NSError) => void): void; sendRequestWithFlagCommandCodeDataCompletionHandler(flags: number, commandCode: number, data: NSData, completionHandler: (p1: NFCISO15693ResponseFlag, p2: NSData) => void): void; stayQuietWithCompletionHandler(completionHandler: (p1: NSError) => void): void; writeAFIWithRequestFlagAfiCompletionHandler(flags: NFCISO15693RequestFlag, afi: number, completionHandler: (p1: NSError) => void): void; writeDSFIDWithRequestFlagDsfidCompletionHandler(flags: NFCISO15693RequestFlag, dsfid: number, completionHandler: (p1: NSError) => void): void; writeMultipleBlocksWithRequestFlagsBlockRangeDataBlocksCompletionHandler(flags: NFCISO15693RequestFlag, blockRange: NSRange, dataBlocks: NSArray<NSData> | NSData[], completionHandler: (p1: NSError) => void): void; writeSingleBlockWithRequestFlagsBlockNumberDataBlockCompletionHandler(flags: NFCISO15693RequestFlag, blockNumber: number, dataBlock: NSData, completionHandler: (p1: NSError) => void): void; } declare var NFCISO15693Tag: { prototype: NFCISO15693Tag; }; declare var NFCISO15693TagResponseErrorKey: string; declare class NFCISO7816APDU extends NSObject implements NSCopying { static alloc(): NFCISO7816APDU; // inherited from NSObject static new(): NFCISO7816APDU; // inherited from NSObject readonly data: NSData; readonly expectedResponseLength: number; readonly instructionClass: number; readonly instructionCode: number; readonly p1Parameter: number; readonly p2Parameter: number; constructor(o: { data: NSData; }); constructor(o: { instructionClass: number; instructionCode: number; p1Parameter: number; p2Parameter: number; data: NSData; expectedResponseLength: number; }); copyWithZone(zone: interop.Pointer | interop.Reference<any>): any; initWithData(data: NSData): this; initWithInstructionClassInstructionCodeP1ParameterP2ParameterDataExpectedResponseLength(instructionClass: number, instructionCode: number, p1Parameter: number, p2Parameter: number, data: NSData, expectedResponseLength: number): this; } interface NFCISO7816Tag extends NFCNDEFTag, NFCTag { applicationData: NSData; historicalBytes: NSData; identifier: NSData; initialSelectedAID: string; proprietaryApplicationDataCoding: boolean; sendCommandAPDUCompletionHandler(apdu: NFCISO7816APDU, completionHandler: (p1: NSData, p2: number, p3: number, p4: NSError) => void): void; } declare var NFCISO7816Tag: { prototype: NFCISO7816Tag; }; declare const enum NFCMiFareFamily { Unknown = 1, Ultralight = 2, Plus = 3, DESFire = 4 } interface NFCMiFareTag extends NFCNDEFTag, NFCTag { historicalBytes: NSData; identifier: NSData; mifareFamily: NFCMiFareFamily; sendMiFareCommandCompletionHandler(command: NSData, completionHandler: (p1: NSData, p2: NSError) => void): void; sendMiFareISO7816CommandCompletionHandler(apdu: NFCISO7816APDU, completionHandler: (p1: NSData, p2: number, p3: number, p4: NSError) => void): void; } declare var NFCMiFareTag: { prototype: NFCMiFareTag; }; declare class NFCNDEFMessage extends NSObject implements NSSecureCoding { static alloc(): NFCNDEFMessage; // inherited from NSObject static ndefMessageWithData(data: NSData): NFCNDEFMessage; static new(): NFCNDEFMessage; // inherited from NSObject readonly length: number; records: NSArray<NFCNDEFPayload>; static readonly supportsSecureCoding: boolean; // inherited from NSSecureCoding constructor(o: { coder: NSCoder; }); // inherited from NSCoding constructor(o: { NDEFRecords: NSArray<NFCNDEFPayload> | NFCNDEFPayload[]; }); encodeWithCoder(coder: NSCoder): void; initWithCoder(coder: NSCoder): this; initWithNDEFRecords(records: NSArray<NFCNDEFPayload> | NFCNDEFPayload[]): this; } declare class NFCNDEFPayload extends NSObject implements NSSecureCoding { static alloc(): NFCNDEFPayload; // inherited from NSObject static new(): NFCNDEFPayload; // inherited from NSObject static wellKnowTypeTextPayloadWithStringLocale(text: string, locale: NSLocale): NFCNDEFPayload; static wellKnownTypeTextPayloadWithStringLocale(text: string, locale: NSLocale): NFCNDEFPayload; static wellKnownTypeURIPayloadWithString(uri: string): NFCNDEFPayload; static wellKnownTypeURIPayloadWithURL(url: NSURL): NFCNDEFPayload; identifier: NSData; payload: NSData; type: NSData; typeNameFormat: NFCTypeNameFormat; static readonly supportsSecureCoding: boolean; // inherited from NSSecureCoding constructor(o: { coder: NSCoder; }); // inherited from NSCoding constructor(o: { format: NFCTypeNameFormat; type: NSData; identifier: NSData; payload: NSData; }); constructor(o: { format: NFCTypeNameFormat; type: NSData; identifier: NSData; payload: NSData; chunkSize: number; }); encodeWithCoder(coder: NSCoder): void; initWithCoder(coder: NSCoder): this; initWithFormatTypeIdentifierPayload(format: NFCTypeNameFormat, type: NSData, identifier: NSData, payload: NSData): this; initWithFormatTypeIdentifierPayloadChunkSize(format: NFCTypeNameFormat, type: NSData, identifier: NSData, payload: NSData, chunkSize: number): this; wellKnownTypeTextPayloadWithLocale(locale: interop.Pointer | interop.Reference<NSLocale>): string; wellKnownTypeURIPayload(): NSURL; } declare class NFCNDEFReaderSession extends NFCReaderSession { static alloc(): NFCNDEFReaderSession; // inherited from NSObject static new(): NFCNDEFReaderSession; // inherited from NSObject constructor(o: { delegate: NFCNDEFReaderSessionDelegate; queue: NSObject; invalidateAfterFirstRead: boolean; }); connectToTagCompletionHandler(tag: NFCNDEFTag, completionHandler: (p1: NSError) => void): void; initWithDelegateQueueInvalidateAfterFirstRead(delegate: NFCNDEFReaderSessionDelegate, queue: NSObject, invalidateAfterFirstRead: boolean): this; restartPolling(): void; } interface NFCNDEFReaderSessionDelegate extends NSObjectProtocol { readerSessionDidBecomeActive?(session: NFCNDEFReaderSession): void; readerSessionDidDetectNDEFs(session: NFCNDEFReaderSession, messages: NSArray<NFCNDEFMessage> | NFCNDEFMessage[]): void; readerSessionDidDetectTags?(session: NFCNDEFReaderSession, tags: NSArray<NFCNDEFTag> | NFCNDEFTag[]): void; readerSessionDidInvalidateWithError(session: NFCNDEFReaderSession, error: NSError): void; } declare var NFCNDEFReaderSessionDelegate: { prototype: NFCNDEFReaderSessionDelegate; }; declare const enum NFCNDEFStatus { NotSupported = 1, ReadWrite = 2, ReadOnly = 3 } interface NFCNDEFTag extends NSCopying, NSObjectProtocol, NSSecureCoding { available: boolean; queryNDEFStatusWithCompletionHandler(completionHandler: (p1: NFCNDEFStatus, p2: number, p3: NSError) => void): void; readNDEFWithCompletionHandler(completionHandler: (p1: NFCNDEFMessage, p2: NSError) => void): void; writeLockWithCompletionHandler(completionHandler: (p1: NSError) => void): void; writeNDEFCompletionHandler(ndefMessage: NFCNDEFMessage, completionHandler: (p1: NSError) => void): void; } declare var NFCNDEFTag: { prototype: NFCNDEFTag; }; declare const enum NFCPollingOption { ISO14443 = 1, ISO15693 = 2, ISO18092 = 4 } declare const enum NFCReaderError { ReaderErrorUnsupportedFeature = 1, ReaderErrorSecurityViolation = 2, ReaderErrorInvalidParameter = 3, ReaderErrorInvalidParameterLength = 4, ReaderErrorParameterOutOfBound = 5, ReaderErrorRadioDisabled = 6, ReaderTransceiveErrorTagConnectionLost = 100, ReaderTransceiveErrorRetryExceeded = 101, ReaderTransceiveErrorTagResponseError = 102, ReaderTransceiveErrorSessionInvalidated = 103, ReaderTransceiveErrorTagNotConnected = 104, ReaderTransceiveErrorPacketTooLong = 105, ReaderSessionInvalidationErrorUserCanceled = 200, ReaderSessionInvalidationErrorSessionTimeout = 201, ReaderSessionInvalidationErrorSessionTerminatedUnexpectedly = 202, ReaderSessionInvalidationErrorSystemIsBusy = 203, ReaderSessionInvalidationErrorFirstNDEFTagRead = 204, TagCommandConfigurationErrorInvalidParameters = 300, NdefReaderSessionErrorTagNotWritable = 400, NdefReaderSessionErrorTagUpdateFailure = 401, NdefReaderSessionErrorTagSizeTooSmall = 402, NdefReaderSessionErrorZeroLengthMessage = 403 } declare class NFCReaderSession extends NSObject implements NFCReaderSessionProtocol { static alloc(): NFCReaderSession; // inherited from NSObject static new(): NFCReaderSession; // inherited from NSObject readonly delegate: any; readonly sessionQueue: NSObject; static readonly readingAvailable: boolean; alertMessage: string; // inherited from NFCReaderSessionProtocol readonly debugDescription: string; // inherited from NSObjectProtocol readonly description: string; // inherited from NSObjectProtocol readonly hash: number; // inherited from NSObjectProtocol readonly isProxy: boolean; // inherited from NSObjectProtocol readonly ready: boolean; // inherited from NFCReaderSessionProtocol readonly superclass: typeof NSObject; // inherited from NSObjectProtocol readonly // inherited from NSObjectProtocol beginSession(): void; class(): typeof NSObject; conformsToProtocol(aProtocol: any /* Protocol */): boolean; invalidateSession(): void; invalidateSessionWithErrorMessage(errorMessage: string): void; isEqual(object: any): boolean; isKindOfClass(aClass: typeof NSObject): boolean; isMemberOfClass(aClass: typeof NSObject): boolean; performSelector(aSelector: string): any; performSelectorWithObject(aSelector: string, object: any): any; performSelectorWithObjectWithObject(aSelector: string, object1: any, object2: any): any; respondsToSelector(aSelector: string): boolean; retainCount(): number; self(): this; } interface NFCReaderSessionDelegate extends NSObjectProtocol { readerSessionDidBecomeActive(session: NFCReaderSession): void; readerSessionDidDetectTags?(session: NFCReaderSession, tags: NSArray<NFCTag> | NFCTag[]): void; readerSessionDidInvalidateWithError(session: NFCReaderSession, error: NSError): void; } declare var NFCReaderSessionDelegate: { prototype: NFCReaderSessionDelegate; }; interface NFCReaderSessionProtocol extends NSObjectProtocol { alertMessage: string; ready: boolean; beginSession(): void; invalidateSession(): void; invalidateSessionWithErrorMessage(errorMessage: string): void; } declare var NFCReaderSessionProtocol: { prototype: NFCReaderSessionProtocol; }; interface NFCTag extends NSCopying, NSObjectProtocol, NSSecureCoding { available: boolean; session: NFCReaderSessionProtocol; type: NFCTagType; asNFCFeliCaTag(): NFCFeliCaTag; asNFCISO15693Tag(): NFCISO15693Tag; asNFCISO7816Tag(): NFCISO7816Tag; asNFCMiFareTag(): NFCMiFareTag; } declare var NFCTag: { prototype: NFCTag; }; declare class NFCTagCommandConfiguration extends NSObject implements NSCopying { static alloc(): NFCTagCommandConfiguration; // inherited from NSObject static new(): NFCTagCommandConfiguration; // inherited from NSObject maximumRetries: number; retryInterval: number; copyWithZone(zone: interop.Pointer | interop.Reference<any>): any; } declare class NFCTagReaderSession extends NFCReaderSession { static alloc(): NFCTagReaderSession; // inherited from NSObject static new(): NFCTagReaderSession; // inherited from NSObject readonly connectedTag: NFCTag; constructor(o: { pollingOption: NFCPollingOption; delegate: NFCTagReaderSessionDelegate; queue: NSObject; }); connectToTagCompletionHandler(tag: NFCTag, completionHandler: (p1: NSError) => void): void; initWithPollingOptionDelegateQueue(pollingOption: NFCPollingOption, delegate: NFCTagReaderSessionDelegate, queue: NSObject): this; restartPolling(): void; } interface NFCTagReaderSessionDelegate extends NSObjectProtocol { tagReaderSessionDidBecomeActive?(session: NFCTagReaderSession): void; tagReaderSessionDidDetectTags?(session: NFCTagReaderSession, tags: NSArray<NFCTag> | NFCTag[]): void; tagReaderSessionDidInvalidateWithError(session: NFCTagReaderSession, error: NSError): void; } declare var NFCTagReaderSessionDelegate: { prototype: NFCTagReaderSessionDelegate; }; declare var NFCTagResponseUnexpectedLengthErrorKey: string; declare const enum NFCTagType { ISO15693 = 1, FeliCa = 2, ISO7816Compatible = 3, MiFare = 4 } declare const enum NFCTypeNameFormat { Empty = 0, NFCWellKnown = 1, Media = 2, AbsoluteURI = 3, NFCExternal = 4, Unknown = 5, Unchanged = 6 } declare class NFCVASCommandConfiguration extends NSObject implements NSCopying { static alloc(): NFCVASCommandConfiguration; // inherited from NSObject static new(): NFCVASCommandConfiguration; // inherited from NSObject mode: NFCVASMode; passTypeIdentifier: string; url: NSURL; constructor(o: { VASMode: NFCVASMode; passTypeIdentifier: string; url: NSURL; }); copyWithZone(zone: interop.Pointer | interop.Reference<any>): any; initWithVASModePassTypeIdentifierUrl(mode: NFCVASMode, passTypeIdentifier: string, url: NSURL): this; } declare const enum NFCVASErrorCode { NFCVASErrorCodeSuccess = 36864, NFCVASErrorCodeDataNotFound = 27267, NFCVASErrorCodeDataNotActivated = 25223, NFCVASErrorCodeWrongParameters = 27392, NFCVASErrorCodeWrongLCField = 26368, NFCVASErrorCodeUserIntervention = 27012, NFCVASErrorCodeIncorrectData = 27264, NFCVASErrorCodeUnsupportedApplicationVersion = 25408, VASErrorCodeSuccess = 36864, VASErrorCodeDataNotFound = 27267, VASErrorCodeDataNotActivated = 25223, VASErrorCodeWrongParameters = 27392, VASErrorCodeWrongLCField = 26368, VASErrorCodeUserIntervention = 27012, VASErrorCodeIncorrectData = 27264, VASErrorCodeUnsupportedApplicationVersion = 25408 } declare const enum NFCVASMode { NFCVASModeURLOnly = 0, NFCVASModeNormal = 1, VASModeURLOnly = 0, VASModeNormal = 1 } declare class NFCVASReaderSession extends NFCReaderSession { static alloc(): NFCVASReaderSession; // inherited from NSObject static new(): NFCVASReaderSession; // inherited from NSObject constructor(o: { VASCommandConfigurations: NSArray<NFCVASCommandConfiguration> | NFCVASCommandConfiguration[]; delegate: NFCVASReaderSessionDelegate; queue: NSObject; }); initWithVASCommandConfigurationsDelegateQueue(commandConfigurations: NSArray<NFCVASCommandConfiguration> | NFCVASCommandConfiguration[], delegate: NFCVASReaderSessionDelegate, queue: NSObject): this; } interface NFCVASReaderSessionDelegate extends NSObjectProtocol { readerSessionDidBecomeActive?(session: NFCVASReaderSession): void; readerSessionDidInvalidateWithError(session: NFCVASReaderSession, error: NSError): void; readerSessionDidReceiveVASResponses(session: NFCVASReaderSession, responses: NSArray<NFCVASResponse> | NFCVASResponse[]): void; } declare var NFCVASReaderSessionDelegate: { prototype: NFCVASReaderSessionDelegate; }; declare class NFCVASResponse extends NSObject implements NSCopying { static alloc(): NFCVASResponse; // inherited from NSObject static new(): NFCVASResponse; // inherited from NSObject readonly mobileToken: NSData; readonly status: NFCVASErrorCode; readonly vasData: NSData; copyWithZone(zone: interop.Pointer | interop.Reference<any>): any; }
the_stack
import { Client, Crypto, Model, Trust } from "@core/types"; import { verifyJson, encryptJson, decryptJson, signJson, verifyPublicKeySignature, } from "@core/lib/crypto/proxy"; import { dispatch } from "../../handler"; import * as R from "ramda"; import { getActiveGeneratedEnvkeysByKeyableParentId, getKeyablesByPubkeyId, graphTypes, } from "@core/lib/graph"; import { getAuth, getPubkeyHash } from "@core/lib/client"; import { log } from "@core/lib/utils/logger"; export const verifyCurrentUser = async ( initialState: Client.State, context: Client.Context ) => { let state = initialState; const auth = getAuth(state, context.accountIdOrCliKey); if (!auth || !auth.privkey || !context.accountIdOrCliKey) { throw new Error("Action requires authentication and decrypted privkey"); } let pubkey: Crypto.Pubkey | undefined; let keyableId: string | undefined; const user = state.graph[auth.userId] as | Model.CliUser | Model.OrgUser | undefined; if (!user) { throw new Error("authenticated user or cli user not found in graph"); } if (user.type == "cliUser") { pubkey = user.pubkey; keyableId = user.id; } else if (auth.type == "clientUserAuth") { const currentOrgUserDevice = state.graph[auth.deviceId] as | Model.OrgUserDevice | undefined; if (!currentOrgUserDevice) { throw new Error("currentOrgUserDevice not found in graph"); } pubkey = currentOrgUserDevice.pubkey; keyableId = currentOrgUserDevice.id; } if (!pubkey || !keyableId) { throw new Error("pubkey or keyableId undefined"); } const [verifyRes, _] = await Promise.all([ verifySignedTrustedRootPubkey(state, pubkey, context), verifyKeypair(pubkey, auth.privkey), ]); if (!verifyRes.success) { return verifyRes; } const replacementsRes = await processRootPubkeyReplacementsIfNeeded( verifyRes.state, context, true ); if (replacementsRes && !replacementsRes.success) { throw new Error("couldn't process root pubkey replacements"); } const res = await verifyOrgKeyable( (replacementsRes ?? verifyRes).state, keyableId, context ); if (!res) { throw new Error("current user pubkey couldn't be verified"); } return { success: true, state: res }; }, verifyKeypair = async (pubkey: Crypto.Pubkey, privkey: Crypto.Privkey) => { const data = { message: "test" }, [encrypted, signed] = await Promise.all([ encryptJson({ data, pubkey, privkey, }), signJson({ data, privkey }), ]), [decrypted, verified] = await Promise.all([ decryptJson({ encrypted, privkey, pubkey, }), verifyJson({ signed, pubkey }).catch((err) => undefined), ]); if (!verified || !R.equals(data, decrypted) || !R.equals(data, verified)) { throw new Error("keypair verification failed"); } }, verifySignedTrustedRootPubkey = async ( state: Client.State, pubkey: Crypto.Pubkey, context: Client.Context ) => { if (state.trustedRoot) { return { success: true, state }; } if (!state.signedTrustedRoot) { throw new Error("signedTrustedRoot undefined"); } const verified = (await verifyJson({ signed: state.signedTrustedRoot.data, pubkey: pubkey, })) as Trust.RootTrustChain; return dispatch( { type: Client.ActionType.VERIFIED_SIGNED_TRUSTED_ROOT_PUBKEY, payload: verified, }, context ); }, getTrustAttributes = (state: Client.State, keyableId: string) => { if (!keyableId) { throw new Error("keyableId undefined"); } const keyable = state.graph[keyableId] as | Model.KeyableParent | Model.CliUser | Model.Invite | Model.DeviceGrant | Model.OrgUserDevice | Model.RecoveryKey | undefined; if (!keyable) { throw new Error("Keyable not found"); } let pubkey: Crypto.Pubkey, invitePubkey: Crypto.Pubkey | undefined, signedById: string | undefined, isRoot = false, keyableType: Trust.TrustedPubkey[0]; if (keyable.type == "localKey" || keyable.type == "server") { const generatedEnvkey = getActiveGeneratedEnvkeysByKeyableParentId( state.graph )[keyable.id]; if (!generatedEnvkey) { throw new Error("No envkey generated for keyableParent."); } keyableType = "generatedEnvkey"; pubkey = generatedEnvkey.pubkey; signedById = generatedEnvkey.signedById; } else { if (!keyable.pubkey) { throw new Error("Keyable pubkey not generated"); } pubkey = keyable.pubkey; switch (keyable.type) { case "orgUserDevice": keyableType = "orgUserDevice"; if (keyable.approvedByType == "creator" || keyable.isRoot) { isRoot = true; } else { let intermediateKeyableId: string; switch (keyable.approvedByType) { case "invite": intermediateKeyableId = keyable.inviteId; break; case "deviceGrant": intermediateKeyableId = keyable.deviceGrantId; break; case "recoveryKey": intermediateKeyableId = keyable.recoveryKeyId; break; } const intermediateKeyable = state.graph[intermediateKeyableId] as | Model.Invite | Model.DeviceGrant | Model.RecoveryKey; signedById = intermediateKeyable.signedById; invitePubkey = intermediateKeyable.pubkey; } break; case "cliUser": case "invite": case "deviceGrant": case "recoveryKey": keyableType = keyable.type; signedById = keyable.signedById; break; } } let signedByPubkeyId: string | undefined; if (signedById) { const { pubkey: signedByPubkey } = state.graph[signedById] as | Model.OrgUserDevice | Model.CliUser; signedByPubkeyId = getPubkeyHash(signedByPubkey); } return { pubkeyId: getPubkeyHash(pubkey), keyableType, pubkey, invitePubkey, signedById, signedByPubkeyId, isRoot, }; }, getAlreadyTrusted = ( state: Client.State, pubkeyId: string, keyableType: Trust.TrustedPubkey[0], pubkey: Crypto.Pubkey, invitePubkey: Crypto.Pubkey | undefined, signedByPubkeyId: string | undefined, isRoot: boolean ) => { let alreadyTrusted: Trust.TrustedPubkey; if (isRoot === true) { alreadyTrusted = state.trustedRoot![pubkeyId]; } else { alreadyTrusted = state.trustedSessionPubkeys[pubkeyId]; } if (alreadyTrusted) { const shouldEq = [ isRoot ? "root" : keyableType, pubkey, invitePubkey, signedByPubkeyId, ].filter(Boolean); if (!R.equals(shouldEq, alreadyTrusted)) { return false; } return true; } return false; }, verifyOrgKeyable = async ( initialState: Client.State, initialKeyableId: string, context: Client.Context ): Promise<false | Client.State> => { let state = initialState; if (!state.trustedRoot || R.isEmpty(state.trustedRoot)) { throw new Error("Verified trustedRoot required."); } const { pubkeyId: initialPubkeyId, keyableType: initialKeyableType, pubkey: initialPubkey, invitePubkey: initialInvitePubkey, signedById: initialSignedById, signedByPubkeyId: initialSignedByPubkeyId, isRoot: initialIsRoot, } = getTrustAttributes(state, initialKeyableId); // Check if initial keyable is already trusted if ( getAlreadyTrusted( state, initialPubkeyId, initialKeyableType, initialPubkey, initialInvitePubkey, initialSignedByPubkeyId, initialIsRoot ) ) { return state; } // If keyable is not yet trusted, attempt to verify back to a signer who *is* trusted let verifyingChain = [ [ initialPubkeyId, [ initialKeyableType, initialPubkey, initialInvitePubkey, initialSignedByPubkeyId, ].filter(Boolean), ], ] as [string, Trust.TrustedSessionPubkey][]; let currentKeyableId = initialSignedById!; while (true) { const { pubkeyId, keyableType, signedById, signedByPubkeyId, pubkey, invitePubkey, isRoot, } = getTrustAttributes(state, currentKeyableId); if (!isRoot) { const { pubkey: signerPubkey } = getTrustAttributes(state, signedById!); if (invitePubkey) { // ensure pubkey is signed by invite pubkey, and invite pubkey is signed by signer // verification throws error if invalid await Promise.all([ verifyPublicKeySignature({ signedPubkey: pubkey, signerPubkey: invitePubkey, }), verifyPublicKeySignature({ signedPubkey: invitePubkey, signerPubkey, }), ]); } else { // ensure pubkey is signed by signer // verification throws error if invalid await verifyPublicKeySignature({ signedPubkey: pubkey, signerPubkey, }); } } if ( getAlreadyTrusted( state, pubkeyId, keyableType, pubkey, invitePubkey, signedByPubkeyId, isRoot ) ) { for (let [verifiedPubkeyId, verifiedTrustedPubkey] of verifyingChain) { const res = await dispatch( { type: Client.ActionType.ADD_TRUSTED_SESSION_PUBKEY, payload: { id: verifiedPubkeyId, trusted: verifiedTrustedPubkey as Trust.TrustedSessionPubkey, }, }, context ); if (res.success) { state = res.state; } } return state; } else { if (!signedById || !signedByPubkeyId || !invitePubkey) { throw new Error("Keyable could not be verified."); } verifyingChain.push([ pubkeyId, [keyableType, pubkey, invitePubkey, signedByPubkeyId].filter( Boolean ) as Trust.TrustedSessionPubkey, ]); currentKeyableId = signedById; } } throw new Error("Keyable could not be verified."); }, processRevocationRequestsIfNeeded = async ( state: Client.State, context: Client.Context ) => { // this function is intended to be called asynchronously by the handler after graph updates, not awaited (doing so would block state updates/rendering for no good reason) let { pubkeyRevocationRequests } = graphTypes(state.graph); if ( !state.isProcessingRevocationRequests && pubkeyRevocationRequests.length > 0 ) { return dispatch( { type: Client.ActionType.PROCESS_REVOCATION_REQUESTS, }, context ); } }, processRootPubkeyReplacementsIfNeeded = async ( state: Client.State, context: Client.Context, commitTrusted?: true ) => { const { rootPubkeyReplacements } = graphTypes(state.graph); if ( !state.isProcessingRootPubkeyReplacements && rootPubkeyReplacements.length > 0 ) { return dispatch( { type: Client.ActionType.PROCESS_ROOT_PUBKEY_REPLACEMENTS, payload: { commitTrusted }, }, context ); } }, clearRevokedOrOutdatedSessionPubkeys = ( state: Client.State, context: Client.Context ) => { if (R.isEmpty(state.trustedSessionPubkeys)) { return; } const keyablesByPubkeyId = getKeyablesByPubkeyId(state.graph); for (let trustedPubkeyId in state.trustedSessionPubkeys) { let shouldClear = false; if (keyablesByPubkeyId[trustedPubkeyId]) { // apart from clearing keys that have been revoked and are no longer in the graph, we should also clear any whose trust attributes have been updated const keyableId = keyablesByPubkeyId[trustedPubkeyId].id; const { pubkeyId, keyableType, signedByPubkeyId, pubkey, invitePubkey, isRoot, } = getTrustAttributes(state, keyableId); shouldClear = !getAlreadyTrusted( state, pubkeyId, keyableType, pubkey, invitePubkey, signedByPubkeyId, isRoot ); } else { shouldClear = true; } if (shouldClear) { dispatch( { type: Client.ActionType.CLEAR_TRUSTED_SESSION_PUBKEY, payload: { id: trustedPubkeyId }, }, context ); } } }, verifyRootPubkeyReplacement = async ( state: Client.State, replacement: Model.RootPubkeyReplacement ): Promise<true> => { if (!state.trustedRoot) { throw new Error("trustedRoot undefined"); } const replacingTrustChain = (await verifyJson({ signed: replacement.signedReplacingTrustChain.data, pubkey: replacement.replacingPubkey, })) as Trust.UserTrustChain; return verifyPubkeyWithTrustChain( replacement.replacingPubkey, state.trustedRoot, replacingTrustChain ); }, verifyPubkeyWithTrustChain = async ( verifyPubkey: Crypto.Pubkey, trustedRoot: Trust.RootTrustChain, trustChain: Trust.UserTrustChain ): Promise<true> => { const checked: { [id: string]: true } = {}; let currentPubkey = verifyPubkey; let currentPubkeyId = getPubkeyHash(currentPubkey); while (true) { if (checked[currentPubkeyId]) { throw new Error( "Circular trust chain. Couldn't find trusted root pubkey." ); } if (trustedRoot[currentPubkeyId]) { return true; } const trusted = trustChain[currentPubkeyId]; if (!trusted) { throw new Error("Trusted pubkey chain broken."); } let trustedSignerId: string; let invitePubkey: Crypto.Pubkey | undefined; if (trusted[0] == "orgUserDevice") { invitePubkey = trusted[2]; trustedSignerId = trusted[3]; } else { trustedSignerId = trusted[2]; } const trustedSigner = (trustChain[trustedSignerId] ?? trustedRoot[trustedSignerId]) as | Trust.TrustedUserPubkey | Trust.TrustedRootPubkey; if (!trustedSigner) { throw new Error("Trusted pubkey chain broken."); } const signerPubkey = trustedSigner[1]; if (invitePubkey) { // ensure pubkey is signed by invite pubkey, and invite pubkey is signed by signer // verification throws error if invalid await Promise.all([ verifyPublicKeySignature({ signedPubkey: currentPubkey, signerPubkey: invitePubkey, }), verifyPublicKeySignature({ signedPubkey: invitePubkey, signerPubkey, }), ]); } else { // ensure pubkey is signed by signer // verification throws error if invalid await verifyPublicKeySignature({ signedPubkey: currentPubkey, signerPubkey, }); } if (trustedSigner[0] == "root") { return true; } else { currentPubkey = signerPubkey; currentPubkeyId = trustedSignerId; } } throw new Error("Unreachable"); };
the_stack
import Web3 from 'web3'; import { TransactionConfig } from 'web3-eth'; import { DelegateTransactionUnsigned, TransferTransactionUnsigned, UndelegateTransactionUnsigned, RedelegateTransactionUnsigned, VoteTransactionUnsigned, NFTTransferUnsigned, WithdrawStakingRewardUnsigned, NFTDenomIssueUnsigned, NFTMintUnsigned, } from './signers/TransactionSupported'; import { BroadCastResult } from '../models/Transaction'; import { getBaseScaledAmount } from '../utils/NumberUtils'; import { UserAsset, UserAssetType } from '../models/UserAsset'; import { DEFAULT_CLIENT_MEMO } from '../config/StaticConfig'; import { TransferRequest, DelegationRequest, UndelegationRequest, RedelegationRequest, VoteRequest, NFTTransferRequest, WithdrawStakingRewardRequest, BridgeTransferRequest, NFTDenomIssueRequest, NFTMintRequest, } from './TransactionRequestModels'; import { StorageService } from '../storage/StorageService'; import { CronosClient } from './cronos/CronosClient'; import { TransactionPrepareService } from './TransactionPrepareService'; import { evmTransactionSigner } from './signers/EvmTransactionSigner'; import { LEDGER_WALLET_TYPE, createLedgerDevice } from './LedgerService'; import { TransactionHistoryService } from './TransactionHistoryService'; import { getCronosAsset, sleep } from '../utils/utils'; import { BridgeService } from './bridge/BridgeService'; import { walletService } from './WalletService'; export class TransactionSenderService { public readonly storageService: StorageService; public readonly transactionPrepareService: TransactionPrepareService; public readonly txHistoryManager: TransactionHistoryService; constructor( storageService: StorageService, transactionPrepareService: TransactionPrepareService, txHistoryManager: TransactionHistoryService, ) { this.storageService = storageService; this.transactionPrepareService = transactionPrepareService; this.txHistoryManager = txHistoryManager; } public async sendTransfer(transferRequest: TransferRequest): Promise<BroadCastResult> { // eslint-disable-next-line no-console console.log('TRANSFER_ASSET', transferRequest.asset); const currentAsset = transferRequest.asset; const scaledBaseAmount = getBaseScaledAmount(transferRequest.amount, currentAsset); const currentSession = await this.storageService.retrieveCurrentSession(); const fromAddress = currentSession.wallet.address; const walletAddressIndex = currentSession.wallet.addressIndex; if (!transferRequest.memo && !currentSession.wallet.config.disableDefaultClientMemo) { transferRequest.memo = DEFAULT_CLIENT_MEMO; } switch (currentAsset.assetType) { case UserAssetType.EVM: try { if (!currentAsset.address || !currentAsset.config?.nodeUrl) { throw TypeError(`Missing asset config: ${currentAsset.config}`); } const cronosClient = new CronosClient( currentAsset.config?.nodeUrl, currentAsset.config?.indexingUrl, ); const transfer: TransferTransactionUnsigned = { fromAddress, toAddress: transferRequest.toAddress, amount: String(scaledBaseAmount), memo: transferRequest.memo, accountNumber: 0, accountSequence: 0, asset: currentAsset, }; const web3 = new Web3(''); const txConfig: TransactionConfig = { from: currentAsset.address, to: transferRequest.toAddress, value: web3.utils.toWei(transferRequest.amount, 'ether'), }; const prepareTxInfo = await this.transactionPrepareService.prepareEVMTransaction( currentAsset, txConfig, ); transfer.nonce = prepareTxInfo.nonce; transfer.gasPrice = prepareTxInfo.loadedGasPrice; transfer.gasLimit = prepareTxInfo.gasLimit; const isMemoProvided = transferRequest.memo && transferRequest.memo.length > 0; // If transaction is provided with memo, add a little bit more gas to it to be accepted. 10% more transfer.gasLimit = isMemoProvided ? Number(transfer.gasLimit) + Number(transfer.gasLimit) * (10 / 100) : transfer.gasLimit; let signedTx = ''; if (currentSession.wallet.walletType === LEDGER_WALLET_TYPE) { const device = createLedgerDevice(); const gasLimitTx = web3.utils.toBN(transfer.gasLimit!); const gasPriceTx = web3.utils.toBN(transfer.gasPrice); signedTx = await device.signEthTx( walletAddressIndex, Number(transfer.asset?.config?.chainId), // chainid transfer.nonce, web3.utils.toHex(gasLimitTx) /* gas limit */, web3.utils.toHex(gasPriceTx) /* gas price */, transfer.toAddress, web3.utils.toHex(transfer.amount), `0x${Buffer.from(transfer.memo).toString('hex')}`, ); } else { signedTx = await evmTransactionSigner.signTransfer( transfer, transferRequest.decryptedPhrase, ); } const result = await cronosClient.broadcastRawTransactionHex(signedTx); return { transactionHash: result, message: '', code: 200, }; } catch (e) { // eslint-disable-next-line no-console console.log(`ERROR_TRANSFERRING - ${currentAsset.assetType}`, e); throw TypeError(e); } case UserAssetType.CRC_20_TOKEN: try { // all CRC20 tokens shares the same chainConfig based on CRONOS native asset CRO's config // we can't simply update all CRC20 tokens' config to CRONOS native asset CRO's config while update node config in settings // because we can't take control with the future asset received in future, so we have to change it here in the very end, a little bit hacky const allAssets = await walletService.retrieveWalletAssets( currentSession.wallet.identifier, ); const chainConfig = getCronosAsset(allAssets)?.config; // currentAsset's config is not changeable, use a new instance instead const transferAsset: UserAsset = { ...currentAsset, config: chainConfig, }; if (!transferAsset.address || !transferAsset.config || !transferAsset.contractAddress) { throw TypeError(`Missing asset config: ${transferAsset.config}`); } const cronosClient = new CronosClient( transferAsset.config?.nodeUrl, transferAsset.config?.indexingUrl, ); const transfer: TransferTransactionUnsigned = { fromAddress, toAddress: transferRequest.toAddress, amount: String(scaledBaseAmount), memo: transferRequest.memo, accountNumber: 0, accountSequence: 0, asset: transferAsset, }; const encodedABITokenTransfer = evmTransactionSigner.encodeTokenTransferABI( transferAsset.contractAddress, transfer, ); const web3 = new Web3(''); const txConfig: TransactionConfig = { from: transferAsset.address, to: transferAsset.contractAddress, value: 0, data: encodedABITokenTransfer, }; const prepareTxInfo = await this.transactionPrepareService.prepareEVMTransaction( transferAsset, txConfig, ); const staticTokenTransferGasLimit = 130_000; transfer.nonce = prepareTxInfo.nonce; transfer.gasPrice = prepareTxInfo.loadedGasPrice; transfer.gasLimit = staticTokenTransferGasLimit; // eslint-disable-next-line no-console console.log('TX_DATA', { gasLimit: transfer.gasLimit }); let signedTx = ''; if (currentSession.wallet.walletType === LEDGER_WALLET_TYPE) { const device = createLedgerDevice(); const gasLimitTx = web3.utils.toBN(transfer.gasLimit!); const gasPriceTx = web3.utils.toBN(transfer.gasPrice); signedTx = await device.signEthTx( walletAddressIndex, Number(transfer.asset?.config?.chainId), // chainid transfer.nonce, web3.utils.toHex(gasLimitTx) /* gas limit */, web3.utils.toHex(gasPriceTx) /* gas price */, transferAsset.contractAddress, '0x0', encodedABITokenTransfer, ); } else { signedTx = await evmTransactionSigner.signTokenTransfer( transfer, transferRequest.decryptedPhrase, ); } const result = await cronosClient.broadcastRawTransactionHex(signedTx); return { transactionHash: result, message: '', code: 200, }; } catch (e) { // eslint-disable-next-line no-console console.log( `ERROR_TRANSFERRING_TOKEN - ${currentAsset.assetType} ${currentAsset.symbol}`, e, ); throw TypeError(e); } case UserAssetType.TENDERMINT: case UserAssetType.IBC: case undefined: { const { nodeRpc, accountNumber, accountSequence, transactionSigner, ledgerTransactionSigner, } = await this.transactionPrepareService.prepareTransaction(); const transfer: TransferTransactionUnsigned = { fromAddress, toAddress: transferRequest.toAddress, amount: String(scaledBaseAmount), memo: transferRequest.memo, accountNumber, accountSequence, asset: currentAsset, }; let signedTxHex: string = ''; if (transferRequest.walletType === LEDGER_WALLET_TYPE) { signedTxHex = await ledgerTransactionSigner.signTransfer( transfer, transferRequest.decryptedPhrase, ); } else { signedTxHex = await transactionSigner.signTransfer( transfer, transferRequest.decryptedPhrase, ); } const broadCastResult = await nodeRpc.broadcastTransaction(signedTxHex); await Promise.all([ await this.txHistoryManager.fetchAndUpdateBalances(currentSession), await this.txHistoryManager.fetchAndSaveTransfers(currentSession), ]); return broadCastResult; } default: return {}; } } public async sendDelegateTransaction( delegationRequest: DelegationRequest, ): Promise<BroadCastResult> { const { nodeRpc, accountNumber, accountSequence, currentSession, transactionSigner, ledgerTransactionSigner, } = await this.transactionPrepareService.prepareTransaction(); const delegationAmountScaled = getBaseScaledAmount( delegationRequest.amount, delegationRequest.asset, ); let { memo } = delegationRequest; if (!memo && !currentSession.wallet.config.disableDefaultClientMemo) { memo = DEFAULT_CLIENT_MEMO; } const delegateTransaction: DelegateTransactionUnsigned = { delegatorAddress: currentSession.wallet.address, validatorAddress: delegationRequest.validatorAddress, amount: String(delegationAmountScaled), memo, accountNumber, accountSequence, }; let signedTxHex: string; if (delegationRequest.walletType === LEDGER_WALLET_TYPE) { signedTxHex = await ledgerTransactionSigner.signDelegateTx( delegateTransaction, delegationRequest.decryptedPhrase, ); } else { signedTxHex = await transactionSigner.signDelegateTx( delegateTransaction, delegationRequest.decryptedPhrase, ); } const broadCastResult = await nodeRpc.broadcastTransaction(signedTxHex); await Promise.all([ await this.txHistoryManager.fetchAndUpdateBalances(currentSession), await this.txHistoryManager.fetchAndSaveDelegations(nodeRpc, currentSession), ]); return broadCastResult; } public async sendUnDelegateTransaction( undelegationRequest: UndelegationRequest, ): Promise<BroadCastResult> { const { nodeRpc, accountNumber, accountSequence, currentSession, transactionSigner, ledgerTransactionSigner, } = await this.transactionPrepareService.prepareTransaction(); const undelegationAmountScaled = getBaseScaledAmount( undelegationRequest.amount, undelegationRequest.asset, ); let { memo } = undelegationRequest; if (!memo && !currentSession.wallet.config.disableDefaultClientMemo) { memo = DEFAULT_CLIENT_MEMO; } const undelegateTransaction: UndelegateTransactionUnsigned = { delegatorAddress: currentSession.wallet.address, validatorAddress: undelegationRequest.validatorAddress, amount: undelegationAmountScaled, memo, accountNumber, accountSequence, }; let signedTxHex: string; if (undelegationRequest.walletType === LEDGER_WALLET_TYPE) { signedTxHex = await ledgerTransactionSigner.signUndelegateTx( undelegateTransaction, undelegationRequest.decryptedPhrase, ); } else { signedTxHex = await transactionSigner.signUndelegateTx( undelegateTransaction, undelegationRequest.decryptedPhrase, ); } const broadCastResult = await nodeRpc.broadcastTransaction(signedTxHex); await Promise.all([ await this.txHistoryManager.fetchAndUpdateBalances(currentSession), await this.txHistoryManager.fetchAndSaveDelegations(nodeRpc, currentSession), await this.txHistoryManager.fetchAndSaveUnbondingDelegations(nodeRpc, currentSession), ]); return broadCastResult; } public async sendReDelegateTransaction( redelegationRequest: RedelegationRequest, ): Promise<BroadCastResult> { const { nodeRpc, accountNumber, accountSequence, currentSession, transactionSigner, ledgerTransactionSigner, } = await this.transactionPrepareService.prepareTransaction(); const redelegationAmountScaled = getBaseScaledAmount( redelegationRequest.amount, redelegationRequest.asset, ); let { memo } = redelegationRequest; if (!memo && !currentSession.wallet.config.disableDefaultClientMemo) { memo = DEFAULT_CLIENT_MEMO; } const redelegateTransactionUnsigned: RedelegateTransactionUnsigned = { delegatorAddress: currentSession.wallet.address, sourceValidatorAddress: redelegationRequest.validatorSourceAddress, destinationValidatorAddress: redelegationRequest.validatorDestinationAddress, amount: redelegationAmountScaled, memo, accountNumber, accountSequence, }; let signedTxHex: string; if (redelegationRequest.walletType === LEDGER_WALLET_TYPE) { signedTxHex = await ledgerTransactionSigner.signRedelegateTx( redelegateTransactionUnsigned, redelegationRequest.decryptedPhrase, ); } else { signedTxHex = await transactionSigner.signRedelegateTx( redelegateTransactionUnsigned, redelegationRequest.decryptedPhrase, ); } const broadCastResult = await nodeRpc.broadcastTransaction(signedTxHex); await Promise.all([ await this.txHistoryManager.fetchAndUpdateBalances(currentSession), await this.txHistoryManager.fetchAndSaveDelegations(nodeRpc, currentSession), ]); return broadCastResult; } public async sendVote(voteRequest: VoteRequest): Promise<BroadCastResult> { const { nodeRpc, accountNumber, accountSequence, currentSession, transactionSigner, ledgerTransactionSigner, } = await this.transactionPrepareService.prepareTransaction(); const voteTransactionUnsigned: VoteTransactionUnsigned = { option: voteRequest.voteOption, voter: currentSession.wallet.address, proposalID: voteRequest.proposalID, memo: voteRequest.memo, accountNumber, accountSequence, }; let signedTxHex: string = ''; if (voteRequest.walletType === LEDGER_WALLET_TYPE) { signedTxHex = await ledgerTransactionSigner.signVoteTransaction( voteTransactionUnsigned, voteRequest.decryptedPhrase, ); } else { signedTxHex = await transactionSigner.signVoteTransaction( voteTransactionUnsigned, voteRequest.decryptedPhrase, ); } const broadCastResult = await nodeRpc.broadcastTransaction(signedTxHex); await this.txHistoryManager.fetchAndSaveProposals(currentSession); return broadCastResult; } public async sendNFT(nftTransferRequest: NFTTransferRequest): Promise<BroadCastResult> { const { nodeRpc, accountNumber, accountSequence, currentSession, transactionSigner, ledgerTransactionSigner, } = await this.transactionPrepareService.prepareTransaction(); const memo = !nftTransferRequest.memo ? DEFAULT_CLIENT_MEMO : nftTransferRequest.memo; const nftTransferUnsigned: NFTTransferUnsigned = { tokenId: nftTransferRequest.tokenId, denomId: nftTransferRequest.denomId, sender: nftTransferRequest.sender, recipient: nftTransferRequest.recipient, memo, accountNumber, accountSequence, }; let signedTxHex: string = ''; if (nftTransferRequest.walletType === LEDGER_WALLET_TYPE) { signedTxHex = await ledgerTransactionSigner.signNFTTransfer( nftTransferUnsigned, nftTransferRequest.decryptedPhrase, ); } else { signedTxHex = await transactionSigner.signNFTTransfer( nftTransferUnsigned, nftTransferRequest.decryptedPhrase, ); } const broadCastResult = await nodeRpc.broadcastTransaction(signedTxHex); // It takes a few seconds for the indexing service to sync latest NFT state await sleep(7_000); await Promise.all([ this.txHistoryManager.fetchAndSaveNFTs(currentSession), this.txHistoryManager.fetchAndSaveNFTAccountTxs(currentSession), ]); return broadCastResult; } public async sendStakingRewardWithdrawalTx( rewardWithdrawRequest: WithdrawStakingRewardRequest, ): Promise<BroadCastResult> { const { nodeRpc, accountNumber, accountSequence, currentSession, transactionSigner, ledgerTransactionSigner, } = await this.transactionPrepareService.prepareTransaction(); const withdrawStakingReward: WithdrawStakingRewardUnsigned = { delegatorAddress: currentSession.wallet.address, validatorAddress: rewardWithdrawRequest.validatorAddress, memo: DEFAULT_CLIENT_MEMO, accountNumber, accountSequence, }; let signedTxHex: string; if (rewardWithdrawRequest.walletType === LEDGER_WALLET_TYPE) { signedTxHex = await ledgerTransactionSigner.signWithdrawStakingRewardTx( withdrawStakingReward, rewardWithdrawRequest.decryptedPhrase, ); } else { signedTxHex = await transactionSigner.signWithdrawStakingRewardTx( withdrawStakingReward, rewardWithdrawRequest.decryptedPhrase, ); } const broadCastResult = await nodeRpc.broadcastTransaction(signedTxHex); await Promise.all([ await this.txHistoryManager.fetchAndSaveRewards(nodeRpc, currentSession), await this.txHistoryManager.fetchAndUpdateBalances(currentSession), ]); return broadCastResult; } public async sendBridgeTransaction(bridgeTransferRequest: BridgeTransferRequest) { const currentSession = await this.storageService.retrieveCurrentSession(); const bridgeService = new BridgeService(this.storageService); const bridgeTransactionResult = await bridgeService.handleBridgeTransaction( bridgeTransferRequest, ); await Promise.all([ await this.txHistoryManager.fetchAndUpdateBalances(currentSession), await this.txHistoryManager.fetchAndSaveTransfers(currentSession), ]); return bridgeTransactionResult; } /* _______________________ NFT RELATED FUNCTIONS _________________________ */ public async sendMintNFT(nftMintRequest: NFTMintRequest): Promise<BroadCastResult> { const { nodeRpc, accountNumber, accountSequence, currentSession, transactionSigner, ledgerTransactionSigner, } = await this.transactionPrepareService.prepareTransaction(); const memo = !nftMintRequest.memo ? DEFAULT_CLIENT_MEMO : nftMintRequest.memo; const nftMintUnsigned: NFTMintUnsigned = { data: nftMintRequest.data, name: nftMintRequest.name, uri: nftMintRequest.uri, tokenId: nftMintRequest.tokenId, denomId: nftMintRequest.denomId, sender: nftMintRequest.sender, recipient: nftMintRequest.recipient, memo, accountNumber, accountSequence, }; let signedTxHex: string = ''; if (nftMintRequest.walletType === LEDGER_WALLET_TYPE) { signedTxHex = await ledgerTransactionSigner.signNFTMint( nftMintUnsigned, nftMintRequest.decryptedPhrase, ); } else { signedTxHex = await transactionSigner.signNFTMint( nftMintUnsigned, nftMintRequest.decryptedPhrase, ); } const broadCastResult = await nodeRpc.broadcastTransaction(signedTxHex); // It takes a few seconds for the indexing service to sync latest NFT state await sleep(5_000); await Promise.all([ this.txHistoryManager.fetchAndSaveNFTs(currentSession), this.txHistoryManager.fetchAndSaveNFTAccountTxs(currentSession), ]); return broadCastResult; } public async sendNFTDenomIssueTx( nftDenomIssueRequest: NFTDenomIssueRequest, ): Promise<BroadCastResult> { const { nodeRpc, accountNumber, accountSequence, currentSession, transactionSigner, ledgerTransactionSigner, } = await this.transactionPrepareService.prepareTransaction(); const memo = !nftDenomIssueRequest.memo ? DEFAULT_CLIENT_MEMO : nftDenomIssueRequest.memo; const nftDenomIssueUnsigned: NFTDenomIssueUnsigned = { ...nftDenomIssueRequest, memo, accountNumber, accountSequence, }; let signedTxHex: string = ''; if (nftDenomIssueRequest.walletType === LEDGER_WALLET_TYPE) { signedTxHex = await ledgerTransactionSigner.signNFTDenomIssue( nftDenomIssueUnsigned, nftDenomIssueRequest.decryptedPhrase, ); } else { signedTxHex = await transactionSigner.signNFTDenomIssue( nftDenomIssueUnsigned, nftDenomIssueRequest.decryptedPhrase, ); } const broadCastResult = await nodeRpc.broadcastTransaction(signedTxHex); // It takes a few seconds for the indexing service to sync latest NFT state await sleep(5_000); await Promise.all([ this.txHistoryManager.fetchAndSaveNFTs(currentSession), this.txHistoryManager.fetchAndSaveNFTAccountTxs(currentSession), ]); return broadCastResult; } }
the_stack
import {Paths} from 'chrome://personalization/trusted/personalization_router_element.js'; import {emptyState} from 'chrome://personalization/trusted/personalization_state.js'; import {WallpaperActionName} from 'chrome://personalization/trusted/wallpaper/wallpaper_actions.js'; import {mockTimeoutForTesting, WallpaperSelected} from 'chrome://personalization/trusted/wallpaper/wallpaper_selected_element.js'; import {assertDeepEquals, assertEquals, assertFalse, assertNotEquals, assertNotReached, assertTrue} from 'chrome://webui-test/chai_assert.js'; import {flushTasks, waitAfterNextRender} from 'chrome://webui-test/test_util.js'; import {baseSetup, initElement} from './personalization_app_test_utils.js'; import {TestPersonalizationStore} from './test_personalization_store.js'; import {TestWallpaperProvider} from './test_wallpaper_interface_provider.js'; export function WallpaperSelectedTest() { let wallpaperSelectedElement: WallpaperSelected|null; let wallpaperProvider: TestWallpaperProvider; let personalizationStore: TestPersonalizationStore; setup(() => { const mocks = baseSetup(); wallpaperProvider = mocks.wallpaperProvider; personalizationStore = mocks.personalizationStore; }); teardown(async () => { if (wallpaperSelectedElement) { wallpaperSelectedElement.remove(); } wallpaperSelectedElement = null; await flushTasks(); }); test( 'shows loading placeholder when there are in-flight requests', async () => { personalizationStore.data.wallpaper.loading = { ...personalizationStore.data.wallpaper.loading, selected: 1, setImage: 0, }; wallpaperSelectedElement = initElement(WallpaperSelected); assertEquals( null, wallpaperSelectedElement.shadowRoot!.querySelector('img')); assertEquals( null, wallpaperSelectedElement.shadowRoot!.getElementById( 'textContainer')); const placeholder = wallpaperSelectedElement.shadowRoot!.getElementById( 'imagePlaceholder'); assertTrue(!!placeholder); // Loading placeholder should be hidden. personalizationStore.data.wallpaper.loading = { ...personalizationStore.data.wallpaper.loading, selected: 0, setImage: 0, }; personalizationStore.data.wallpaper.currentSelected = wallpaperProvider.currentWallpaper; personalizationStore.notifyObservers(); await waitAfterNextRender(wallpaperSelectedElement); assertEquals('none', placeholder!.style.display); // Sent a request to update user wallpaper. Loading placeholder should // come back. personalizationStore.data.wallpaper.loading = { ...personalizationStore.data.wallpaper.loading, selected: 0, setImage: 1, }; personalizationStore.notifyObservers(); await waitAfterNextRender(wallpaperSelectedElement); assertEquals('', placeholder!.style.display); }); test('sets wallpaper image in store on first load', async () => { personalizationStore.expectAction(WallpaperActionName.SET_SELECTED_IMAGE); wallpaperSelectedElement = initElement(WallpaperSelected); const action = await personalizationStore.waitForAction( WallpaperActionName.SET_SELECTED_IMAGE); assertDeepEquals(wallpaperProvider.currentWallpaper, action.image); }); test('shows wallpaper image and attribution when loaded', async () => { personalizationStore.data.wallpaper.currentSelected = wallpaperProvider.currentWallpaper; wallpaperSelectedElement = initElement(WallpaperSelected); await waitAfterNextRender(wallpaperSelectedElement); const img = wallpaperSelectedElement.shadowRoot!.querySelector('img'); assertEquals( `chrome://image/?${wallpaperProvider.currentWallpaper.url.url}`, img!.src); const textContainerElements = wallpaperSelectedElement.shadowRoot!.querySelectorAll( '#textContainer span'); // First span tag is 'Currently Set' text. assertEquals('currentlySet', textContainerElements[0]!.id); assertEquals( wallpaperSelectedElement.i18n('currentlySet'), textContainerElements[0]!.textContent); // Following text elements are for the photo attribution text. const attributionLines = Array.from(textContainerElements).slice(1) as HTMLElement[]; assertEquals( wallpaperProvider.currentWallpaper.attribution.length, attributionLines.length); wallpaperProvider.currentWallpaper.attribution.forEach((line, i) => { assertEquals(line, attributionLines[i]!.innerText); }); }); test('shows unknown for empty attribution', async () => { personalizationStore.data.wallpaper.currentSelected = { url: {url: 'data:image/png;base64,abc='}, attribution: [], assetId: BigInt(100), }; personalizationStore.data.wallpaper.loading.selected = false; wallpaperSelectedElement = initElement(WallpaperSelected); await waitAfterNextRender(wallpaperSelectedElement); const title = wallpaperSelectedElement.shadowRoot!.getElementById('imageTitle'); assertEquals( wallpaperSelectedElement.i18n('unknownImageAttribution'), title!.textContent!.trim()); }); test('removes high resolution suffix from image url', async () => { personalizationStore.data.wallpaper.currentSelected = { url: {url: 'https://images.googleusercontent.com/abc12=w456'}, attribution: [], assetId: BigInt(100), }; personalizationStore.data.wallpaper.loading.selected = false; wallpaperSelectedElement = initElement(WallpaperSelected); await waitAfterNextRender(wallpaperSelectedElement); const img = wallpaperSelectedElement.shadowRoot!.querySelector('img'); assertEquals( 'chrome://image/?https://images.googleusercontent.com/abc12', img!.src); }); test('updates image when store is updated', async () => { personalizationStore.data.wallpaper.currentSelected = wallpaperProvider.currentWallpaper; personalizationStore.data.wallpaper.loading.selected = false; wallpaperSelectedElement = initElement(WallpaperSelected); await waitAfterNextRender(wallpaperSelectedElement); const img = wallpaperSelectedElement.shadowRoot!.querySelector('img') as HTMLImageElement; assertEquals( `chrome://image/?${wallpaperProvider.currentWallpaper.url.url}`, img.src); personalizationStore.data.wallpaper.currentSelected = { url: {url: 'https://testing'}, attribution: ['New attribution'], assetId: BigInt(100), }; personalizationStore.notifyObservers(); await waitAfterNextRender(wallpaperSelectedElement); assertEquals('chrome://image/?https://testing', img.src); }); test('shows placeholders when image fails to load', async () => { wallpaperSelectedElement = initElement(WallpaperSelected); await waitAfterNextRender(wallpaperSelectedElement); // Still loading. personalizationStore.data.wallpaper.loading.selected = true; personalizationStore.data.wallpaper.currentSelected = null; personalizationStore.notifyObservers(); await waitAfterNextRender(wallpaperSelectedElement); const placeholder = wallpaperSelectedElement.shadowRoot!.getElementById('imagePlaceholder'); assertTrue(!!placeholder); // Loading finished and still no current wallpaper. personalizationStore.data.wallpaper.loading.selected = false; personalizationStore.notifyObservers(); await waitAfterNextRender(wallpaperSelectedElement); // Dom-if will set display: none if the element is hidden. Make sure it is // not hidden. assertNotEquals('none', placeholder!.style.display); assertEquals( null, wallpaperSelectedElement.shadowRoot!.querySelector('img')); }); test('sets selected wallpaper data in store on changed', async () => { // Make sure state starts as expected. assertDeepEquals(emptyState(), personalizationStore.data); wallpaperSelectedElement = initElement(WallpaperSelected); await wallpaperProvider.whenCalled('setWallpaperObserver'); personalizationStore.expectAction(WallpaperActionName.SET_SELECTED_IMAGE); wallpaperProvider.wallpaperObserverRemote!.onWallpaperChanged( wallpaperProvider.currentWallpaper); const {image} = await personalizationStore.waitForAction( WallpaperActionName.SET_SELECTED_IMAGE); assertDeepEquals(wallpaperProvider.currentWallpaper, image); }); test('shows image url with data scheme', async () => { personalizationStore.data.wallpaper.currentSelected = { url: {url: 'data:image/png;base64,abc='}, attribution: [], assetId: BigInt(100), }; personalizationStore.data.wallpaper.loading.selected = false; wallpaperSelectedElement = initElement(WallpaperSelected); await waitAfterNextRender(wallpaperSelectedElement); const img = wallpaperSelectedElement.shadowRoot!.querySelector('img'); assertEquals('data:image/png;base64,abc=', img!.src); }); test('shows daily refresh option on the collection view', async () => { personalizationStore.data.wallpaper.currentSelected = { url: {url: 'data:image/png;base64,abc='}, attribution: [], assetId: BigInt(100), }; personalizationStore.data.wallpaper.loading.selected = false; wallpaperSelectedElement = initElement(WallpaperSelected, {'path': Paths.CollectionImages}); await waitAfterNextRender(wallpaperSelectedElement); const dailyRefresh = wallpaperSelectedElement.shadowRoot!.getElementById('dailyRefresh'); assertTrue(!!dailyRefresh); const refreshWallpaper = wallpaperSelectedElement.shadowRoot!.getElementById('refreshWallpaper'); assertTrue(refreshWallpaper!.hidden); }); test( 'shows refresh button only on collection with daily refresh enabled', async () => { personalizationStore.data.wallpaper.currentSelected = { url: {url: 'data:image/png;base64,abc='}, attribution: [], assetId: BigInt(100), }; personalizationStore.data.wallpaper.loading.selected = false; const collection_id = wallpaperProvider.collections![0]!.id; personalizationStore.data.wallpaper.dailyRefresh = { collectionId: collection_id, }; wallpaperSelectedElement = initElement( WallpaperSelected, {'path': Paths.CollectionImages, 'collectionId': collection_id}); personalizationStore.notifyObservers(); await waitAfterNextRender(wallpaperSelectedElement); const newRefreshWallpaper = wallpaperSelectedElement.shadowRoot!.getElementById( 'refreshWallpaper'); assertFalse(newRefreshWallpaper!.hidden); }); test('sets current image to null after timeout', async () => { let timeoutCallback: Function; mockTimeoutForTesting({ setTimeout(callback, delay) { assertEquals(120 * 1000, delay); timeoutCallback = callback as Function; return 1234; }, clearTimeout() { assertNotReached('Should not clear timeout'); }, }); wallpaperProvider.wallpaperObserverUpdateTimeout = 100; wallpaperSelectedElement = initElement(WallpaperSelected, {'path': Paths.CollectionImages}); await waitAfterNextRender(wallpaperSelectedElement); personalizationStore.expectAction(WallpaperActionName.SET_SELECTED_IMAGE); timeoutCallback!.call(wallpaperSelectedElement); const action = await personalizationStore.waitForAction( WallpaperActionName.SET_SELECTED_IMAGE); assertEquals(null, action.image); }); test('cancels timeout after receiving first image', async () => { const timeoutId = 1234; const clearTimeoutPromise = new Promise<void>(resolve => { mockTimeoutForTesting({ setTimeout() { return timeoutId; }, clearTimeout(id) { assertEquals(timeoutId, id); resolve(); }, }); }); wallpaperSelectedElement = initElement(WallpaperSelected, {'path': Paths.CollectionImages}); await waitAfterNextRender(wallpaperSelectedElement); wallpaperProvider.wallpaperObserverRemote!.onWallpaperChanged( wallpaperProvider.currentWallpaper); await clearTimeoutPromise; }); test('skips updating OnWallpaperChange while in fullscreen', async () => { personalizationStore.data.wallpaper.fullscreen = true; wallpaperSelectedElement = initElement(WallpaperSelected, {'path': Paths.CollectionImages}); await waitAfterNextRender(wallpaperSelectedElement); personalizationStore.resetLastAction(); wallpaperProvider.wallpaperObserverRemote!.onWallpaperChanged( wallpaperProvider.currentWallpaper); await waitAfterNextRender(wallpaperSelectedElement); assertEquals(null, personalizationStore.lastAction); personalizationStore.data.wallpaper.fullscreen = false; personalizationStore.notifyObservers(); personalizationStore.expectAction(WallpaperActionName.SET_SELECTED_IMAGE); wallpaperProvider.wallpaperObserverRemote!.onWallpaperChanged( wallpaperProvider.currentWallpaper); const action = await personalizationStore.waitForAction( WallpaperActionName.SET_SELECTED_IMAGE); assertDeepEquals( { name: WallpaperActionName.SET_SELECTED_IMAGE, image: wallpaperProvider.currentWallpaper, }, action); }); }
the_stack
import { Component, QueryList, ViewChild, ViewChildren } from '@angular/core'; import { ComponentFixture, TestBed, waitForAsync } from '@angular/core/testing'; import { CommonModule } from '@angular/common'; import { CardModule } from '@fundamental-ngx/core/card'; import { ListModule } from '@fundamental-ngx/core/list'; import { IconModule } from '@fundamental-ngx/core/icon'; import { whenStable } from '@fundamental-ngx/core/tests'; import { ResizableCardLayoutComponent } from './resizable-card-layout.component'; import { ResizableCardItemComponent } from './resizable-card-item/resizable-card-item.component'; @Component({ template: ` <fd-resizable-card-layout> <fd-resizable-card-item title="card1" [rank]="1" [cardWidthColSpan]="1" [cardHeightRowSpan]="25" [cardMiniHeaderRowSpan]="5" [cardMiniContentRowSpan]="10" > <fd-card> <fd-card-header> <h2 fd-card-title>Card Title 1</h2> </fd-card-header> <fd-card-content> <ul fd-list [noBorder]="true"> <li fd-list-item> <span fd-list-title> item 1 </span> </li> </ul> </fd-card-content> </fd-card> </fd-resizable-card-item> <fd-resizable-card-item title="card2" [rank]="2" [cardWidthColSpan]="1" [cardHeightRowSpan]="19" [cardMiniHeaderRowSpan]="5" [cardMiniContentRowSpan]="7" > <fd-card> <fd-card-header> <h2 fd-card-title>Card Title 2</h2> </fd-card-header> <fd-card-content> <ul fd-list [noBorder]="true"> <li fd-list-item> <span fd-list-title> item 1 </span> </li> </ul> </fd-card-content> </fd-card> </fd-resizable-card-item> <fd-resizable-card-item title="card3" [rank]="3" [cardWidthColSpan]="2" [cardHeightRowSpan]="14" [cardMiniHeaderRowSpan]="5" [cardMiniContentRowSpan]="7" > <fd-card> <fd-card-header> <h2 fd-card-title>Card Title 3</h2> </fd-card-header> <fd-card-content> <ul fd-list [noBorder]="true"> <li fd-list-item> <span fd-list-title> item 1 </span> </li> </ul> </fd-card-content> </fd-card> </fd-resizable-card-item> <fd-resizable-card-item title="card4" [rank]="4" [cardWidthColSpan]="1" [cardHeightRowSpan]="14" [cardMiniHeaderRowSpan]="5" [cardMiniContentRowSpan]="7" > <fd-card> <fd-card-header> <h2 fd-card-title>Card Title 4</h2> </fd-card-header> <fd-card-content> <ul fd-list [noBorder]="true"> <li fd-list-item> <span fd-list-title> item 1 </span> </li> </ul> </fd-card-content> </fd-card> </fd-resizable-card-item> </fd-resizable-card-layout> ` }) class TestResizableCardLayout { @ViewChild(ResizableCardLayoutComponent) resizableCardLayout: ResizableCardLayoutComponent; @ViewChildren(ResizableCardItemComponent) cards: QueryList<ResizableCardItemComponent>; } describe('ResizableCardLayoutComponent', () => { let component: TestResizableCardLayout; let fixture: ComponentFixture<TestResizableCardLayout>; beforeEach( waitForAsync(() => { TestBed.configureTestingModule({ declarations: [ResizableCardLayoutComponent, ResizableCardItemComponent, TestResizableCardLayout], imports: [CommonModule, CardModule, ListModule, IconModule] }).compileComponents(); }) ); beforeEach(() => { fixture = TestBed.createComponent(TestResizableCardLayout); component = fixture.componentInstance; fixture.detectChanges(); }); it('should create', () => { expect(component).toBeTruthy(); }); it('should be placed in layout', () => { whenStable(fixture); spyOn(component.resizableCardLayout, 'getWidthAvailable').and.returnValue(1200); component.resizableCardLayout.onResize(); whenStable(fixture); // for lg screen const cards = component.cards.toArray(); expect(cards[0].cardWidth).toEqual(320); expect(cards[0].cardHeight).toEqual(400); expect(cards[0].cardWidthColSpan).toEqual(1); expect(cards[0].cardHeightRowSpan).toEqual(25); expect(cards[0].left).toEqual(16); expect(cards[0].top).toEqual(0); expect(cards[1].cardWidth).toEqual(320); expect(cards[1].cardHeight).toEqual(304); expect(cards[1].cardWidthColSpan).toEqual(1); expect(cards[1].cardHeightRowSpan).toEqual(19); expect(cards[1].left).toEqual(352); expect(cards[1].top).toEqual(0); expect(cards[2].cardWidth).toEqual(656); expect(cards[2].cardHeight).toEqual(224); expect(cards[2].cardWidthColSpan).toEqual(2); expect(cards[2].cardHeightRowSpan).toEqual(14); expect(cards[2].left).toEqual(352); expect(cards[2].top).toEqual(320); expect(cards[3].cardWidth).toEqual(320); expect(cards[3].cardHeight).toEqual(224); expect(cards[3].cardWidthColSpan).toEqual(1); expect(cards[3].cardHeightRowSpan).toEqual(14); expect(cards[3].left).toEqual(16); expect(cards[3].top).toEqual(416); }); it('should layout cards again on changing width of any card 1', () => { // for lg screen whenStable(fixture); spyOn(component.resizableCardLayout, 'getWidthAvailable').and.returnValue(1200); component.resizableCardLayout.onResize(); whenStable(fixture); const mouseEvent1 = new MouseEvent('changeWidth', { clientX: 7, clientY: 20 }); const card = component.cards.toArray()[0]; // increasing width card.onMouseDown(mouseEvent1, 'horizontal'); const mouseEvent2 = new MouseEvent('changeWidth', { clientX: 200, clientY: 20 }); card.onMouseMove(mouseEvent2); card.onMouseUp(mouseEvent2); fixture.detectChanges(); expect(card.cardWidthColSpan).toEqual(2); expect(card.cardHeightRowSpan).toEqual(25); const cards = component.cards.toArray(); expect(cards[0].left).toEqual(16); expect(cards[0].top).toEqual(0); expect(cards[1].left).toEqual(688); expect(cards[1].top).toEqual(0); expect(cards[2].left).toEqual(16); expect(cards[2].top).toEqual(416); expect(cards[3].left).toEqual(688); expect(cards[3].top).toEqual(320); }); it('should layout cards again on changing width of any card 2', () => { // for lg screen whenStable(fixture); spyOn(component.resizableCardLayout, 'getWidthAvailable').and.returnValue(1200); component.resizableCardLayout.onResize(); whenStable(fixture); const mouseEvent1 = new MouseEvent('changeWidth', { clientX: 7, clientY: 20 }); const card = component.cards.toArray()[1]; // increase width card.onMouseDown(mouseEvent1, 'horizontal'); const mouseEvent2 = new MouseEvent('changeWidth', { clientX: 440, clientY: 20 }); card.onMouseMove(mouseEvent2); card.onMouseUp(mouseEvent2); fixture.detectChanges(); expect(card.cardWidthColSpan).toEqual(2); expect(card.cardHeightRowSpan).toEqual(19); const cards = component.cards.toArray(); expect(cards[0].left).toEqual(16); expect(cards[0].top).toEqual(0); expect(cards[1].left).toEqual(352); expect(cards[1].top).toEqual(0); expect(cards[2].left).toEqual(16); expect(cards[2].top).toEqual(560); expect(cards[3].left).toEqual(352); expect(cards[3].top).toEqual(320); // decrease width const mouseEvent3 = new MouseEvent('changeWidth', { clientX: 7, clientY: 20 }); const card2 = component.cards.toArray()[1]; // decrease width card2.onMouseDown(mouseEvent3, 'horizontal'); const mouseEvent4 = new MouseEvent('changeWidth', { clientX: 5, clientY: 20 }); card2.onMouseMove(mouseEvent4); card2.onMouseUp(mouseEvent4); fixture.detectChanges(); expect(card.cardWidthColSpan).toEqual(2); expect(card.cardHeightRowSpan).toEqual(19); // layout should also change expect(cards[0].left).toEqual(16); expect(cards[0].top).toEqual(0); expect(cards[1].left).toEqual(352); expect(cards[1].top).toEqual(0); expect(cards[2].left).toEqual(16); expect(cards[2].top).toEqual(560); expect(cards[3].left).toEqual(352); expect(cards[3].top).toEqual(320); }); it('should layout cards again on changing height of any card', () => { // for lg screen whenStable(fixture); spyOn(component.resizableCardLayout, 'getWidthAvailable').and.returnValue(1200); component.resizableCardLayout.onResize(); whenStable(fixture); const mouseEvent1 = new MouseEvent('changeWidth', { clientX: 7, clientY: 20 }); const card = component.cards.toArray()[1]; card.onMouseDown(mouseEvent1, 'vertical'); const mouseEvent2 = new MouseEvent('changeWidth', { clientX: 7, clientY: 90 }); card.onMouseMove(mouseEvent2); card.onMouseUp(mouseEvent2); fixture.detectChanges(); expect(card.cardWidthColSpan).toEqual(1); expect(card.cardHeightRowSpan).toEqual(23); // from 19 row to 23 row height expect(card.cardWidth).toEqual(320); expect(card.cardHeight).toEqual(368); const cards = component.cards.toArray(); expect(cards[0].left).toEqual(16); expect(cards[0].top).toEqual(0); expect(cards[1].left).toEqual(352); expect(cards[1].top).toEqual(0); expect(cards[2].left).toEqual(352); expect(cards[2].top).toEqual(384); expect(cards[3].left).toEqual(16); expect(cards[3].top).toEqual(416); }); it('should layout cards again on changing width and height of any card', () => { // for lg screen whenStable(fixture); spyOn(component.resizableCardLayout, 'getWidthAvailable').and.returnValue(1200); component.resizableCardLayout.onResize(); whenStable(fixture); const mouseEvent1 = new MouseEvent('changeWidth', { clientX: 7, clientY: 20 }); const card = component.cards.toArray()[1]; card.onMouseDown(mouseEvent1, 'both'); const mouseEvent2 = new MouseEvent('changeWidth', { clientX: 440, clientY: 90 }); card.onMouseMove(mouseEvent2); card.onMouseUp(mouseEvent2); fixture.detectChanges(); expect(card.cardWidthColSpan).toEqual(2); expect(card.cardHeightRowSpan).toEqual(23); const cards = component.cards.toArray(); expect(cards[0].left).toEqual(16); expect(cards[0].top).toEqual(0); expect(cards[1].left).toEqual(352); expect(cards[1].top).toEqual(0); expect(cards[2].left).toEqual(16); expect(cards[2].top).toEqual(624); expect(cards[3].left).toEqual(352); expect(cards[3].top).toEqual(384); }); it('should not increase width of card more than the layout width capacity', () => { // for lg screen whenStable(fixture); spyOn(component.resizableCardLayout, 'getWidthAvailable').and.returnValue(1200); component.resizableCardLayout.onResize(); whenStable(fixture); const mouseEvent1 = new MouseEvent('changeWidth', { clientX: 7, clientY: 20 }); const card = component.cards.toArray()[1]; card.onMouseDown(mouseEvent1, 'both'); const mouseEvent2 = new MouseEvent('changeWidth', { clientX: 440, clientY: 90 }); card.onMouseMove(mouseEvent2); card.onMouseUp(mouseEvent2); fixture.detectChanges(); expect(card.cardWidthColSpan).toEqual(2); expect(card.cardHeightRowSpan).toEqual(23); const cards = component.cards.toArray(); expect(cards[0].left).toEqual(16); expect(cards[0].top).toEqual(0); expect(cards[1].left).toEqual(352); expect(cards[1].top).toEqual(0); expect(cards[2].left).toEqual(16); expect(cards[2].top).toEqual(624); expect(cards[3].left).toEqual(352); expect(cards[3].top).toEqual(384); // increase width of card 2 again const mouseEvent3 = new MouseEvent('changeWidth', { clientX: 7, clientY: 20 }); const card2 = component.cards.toArray()[1]; card2.onMouseDown(mouseEvent3, 'both'); const mouseEvent4 = new MouseEvent('changeWidth', { clientX: 440, clientY: 30 }); card2.onMouseMove(mouseEvent4); card2.onMouseUp(mouseEvent4); fixture.detectChanges(); // only increment in height. width did not increase expect(card.cardWidthColSpan).toEqual(3); expect(card.cardHeightRowSpan).toEqual(24); }); it('should not decrease width of card less than 1 column', () => { // for lg screen whenStable(fixture); spyOn(component.resizableCardLayout, 'getWidthAvailable').and.returnValue(1200); component.resizableCardLayout.onResize(); whenStable(fixture); const mouseEvent1 = new MouseEvent('changeWidth', { clientX: 7, clientY: 20 }); const card = component.cards.toArray()[0]; const cards1 = component.cards.toArray(); expect(cards1[0].left).toEqual(16); expect(cards1[0].top).toEqual(0); expect(cards1[1].left).toEqual(352); expect(cards1[1].top).toEqual(0); expect(cards1[2].left).toEqual(352); expect(cards1[2].top).toEqual(320); expect(cards1[3].left).toEqual(16); expect(cards1[3].top).toEqual(416); // decreasing width card.onMouseDown(mouseEvent1, 'horizontal'); const mouseEvent2 = new MouseEvent('changeWidth', { clientX: 6, clientY: 20 }); card.onMouseMove(mouseEvent2); card.onMouseUp(mouseEvent2); fixture.detectChanges(); expect(card.cardWidthColSpan).toEqual(1); expect(card.cardHeightRowSpan).toEqual(25); // verify no change in layout const cards = component.cards.toArray(); expect(cards[0].left).toEqual(16); expect(cards[0].top).toEqual(0); expect(cards[1].left).toEqual(352); expect(cards[1].top).toEqual(0); expect(cards[2].left).toEqual(352); expect(cards[2].top).toEqual(320); expect(cards[3].left).toEqual(16); expect(cards[3].top).toEqual(416); }); });
the_stack
import * as estree from "estree"; import * as sourceMap from "source-map"; /** * JS2Coffee API. * * @param source JavaScript code to compile. In order to compile JSON as CSON, you must wrap the string in * parentheses like so: `(...)`. * @param [options] JS2Coffee compiler options. * @param [options.bare=false] Whether to omit a top-level IIFE safety wrapper. * @param [options.comments=true] Whether to keep comments in the output. * @param [options.compat=false] Compatibility mode with JS. * @param [options.filename=index.js] File name for JS script to compile to CoffeeScript. * @param [options.indent=2] Indentation character(s) used in the compiler output. * @param [options.source] The source code itself - always overwritten by * `source`. * @returns Compiled CoffeeScript code. */ declare function js2coffee(source: string, options?: js2coffee.Options): string; declare namespace js2coffee { /** * @param source JavaScript code to compile. In order to compile JSON as CSON, you must wrap the string in * parentheses like so: `(...)`. * @param [options] JS2Coffee compiler options. * @param [options.bare=false] Whether to omit a top-level IIFE safety wrapper. * @param [options.comments=true] Whether to keep comments in the output. * @param [options.compat=false] Compatibility mode with JS. * @param [options.filename=index.js] File name for JS script to compile to CoffeeScript. * @param [options.indent=2] Indentation character(s) used in the compiler output. * @param [options.source] The source code itself - always overwritten by * `source`. * @returns Build output in CoffeeScript. */ function build(source: string, options?: Options): Build; /** * Compiles JavaScript into a ESTree-style CoffeeScript AST. The AST has the following custom types exclusive to * JS2Coffee: * - `CoffeeDoExpression` * - `CoffeeEscapedExpression` * - `CoffeeListExpression` * - `CoffeeLoopStatement` * - `CoffeePrototypeExpression` * * @param source JavaScript code to compile. In order to compile JSON as CSON, * you must wrap the string in parentheses like so: `(...)`. * @param [options] JS2Coffee compiler options. * @param [options.bare=false] Whether to omit a top-level IIFE safety wrapper. * @param [options.comments=true] Whether to keep comments in the output. * @param [options.compat=false] Compatibility mode with JS. * @param [options.filename=index.js] File name for JS script to compile to CoffeeScript. * @param [options.indent=2] Indentation character(s) used in the compiler output. * @param [options.source] The source code itself - always overwritten by * `source`. * @returns JavaScript AST in ESTree format. */ function parseJS(source: string, options?: Options): AST; /** * Mutates the `ast` JavaScript syntax tree into a CoffeeScript AST transform. * * @param JavaScript AST in ESTree format. * @param [options] JS2Coffee compiler options. * @param [options.bare=false] Whether to omit a top-level IIFE safety wrapper. * @param [options.comments=true] Whether to keep comments in the output. * @param [options.compat=false] Compatibility mode with JS. * @param [options.filename=index.js] File name for JS script to compile to CoffeeScript. * @param [options.indent=2] Indentation character(s) used in the compiler output. * @param [options.source] The source code itself - always overwritten by * `source`. * @returns Abstract syntax tree for post-transform CoffeeScript. */ function transform(ast: AST, options?: Options): Transform; /** * Generates a CoffeeScript `CodeWithSourceMap` instance from a given CoffeeScript transform. * * @param ast Transformed CoffeeScript AST in ESTree format. * @param [options] JS2Coffee compiler options. * @param [options.bare=false] Whether to omit a top-level IIFE safety wrapper. * @param [options.comments=true] Whether to keep comments in the output. * @param [options.compat=false] Compatibility mode with JS. * @param [options.filename=index.js] File name for JS script to compile to CoffeeScript. * @param [options.indent=2] Indentation character(s) used in the compiler output. * @param [options.source] The source code itself - always overwritten by * `source`. * @returns CoffeeScript output as a `CodeWithSourceMap` object. */ function generate(ast: Transform, options?: Options): sourceMap.CodeWithSourceMap; /** * Version number. Type defintions are written for JS2Coffee v1.9.2. */ let version: string; /** * Collection of helper functions used to parse JavaScript in */ let helpers: Helpers; /** * ESTree node types for CoffeeScript AST nodes in `AST` body. */ type CoffeeNodeType = ( | "CoffeeDoExpression" | "CoffeeEscapedExpression" | "CoffeeListExpression" | "CoffeeLoopStatement" | "CoffeePrototypeExpression" ); /** * Custom ESTree-style node used to define CoffeeScript in JS2Coffee ASTs. */ interface CustomNode extends Omit<estree.Node, "type"> { type: CoffeeNodeType; } /** * JS2Coffee compiler options. * * `source` parameter. */ interface Options { bare?: boolean; comments?: boolean; compat?: boolean; filename?: string; indent?: number; source?: string; } /** * Custom ESTree-style node used to define converted CoffeeScript nodes JS2Coffee ASTs. */ interface CoffeeNode extends Omit<estree.Node, "type"> { type: estree.Node["type"] | CoffeeNodeType; } /** * Generic compilation error in * */ interface CompileError extends Error { description: string; end: { line: number; column: number; }; start: { line: number; column: number; }; } /** * Esprima-style error thrown by * */ interface EsprimaStyleError { column: number; description: string; lineNumber: number; } /** * JavaScript syntax error thrown by JS2Coffee compiler. */ interface SyntaxProblem extends CompileError { filename: string; js2coffee: true; sourcePreview: string[]; } /** * Collection of helper functions used to parse JavaScript in */ interface Helpers { /** * Reserved words taken from COFFEE_KEYWORDS (lexer.coffee). * We don't check for "undefined" because it"s already explicitly * accounted for elsewhere. */ reserved: { keywords: string[]; reserved: string[]; aliases: string[]; }; reservedWords: string[]; /** * Builds a syntax error message. * * @param err Error to convert into syntax error. * @param source Source code that threw the JS2Coffee compiler error * @param file File name including extension. */ buildError( err: CompileError | EsprimaStyleError, source: string, file: string ): SyntaxProblem; /** * Duplicates all primitive members of an object recursively. * * @param obj Object to clone. * @returns Deep copy of object. */ clone(obj: object): object; /** * Turns an array of strings into a comma-separated list. * Takes new lines into account. * * @param list Array of elements to join with `,`. * @returns Array with elements separated by `,`. */ commaDelimit(list: string[]): string[]; /** * Intersperses `joiner` into `list`. * Used for things like adding indentations. * * @param list Array of elements to be joined by `joiner`. * @param joiner Element to insert between each element of `list`. */ delimit(list: any[], joiner: any): any[]; /** * Escapes JS that cannot be converted to CoffeeScript. * * @param node Unconvertable node. * @returns Node with type "CoffeeEscapedExpression". */ escapeJs(node: estree.Node): CoffeeNode & { type: "CoffeeEscapedExpression" }; /** * Inspect a ESTree node for debugging. * * @param node Node to inspect. * @returns String representation bounded by `~~~~`. */ inspect(node: estree.BaseNode): `~~~~\n${string}\n~~~~`; /** * ESTree comment node assertion. * * @param node Node to apply test to. * @returns Whether the ESTree node is a comment. */ isComment(node: estree.BaseNode): boolean; /** * ESTree infinite loop node assertion. * * @param node Node to apply test to. * @returns Whether the ESTree node is a infinite loop. */ isLoop(node: estree.BaseNode): boolean; /** * ESTree "truthy" node assertion. * A node is truthy when it has a "Literal" type and a value. * * @param node Node to apply test to. * @returns Whether the ESTree node is a "truthy" node. */ isTruthy(node: estree.BaseNode): boolean; /** * Returns the final return statements in a body. * * @param body AST colleciton of nodes describing a program. * @returns Array of ESTree nodes for final return statement or empty array. */ getReturnStatements(body: estree.BaseNode[]): estree.BaseNode[] | []; /** * Returns the precedence level of a ESTree operator node. * If a node"s precedence level is greater than its parent, it has to be * parenthesized. * * @param node ESTree operator node. * @returns Precedence level. */ getPrecedence(node: estree.BaseNode): number; joinLines(props: string[], indent: string): string[]; /** * Get the last statement in a program. * * @param body AST colleciton of nodes describing a program. * @returns Last non-comment node in a program. */ lastStatement(body: estree.BaseNode[]): estree.BaseNode; /** * Appends a new line to a given SourceNode (what `walk()` returns). If it * already ends in a newline, it is left alone. * * @param srcnode Either a ESTree node or a node array terminating with `\n`. * @returns ESTree node array terminating with `\n`. */ newline(srcnode: estree.BaseNode | [estree.BaseNode, "\n"]): [estree.BaseNode, "\n"]; /** * Get the next ESTree node after `node` that is not a comment * * @param body AST colleciton of nodes describing a program. * @param node Current node in JS2Coffee stack. * @returns Next non-comment stack, if one is available. */ nextNonComment(body: estree.BaseNode[], node: estree.BaseNode): estree.BaseNode | undefined; /** * Iterate to the next ESTree node until `fn` returns true. * * @param body AST colleciton of nodes describing a program. * @param node Current node in JS2Coffee stack. * @returns Next ESTree node that passes the `fn` callback. */ nextUntil(body: estree.BaseNode[], node: estree.BaseNode, fn: (n: estree.BaseNode) => boolean): estree.BaseNode | undefined; /** * Prepends every item in the `list` with a given `prefix`. * * @param list Array of elements. * @param prefix Prefix to insert before every element. * @returns Array with all elements preceded by `prefix`. */ prependAll(list: any[], prefix: any): any[]; /** * Quotes a string or primitive with single quotes. * * @param str String to quote. */ quote(str: any): string; /** * Fabricates a replacement node for `node` that maintains the same source * location. * * @param node Prevous node. * @param node.loc Previous node"s location (preserved in output). * @param node.range Previous node"s character range (preserved in output). * @param newNode New ESTree node with a specified `type` and `name`. * @param newNode.type ESTree or JS2Coffee type for the new node. * @param newNode.name Name of the new node. * @returns Newly typed and named node with previous source location. */ replace(node: estree.BaseNode, newNode: estree.BaseNode): estree.BaseNode; /** * Delimit using spaces. This also accounts for times where one of the * statements begin with a new line, such as in the case of function * expressions and object expressions. * * @param list Array of code tokens. * @returns Array of code tokens separated by spaces. */ space(list: string[]): string[]; /** * Convert identifier, custom character or indentation level into indent. * * @param ind Either "tab", "t", custom character or indentation level. * @returns Indentation character sequence (character default: ` `). */ toIndent(ind: "tab" | "t" | string | number): string; } /** * Collection of syntax warnings to return to user (may be empty). */ type Warnings = SyntaxProblem[] | []; /** * Abstract syntax tree for CoffeeScript file. * */ interface AST extends Omit<estree.Program, "body"> { body: CoffeeNode[]; } /** * Abstract syntax tree for post-transform CoffeeScript. * */ interface Transform { ast: AST; warnings: Warnings; } /** * Build output for JS code compiled to CoffeeScript. * * (See `CodeWithSourceMap` definition in `source-map`). */ interface Build { ast: AST; code: string; map: sourceMap.CodeWithSourceMap; warnings: Warnings; } } export = js2coffee;
the_stack
import './index'; import { expect } from 'chai'; import { CommandsSk, } from './commands-sk'; import { setUpElementUnderTest, eventPromise } from '../../../infra-sk/modules/test_util'; import { SkpJsonCommandList } from '../debugger'; import { testData } from './test-data'; import { MoveCommandPositionEventDetail, SelectImageEventDetail, MoveCommandPositionEvent, SelectImageEvent, } from '../events'; describe('commands-sk', () => { const newInstance = setUpElementUnderTest<CommandsSk>('commands-sk'); let commandsSk: CommandsSk; beforeEach(() => { commandsSk = newInstance(); }); it('can process a list of commands', () => { commandsSk.processCommands(testData); expect(commandsSk.count).to.equal(10); // default filter excludes DrawAnnotation, so one less command expect(commandsSk.countFiltered).to.equal(9); expect(commandsSk.position).to.equal(9); // last item in list }); it('can process a second command list after loading a first', () => { commandsSk.processCommands(testData); commandsSk.range = [4, 9]; const newData: SkpJsonCommandList = { commands: [ { command: 'DrawRect', shortDesc: '', key: '', imageIndex: 0, layerNodeId: 0, auditTrail: { Ops: [] }, }, { command: 'DrawOval', shortDesc: '', key: '', imageIndex: 0, layerNodeId: 0, auditTrail: { Ops: [] }, }, { command: 'DrawPaint', shortDesc: '', key: '', imageIndex: 0, layerNodeId: 0, auditTrail: { Ops: [] }, }, ], }; commandsSk.processCommands(newData); expect(commandsSk.count).to.equal(3); expect(commandsSk.countFiltered).to.equal(3); expect(commandsSk.position).to.equal(2); // confirm filters gone expect(commandsSk.querySelector<HTMLInputElement>('#rangelo')!.value) .to.equal('0'); expect(commandsSk.querySelector<HTMLInputElement>('#rangehi')!.value) .to.equal('2'); // the highest index expect(commandsSk.querySelector<HTMLInputElement>('#text-filter')!.value) .to.equal('!DrawAnnotation'); // We don't intend to clear this. }); it('can apply a range filter by setting range attribute', () => { commandsSk.clearFilter(); commandsSk.processCommands(testData); commandsSk.range = [2, 6]; expect(commandsSk.count).to.equal(10); // this should never change expect(commandsSk.countFiltered).to.equal(5); expect(commandsSk.position).to.equal(6); expect(commandsSk.filtered).to.eql([2, 3, 4, 5, 6]); // chai deep equals }); it('can apply a range filter by clicking the zoom button on one of the ops', () => { commandsSk.clearFilter(); commandsSk.processCommands(testData); // a div containing a save op with at matching restore at op 8. const opDiv = commandsSk.querySelector<HTMLElement>('#op-4')!; // CommandsSk is supposed to find it and remember the range during processCommands. // If there is no button, that part failed. (opDiv.querySelector('button') as HTMLButtonElement).click(); expect(commandsSk.countFiltered).to.equal(5); expect(commandsSk.position).to.equal(8); expect(commandsSk.filtered).to.eql([4, 5, 6, 7, 8]); }); it('can apply a positive text filter (ClipRect cliprrect)', () => { commandsSk.clearFilter(); commandsSk.processCommands(testData); commandsSk.textFilter = 'ClipRect cliprrect'; expect(commandsSk.countFiltered).to.equal(2); // the last item to pass the filter, op 5, cliprrect expect(commandsSk.position).to.equal(5); expect(commandsSk.filtered).to.eql([2, 5]); }); it('can apply a negative text filter (!Restore Save)', () => { commandsSk.clearFilter(); commandsSk.processCommands(testData); commandsSk.textFilter = '!Restore Save'; expect(commandsSk.countFiltered).to.equal(6); expect(commandsSk.position).to.equal(7); expect(commandsSk.filtered).to.eql([1, 2, 3, 5, 6, 7]); }); // because theres a token that doesn't match a command name, it should be interpreted // as a free text search it('Can apply a free text search filter (money)', () => { commandsSk.clearFilter(); commandsSk.processCommands(testData); commandsSk.textFilter = 'money'; expect(commandsSk.countFiltered).to.equal(2); expect(commandsSk.position).to.equal(8); expect(commandsSk.filtered).to.eql([4, 8]); }); it('can apply a range filter while a positive text filter is applied', () => { commandsSk.clearFilter(); commandsSk.processCommands(testData); commandsSk.textFilter = 'Save'; // there's save at ops 0 and 4 commandsSk.range = [2, 9]; // only one op, the save at position 4, satisfies both filters expect(commandsSk.countFiltered).to.equal(1); expect(commandsSk.position).to.equal(4); expect(commandsSk.filtered).to.eql([4]); }); it('can apply a range filter while a negative text filter is applied', () => { commandsSk.clearFilter(); commandsSk.processCommands(testData); commandsSk.textFilter = '!Save'; // there's saves at ops 0 and 4 commandsSk.range = [2, 9]; // only one op, the save at position 4, satisfies both filters expect(commandsSk.countFiltered).to.equal(7); expect(commandsSk.position).to.equal(9); expect(commandsSk.filtered).to.eql([2, 3, 5, 6, 7, 8, 9]); }); it('can apply a range filter while a free text filter is applied', () => { commandsSk.clearFilter(); commandsSk.processCommands(testData); commandsSk.textFilter = 'trees'; // there's matches at ops 0 and 9 commandsSk.range = [0, 2]; expect(commandsSk.countFiltered).to.equal(1); expect(commandsSk.position).to.equal(0); expect(commandsSk.filtered).to.eql([0]); }); it('can click clear filter button while both types of filter apply.', () => { commandsSk.clearFilter(); commandsSk.processCommands(testData); commandsSk.textFilter = 'trees'; // there's matches at ops 0 and 9 commandsSk.range = [0, 2]; commandsSk.querySelector<HTMLButtonElement>('#clear-filter-button')!.click(); // confirm filters gone expect(commandsSk.querySelector<HTMLInputElement>('#rangelo')!.value) .to.equal('0'); expect(commandsSk.querySelector<HTMLInputElement>('#rangehi')!.value) .to.equal('9'); // the highest index expect(commandsSk.querySelector<HTMLInputElement>('#text-filter')!.value) .to.equal(''); // And applied expect(commandsSk.countFiltered).to.equal(10); // Does not change, also tested below in different circumstances expect(commandsSk.position).to.equal(0); expect(commandsSk.filtered).to.eql([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]); }); it('can put playback on an arbitrary command by clicking the <summary> element', () => { commandsSk.processCommands(testData); const opDiv = commandsSk.querySelector<HTMLElement>('#op-5')!; // ClipRRect (opDiv.querySelector('summary') as HTMLElement).click(); expect(commandsSk.countFiltered).to.equal(9); expect(commandsSk.position).to.equal(5); }); it('can apply a filter without clobbering selection', () => { // Apply a filter that would not exclude the currently selected item and confirm // it is still selected. commandsSk.clearFilter(); commandsSk.processCommands(testData); // select item 6, DrawTextBlob const opDiv = commandsSk.querySelector<HTMLElement>('#op-6')!; // ClipRRect (opDiv.querySelector('summary') as HTMLElement).click(); commandsSk.textFilter = '!Save Restore'; expect(commandsSk.position).to.equal(6); }); it('can apply a filter that removes selection and alter it correctly.', () => { commandsSk.clearFilter(); commandsSk.processCommands(testData); // select item 6, DrawTextBlob const opDiv = commandsSk.querySelector<HTMLElement>('#op-6')!; // ClipRRect (opDiv.querySelector('summary') as HTMLElement).click(); commandsSk.textFilter = '!DrawTextBlob'; expect(commandsSk.position).to.equal(9); }); it('playback loops around at the end of a filtered list', async () => { commandsSk.clearFilter(); commandsSk.processCommands(testData); commandsSk.range = [4, 9]; expect(commandsSk.position).to.equal(9); // set up event promise const ep = eventPromise<CustomEvent<MoveCommandPositionEventDetail>>( MoveCommandPositionEvent, 200, ); // click the play button commandsSk.querySelector<HTMLButtonElement>('#play-button')!.click(); expect((await ep).detail.position).to.equal(4); }); it('full op representatoin contains image buttons for image shaders', async () => { commandsSk.clearFilter(); commandsSk.processCommands(JSON.parse(` { "version": 1, "commands": [ { "command": "DrawOval", "visible": true, "coords": [ 0, 0, 99, 99 ], "paint": { "antiAlias": true, "filterQuality": "low", "shader": { "name": "SkLocalMatrixShader", "data": "/data/1", "values": { "00_matrix": [ [ 1.45588, 0, 0 ], [ 0, 1.45588, 0 ], [ 0, 0, 1 ] ], "01_SkImageShader": { "00_uint": 0, "01_uint": 0, "02_bool": false, "03_matrix": [ [ 1, 0, 0 ], [ 0, 1, 0 ], [ 0, 0, 1 ] ], "04_image": { "imageIndex": 1000 } } } } } } ] } `)); // Expand the command in this test data, by clicking it two times. const opDiv = commandsSk.querySelector<HTMLElement>('#op-0')!; const summary = (opDiv.querySelector('summary') as HTMLElement); summary.click(); summary.click(); // Click the image button. confirm event generated const ep = eventPromise<CustomEvent<SelectImageEventDetail>>( SelectImageEvent, 200, ); opDiv.querySelector<HTMLButtonElement>('button')!.click(); expect((await ep).detail.id).to.equal(1000); }); });
the_stack
import React from 'react'; import PropTypes from 'prop-types'; import Component from '../../react-class'; import { Flex } from '../../Flex'; import assign from '../../../common/assign'; import join from '../../../common/join'; import toMoment from './toMoment'; import joinFunctions from './joinFunctions'; import Footer from './Footer'; import YearView from './YearView'; import assignDefined from './assignDefined'; import DecadeView, { prepareDateProps, getInitialState, onViewDateChange, onActiveDateChange, onChange, navigate, select, confirm, gotoViewDate, } from './DecadeView'; const preventDefault = e => { e.preventDefault(); }; export default class MonthDecadeView extends Component { constructor(props) { super(props); this.state = getInitialState(props); } componentWillUnmount() { this.unmounted = true; } toMoment(date, format) { return toMoment(date, format, this.props); } render() { const dateProps = prepareDateProps(this.props, this.state); const props = (this.p = { ...this.props, ...dateProps }); props.children = React.Children.toArray(props.children); const { rootClassName } = props; const className = join( props.className, rootClassName, props.theme && `${rootClassName}--theme-${props.theme}` ); const separatorClassName = `${rootClassName}__separator`; const commonProps = assignDefined( {}, { locale: props.locale, theme: props.theme, minDate: props.minDate, maxDate: props.maxDate, viewDate: props.viewMoment, activeDate: props.activeDate, date: props.date, dateFormat: props.dateFormat, } ); const yearViewProps = assign({}, commonProps); const decadeViewProps = assign({}, commonProps, { ref: view => { this.decadeView = view; }, }); const flexProps = assign({}, this.props); delete flexProps.rootClassName; delete flexProps.activeDate; delete flexProps.adjustDateStartOf; delete flexProps.adjustMaxDateStartOf; delete flexProps.adjustMinDateStartOf; delete flexProps.cleanup; delete flexProps.date; delete flexProps.dateFormat; delete flexProps.defaultDate; delete flexProps.defaultViewDate; delete flexProps.focusDecadeView; delete flexProps.focusYearView; delete flexProps.okButtonText; delete flexProps.cancelButtonText; delete flexProps.footer; delete flexProps.locale; delete flexProps.maxDate; delete flexProps.minDate; delete flexProps.onOkClick; delete flexProps.onCancelClick; delete flexProps.okOnEnter; delete flexProps.navigation; delete flexProps.theme; delete flexProps.viewMoment; if (typeof props.cleanup == 'function') { props.cleanup(flexProps); } return ( <Flex inline column alignItems="stretch" {...flexProps} className={className} > {this.renderYearView(yearViewProps)} <div className={separatorClassName} /> {this.renderDecadeView(decadeViewProps)} <div className={separatorClassName} /> {this.renderFooter()} </Flex> ); } renderFooter() { const props = this.p; const children = props.children; if (!props.footer) { return null; } const { okButtonText, cancelButtonText } = props; const defaultFooterProps = assignDefined( {}, { okButtonText, cancelButtonText, theme: props.theme } ); const footerChild = children.filter( c => c && c.props && c.props.isDatePickerFooter )[0]; if (footerChild) { const newFooterProps = { onOkClick: joinFunctions(this.onOkClick, footerChild.props.onOkClick), onCancelClick: joinFunctions( this.onCancelClick, footerChild.props.onCancelClick ), }; assignDefined(newFooterProps, defaultFooterProps); if (footerChild.props.centerButtons === undefined) { newFooterProps.centerButtons = true; } if (footerChild.props.todayButton === undefined) { newFooterProps.todayButton = false; } if (footerChild.props.clearButton === undefined) { newFooterProps.clearButton = false; } return React.cloneElement(footerChild, newFooterProps); } return ( <Footer key="month_decade_footer" {...defaultFooterProps} todayButton={false} clearButton={false} onOkClick={this.onOkClick} onCancelClick={this.onCancelClick} centerButtons /> ); } onOkClick() { if (this.props.onOkClick) { const dateMoment = this.p.activeMoment; const dateString = this.format(dateMoment); const timestamp = +dateMoment; this.props.onOkClick(dateString, { dateMoment, timestamp }); } } onCancelClick() { if (this.props.onCancelClick) { this.props.onCancelClick(); } } renderYearView(yearViewProps) { const props = this.p; const children = props.children; const yearViewChild = children.filter( c => c && c.props && c.props.isYearView )[0]; const yearViewChildProps = yearViewChild ? yearViewChild.props : {}; const tabIndex = yearViewChildProps.tabIndex == null ? null : yearViewChildProps.tabIndex; yearViewProps.tabIndex = tabIndex; if (props.focusYearView === false || tabIndex == null) { yearViewProps.tabIndex = null; yearViewProps.onFocus = this.onYearViewFocus; yearViewProps.onMouseDown = this.onYearViewMouseDown; } assign(yearViewProps, { onViewDateChange: joinFunctions( this.onViewDateChange, yearViewChildProps.onViewDateChange ), onActiveDateChange: joinFunctions( this.onActiveDateChange, yearViewChildProps.onActiveDateChange ), onChange: joinFunctions( this.handleYearViewOnChange, yearViewChildProps.onChange ), }); if (yearViewChild) { return React.cloneElement(yearViewChild, yearViewProps); } return <YearView {...yearViewProps} />; } renderDecadeView(decadeViewProps) { const props = this.p; const children = props.children; const decadeViewChild = children.filter( c => c && c.props && c.props.isDecadeView )[0]; const decadeViewChildProps = decadeViewChild ? decadeViewChild.props : {}; const tabIndex = decadeViewChildProps.tabIndex == null ? null : decadeViewChildProps.tabIndex; decadeViewProps.tabIndex = tabIndex; if (props.focusDecadeView === false || tabIndex == null) { decadeViewProps.tabIndex = null; decadeViewProps.onMouseDown = this.onDecadeViewMouseDown; } assign(decadeViewProps, { onConfirm: joinFunctions( this.handleDecadeViewOnConfirm, decadeViewChildProps.onConfirm ), onViewDateChange: joinFunctions( this.handleDecadeOnViewDateChange, decadeViewChildProps.onViewDateChange ), onActiveDateChange: joinFunctions( this.handleDecadeOnActiveDateChange, decadeViewChildProps.onActiveDateChange ), onChange: joinFunctions( this.handleDecadeOnChange, decadeViewChildProps.onChange ), }); if (decadeViewChild) { return React.cloneElement(decadeViewChild, decadeViewProps); } return <DecadeView {...decadeViewProps} />; } onYearViewFocus() { if (this.props.focusYearView === false) { this.focus(); } } focus() { if (this.decadeView && this.props.focusDecadeView) { this.decadeView.focus(); } } getDOMNode() { return this.decadeView; } onYearViewMouseDown(e) { preventDefault(e); this.focus(); } onDecadeViewMouseDown(e) { preventDefault(e); } format(mom, format) { format = format || this.props.dateFormat; return mom.format(format); } handleDecadeViewOnConfirm() { if (this.props.okOnEnter) { this.onOkClick(); } } onKeyDown(event) { if (event.key == 'Escape') { return this.onCancelClick(); } if (this.decadeView) { this.decadeView.onKeyDown(event); } return undefined; } confirm(date, event) { return confirm.call(this, date, event); } navigate(direction, event) { return navigate.call(this, direction, event); } select({ dateMoment, timestamp }, event) { return select.call(this, { dateMoment, timestamp }, event); } handleDecadeOnViewDateChange(dateString, { dateMoment, timestamp }) { const props = this.p; const currentViewMoment = props.viewMoment; if (currentViewMoment) { dateMoment.set('month', currentViewMoment.get('month')); dateString = this.format(dateMoment); timestamp = +dateMoment; } this.onViewDateChange(dateString, { dateMoment, timestamp }); } handleDecadeOnActiveDateChange(dateString, { dateMoment, timestamp }) { const props = this.p; const currentViewMoment = props.viewMoment; if (currentViewMoment) { dateMoment.set('month', currentViewMoment.get('month')); dateString = this.format(dateMoment); timestamp = +dateMoment; } this.onActiveDateChange(dateString, { dateMoment, timestamp }); } handleDecadeOnChange(dateString, { dateMoment, timestamp }, event) { const props = this.p; const currentViewMoment = props.viewMoment; if (currentViewMoment) { dateMoment.set('month', currentViewMoment.get('month')); dateString = this.format(dateMoment); timestamp = +dateMoment; } this.onChange(dateString, { dateMoment, timestamp }, event); } handleYearViewOnChange(dateString, { dateMoment, timestamp }, event) { const props = this.p; const currentMoment = props.moment; if (currentMoment) { dateMoment.set('year', currentMoment.get('year')); dateString = this.format(dateMoment); timestamp = +dateMoment; } this.onChange(dateString, { dateMoment, timestamp }, event); } onViewDateChange(dateString, { dateMoment, timestamp }) { return onViewDateChange.call(this, { dateMoment, timestamp }); } gotoViewDate({ dateMoment, timestamp }) { return gotoViewDate.call(this, { dateMoment, timestamp }); } onActiveDateChange(dateString, { dateMoment, timestamp }) { return onActiveDateChange.call(this, { dateMoment, timestamp }); } onChange(dateString, { dateMoment, timestamp }, event) { return onChange.call(this, { dateMoment, timestamp }, event); } } MonthDecadeView.defaultProps = { rootClassName: 'inovua-react-toolkit-calendar__month-decade-view', okOnEnter: true, footer: true, theme: 'default', navigation: true, focusYearView: false, focusDecadeView: true, dateFormat: 'YYYY-MM-DD', adjustDateStartOf: 'month', adjustMinDateStartOf: 'month', adjustMaxDateStartOf: 'month', }; MonthDecadeView.propTypes = { okOnEnter: PropTypes.bool, navigation: PropTypes.bool, focusYearView: PropTypes.bool, focusDecadeView: PropTypes.bool, footer: PropTypes.bool, minDate: PropTypes.oneOfType([ PropTypes.number, PropTypes.object, PropTypes.string, ]), maxDate: PropTypes.oneOfType([ PropTypes.number, PropTypes.object, PropTypes.string, ]), viewMoment: PropTypes.oneOfType([ PropTypes.number, PropTypes.object, PropTypes.string, ]), activeDate: PropTypes.oneOfType([ PropTypes.number, PropTypes.object, PropTypes.string, ]), date: PropTypes.oneOfType([ PropTypes.number, PropTypes.object, PropTypes.string, ]), defaultDate: PropTypes.oneOfType([ PropTypes.number, PropTypes.object, PropTypes.string, ]), defaultViewDate: PropTypes.oneOfType([ PropTypes.number, PropTypes.object, PropTypes.string, ]), dateFormat: PropTypes.string, moment: PropTypes.object, locale: PropTypes.string, theme: PropTypes.string, dateFormat: PropTypes.string, adjustDateStartOf: PropTypes.string, adjustMinDateStartOf: PropTypes.string, adjustMaxDateStartOf: PropTypes.string, cleanup: PropTypes.func, onCancelClick: PropTypes.func, onOkClick: PropTypes.func, onChange: PropTypes.func, };
the_stack
import * as pulumi from "@pulumi/pulumi"; import { input as inputs, output as outputs } from "../types"; import * as utilities from "../utilities"; /** * Entry Metadata. A Data Catalog Entry resource represents another resource in Google Cloud Platform * (such as a BigQuery dataset or a Pub/Sub topic) or outside of Google Cloud Platform. Clients can use * the linkedResource field in the Entry resource to refer to the original resource ID of the source system. * * An Entry resource contains resource details, such as its schema. An Entry can also be used to attach * flexible metadata, such as a Tag. * * To get more information about Entry, see: * * * [API documentation](https://cloud.google.com/data-catalog/docs/reference/rest/v1/projects.locations.entryGroups.entries) * * How-to Guides * * [Official Documentation](https://cloud.google.com/data-catalog/docs) * * ## Example Usage * ### Data Catalog Entry Basic * * ```typescript * import * as pulumi from "@pulumi/pulumi"; * import * as gcp from "@pulumi/gcp"; * * const entryGroup = new gcp.datacatalog.EntryGroup("entryGroup", {entryGroupId: "my_group"}); * const basicEntry = new gcp.datacatalog.Entry("basicEntry", { * entryGroup: entryGroup.id, * entryId: "my_entry", * userSpecifiedType: "my_custom_type", * userSpecifiedSystem: "SomethingExternal", * }); * ``` * ### Data Catalog Entry Fileset * * ```typescript * import * as pulumi from "@pulumi/pulumi"; * import * as gcp from "@pulumi/gcp"; * * const entryGroup = new gcp.datacatalog.EntryGroup("entryGroup", {entryGroupId: "my_group"}); * const basicEntry = new gcp.datacatalog.Entry("basicEntry", { * entryGroup: entryGroup.id, * entryId: "my_entry", * type: "FILESET", * gcsFilesetSpec: { * filePatterns: ["gs://fake_bucket/dir/*"], * }, * }); * ``` * ### Data Catalog Entry Full * * ```typescript * import * as pulumi from "@pulumi/pulumi"; * import * as gcp from "@pulumi/gcp"; * * const entryGroup = new gcp.datacatalog.EntryGroup("entryGroup", {entryGroupId: "my_group"}); * const basicEntry = new gcp.datacatalog.Entry("basicEntry", { * entryGroup: entryGroup.id, * entryId: "my_entry", * userSpecifiedType: "my_user_specified_type", * userSpecifiedSystem: "Something_custom", * linkedResource: "my/linked/resource", * displayName: "my custom type entry", * description: "a custom type entry for a user specified system", * schema: `{ * "columns": [ * { * "column": "first_name", * "description": "First name", * "mode": "REQUIRED", * "type": "STRING" * }, * { * "column": "last_name", * "description": "Last name", * "mode": "REQUIRED", * "type": "STRING" * }, * { * "column": "address", * "description": "Address", * "mode": "REPEATED", * "subcolumns": [ * { * "column": "city", * "description": "City", * "mode": "NULLABLE", * "type": "STRING" * }, * { * "column": "state", * "description": "State", * "mode": "NULLABLE", * "type": "STRING" * } * ], * "type": "RECORD" * } * ] * } * `, * }); * ``` * * ## Import * * Entry can be imported using any of these accepted formats * * ```sh * $ pulumi import gcp:datacatalog/entry:Entry default {{name}} * ``` */ export class Entry extends pulumi.CustomResource { /** * Get an existing Entry resource's state with the given name, ID, and optional extra * properties used to qualify the lookup. * * @param name The _unique_ name of the resulting resource. * @param id The _unique_ provider ID of the resource to lookup. * @param state Any extra arguments used during the lookup. * @param opts Optional settings to control the behavior of the CustomResource. */ public static get(name: string, id: pulumi.Input<pulumi.ID>, state?: EntryState, opts?: pulumi.CustomResourceOptions): Entry { return new Entry(name, <any>state, { ...opts, id: id }); } /** @internal */ public static readonly __pulumiType = 'gcp:datacatalog/entry:Entry'; /** * Returns true if the given object is an instance of Entry. This is designed to work even * when multiple copies of the Pulumi SDK have been loaded into the same process. */ public static isInstance(obj: any): obj is Entry { if (obj === undefined || obj === null) { return false; } return obj['__pulumiType'] === Entry.__pulumiType; } /** * Specification for a group of BigQuery tables with name pattern [prefix]YYYYMMDD. Context: * https://cloud.google.com/bigquery/docs/partitioned-tables#partitioning_versus_sharding. */ public /*out*/ readonly bigqueryDateShardedSpecs!: pulumi.Output<outputs.datacatalog.EntryBigqueryDateShardedSpec[]>; /** * Specification that applies to a BigQuery table. This is only valid on entries of type TABLE. */ public /*out*/ readonly bigqueryTableSpecs!: pulumi.Output<outputs.datacatalog.EntryBigqueryTableSpec[]>; /** * Entry description, which can consist of several sentences or paragraphs that describe entry contents. */ public readonly description!: pulumi.Output<string | undefined>; /** * Display information such as title and description. A short name to identify the entry, * for example, "Analytics Data - Jan 2011". */ public readonly displayName!: pulumi.Output<string | undefined>; /** * The name of the entry group this entry is in. */ public readonly entryGroup!: pulumi.Output<string>; /** * The id of the entry to create. */ public readonly entryId!: pulumi.Output<string>; /** * Specification that applies to a Cloud Storage fileset. This is only valid on entries of type FILESET. * Structure is documented below. */ public readonly gcsFilesetSpec!: pulumi.Output<outputs.datacatalog.EntryGcsFilesetSpec | undefined>; /** * This field indicates the entry's source system that Data Catalog integrates with, such as BigQuery or Pub/Sub. */ public /*out*/ readonly integratedSystem!: pulumi.Output<string>; /** * The resource this metadata entry refers to. * For Google Cloud Platform resources, linkedResource is the full name of the resource. * For example, the linkedResource for a table resource from BigQuery is: * //bigquery.googleapis.com/projects/projectId/datasets/datasetId/tables/tableId * Output only when Entry is of type in the EntryType enum. For entries with userSpecifiedType, * this field is optional and defaults to an empty string. */ public readonly linkedResource!: pulumi.Output<string>; /** * The Data Catalog resource name of the entry in URL format. Example: * projects/{project_id}/locations/{location}/entryGroups/{entryGroupId}/entries/{entryId}. Note that this Entry and its * child resources may not actually be stored in the location in this name. */ public /*out*/ readonly name!: pulumi.Output<string>; /** * Schema of the entry (e.g. BigQuery, GoogleSQL, Avro schema), as a json string. An entry might not have any schema * attached to it. See * https://cloud.google.com/data-catalog/docs/reference/rest/v1/projects.locations.entryGroups.entries#schema * for what fields this schema can contain. */ public readonly schema!: pulumi.Output<string | undefined>; /** * The type of the entry. Only used for Entries with types in the EntryType enum. * Currently, only FILESET enum value is allowed. All other entries created through Data Catalog must use userSpecifiedType. * Possible values are `FILESET`. */ public readonly type!: pulumi.Output<string | undefined>; /** * This field indicates the entry's source system that Data Catalog does not integrate with. * userSpecifiedSystem strings must begin with a letter or underscore and can only contain letters, numbers, * and underscores; are case insensitive; must be at least 1 character and at most 64 characters long. */ public readonly userSpecifiedSystem!: pulumi.Output<string | undefined>; /** * Entry type if it does not fit any of the input-allowed values listed in EntryType enum above. * When creating an entry, users should check the enum values first, if nothing matches the entry * to be created, then provide a custom value, for example "mySpecialType". * userSpecifiedType strings must begin with a letter or underscore and can only contain letters, * numbers, and underscores; are case insensitive; must be at least 1 character and at most 64 characters long. */ public readonly userSpecifiedType!: pulumi.Output<string | undefined>; /** * Create a Entry resource with the given unique name, arguments, and options. * * @param name The _unique_ name of the resource. * @param args The arguments to use to populate this resource's properties. * @param opts A bag of options that control this resource's behavior. */ constructor(name: string, args: EntryArgs, opts?: pulumi.CustomResourceOptions) constructor(name: string, argsOrState?: EntryArgs | EntryState, opts?: pulumi.CustomResourceOptions) { let inputs: pulumi.Inputs = {}; opts = opts || {}; if (opts.id) { const state = argsOrState as EntryState | undefined; inputs["bigqueryDateShardedSpecs"] = state ? state.bigqueryDateShardedSpecs : undefined; inputs["bigqueryTableSpecs"] = state ? state.bigqueryTableSpecs : undefined; inputs["description"] = state ? state.description : undefined; inputs["displayName"] = state ? state.displayName : undefined; inputs["entryGroup"] = state ? state.entryGroup : undefined; inputs["entryId"] = state ? state.entryId : undefined; inputs["gcsFilesetSpec"] = state ? state.gcsFilesetSpec : undefined; inputs["integratedSystem"] = state ? state.integratedSystem : undefined; inputs["linkedResource"] = state ? state.linkedResource : undefined; inputs["name"] = state ? state.name : undefined; inputs["schema"] = state ? state.schema : undefined; inputs["type"] = state ? state.type : undefined; inputs["userSpecifiedSystem"] = state ? state.userSpecifiedSystem : undefined; inputs["userSpecifiedType"] = state ? state.userSpecifiedType : undefined; } else { const args = argsOrState as EntryArgs | undefined; if ((!args || args.entryGroup === undefined) && !opts.urn) { throw new Error("Missing required property 'entryGroup'"); } if ((!args || args.entryId === undefined) && !opts.urn) { throw new Error("Missing required property 'entryId'"); } inputs["description"] = args ? args.description : undefined; inputs["displayName"] = args ? args.displayName : undefined; inputs["entryGroup"] = args ? args.entryGroup : undefined; inputs["entryId"] = args ? args.entryId : undefined; inputs["gcsFilesetSpec"] = args ? args.gcsFilesetSpec : undefined; inputs["linkedResource"] = args ? args.linkedResource : undefined; inputs["schema"] = args ? args.schema : undefined; inputs["type"] = args ? args.type : undefined; inputs["userSpecifiedSystem"] = args ? args.userSpecifiedSystem : undefined; inputs["userSpecifiedType"] = args ? args.userSpecifiedType : undefined; inputs["bigqueryDateShardedSpecs"] = undefined /*out*/; inputs["bigqueryTableSpecs"] = undefined /*out*/; inputs["integratedSystem"] = undefined /*out*/; inputs["name"] = undefined /*out*/; } if (!opts.version) { opts = pulumi.mergeOptions(opts, { version: utilities.getVersion()}); } super(Entry.__pulumiType, name, inputs, opts); } } /** * Input properties used for looking up and filtering Entry resources. */ export interface EntryState { /** * Specification for a group of BigQuery tables with name pattern [prefix]YYYYMMDD. Context: * https://cloud.google.com/bigquery/docs/partitioned-tables#partitioning_versus_sharding. */ bigqueryDateShardedSpecs?: pulumi.Input<pulumi.Input<inputs.datacatalog.EntryBigqueryDateShardedSpec>[]>; /** * Specification that applies to a BigQuery table. This is only valid on entries of type TABLE. */ bigqueryTableSpecs?: pulumi.Input<pulumi.Input<inputs.datacatalog.EntryBigqueryTableSpec>[]>; /** * Entry description, which can consist of several sentences or paragraphs that describe entry contents. */ description?: pulumi.Input<string>; /** * Display information such as title and description. A short name to identify the entry, * for example, "Analytics Data - Jan 2011". */ displayName?: pulumi.Input<string>; /** * The name of the entry group this entry is in. */ entryGroup?: pulumi.Input<string>; /** * The id of the entry to create. */ entryId?: pulumi.Input<string>; /** * Specification that applies to a Cloud Storage fileset. This is only valid on entries of type FILESET. * Structure is documented below. */ gcsFilesetSpec?: pulumi.Input<inputs.datacatalog.EntryGcsFilesetSpec>; /** * This field indicates the entry's source system that Data Catalog integrates with, such as BigQuery or Pub/Sub. */ integratedSystem?: pulumi.Input<string>; /** * The resource this metadata entry refers to. * For Google Cloud Platform resources, linkedResource is the full name of the resource. * For example, the linkedResource for a table resource from BigQuery is: * //bigquery.googleapis.com/projects/projectId/datasets/datasetId/tables/tableId * Output only when Entry is of type in the EntryType enum. For entries with userSpecifiedType, * this field is optional and defaults to an empty string. */ linkedResource?: pulumi.Input<string>; /** * The Data Catalog resource name of the entry in URL format. Example: * projects/{project_id}/locations/{location}/entryGroups/{entryGroupId}/entries/{entryId}. Note that this Entry and its * child resources may not actually be stored in the location in this name. */ name?: pulumi.Input<string>; /** * Schema of the entry (e.g. BigQuery, GoogleSQL, Avro schema), as a json string. An entry might not have any schema * attached to it. See * https://cloud.google.com/data-catalog/docs/reference/rest/v1/projects.locations.entryGroups.entries#schema * for what fields this schema can contain. */ schema?: pulumi.Input<string>; /** * The type of the entry. Only used for Entries with types in the EntryType enum. * Currently, only FILESET enum value is allowed. All other entries created through Data Catalog must use userSpecifiedType. * Possible values are `FILESET`. */ type?: pulumi.Input<string>; /** * This field indicates the entry's source system that Data Catalog does not integrate with. * userSpecifiedSystem strings must begin with a letter or underscore and can only contain letters, numbers, * and underscores; are case insensitive; must be at least 1 character and at most 64 characters long. */ userSpecifiedSystem?: pulumi.Input<string>; /** * Entry type if it does not fit any of the input-allowed values listed in EntryType enum above. * When creating an entry, users should check the enum values first, if nothing matches the entry * to be created, then provide a custom value, for example "mySpecialType". * userSpecifiedType strings must begin with a letter or underscore and can only contain letters, * numbers, and underscores; are case insensitive; must be at least 1 character and at most 64 characters long. */ userSpecifiedType?: pulumi.Input<string>; } /** * The set of arguments for constructing a Entry resource. */ export interface EntryArgs { /** * Entry description, which can consist of several sentences or paragraphs that describe entry contents. */ description?: pulumi.Input<string>; /** * Display information such as title and description. A short name to identify the entry, * for example, "Analytics Data - Jan 2011". */ displayName?: pulumi.Input<string>; /** * The name of the entry group this entry is in. */ entryGroup: pulumi.Input<string>; /** * The id of the entry to create. */ entryId: pulumi.Input<string>; /** * Specification that applies to a Cloud Storage fileset. This is only valid on entries of type FILESET. * Structure is documented below. */ gcsFilesetSpec?: pulumi.Input<inputs.datacatalog.EntryGcsFilesetSpec>; /** * The resource this metadata entry refers to. * For Google Cloud Platform resources, linkedResource is the full name of the resource. * For example, the linkedResource for a table resource from BigQuery is: * //bigquery.googleapis.com/projects/projectId/datasets/datasetId/tables/tableId * Output only when Entry is of type in the EntryType enum. For entries with userSpecifiedType, * this field is optional and defaults to an empty string. */ linkedResource?: pulumi.Input<string>; /** * Schema of the entry (e.g. BigQuery, GoogleSQL, Avro schema), as a json string. An entry might not have any schema * attached to it. See * https://cloud.google.com/data-catalog/docs/reference/rest/v1/projects.locations.entryGroups.entries#schema * for what fields this schema can contain. */ schema?: pulumi.Input<string>; /** * The type of the entry. Only used for Entries with types in the EntryType enum. * Currently, only FILESET enum value is allowed. All other entries created through Data Catalog must use userSpecifiedType. * Possible values are `FILESET`. */ type?: pulumi.Input<string>; /** * This field indicates the entry's source system that Data Catalog does not integrate with. * userSpecifiedSystem strings must begin with a letter or underscore and can only contain letters, numbers, * and underscores; are case insensitive; must be at least 1 character and at most 64 characters long. */ userSpecifiedSystem?: pulumi.Input<string>; /** * Entry type if it does not fit any of the input-allowed values listed in EntryType enum above. * When creating an entry, users should check the enum values first, if nothing matches the entry * to be created, then provide a custom value, for example "mySpecialType". * userSpecifiedType strings must begin with a letter or underscore and can only contain letters, * numbers, and underscores; are case insensitive; must be at least 1 character and at most 64 characters long. */ userSpecifiedType?: pulumi.Input<string>; }
the_stack
import { assert } from 'chai'; import { addStage, Konva, createCanvas, compareLayerAndCanvas, compareLayers, } from './test-utils'; describe('Line', function () { // ====================================================== it('add line', function () { var stage = addStage(); var layer = new Konva.Layer(); var line = new Konva.Line({ stroke: 'blue', strokeWidth: 20, lineCap: 'round', lineJoin: 'round', draggable: true, tension: 0, }); layer.add(line); stage.add(layer); line.points([1, 2, 3, 4]); assert.equal(line.points()[0], 1); line.points([5, 6, 7, 8]); assert.equal(line.points()[0], 5); line.points([73, 160, 340, 23, 340, 80]); assert.equal(line.points()[0], 73); assert.equal(line.getClassName(), 'Line'); layer.draw(); }); // ====================================================== it('test default ponts array for two lines', function () { var stage = addStage(); var layer = new Konva.Layer(); var line = new Konva.Line({ stroke: 'blue', strokeWidth: 20, lineCap: 'round', lineJoin: 'round', draggable: true, }); var redLine = new Konva.Line({ x: 50, stroke: 'red', strokeWidth: 20, lineCap: 'round', lineJoin: 'round', draggable: true, }); line.points([0, 1, 2, 3]); redLine.points([4, 5, 6, 7]); layer.add(line).add(redLine); stage.add(layer); assert.equal(line.points()[0], 0); assert.equal(redLine.points()[0], 4); }); // ====================================================== it('add dashed line', function () { var stage = addStage(); var layer = new Konva.Layer(); /* var points = [{ x: 73, y: 160 }, { x: 340, y: 23 }, { x: 500, y: 109 }, { x: 500, y: 180 }]; */ var line = new Konva.Line({ points: [73, 160, 340, 23, 500, 109, 500, 180], stroke: 'blue', strokeWidth: 10, lineCap: 'round', lineJoin: 'round', draggable: true, dash: [30, 10, 0, 10, 10, 20], shadowColor: '#aaa', shadowBlur: 10, shadowOffset: { x: 20, y: 20, }, //opacity: 0.2 }); layer.add(line); stage.add(layer); assert.equal(line.dash().length, 6); line.dash([10, 10]); assert.equal(line.dash().length, 2); assert.equal(line.points().length, 8); }); // ====================================================== it('add line with shadow', function () { const oldRatio = Konva.pixelRatio; Konva.pixelRatio = 1; var stage = addStage(); var layer = new Konva.Layer(); var line = new Konva.Line({ points: [73, 160, 340, 23], stroke: 'blue', strokeWidth: 20, lineCap: 'round', lineJoin: 'round', shadowColor: 'black', shadowBlur: 20, shadowOffset: { x: 10, y: 10, }, shadowOpacity: 0.5, draggable: true, }); layer.add(line); stage.add(layer); var canvas = createCanvas(); var context = canvas.getContext('2d'); context.save(); context.lineJoin = 'round'; context.lineCap = 'round'; context.lineWidth = 20; context.strokeStyle = 'blue'; context.shadowColor = 'rgba(0,0,0,0.5)'; context.shadowBlur = 20; context.shadowOffsetX = 10; context.shadowOffsetY = 10; context.moveTo(73, 160); context.lineTo(340, 23); context.stroke(); // context.fill(); context.restore(); Konva.pixelRatio = oldRatio; compareLayerAndCanvas(layer, canvas, 50); var trace = layer.getContext().getTrace(); assert.equal( trace, 'clearRect(0,0,578,200);save();lineJoin=round;transform(1,0,0,1,0,0);shadowColor=rgba(0,0,0,0.5);shadowBlur=20;shadowOffsetX=10;shadowOffsetY=10;beginPath();moveTo(73,160);lineTo(340,23);lineCap=round;lineWidth=20;strokeStyle=blue;stroke();restore();' ); }); it('line hit test with strokeScaleEnabled = false', function () { var stage = addStage(); var scale = 0.1; var layer = new Konva.Layer(); var group = new Konva.Group({ scale: { x: scale, y: scale, }, }); var line1 = new Konva.Line({ points: [0, 0, 300, 0], stroke: 'red', strokeScaleEnabled: false, strokeWidth: 10, y: 0, }); group.add(line1); var line2 = new Konva.Line({ points: [0, 0, 300, 0], stroke: 'green', strokeWidth: 40 / scale, y: 60 / scale, }); group.add(line2); layer.add(group); stage.add(layer); var shape = layer.getIntersection({ x: 10, y: 60, }); assert.equal(shape, line2, 'second line detected'); shape = layer.getIntersection({ x: 10, y: 4, }); assert.equal(shape, line1, 'first line detected'); }); it('line get size', function () { var stage = addStage(); var layer = new Konva.Layer(); var line = new Konva.Line({ points: [73, 160, 340, 23, 500, 109, 500, 180], stroke: 'blue', strokeWidth: 10, }); layer.add(line); stage.add(layer); assert.deepEqual(line.size(), { width: 500 - 73, height: 180 - 23, }); }); it('getSelfRect', function () { var stage = addStage(); var layer = new Konva.Layer(); var blob = new Konva.Line({ x: 50, y: 50, points: [-25, 50, 250, -30, 150, 50, 250, 110], stroke: 'blue', strokeWidth: 10, draggable: true, fill: '#aaf', closed: true, }); layer.add(blob); stage.add(layer); assert.deepEqual(blob.getSelfRect(), { x: -25, y: -30, width: 275, height: 140, }); }); it('getClientRect', function () { var stage = addStage(); var layer = new Konva.Layer(); var poly = new Konva.Line({ x: 0, y: 0, points: [-100, 0, +100, 0, +100, 100, -100, 100], closed: true, fill: '#0f0', }); stage.position({ x: 150, y: 50, }); layer.add(poly); stage.add(layer); var rect = layer.getClientRect({ relativeTo: stage as any }); assert.deepEqual(rect, { x: -100, y: 0, width: 200, height: 100, }); }); it('getClientRect with tension', function () { var stage = addStage(); stage.draggable(true); var layer = new Konva.Layer(); var line = new Konva.Line({ x: 0, y: 0, points: [75, 75, 100, 200, 300, 140], tension: 0.5, stroke: '#0f0', }); layer.add(line); var client = line.getClientRect(); var rect = new Konva.Rect(Konva.Util._assign({ stroke: 'red' }, client)); layer.add(rect); stage.add(layer); assert.equal(Math.round(client.x), 56, 'check x'); assert.equal(Math.round(client.y), 74, 'check y'); assert.equal(Math.round(client.width), 245, 'check width'); assert.equal(Math.round(client.height), 147, 'check height'); }); it('getClientRect with tension 2', function () { var stage = addStage(); stage.draggable(true); var layer = new Konva.Layer(); var line = new Konva.Line({ x: 0, y: 0, points: [ 494.39880507841673, 795.3696788648244, 494.49880507841675, 795.4696788648245, 494.39880507841673, 796.8633308439133, 489.9178491411501, 798.3569828230022, 480.95593726661684, 802.8379387602688, 467.513069454817, 810.3061986557132, 451.0828976848394, 820.7617625093353, 433.15907393577294, 832.7109783420462, 415.2352501867065, 846.1538461538461, 398.8050784167289, 859.596713965646, 383.8685586258402, 871.545929798357, 374.90664675130694, 880.5078416728902, 371.9193427931292, 883.4951456310679, 371.9193427931292, 883.4951456310679, 371.9193427931292, 883.4951456310679, 376.40029873039583, 882.0014936519791, 395.8177744585511, 876.0268857356235, 443.6146377893951, 856.6094100074682, 507.84167289021656, 838.6855862584017, 551.1575802837939, 825.2427184466019, 624.3465272591486, 807.3188946975355, 696.0418222554144, 789.395070948469, 758.7752053771471, 777.445855115758, 802.0911127707244, 772.9648991784914, 820.0149365197909, 771.4712471994025, 821.5085884988797, 771.4712471994025, 820.0149365197909, 775.9522031366691, 799.1038088125466, 790.8887229275579, 743.8386855862584, 825.2427184466019, 652.7259148618372, 871.545929798357, 542.1956684092606, 926.8110530246452, 455.563853622106, 977.5952203136669, 412.24794622852875, 1010.455563853622, 397.31142643764, 1026.8857356235997, 397.31142643764, 1032.8603435399552, 400.29873039581776, 1038.8349514563106, 415.2352501867065, 1043.3159073935774, 463.0321135175504, 1043.3159073935774, 563.1067961165048, 1040.3286034353996, 696.0418222554144, 1032.8603435399552, 787.1545929798357, 1026.8857356235997, 921.5832710978342, 1017.9238237490664, 1018.6706497386109, 1013.4428678117998, 1069.4548170276325, 1013.4428678117998, 1076.923076923077, 1013.4428678117998, 1075.4294249439881, 1014.9365197908887, 1051.530993278566, 1026.8857356235997, 979.8356982823002, 1053.7714712471993, 888.722927557879, 1079.1635548917102, 761.7625093353248, 1116.504854368932, 672.1433905899925, 1150.858849887976, 628.8274831964152, 1171.7699775952203, 615.3846153846154, 1180.7318894697535, 615.3846153846154, 1182.2255414488425, 618.3719193427931, 1183.7191934279313, 633.3084391336819, 1182.2255414488425, 687.0799103808812, 1171.7699775952203, 775.2053771471248, 1150.858849887976, 902.1657953696788, 1116.504854368932, 990.2912621359224, 1091.1127707244211, 1082.8976848394325, 1062.7333831217327, 1133.681852128454, 1046.303211351755, 1144.1374159820762, 1041.8222554144884, 1144.1374159820762, 1041.8222554144884, 1141.1501120238984, 1041.8222554144884, 1117.2516803584765, 1043.3159073935774, 1082.8976848394325, 1046.303211351755, 1008.2150858849888, 1062.7333831217327, 917.1023151605675, 1092.6064227035101, 861.8371919342793, 1117.9985063480208, 814.0403286034353, 1152.352501867065, 794.62285287528, 1176.250933532487, 790.1418969380135, 1189.6938013442868, 793.1292008961912, 1198.65571321882, 802.0911127707244, 1206.1239731142643, 831.9641523525019, 1216.5795369678865, 903.6594473487677, 1225.5414488424196, 1014.1896938013442, 1228.5287528005974, 1148.6183719193427, 1228.5287528005974, 1272.591486183719, 1225.5414488424196, 1314.4137415982075, 1225.5414488424196, 1326.3629574309186, 1225.5414488424196, 1326.3629574309186, 1225.5414488424196, 1314.4137415982075, 1228.5287528005974, 1272.591486183719, 1237.4906646751306, 1197.9088872292755, 1247.9462285287527, 1105.3024645257656, 1270.3510082150858, 1048.5436893203882, 1286.7811799850635, 1024.6452576549664, 1295.7430918595967, 1006.7214339058999, 1306.1986557132188, 1000.7468259895444, 1313.6669156086632, 1000.7468259895444, 1315.160567587752, 1003.7341299477222, 1316.6542195668408, 1015.6833457804331, 1319.6415235250186, 1050.0373412994772, 1321.1351755041076, 1103.8088125466766, 1321.1351755041076, 1169.529499626587, 1316.6542195668408, 1220.3136669156086, 1310.6796116504854, 1248.6930545182972, 1307.6923076923076, 1253.1740104555638, 1307.6923076923076, 1253.1740104555638, 1307.6923076923076, 1253.1740104555638, 1307.6923076923076, 1248.6930545182972, 1309.1859596713964, 1229.275578790142, 1312.1732636295742, 1199.4025392083645, 1319.6415235250186, 1172.5168035847648, 1330.0970873786407, 1154.5929798356983, 1342.0463032113516, 1144.1374159820762, 1353.9955190440626, 1139.6564600448096, 1361.463778939507, 1138.1628080657206, 1364.4510828976847, 1138.1628080657206, 1365.9447348767737, 1138.1628080657206, 1365.9447348767737, ], tension: 0.5, stroke: '#0f0', }); layer.add(line); var client = line.getClientRect(); var rect = new Konva.Rect(Konva.Util._assign({ stroke: 'red' }, client)); layer.add(rect); stage.add(layer); assert.equal(Math.round(client.x), 371, 'check x'); assert.equal(Math.round(client.y), 770, 'check y'); assert.equal(Math.round(client.width), 956, 'check width'); assert.equal(Math.round(client.height), 597, 'check height'); }); it('getClientRect with low number of points', function () { var stage = addStage(); var layer = new Konva.Layer(); stage.add(layer); var line = new Konva.Line({ x: 0, y: 0, points: [], tension: 0.5, stroke: '#0f0', }); layer.add(line); layer.draw(); var client = line.getClientRect(); assert.equal(client.x, -1, 'check x'); assert.equal(client.y, -1, 'check y'); assert.equal(client.width, 2, 'check width'); assert.equal(client.height, 2, 'check height'); line.points([10, 10]); client = line.getClientRect(); assert.equal(client.x, 9, 'check x'); assert.equal(client.y, 9, 'check y'); assert.equal(client.width, 2, 'check width'); assert.equal(client.height, 2, 'check height'); }); it('line caching', function () { var stage = addStage(); var layer = new Konva.Layer(); var blob = new Konva.Line({ x: 50, y: 50, points: [-25, 50, 250, -30, 150, 50, 250, 110], stroke: 'black', strokeWidth: 10, draggable: true, closed: true, }); layer.add(blob); var layer2 = layer.clone(); blob.cache({ offset: 30, }); stage.add(layer); stage.add(layer2); layer2.hide(); compareLayers(layer, layer2, 150); }); it('updating points with old mutable array should trigger recalculations', function () { var stage = addStage(); var layer = new Konva.Layer(); var points = [-25, 50, 250, -30, 150, 50]; var blob = new Konva.Line({ x: 50, y: 50, points: points, stroke: 'blue', strokeWidth: 10, draggable: true, closed: true, tension: 1, }); var tensionPoints = blob.getTensionPoints(); points.push(250, 100); blob.points(points); layer.add(blob); stage.add(layer); assert.equal( tensionPoints === blob.getTensionPoints(), false, 'calculated points should change' ); }); it('hit test for scaled line', function () { var stage = addStage(); var scale = 42; stage.scaleX(scale); stage.scaleY(scale); var layer = new Konva.Layer(); stage.add(layer); var points = [1, 1, 7, 2, 8, 7, 2, 6]; var line = new Konva.Line({ points: points.map(function (v) { return (v * 20) / scale; }), closed: true, fill: 'green', draggable: true, }); layer.add(line); layer.draw(); assert.equal(line.hasHitStroke(), false); assert.equal(layer.getIntersection({ x: 1, y: 1 }), null); layer.toggleHitCanvas(); }); it('getClientRect with scaling', function () { var stage = addStage(); var scale = 42; stage.scaleX(scale); stage.scaleY(scale); var layer = new Konva.Layer(); stage.add(layer); var points = [1, 1, 7, 2, 8, 7, 2, 6]; var line = new Konva.Line({ points: points.map(function (v) { return (v * 20) / scale; }), closed: true, fill: 'green', draggable: true, }); layer.add(line); layer.draw(); var client = line.getClientRect(); assert.equal(client.x, 20, 'check x'); assert.equal(client.y, 20, 'check y'); assert.equal(client.width, 140, 'check width'); assert.equal(client.height, 120, 'check height'); }); });
the_stack
import { IElementAppliable } from "./tags"; export declare class CssProp implements IElementAppliable { readonly key: string; readonly value: string | 0; readonly name: string; constructor(key: string, value: string | 0); /** * Set the attribute value on an HTMLElement * @param elem - the element on which to set the attribute. */ applyToElement(elem: HTMLElement): void; } export declare class CssPropSet implements IElementAppliable { private rest; constructor(...rest: (CssProp | CssPropSet)[]); /** * Set the attribute value on an HTMLElement * @param style - the element on which to set the attribute. */ applyToElement(elem: HTMLElement): void; } /** * Combine style properties. **/ export declare function styles(...rest: (CssProp | CssPropSet)[]): CssPropSet; declare type globalValues = "inherit" | "initial" | "revert" | "unset"; export declare function alignContent(v: string): CssProp; export declare function alignItems(v: string): CssProp; export declare function alignSelf(v: string): CssProp; export declare function alignmentBaseline(v: string): CssProp; export declare function all(v: string): CssProp; export declare function animation(v: string): CssProp; export declare function animationDelay(v: string): CssProp; export declare function animationDirection(v: string): CssProp; export declare function animationDuration(v: string): CssProp; export declare function animationFillMode(v: string): CssProp; export declare function animationIterationCount(v: string): CssProp; export declare function animationName(v: string): CssProp; export declare function animationPlayState(v: string): CssProp; export declare function animationTimingFunction(v: string): CssProp; export declare function appearance(v: string): CssProp; export declare function backdropFilter(v: string): CssProp; export declare function backfaceVisibility(v: string): CssProp; export declare function background(v: string): CssProp; export declare function backgroundAttachment(v: string): CssProp; export declare function backgroundBlendMode(v: string): CssProp; export declare function backgroundClip(v: string): CssProp; export declare function backgroundColor(v: string): CssProp; export declare function backgroundImage(v: string): CssProp; export declare function backgroundOrigin(v: string): CssProp; export declare function backgroundPosition(v: string): CssProp; export declare function backgroundPositionX(v: string): CssProp; export declare function backgroundPositionY(v: string): CssProp; export declare function backgroundRepeat(v: string): CssProp; export declare function backgroundRepeatX(v: string): CssProp; export declare function backgroundRepeatY(v: string): CssProp; export declare function backgroundSize(v: string): CssProp; export declare function baselineShift(v: string): CssProp; export declare function blockSize(v: string): CssProp; export declare function border(v: string | 0): CssProp; export declare function borderBlockEnd(v: string): CssProp; export declare function borderBlockEndColor(v: string): CssProp; export declare function borderBlockEndStyle(v: string): CssProp; export declare function borderBlockEndWidth(v: string): CssProp; export declare function borderBlockStart(v: string): CssProp; export declare function borderBlockStartColor(v: string): CssProp; export declare function borderBlockStartStyle(v: string): CssProp; export declare function borderBlockStartWidth(v: string): CssProp; export declare function borderBottom(v: string): CssProp; export declare function borderBottomColor(v: string): CssProp; export declare function borderBottomLeftRadius(v: string): CssProp; export declare function borderBottomRightRadius(v: string): CssProp; export declare function borderBottomStyle(v: string): CssProp; export declare function borderBottomWidth(v: string): CssProp; export declare function borderCollapse(v: string): CssProp; export declare function borderColor(v: string): CssProp; export declare function borderImage(v: string): CssProp; export declare function borderImageOutset(v: string): CssProp; export declare function borderImageRepeat(v: string): CssProp; export declare function borderImageSlice(v: string): CssProp; export declare function borderImageSource(v: string): CssProp; export declare function borderImageWidth(v: string): CssProp; export declare function borderInlineEnd(v: string): CssProp; export declare function borderInlineEndColor(v: string): CssProp; export declare function borderInlineEndStyle(v: string): CssProp; export declare function borderInlineEndWidth(v: string): CssProp; export declare function borderInlineStart(v: string): CssProp; export declare function borderInlineStartColor(v: string): CssProp; export declare function borderInlineStartStyle(v: string): CssProp; export declare function borderInlineStartWidth(v: string): CssProp; export declare function borderLeft(v: string): CssProp; export declare function borderLeftColor(v: string): CssProp; export declare function borderLeftStyle(v: string): CssProp; export declare function borderLeftWidth(v: string): CssProp; export declare function borderRadius(v: string): CssProp; export declare function borderRight(v: string): CssProp; export declare function borderRightColor(v: string): CssProp; export declare function borderRightStyle(v: string): CssProp; export declare function borderRightWidth(v: string): CssProp; export declare function borderSpacing(v: string): CssProp; export declare function borderStyle(v: string): CssProp; export declare function borderTop(v: string): CssProp; export declare function borderTopColor(v: string): CssProp; export declare function borderTopLeftRadius(v: string): CssProp; export declare function borderTopRightRadius(v: string): CssProp; export declare function borderTopStyle(v: string): CssProp; export declare function borderTopWidth(v: string): CssProp; export declare function borderWidth(v: string | 0): CssProp; export declare function bottom(v: string | 0): CssProp; export declare function boxShadow(v: string): CssProp; export declare function boxSizing(v: string): CssProp; export declare function breakAfter(v: string): CssProp; export declare function breakBefore(v: string): CssProp; export declare function breakInside(v: string): CssProp; export declare function bufferedRendering(v: string): CssProp; export declare function captionSide(v: string): CssProp; export declare function caretColor(v: string): CssProp; export declare function clear(v: string): CssProp; export declare function clip(v: string): CssProp; export declare function clipPath(v: string): CssProp; export declare function clipRule(v: string): CssProp; export declare function color(v: string): CssProp; export declare function colorInterpolation(v: string): CssProp; export declare function colorInterpolationFilters(v: string): CssProp; export declare function colorRendering(v: string): CssProp; export declare function colorScheme(v: string): CssProp; export declare function columnCount(v: string): CssProp; export declare function columnFill(v: string): CssProp; export declare function columnGap(v: string): CssProp; export declare function columnRule(v: string): CssProp; export declare function columnRuleColor(v: string): CssProp; export declare function columnRuleStyle(v: string): CssProp; export declare function columnRuleWidth(v: string): CssProp; export declare function columnSpan(v: string): CssProp; export declare function columnWidth(v: string): CssProp; export declare function columns(v: string): CssProp; export declare function contain(v: string): CssProp; export declare function containIntrinsicSize(v: string): CssProp; export declare function counterIncrement(v: string): CssProp; export declare function counterReset(v: string): CssProp; export declare function cursor(v: string): CssProp; export declare function cx(v: string): CssProp; export declare function cy(v: string): CssProp; export declare function d(v: string): CssProp; export declare function direction(v: string): CssProp; export declare function display(v: string): CssProp; export declare function dominantBaseline(v: string): CssProp; export declare function emptyCells(v: string): CssProp; export declare function fill(v: string): CssProp; export declare function fillOpacity(v: string): CssProp; export declare function fillRule(v: string): CssProp; export declare function filter(v: string): CssProp; export declare function flex(v: string): CssProp; export declare function flexBasis(v: string): CssProp; export declare function flexDirection(v: string): CssProp; export declare function flexFlow(v: string): CssProp; export declare function flexGrow(v: string): CssProp; export declare function flexShrink(v: string): CssProp; export declare function flexWrap(v: string): CssProp; export declare function float(v: string): CssProp; export declare function floodColor(v: string): CssProp; export declare function floodOpacity(v: string): CssProp; export declare function font(v: string): CssProp; export declare function fontDisplay(v: string): CssProp; export declare function fontFamily(v: string): CssProp; export declare function fontFeatureSettings(v: string): CssProp; export declare function fontKerning(v: string): CssProp; export declare function fontOpticalSizing(v: string): CssProp; export declare function fontSize(v: string): CssProp; export declare function fontStretch(v: string): CssProp; export declare function fontStyle(v: string): CssProp; export declare function fontVariant(v: string): CssProp; export declare function fontVariantCaps(v: string): CssProp; export declare function fontVariantEastAsian(v: string): CssProp; export declare function fontVariantLigatures(v: string): CssProp; export declare function fontVariantNumeric(v: string): CssProp; export declare function fontVariationSettings(v: string): CssProp; export declare function fontWeight(v: string): CssProp; export declare function forcedColorAdjust(v: string): CssProp; export declare function gap(v: string): CssProp; export declare function grid(v: string): CssProp; export declare function gridArea(v: string): CssProp; export declare function gridAutoColumns(v: string): CssProp; declare type gridAutoFlowType = "row" | "column" | "dense" | "row dense" | "column dense" | globalValues; export declare function gridAutoFlow(v: gridAutoFlowType): CssProp; export declare function gridAutoRows(v: string): CssProp; export declare function gridColumn(v: string): CssProp; export declare function gridColumnEnd(v: string): CssProp; export declare function gridColumnGap(v: string): CssProp; export declare function gridColumnStart(v: string): CssProp; export declare function gridGap(v: string): CssProp; export declare function gridRow(v: string): CssProp; export declare function gridRowEnd(v: string): CssProp; export declare function gridRowGap(v: string): CssProp; export declare function gridRowStart(v: string): CssProp; export declare function gridTemplate(v: string): CssProp; export declare function gridTemplateAreas(v: string): CssProp; export declare function gridTemplateColumns(v: string): CssProp; export declare function gridTemplateRows(v: string): CssProp; export declare function height(v: string | 0): CssProp; export declare function hyphens(v: string): CssProp; export declare function imageOrientation(v: string): CssProp; export declare function imageRendering(v: string): CssProp; export declare function inlineSize(v: string): CssProp; export declare function isolation(v: string): CssProp; export declare function justifyContent(v: string): CssProp; export declare function justifyItems(v: string): CssProp; export declare function justifySelf(v: string): CssProp; export declare function left(v: string | 0): CssProp; export declare function letterSpacing(v: string): CssProp; export declare function lightingColor(v: string): CssProp; export declare function lineBreak(v: string): CssProp; export declare function lineHeight(v: string): CssProp; export declare function listStyle(v: string): CssProp; export declare function listStyleImage(v: string): CssProp; export declare function listStylePosition(v: string): CssProp; export declare function listStyleType(v: string): CssProp; export declare function margin(v: string | 0): CssProp; export declare function marginBlockEnd(v: string): CssProp; export declare function marginBlockStart(v: string): CssProp; export declare function marginBottom(v: string | 0): CssProp; export declare function marginInlineEnd(v: string): CssProp; export declare function marginInlineStart(v: string): CssProp; export declare function marginLeft(v: string | 0): CssProp; export declare function marginRight(v: string | 0): CssProp; export declare function marginTop(v: string | 0): CssProp; export declare function marker(v: string): CssProp; export declare function markerEnd(v: string): CssProp; export declare function markerMid(v: string): CssProp; export declare function markerStart(v: string): CssProp; export declare function mask(v: string): CssProp; export declare function maskType(v: string): CssProp; export declare function maxBlockSize(v: string): CssProp; export declare function maxHeight(v: string | 0): CssProp; export declare function maxInlineSize(v: string): CssProp; export declare function maxWidth(v: string | 0): CssProp; export declare function maxZoom(v: string): CssProp; export declare function minBlockSize(v: string): CssProp; export declare function minHeight(v: string | 0): CssProp; export declare function minInlineSize(v: string): CssProp; export declare function minWidth(v: string | 0): CssProp; export declare function minZoom(v: string): CssProp; export declare function mixBlendMode(v: string): CssProp; export declare function objectFit(v: string): CssProp; export declare function objectPosition(v: string): CssProp; export declare function offset(v: string): CssProp; export declare function offsetDistance(v: string): CssProp; export declare function offsetPath(v: string): CssProp; export declare function offsetRotate(v: string): CssProp; export declare function opacity(v: string): CssProp; export declare function order(v: string): CssProp; export declare function orientation(v: string): CssProp; export declare function orphans(v: string): CssProp; export declare function outline(v: string): CssProp; export declare function outlineColor(v: string): CssProp; export declare function outlineOffset(v: string): CssProp; export declare function outlineStyle(v: string): CssProp; export declare function outlineWidth(v: string | 0): CssProp; export declare function overflow(v: string): CssProp; export declare function overflowAnchor(v: string): CssProp; export declare function overflowWrap(v: string): CssProp; export declare function overflowX(v: string): CssProp; export declare function overflowY(v: string): CssProp; export declare function overscrollBehavior(v: string): CssProp; export declare function overscrollBehaviorBlock(v: string): CssProp; export declare function overscrollBehaviorInline(v: string): CssProp; export declare function overscrollBehaviorX(v: string): CssProp; export declare function overscrollBehaviorY(v: string): CssProp; export declare function padding(v: string | 0): CssProp; export declare function paddingBlockEnd(v: string): CssProp; export declare function paddingBlockStart(v: string): CssProp; export declare function paddingBottom(v: string | 0): CssProp; export declare function paddingInlineEnd(v: string): CssProp; export declare function paddingInlineStart(v: string): CssProp; export declare function paddingLeft(v: string | 0): CssProp; export declare function paddingRight(v: string | 0): CssProp; export declare function paddingTop(v: string | 0): CssProp; export declare function pageBreakAfter(v: string): CssProp; export declare function pageBreakBefore(v: string): CssProp; export declare function pageBreakInside(v: string): CssProp; export declare function paintOrder(v: string): CssProp; export declare function perspective(v: string): CssProp; export declare function perspectiveOrigin(v: string): CssProp; export declare function placeContent(v: string): CssProp; export declare function placeItems(v: string): CssProp; export declare function placeSelf(v: string): CssProp; export declare function pointerEvents(v: string): CssProp; export declare function position(v: string): CssProp; export declare function quotes(v: string): CssProp; export declare function r(v: string): CssProp; export declare function resize(v: string): CssProp; export declare function right(v: string | 0): CssProp; export declare function rowGap(v: string | 0): CssProp; export declare function rubyPosition(v: string): CssProp; export declare function rx(v: string): CssProp; export declare function ry(v: string): CssProp; export declare function scrollBehavior(v: string): CssProp; export declare function scrollMargin(v: string | 0): CssProp; export declare function scrollMarginBlock(v: string): CssProp; export declare function scrollMarginBlockEnd(v: string): CssProp; export declare function scrollMarginBlockStart(v: string): CssProp; export declare function scrollMarginBottom(v: string | 0): CssProp; export declare function scrollMarginInline(v: string): CssProp; export declare function scrollMarginInlineEnd(v: string): CssProp; export declare function scrollMarginInlineStart(v: string): CssProp; export declare function scrollMarginLeft(v: string | 0): CssProp; export declare function scrollMarginRight(v: string | 0): CssProp; export declare function scrollMarginTop(v: string | 0): CssProp; export declare function scrollPadding(v: string | 0): CssProp; export declare function scrollPaddingBlock(v: string): CssProp; export declare function scrollPaddingBlockEnd(v: string): CssProp; export declare function scrollPaddingBlockStart(v: string): CssProp; export declare function scrollPaddingBottom(v: string | 0): CssProp; export declare function scrollPaddingInline(v: string): CssProp; export declare function scrollPaddingInlineEnd(v: string): CssProp; export declare function scrollPaddingInlineStart(v: string): CssProp; export declare function scrollPaddingLeft(v: string | 0): CssProp; export declare function scrollPaddingRight(v: string | 0): CssProp; export declare function scrollPaddingTop(v: string | 0): CssProp; export declare function scrollSnapAlign(v: string): CssProp; export declare function scrollSnapStop(v: string): CssProp; export declare function scrollSnapType(v: string): CssProp; export declare function shapeImageThreshold(v: string): CssProp; export declare function shapeMargin(v: string): CssProp; export declare function shapeOutside(v: string): CssProp; export declare function shapeRendering(v: string): CssProp; export declare function speak(v: string): CssProp; export declare function stopColor(v: string): CssProp; export declare function stopOpacity(v: string): CssProp; export declare function stroke(v: string): CssProp; export declare function strokeDasharray(v: string): CssProp; export declare function strokeDashoffset(v: string): CssProp; export declare function strokeLinecap(v: string): CssProp; export declare function strokeLinejoin(v: string): CssProp; export declare function strokeMiterlimit(v: string): CssProp; export declare function strokeOpacity(v: string): CssProp; export declare function strokeWidth(v: string | 0): CssProp; export declare function tabSize(v: string): CssProp; export declare function tableLayout(v: string): CssProp; export declare function textAlign(v: string): CssProp; export declare function textAlignLast(v: string): CssProp; export declare function textAnchor(v: string): CssProp; export declare function textCombineUpright(v: string): CssProp; export declare function textDecoration(v: string): CssProp; export declare function textDecorationColor(v: string): CssProp; export declare function textDecorationLine(v: string): CssProp; export declare function textDecorationSkipInk(v: string): CssProp; export declare function textDecorationStyle(v: string): CssProp; export declare function textIndent(v: string): CssProp; export declare function textOrientation(v: string): CssProp; export declare function textOverflow(v: string): CssProp; export declare function textRendering(v: string): CssProp; export declare function textShadow(v: string): CssProp; export declare function textSizeAdjust(v: string): CssProp; export declare function textTransform(v: string): CssProp; export declare function textUnderlinePosition(v: string): CssProp; export declare function top(v: string | 0): CssProp; export declare function touchAction(v: string): CssProp; export declare function transform(v: string): CssProp; export declare function transformBox(v: string): CssProp; export declare function transformOrigin(v: string): CssProp; export declare function transformStyle(v: string): CssProp; export declare function transition(v: string): CssProp; export declare function transitionDelay(v: string | 0): CssProp; export declare function transitionDuration(v: string | 0): CssProp; export declare function transitionProperty(v: string): CssProp; export declare function transitionTimingFunction(v: string): CssProp; export declare function unicodeBidi(v: string): CssProp; export declare function unicodeRange(v: string): CssProp; export declare function userSelect(v: string): CssProp; export declare function userZoom(v: string): CssProp; export declare function vectorEffect(v: string): CssProp; export declare function verticalAlign(v: string): CssProp; export declare function visibility(v: string): CssProp; export declare function whiteSpace(v: string): CssProp; export declare function widows(v: string): CssProp; export declare function width(v: string | 0): CssProp; export declare function willChange(v: string): CssProp; export declare function wordBreak(v: string): CssProp; export declare function wordSpacing(v: string): CssProp; export declare function wordWrap(v: string): CssProp; export declare function writingMode(v: string): CssProp; export declare function x(v: string | 0): CssProp; export declare function y(v: string | 0): CssProp; export declare function zIndex(v: number): CssProp; export declare function zoom(v: number): CssProp; /** * A selection of fonts for preferred monospace rendering. **/ export declare function getMonospaceFonts(): string; /** * A selection of fonts for preferred monospace rendering. **/ export declare function getMonospaceFamily(): CssProp; /** * A selection of fonts that should match whatever the user's operating system normally uses. **/ export declare function getSystemFonts(): string; /** * A selection of fonts that should match whatever the user's operating system normally uses. **/ export declare function getSystemFamily(): CssProp; /** * A selection of serif fonts. **/ export declare function getSerifFonts(): string; export declare function getSerifFamily(): CssProp; export declare class CSSInJSRule { private selector; private props; constructor(selector: string, props: CssProp[]); apply(sheet: CSSStyleSheet): void; } export declare function rule(selector: string, ...props: CssProp[]): CSSInJSRule; export {};
the_stack
import * as React from 'react'; import styles from './KanbanComponent.module.scss'; import bucketstyles from './KanbanBucket.module.scss'; import * as strings from 'KanbanBoardStrings'; import { IKanbanTask, KanbanTaskMamagedPropertyType } from './IKanbanTask'; import { IKanbanBoardTaskSettings } from './IKanbanBoardTaskSettings'; import { IKanbanBoardTaskActions } from './IKanbanBoardTaskActions'; import { IKanbanBoardRenderers } from './IKanbanBoardRenderers'; import { IKanbanBucket } from './IKanbanBucket'; import KanbanBucket from './KanbanBucket'; import KanbanTaskManagedProp from './KanbanTaskManagedProp'; import { Dialog, DialogType, DialogFooter } from 'office-ui-fabric-react/lib/Dialog'; import { PrimaryButton, DefaultButton } from 'office-ui-fabric-react/lib/Button'; import { IStackStyles, Stack } from 'office-ui-fabric-react/lib/Stack'; import { clone } from '@microsoft/sp-lodash-subset'; import { CommandBar } from 'office-ui-fabric-react/lib/CommandBar'; import { TooltipHost, findIndex } from 'office-ui-fabric-react'; export interface IKanbanComponentProps { buckets: IKanbanBucket[]; tasks: IKanbanTask[]; tasksettings: IKanbanBoardTaskSettings; taskactions: IKanbanBoardTaskActions; showCommandbar?: boolean; renderers?: IKanbanBoardRenderers; allowEdit?: boolean; allowAdd?: boolean; editSchema?: boolean; /* showCommandbarNew: boolean; allowDialog: boolean; TODO im mock */ } export interface IKanbanComponentState { leavingTaskId?: string; leavingBucket?: string; openDialog: boolean; openTaskId?: string; dialogState?: DialogState; editTask?: IKanbanTask; addBucket?: IKanbanBucket; } export enum DialogState { New = 1, Edit = 2, Display = 3 } export class KanbanComponent extends React.Component<IKanbanComponentProps, IKanbanComponentState> { private dragelement?: IKanbanTask; private bucketsref: any[]; constructor(props: IKanbanComponentProps) { super(props); this.state = { openDialog: false, leavingTaskId: null, leavingBucket: null, }; this.bucketsref = []; } public render(): React.ReactElement<IKanbanComponentProps> { const { buckets, tasks, tasksettings, taskactions, showCommandbar } = this.props; const { openDialog } = this.state; const bucketwidth: number = buckets.length > 0 ? 100 / buckets.length : 100; const { leavingBucket, leavingTaskId } = this.state; const hasprocessIndicator = buckets.filter((b)=> b.showPercentageHeadline).length >0; return ( <div style={{ overflowX: 'auto' }}> {showCommandbar && <CommandBar items={this.getItems()} farItems={this.getFarItems()} ariaLabel={'Use left and right arrow keys to navigate between commands'} />} <div className={styles.kanbanBoard}> { buckets.map((b, i) => { const merge = { ...b, ...this.state }; return (<div style={{ flexBasis: bucketwidth ? bucketwidth + '%' : '100%' , maxWidth: bucketwidth ? bucketwidth + '%' : '100%' }} className={styles.bucketwrapper} ref={bucketContent => this.bucketsref[i] = bucketContent} key={'BucketWrapper' + b.bucket + i} onDragOver={(event) => this.onDragOver(event, b.bucket)} onDragLeave={(event) => this.onDragLeave(event, b.bucket)} onDrop={(event) => this.onDrop(event, b.bucket)} > <KanbanBucket key={b.bucket} {...merge} hasOneProcessIndicator={hasprocessIndicator} buckettasks={tasks.filter((x) => x.bucket == b.bucket)} tasksettings={tasksettings} toggleCompleted={this.props.taskactions && this.props.taskactions.toggleCompleted ? this.props.taskactions.toggleCompleted : undefined} addTask={this.internalAddTask.bind(this)} openDetails={this.internalOpenDialog.bind(this)} onDragStart={this.onDragStart.bind(this)} onDragEnd={this.onDragEnd.bind(this)} /> </div>); } )} </div> {openDialog && (this.renderDialog())} </div> ); } private getTaskByID(taskId: string): IKanbanTask { const tasks = this.props.tasks.filter(t => t.taskId == this.state.openTaskId); if (tasks.length == 1) { return tasks[0]; } throw "Error Taks not found by taskId"; } private renderDialog(): JSX.Element { let renderer: (task?: IKanbanTask, bucket?: IKanbanBucket) => JSX.Element = () => (<div>Dialog Renderer Not Set</div>); let task: IKanbanTask = undefined; let bucket: IKanbanBucket = undefined; let dialogheadline: string = ''; switch (this.state.dialogState) { case DialogState.Edit: task = this.getTaskByID(this.state.openTaskId); renderer = this.internalTaskEditRenderer.bind(this); dialogheadline = strings.EditTaskDlgHeadline; break; case DialogState.New: renderer = this.internalTaskAddRenderer.bind(this); dialogheadline = strings.AddTaskDlgHeadline; break; default: task = this.getTaskByID(this.state.openTaskId); dialogheadline = task.title; renderer = (this.props.renderers && this.props.renderers.taskDetail) ? this.props.renderers.taskDetail : this.internalTaskDetailRenderer.bind(this); break; } return (<Dialog minWidth={600} hidden={!this.state.openDialog} onDismiss={this.internalCloseDialog.bind(this)} dialogContentProps={{ type: DialogType.largeHeader, title: dialogheadline, subText: '' }} modalProps={{ isBlocking: false, styles: { main: { minWidth: 600 } } }} > {renderer(task, bucket)} <DialogFooter> {(this.props.allowEdit && this.state.dialogState === DialogState.Display) && (<PrimaryButton onClick={this.clickEditTask.bind(this)} text={strings.EditTaskBtn} />)} {(this.props.allowEdit && this.state.dialogState === DialogState.Edit) && (<PrimaryButton onClick={this.saveEditTask.bind(this)} text={strings.SaveTaskBtn} />)} {(this.props.allowAdd && this.state.dialogState === DialogState.New) && (<PrimaryButton onClick={this.saveAddTask.bind(this)} text={strings.SaveAddTaskBtn} />)} <DefaultButton onClick={this.internalCloseDialog.bind(this)} text={strings.CloseTaskDialog} /> </DialogFooter> </Dialog>); } private clickEditTask(): void { const task = this.getTaskByID(this.state.openTaskId); if (this.props.taskactions.taskEdit) { this.internalCloseDialog(); this.props.taskactions.taskEdit(clone(task)); } else { this.setState({ dialogState: DialogState.Edit, editTask: clone(task) }); } } private saveEditTask() { if (this.props.taskactions.editTaskSaved) { const edittask = clone(this.state.editTask); //check fist state and than event or in the other way this.internalCloseDialog(); this.props.taskactions.editTaskSaved(edittask); } else { throw "allowEdit is Set but no handler is set"; } } private saveAddTask() { if (this.props.taskactions.editTaskSaved) { const edittask = clone(this.state.editTask); //check fist state and than event or in the other way this.internalCloseDialog(); this.props.taskactions.editTaskSaved(edittask); } else { throw "allowAdd is Set but no handler is set"; } } private internalTaskDetailRenderer(task: IKanbanTask): JSX.Element { const { tasksettings } = this.props; return (<Stack> {tasksettings && tasksettings.showPriority && ( <KanbanTaskManagedProp name="assignedTo" displayName={strings.Priority} type={KanbanTaskMamagedPropertyType.string} value={task.priority} key={'assignedToProp'} /> )} {tasksettings && tasksettings.showAssignedTo && (<KanbanTaskManagedProp name="assignedTo" displayName={strings.AssignedTo} type={KanbanTaskMamagedPropertyType.person} value={task.assignedTo} key={'assignedToProp'} /> )} <KanbanTaskManagedProp name="assignedTo" displayName={strings.HtmlDescription} type={KanbanTaskMamagedPropertyType.html} value={task.htmlDescription} key={'htmlDescriptionProp'} /> {task.mamagedProperties && ( task.mamagedProperties.map((p, i) => { return ( <KanbanTaskManagedProp {...p} key={p.name + i} /> ); }) )} </Stack> ); } private internalTaskEditRenderer(task: IKanbanTask): JSX.Element { const schema = this.props.editSchema; //TODO return (<div>Edit</div>); } private internalTaskAddRenderer(task?: IKanbanTask, bucket?: IKanbanBucket): JSX.Element { const schema = this.props.editSchema; //TODO return (<div>New</div>); } private internalCloseDialog(ev?: React.MouseEvent<HTMLButtonElement>) { this.setState({ openDialog: false, openTaskId: undefined, dialogState: undefined, editTask: undefined, addBucket: undefined }); } private internalOpenDialog(taskid: string) { this.setState({ openDialog: true, openTaskId: taskid, dialogState: DialogState.Display }); } private internalAddTask(targetbucket?: string) { let bucket: IKanbanBucket = undefined; if (bucket) { const buckets = this.props.buckets.filter((p) => p.bucket === targetbucket); if (buckets.length === 1) { bucket = clone(buckets[0]); } else { throw "Bucket not Found in addDialog"; } } if (this.props.taskactions && this.props.taskactions.taskAdd) { this.props.taskactions.taskAdd(bucket); } else { this.setState({ openDialog: true, openTaskId: '', dialogState: DialogState.New, addBucket: bucket }); } } private onDragLeave(event, bucket): void { const index = findIndex(this.props.buckets, element => element.bucket == bucket); if (index != -1 && this.bucketsref.length > index) { //&& this.bucketsref[index].classList.contains(styles.dragover)) { this.bucketsref[index].classList.remove(styles.dragover); } } private onDragEnd(event): void { this.dragelement = undefined; this.setState({ leavingTaskId: null, leavingBucket: null, }); } private onDragStart(event, taskId: string, bucket: string): void { const taskitem = this.props.tasks.filter(p => p.taskId === taskId); if (taskitem.length === 1) { event.dataTransfer.setData("text", taskId); event.dataTransfer.effectAllowed = 'copy'; //event.dataTransfer.setData("sourcebucket", bucket); //set element because event.dataTransfer is empty by DragOver this.dragelement = taskitem[0]; this.setState({ leavingTaskId: taskId, leavingBucket: bucket, }); } else { // Error not consitent throw "TaskItem not found on DragStart"; } } private onDragOver(event, targetbucket: string): void { event.preventDefault(); if (this.dragelement.bucket !== targetbucket) { const index = findIndex(this.props.buckets, element => element.bucket == targetbucket); if (index > -1 && this.bucketsref.length > index) { //&& this.bucketsref[index].classList.contains(styles.dragover)) { this.bucketsref[index].classList.add(styles.dragover); } } } private onDrop(event, targetbucket: string): void { if (this.bucketsref && this.bucketsref.length > 0) { this.bucketsref.forEach(x => { x.classList.remove(styles.dragover); }); } if (this.dragelement.bucket !== targetbucket) { //event.dataTransfer.getData("text"); const taskId = this.dragelement.taskId; const source = this.props.buckets.filter(s => s.bucket == this.dragelement.bucket)[0]; const target = this.props.buckets.filter(s => s.bucket == targetbucket)[0]; if (this.props.taskactions) { let allowMove = true; if (this.props.taskactions.allowMove) { allowMove = this.props.taskactions.allowMove(taskId, source, target ); } if (allowMove && this.props.taskactions.moved) { this.props.taskactions.moved(taskId, target); } } } this.dragelement = null; this.setState({ leavingTaskId: null, leavingBucket: null, }); } private getItems = () => { if (this.props.allowAdd) { return [ { key: 'newItem', name: 'New', cacheKey: 'myAddBtnKey', iconProps: { iconName: 'Add' }, onClick: () => this.internalAddTask.bind(this) }]; } return []; } private getFarItems = () => { return [ { key: 'info', name: 'Info', ariaLabel: 'Info', iconProps: { iconName: 'Info' }, iconOnly: true, onClick: () => console.log('Info') } ]; } }
the_stack
import { DBAdapter, DBValue } from './dbAdapter'; /** * This adapter uses sql.js to execute queries against the GeoPackage database * @module db/sqljsAdapter * @see {@link http://kripken.github.io/sql.js/documentation/|sqljs} */ // @ts-ignore import sqljs from 'rtree-sql.js/dist/sql-asm-memory-growth.js'; // var sqljs = require('sql.js/js/sql.js'); /** * Class which adapts generic GeoPackage queries to sqljs queries */ export class SqljsAdapter implements DBAdapter { db: any; filePath: string | Buffer | Uint8Array; /** * Returns a Promise which, when resolved, returns a DBAdapter which has connected to the GeoPackage database file */ initialize(): Promise<this> { const promise = new Promise<this>((resolve, reject) => { sqljs().then((SQL: { Database: any }) => { if (this.filePath && typeof this.filePath === 'string') { if (typeof process !== 'undefined' && process.version) { // eslint-disable-next-line @typescript-eslint/no-var-requires const fs = require('fs'); if (this.filePath.indexOf('http') === 0) { // eslint-disable-next-line @typescript-eslint/no-var-requires const http = require('http'); http .get(this.filePath, (response: any) => { if (response.statusCode !== 200) { return reject(new Error('Unable to reach url: ' + this.filePath)); } const body: any = []; response.on('data', (chunk: any) => body.push(chunk)); response.on('end', () => { const t = new Uint8Array(Buffer.concat(body)); this.db = new SQL.Database(t); resolve(this); }); }) .on('error', (e: any) => { return reject(e); }); } else { try { fs.statSync(this.filePath); } catch (e) { this.db = new SQL.Database(); // var adapter = new SqljsAdapter(db); return resolve(this); } const filebuffer = fs.readFileSync(this.filePath); const t = new Uint8Array(filebuffer); this.db = new SQL.Database(t); // console.log('setting wal mode'); // var walMode = db.exec('PRAGMA journal_mode=DELETE'); // console.log('walMode', walMode); // adapter = new SqljsAdapter(db); return resolve(this); } } else { // eslint-disable-next-line no-undef const xhr = new XMLHttpRequest(); xhr.open('GET', this.filePath, true); xhr.responseType = 'arraybuffer'; xhr.onload = (): void => { if (xhr.status !== 200) { return reject(new Error('Unable to reach url: ' + this.filePath)); } const uInt8Array = new Uint8Array(xhr.response); this.db = new SQL.Database(uInt8Array); return resolve(this); }; xhr.onerror = (): void => { return reject(new Error('Error reaching url: ' + this.filePath)); }; xhr.send(); } } else if (this.filePath) { const byteArray = this.filePath; this.db = new SQL.Database(byteArray); return resolve(this); } else { this.db = new SQL.Database(); return resolve(this); } }); }); return promise; } // /** // * Creates an adapter from an already established better-sqlite3 database connection // * @param {any} db sqljs database connection // * @return {module:db/sqljsAdapter~Adapter} // */ // static createAdapterFromDb(db) { // return new SqljsAdapter(db); // } /** * @param {string|Buffer|Uint8Array} [filePath] string path to an existing file or a path to where a new file will be created or a url from which to download a GeoPackage or a Uint8Array containing the contents of the file, if undefined, an in memory database is created */ constructor(filePath?: string | Buffer | Uint8Array) { this.filePath = filePath; } /** * Closes the connection to the GeoPackage */ close(): void { this.db.close(); } /** * Get the connection to the database file * @return {any} */ getDBConnection(): any { return this.db; } /** * Returns a Uint8Array containing the contents of the database as a file */ async export(): Promise<Uint8Array> { return this.db.export(); } /** * Registers the given function so that it can be used by SQL statements * @see {@link http://kripken.github.io/sql.js/documentation/#http://kripken.github.io/sql.js/documentation/class/Database.html#create_function-dynamic|sqljs create_function} * @param {string} name name of function to register * @param {Function} functionDefinition function to register * @return {module:db/sqljsAdapter~Adapter} this */ registerFunction(name: string, functionDefinition: Function): this { this.db.create_function(name, functionDefinition); return this; } /** * Gets one row of results from the statement * @see {@link http://kripken.github.io/sql.js/documentation/#http://kripken.github.io/sql.js/documentation/class/Statement.html#get-dynamic|sqljs get} * @see {@link http://kripken.github.io/sql.js/documentation/#http://kripken.github.io/sql.js/documentation/class/Statement.html#getAsObject-dynamic|sqljs getAsObject} * @param {String} sql statement to run * @param {Array|Object} [params] substitution parameters * @return {Object} */ get(sql: string, params?: [] | Record<string, DBValue>): Record<string, DBValue> { params = params || []; const statement = this.db.prepare(sql); statement.bind(params); const hasResult = statement.step(); let row; if (hasResult) { row = statement.getAsObject(); } statement.free(); return row; } /** * Determines if a tableName exists in the database * @param {String} tableName * @returns {Boolean} */ isTableExists(tableName: string): boolean { const statement = this.db.prepare("SELECT name FROM sqlite_master WHERE type='table' AND name=:name"); statement.bind([tableName]); const hasResult = statement.step(); let row; if (hasResult) { row = statement.getAsObject(); } statement.free(); return !!row; } /** * Gets all results from the statement in an array * @param {String} sql statement to run * @param {Array|Object} [params] bind parameters * @return {Object[]} */ all(sql: string, params?: [] | Record<string, DBValue>): Record<string, DBValue>[] { const rows = []; const iterator = this.each(sql, params); for (const row of iterator) { rows.push(row); } return rows; } /** * Returns an Iterable with results from the query * @param {string} sql statement to run * @param {Object|Array} params bind parameters * @return {IterableIterator<Object>} */ each(sql: string, params?: [] | Record<string, DBValue>): IterableIterator<Record<string, DBValue>> { const statement = this.db.prepare(sql); statement.bind(params); return { [Symbol.iterator](): IterableIterator<Record<string, DBValue>> { return this; }, next: function(): { value: Record<string, DBValue>; done: boolean } { if (statement.step()) { return { value: statement.getAsObject(), done: false, }; } else { statement.free(); return { value: undefined, done: true, }; } }, }; } /** * Runs the statement specified, returning information about what changed * @see {@link http://kripken.github.io/sql.js/documentation/#http://kripken.github.io/sql.js/documentation/class/Statement.html#run-dynamic|sqljs run} * @param {string} sql statement to run * @param {Object|Array} [params] bind parameters * @return {Object} object containing a changes property indicating the number of rows changed and a lastInsertROWID indicating the last inserted row */ run(sql: string, params?: [] | Record<string, DBValue>): { changes: number; lastInsertRowid: number } { if (params && !(params instanceof Array)) { for (const key in params) { params['$' + key] = params[key]; } } this.db.run(sql, params); const lastId = this.db.exec('select last_insert_rowid();'); let lastInsertedId; if (lastId) { lastInsertedId = lastId[0].values[0][0]; } return { lastInsertRowid: lastInsertedId, changes: this.db.getRowsModified(), }; } /** * Runs the specified insert statement and returns the last inserted id or undefined if no insert happened * @param {String} sql statement to run * @param {Object|Array} [params] bind parameters * @return {Number} last inserted row id */ insert(sql: string, params?: [] | Record<string, DBValue>): number { if (params && !(params instanceof Array)) { for (const key in params) { params['$' + key] = params[key]; } } const statement = this.db.prepare(sql, params); statement.step(); statement.free(); const lastId = this.db.exec('select last_insert_rowid();'); if (lastId) { return lastId[0].values[0][0]; } else { return; } } /** * Runs the specified delete statement and returns the number of deleted rows * @param {String} sql statement to run * @param {Object|Array} [params] bind parameters * @return {Number} deleted rows */ delete(sql: string, params?: [] | Record<string, DBValue>): number { let rowsModified = 0; const statement = this.db.prepare(sql, params); statement.step(); rowsModified = this.db.getRowsModified(); statement.free(); return rowsModified; } /** * Drops the table * @param {String} table table name * @return {Boolean} indicates if the table was dropped */ dropTable(table: string): boolean { const response = this.db.exec('DROP TABLE IF EXISTS "' + table + '"'); this.db.exec('VACUUM'); return !!response; } /** * Counts rows that match the query * @param {String} tableName table name from which to count * @param {String} [where] where clause * @param {Object|Array} [whereArgs] where args * @return {Number} count */ count(tableName: string, where?: string, whereArgs?: [] | Record<string, DBValue>): number { let sql = 'SELECT COUNT(*) as count FROM "' + tableName + '"'; if (where) { sql += ' where ' + where; } return this.get(sql, whereArgs).count as number; } transaction(func: Function): void { this.db.exec('BEGIN TRANSACTION'); try { func(); this.db.exec('COMMIT TRANSACTION'); } catch (e) { this.db.exec('ROLLBACK TRANSACTION'); throw e; } } }
the_stack
// The MIT License (MIT) // // vs-deploy (https://github.com/mkloubert/vs-deploy) // Copyright (c) Marcel Joachim Kloubert <marcel.kloubert@gmx.net> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to // deal in the Software without restriction, including without limitation the // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or // sell copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. import * as deploy_contracts from './contracts'; import * as deploy_helpers from './helpers'; import * as deploy_objects from './objects'; import * as deploy_res_css from './resources/css'; import * as deploy_res_html from './resources/html'; import * as deploy_res_javascript from './resources/javascript'; import * as deploy_urls from './urls'; import * as deploy_values from './values'; import * as HtmlEntities from 'html-entities'; import * as i18 from './i18'; import * as Marked from 'marked'; import * as Path from 'path'; import * as vs_deploy from './deploy'; import * as vscode from 'vscode'; import * as Workflows from 'node-workflows'; /** * An extended compare result. */ export interface FileCompareResult extends deploy_contracts.FileCompareResult { /** @inheritdoc */ left: FileInfo; /** @inheritdoc */ right: FileInfo; } /** * An extended file info. */ export interface FileInfo extends deploy_contracts.FileInfo { error?: any; } /** * Checks files. * * @param {string[]} files the files to check. * @param {deploy_contracts.DeployTarget} target The target. * @param {deploy_contracts.DeployPlugin} plugin The plugin. * * @returns {(Promise<false|null|FileCompareResult[]>)} The result. */ export async function checkFiles(files: string[], target: deploy_contracts.DeployTarget, plugin: deploy_contracts.DeployPlugin): Promise<false | null | FileCompareResult[]> { if (!plugin.compareFiles && !plugin.compareWorkspace) { return false; // not supported } if (!plugin.canGetFileInfo) { return null; // no file info support } let wf = Workflows.create(); wf.next((ctx) => { ctx.result = []; }); if (plugin.compareWorkspace) { wf.next(async (ctx) => { let results: FileCompareResult[] = ctx.result; let compareRes = await plugin.compareWorkspace(files, target); results.push .apply(results, compareRes); return compareRes; }); } else { // use compareFiles() instead files.forEach(f => { wf.next(async (ctx) => { let results: FileCompareResult[] = ctx.result; let compareRes = await plugin.compareFiles(f, target); results.push(compareRes); return compareRes; }); }); } return await wf.start(); } /** * Checks for newer files. * * @param {string[]} files the files to check. * @param {deploy_contracts.DeployTarget} target The target. * @param {deploy_contracts.DeployPlugin} plugin The plugin. * * @returns {Promise<boolean>} The promise. */ export async function checkForNewerFiles(files: string[], target: deploy_contracts.DeployTarget, plugin: deploy_contracts.DeployPlugin): Promise<boolean> { let me: vs_deploy.Deployer = this; let wf = Workflows.create(); wf.next((ctx) => { ctx.result = true; }); let differences = await checkFiles(files, target, plugin); if (Array.isArray(differences)) { wf.next(async () => { return (<FileCompareResult[]>differences).filter(d => { try { if (!d.right.exists) { return false; // only if exist } if (!d.right.modifyTime) { return false; // cannot compare } if (!d.left.modifyTime) { return true; } return d.right.modifyTime.utc() .isAfter(d.left.modifyTime.utc()); } catch (e) { d.right.error = e; return true; } }); }); // check data wf.next(async (ctx) => { let newerFiles: FileCompareResult[] = ctx.previousValue; for (let i = 0; i < newerFiles.length; ) { let nf = newerFiles[i]; let remove = false; if (!nf.right.error) { try { if (plugin.canPull) { let leftData = (await deploy_helpers.loadFrom(Path.join(nf.left.path, nf.left.name))).data; let rightdata = await plugin.downloadFile(Path.join(nf.left.path, nf.left.name), target); let toComparableBuffer = async (b: Buffer): Promise<Buffer> => { let isBinary = await deploy_helpers.isBinaryContent(b); if (!isBinary) { let str = b.toString('ascii'); str = deploy_helpers.replaceAllStrings(str, "\r", ""); str = deploy_helpers.replaceAllStrings(str, "\t", " "); b = new Buffer(str, 'ascii'); } return b; }; leftData = await toComparableBuffer(leftData); rightdata = await toComparableBuffer(rightdata); if (leftData.equals(rightdata)) { remove = true; } } } catch (e) { nf.right.error = e; } } if (remove) { newerFiles.splice(i, 1); } else { i++; } } return newerFiles; }); // show wanring if newer files were found wf.next((ctx) => { let newerFiles: FileCompareResult[] = ctx.previousValue; return new Promise<any>((resolve, reject) => { let localFiles = newerFiles.map(nf => { return Path.join(nf.left.path, nf.left.name); }).map(lf => { return Path.resolve(lf); }); if (newerFiles.length > 0) { ctx.result = false; let msg = i18.t('deploy.newerFiles.message', newerFiles.length); // [BUTTON] show let showBtn: deploy_contracts.PopupButton = new deploy_objects.SimplePopupButton(); showBtn.action = () => { ctx.result = false; showFilesInBrowsers(me, newerFiles, target).then(() => { resolve(); }).catch((err) => { reject(err); }); }; showBtn.title = i18.t('deploy.newerFiles.show'); // [BUTTON] deploy let deployBtn: deploy_contracts.PopupButton = new deploy_objects.SimplePopupButton(); deployBtn.action = () => { ctx.result = true; resolve(); }; deployBtn.title = i18.t('deploy.newerFiles.deploy'); let args = [ msg, showBtn, deployBtn ]; // show popup vscode.window.showWarningMessage.apply(null, args).then((btn: deploy_contracts.PopupButton) => { try { if (btn) { btn.action(); } else { ctx.result = null; resolve(); } } catch (e) { reject(e); } }, (err) => { reject(err); }); } else { resolve(); } }); }); } return await wf.start(); } async function showFilesInBrowsers(me: vs_deploy.Deployer, files: FileCompareResult[], target: deploy_contracts.DeployTarget): Promise<any> { let title: string; if (deploy_helpers.isNullUndefinedOrEmptyString(target.name)) { title = i18.t('deploy.newerFiles.titleNoTarget'); } else { title = i18.t('deploy.newerFiles.title', target.name); } let htmlEncoder = new HtmlEntities.AllHtmlEntities(); let markdown = `# ${htmlEncoder.encode(title)}\n`; markdown += `| ${htmlEncoder.encode(i18.t('deploy.newerFiles.localFile'))} | ${htmlEncoder.encode(i18.t('deploy.newerFiles.modifyTime'))} | ${htmlEncoder.encode(i18.t('deploy.newerFiles.size'))} | ${htmlEncoder.encode(i18.t('deploy.newerFiles.remoteFile'))} | ${htmlEncoder.encode(i18.t('deploy.newerFiles.modifyTime'))} | ${htmlEncoder.encode(i18.t('deploy.newerFiles.size'))}\n`; markdown += "| ---------- |:--:|:--:| ---------- |:--:|:--:|\n"; files.map(f => { let localFile = Path.join(f.left.path, f.left.name); let relLocalPath = deploy_helpers.toRelativePath(localFile); if (false !== relLocalPath) { localFile = relLocalPath; } let remoteFile = f.right.name; if (!deploy_helpers.isNullUndefinedOrEmptyString(f.right.path)) { remoteFile = Path.join(f.right.path, f.right.name); remoteFile = deploy_helpers.replaceAllStrings(remoteFile, Path.sep, '/'); let relRemotePath = deploy_helpers.toRelativeTargetPathWithValues(remoteFile, target, me.getValues()); if (false !== relRemotePath) { remoteFile = relRemotePath; } } return { localFile: localFile, localModifyTime: f.left.modifyTime, localSize: f.left.size, remoteFile: remoteFile, remoteModifyTime: f.right.modifyTime, remoteSize: f.right.size, }; }).sort((x, y) => { let comp0 = deploy_helpers.compareValuesBy(x, y, t => deploy_helpers.normalizeString(t.localFile)); if (0 !== comp0) { return comp0; } return deploy_helpers.compareValuesBy(x, y, t => deploy_helpers.normalizeString(t.remoteFile)); }).forEach(x => { markdown += `| ${htmlEncoder.encode(x.localFile)}`; // local last change markdown += '| '; if (x.localModifyTime) { markdown += x.localModifyTime.format(i18.t('format.dateTime')); } else { markdown += '?'; } markdown += ' '; // local size markdown += '| '; if (isNaN(x.localSize)) { markdown += '?'; } else { markdown += x.localSize; } markdown += ' '; markdown += `| ${htmlEncoder.encode(x.remoteFile)}`; // remote last change markdown += '| '; if (x.remoteModifyTime) { markdown += x.remoteModifyTime.format(i18.t('format.dateTime')); } else { markdown += '?'; } markdown += ' '; // remote size markdown += '| '; if (isNaN(x.remoteSize)) { markdown += '?'; } else { markdown += x.remoteSize; } markdown += ' '; markdown += "|\n"; }); let header = deploy_res_html.getContentSync('header_markdown_template.html').toString('utf8'); let footer = deploy_res_html.getContentSync('footer_markdown_template.html').toString('utf8'); let jquery = deploy_res_javascript.getContentSync('jquery.min.js').toString('utf8'); let script = deploy_res_javascript.getContentSync('script.js').toString('utf8'); let highlightJS = deploy_res_javascript.getContentSync('highlight.pack.js').toString('utf8'); let css_highlightJS_css = deploy_res_css.getContentSync('highlight.darkula.css').toString('utf8'); let css_highlightJS_css_default = deploy_res_css.getContentSync('highlight.default.css').toString('utf8'); let css = deploy_res_css.getContentSync('styles.css').toString('utf8'); let html = header + footer; let values: deploy_values.ValueBase[] = []; values.push(new deploy_values.StaticValue({ name: 'vsDeploy-jQuery', value: JSON.stringify(stringToBase64(jquery)), })); values.push(new deploy_values.StaticValue({ name: 'vsDeploy-CSS', value: css, })); values.push(new deploy_values.StaticValue({ name: 'vsDeploy-highlightjs-CSS', value: css_highlightJS_css, })); values.push(new deploy_values.StaticValue({ name: 'vsDeploy-highlightjs-CSS-default', value: css_highlightJS_css_default, })); values.push(new deploy_values.StaticValue({ name: 'vsDeploy-highlightjs', value: JSON.stringify(stringToBase64(highlightJS)), })); values.push(new deploy_values.StaticValue({ name: 'vsDeploy-content', value: JSON.stringify(stringToBase64(Marked(markdown, { breaks: true, gfm: true, tables: true, }))), })); values.push(new deploy_values.StaticValue({ name: 'vsDeploy-header', value: '', })); values.push(new deploy_values.StaticValue({ name: 'vsDeploy-footer', value: '', })); values.push(new deploy_values.StaticValue({ name: 'vsDeploy-project-page', value: deploy_urls.PROJECT_PAGE, })); values.push(new deploy_values.StaticValue({ name: 'vsDeploy-script', value: JSON.stringify(stringToBase64(script)), })); html = deploy_values.replaceWithValues(values, html); await me.openHtml(html, '[vs-deploy] ' + title); } function stringToBase64(str: any): string { str = deploy_helpers.toStringSafe(str); return (new Buffer(str, 'utf8')).toString('base64'); }
the_stack
// https://github.com/derselbst/N64SoundTools/blob/master/N64MidiTool/N64MidiLibrary/MidiParse.cpp#L296 import { copyRange } from "../utils/arrays"; import { assert } from "../utils/debug"; /* eslint-disable */ const LENGTH_HEADER = 0x44; const MIDI_HEADER_MAGIC = 0x4D546864; // MThd const MIDI_TRACK_MAGIC = 0x4D54726B; // MTrk interface IRefs { altPattern: number[] | null; altOffset: number; altLength: number; position: number; original: number; } /** * This parses an entry of MIDI data that the S2 structure contains. */ export function parseGameMidi(inView: DataView, inputSize: number): ArrayBuffer { // TODO: inputs? let usePitchBendSensitity: boolean = false; let pitchBendSensitity: number = 0; let extendTracksToHighest: boolean = false; let hasLoopPoint: boolean; let loopStart: number; let loopEnd: number; const out = new ArrayBuffer(100000); // TODO: How big? const outView = new DataView(out); const trackCount = _getTrackCount(inView); const division = inView.getUint32(0x40); _writeMidiHeader(outView, trackCount, division); let outPos = 14; let numInstruments = 0; let counterTrack = 0; let highestTrackLength = 0; for (let i = 0; i < LENGTH_HEADER - 4; i += 4) { let absoluteTime = 0; const offset = inView.getUint32(i); if (offset === 0) { continue; } let previousEventValue = 0; const loopEndsWithCount = new Map<number, number>(); const refs: IRefs = { altPattern: null, altOffset: 0, altLength: 0, position: offset, original: -1, }; let endFlag = false; while (refs.position < inputSize && !endFlag) { let timePosition = refs.position; refs.original = -1; let timeTag = _getVLBytes(inView, refs, true); absoluteTime += timeTag; if (absoluteTime > highestTrackLength) { highestTrackLength = absoluteTime; } let vlLength = 0; let returnByte = _readMidiByte(inView, refs, true); let eventVal = returnByte; let statusBit = (eventVal < 0x80); if (eventVal === 0xFF || (statusBit && previousEventValue === 0xFF)) { // meta event let subType; if (statusBit) subType = eventVal; else subType = _readMidiByte(inView, refs, true); if (subType == 0x51) { // tempo let microsecondsSinceQuarterNote = ((((_readMidiByte(inView, refs, true) << 8) | _readMidiByte(inView, refs, true)) << 8) | _readMidiByte(inView, refs, true)); } else if (subType == 0x2D) { // end loop let loopCount = _readMidiByte(inView, refs, true); let currentLoopCount = _readMidiByte(inView, refs, true); let offsetToBeginningLoop = ((((((_readMidiByte(inView, refs, false) << 8) | _readMidiByte(inView, refs, false)) << 8) | _readMidiByte(inView, refs, false)) << 8) | _readMidiByte(inView, refs, false)); if ((loopCount == 0xFF) || (loopCount == 0x00)) { break; } else { const it = loopEndsWithCount.get(refs.position); if (loopEndsWithCount.has(refs.position)) { let countLeft = it!; if (countLeft === 0) { loopEndsWithCount.delete(refs.position); } else { loopEndsWithCount.set(refs.position, countLeft - 1); } } else { loopEndsWithCount.set(refs.position, loopCount - 1); } if (refs.altPattern === null) { refs.position = refs.position - offsetToBeginningLoop; } else { loopEndsWithCount.delete(refs.position); } } } else if (subType == 0x2E) { // start loop let loopNumber = _readMidiByte(inView, refs, true); let endLoop = _readMidiByte(inView, refs, true); // Always FF } else if (subType == 0x2F) { endFlag = true; } if (!statusBit) { previousEventValue = eventVal; } } else if ((eventVal >= 0x90 && eventVal < 0xA0) || (statusBit && (previousEventValue >= 0x90) && (previousEventValue < 0xA0))) { let curEventVal; let noteNumber; if (statusBit) { noteNumber = eventVal; curEventVal = previousEventValue; } else { noteNumber = _readMidiByte(inView, refs, true); curEventVal = eventVal; } let velocity = _readMidiByte(inView, refs, true); let timeDuration = _getVLBytes(inView, refs, true); if (!statusBit) previousEventValue = eventVal; } else if (((eventVal >= 0xB0) && (eventVal < 0xC0)) || (statusBit && (previousEventValue >= 0xB0) && (previousEventValue < 0xC0))) // controller change { let controllerTypeText = ""; let controllerType; if (statusBit) { controllerType = eventVal; //previousEventValue; } else { controllerType = _readMidiByte(inView, refs, true); //eventVal; } let controllerValue = _readMidiByte(inView, refs, true); if (!statusBit) previousEventValue = eventVal; } else if (((eventVal >= 0xC0) && (eventVal < 0xD0)) || (statusBit && (previousEventValue >= 0xC0) && (previousEventValue < 0xD0))) // change instrument { let instrument; if (statusBit) { instrument = eventVal; //previousEventValue; } else { instrument = _readMidiByte(inView, refs, true); //eventVal; } if (!statusBit) { previousEventValue = eventVal; } } else if (((eventVal >= 0xD0) && (eventVal < 0xE0)) || (statusBit && (previousEventValue >= 0xD0) && (previousEventValue < 0xE0))) // channel aftertouch { let amount; if (statusBit) { amount = eventVal; //previousEventValue; } else { amount = _readMidiByte(inView, refs, true); //eventVal; } if (!statusBit) { previousEventValue = eventVal; } } else if (((eventVal >= 0xE0) && (eventVal < 0xF0)) || (statusBit && (previousEventValue >= 0xE0) && (previousEventValue < 0xF0))) // pitch bend { let valueLSB; if (statusBit) { valueLSB = eventVal; //previousEventValue; } else { valueLSB = _readMidiByte(inView, refs, true); //eventVal; } let valueMSB = _readMidiByte(inView, refs, true); if (!statusBit) { previousEventValue = eventVal; } } else if (eventVal == 0xFE) { // repeat operation // should not be here... // no prev event set } else { } } } // Second loop over tracks. for (let i = 0; i < LENGTH_HEADER - 4; i += 4) { let absoluteTime = 0; let trackEventCountSub = 0; let trackEventsSub: TrackEvent[] = new Array(0x30000); for (let j = 0; j < 0x30000; j++) { trackEventsSub[j] = new TrackEvent(); } let offset = inView.getUint32(i); if (offset != 0) { outView.setUint32(outPos, 0x4D54726B); // MTrk outPos += 4; let previousEventValue = 0; const loopEndsWithCount = new Map<number, number>(); const loopNumbers: number[] = []; const refs: IRefs = { altPattern: null, altOffset: 0, altLength: 0, position: offset, original: -1, }; let endFlag = false; if (usePitchBendSensitity) { //https://www.midikits.net/midi_analyser/pitch_bend.htm trackEventsSub[trackEventCountSub].type = 0xB0 | ((i / 4) & 0xF); trackEventsSub[trackEventCountSub].contentSize = 2; trackEventsSub[trackEventCountSub].contents = new Array(2); trackEventsSub[trackEventCountSub].contents![0] = 0x64; trackEventsSub[trackEventCountSub].contents![1] = 0x00; trackEventCountSub++; trackEventsSub[trackEventCountSub].type = 0xB0 | ((i / 4) & 0xF); trackEventsSub[trackEventCountSub].contentSize = 2; trackEventsSub[trackEventCountSub].contents = new Array(2); trackEventsSub[trackEventCountSub].contents![0] = 0x65; trackEventsSub[trackEventCountSub].contents![1] = 0x00; trackEventCountSub++; trackEventsSub[trackEventCountSub].type = 0xB0 | ((i / 4) & 0xF); trackEventsSub[trackEventCountSub].contentSize = 2; trackEventsSub[trackEventCountSub].contents = new Array(2); trackEventsSub[trackEventCountSub].contents![0] = 0x06; if (pitchBendSensitity > 0x18) pitchBendSensitity = 0x18; trackEventsSub[trackEventCountSub].contents![1] = pitchBendSensitity; trackEventCountSub++; trackEventsSub[trackEventCountSub].type = 0xB0 | ((i / 4) & 0xF); trackEventsSub[trackEventCountSub].contentSize = 2; trackEventsSub[trackEventCountSub].contents = new Array(2); trackEventsSub[trackEventCountSub].contents![0] = 0x64; trackEventsSub[trackEventCountSub].contents![1] = 0x7F; trackEventCountSub++; trackEventsSub[trackEventCountSub].type = 0xB0 | ((i / 4) & 0xF); trackEventsSub[trackEventCountSub].contentSize = 2; trackEventsSub[trackEventCountSub].contents = new Array(2); trackEventsSub[trackEventCountSub].contents![0] = 0x65; trackEventsSub[trackEventCountSub].contents![1] = 0x7F; trackEventCountSub++; } while ((refs.position < inputSize) && !endFlag) { if (extendTracksToHighest) { if (absoluteTime >= highestTrackLength) { trackEventsSub[trackEventCountSub].absoluteTime = highestTrackLength; trackEventsSub[trackEventCountSub].deltaTime = (highestTrackLength - absoluteTime); trackEventsSub[trackEventCountSub].type = 0xFF; trackEventsSub[trackEventCountSub].contentSize = 2; trackEventsSub[trackEventCountSub].contents = new Array(2); trackEventsSub[trackEventCountSub].contents![0] = 0x2F; trackEventsSub[trackEventCountSub].contents![1] = 0x0; trackEventCountSub++; endFlag = true; break; } } if (trackEventCountSub >= 0x30000) { for (let eventCount = 0; eventCount < trackEventCountSub; eventCount++) { if (trackEventsSub[eventCount].contents != null) { trackEventsSub[eventCount].contents = null; } } // delete [] trackEventsSub; console.error("Overflow? trackEventCountSub >= 0x30000"); return out; } let timePosition = refs.position; refs.original = -1; // trackEventsSub[trackEventCountSub].deltaTime is for loops let timeTag = _getVLBytes(inView, refs, true); if (extendTracksToHighest) { if ((absoluteTime + timeTag) > highestTrackLength) { trackEventsSub[trackEventCountSub].absoluteTime = highestTrackLength; trackEventsSub[trackEventCountSub].deltaTime = (highestTrackLength - absoluteTime); trackEventsSub[trackEventCountSub].type = 0xFF; trackEventsSub[trackEventCountSub].contentSize = 2; trackEventsSub[trackEventCountSub].contents = new Array(2); trackEventsSub[trackEventCountSub].contents![0] = 0x2F; trackEventsSub[trackEventCountSub].contents![1] = 0x0; trackEventCountSub++; endFlag = true; break; } } trackEventsSub[trackEventCountSub].deltaTime += timeTag; absoluteTime += timeTag; trackEventsSub[trackEventCountSub].absoluteTime = absoluteTime; let vlLength = 0; let eventVal = _readMidiByte(inView, refs, true); let statusBit = (eventVal < 0x80); if ((eventVal == 0xFF) || (statusBit && (previousEventValue == 0xFF))) { // meta event let subType; if (statusBit) subType = eventVal; else subType = _readMidiByte(inView, refs, true); if (subType == 0x51) { // tempo let microsecondsSinceQuarterNote = ((((_readMidiByte(inView, refs, true) << 8) | _readMidiByte(inView, refs, true)) << 8) | _readMidiByte(inView, refs, true)); trackEventsSub[trackEventCountSub].type = 0xFF; trackEventsSub[trackEventCountSub].contentSize = 5; trackEventsSub[trackEventCountSub].contents = new Array(5); trackEventsSub[trackEventCountSub].contents![0] = 0x51; trackEventsSub[trackEventCountSub].contents![1] = 0x3; trackEventsSub[trackEventCountSub].contents![2] = ((microsecondsSinceQuarterNote >> 16) & 0xFF); trackEventsSub[trackEventCountSub].contents![3] = ((microsecondsSinceQuarterNote >> 8) & 0xFF); trackEventsSub[trackEventCountSub].contents![4] = ((microsecondsSinceQuarterNote >> 0) & 0xFF); trackEventCountSub++; const MICROSECONDS_PER_MINUTE = 60000000; let beatsPerMinute = MICROSECONDS_PER_MINUTE / microsecondsSinceQuarterNote; // float conversion } else if (subType == 0x2D) { // end loop let loopNumber = 0; if (loopNumbers.length > 0) { loopNumber = loopNumbers.pop()!; } // Fake loop end, controller 103 trackEventsSub[trackEventCountSub].type = 0xB0 | ((i / 4) & 0xF); trackEventsSub[trackEventCountSub].contentSize = 2; trackEventsSub[trackEventCountSub].contents = new Array(2); trackEventsSub[trackEventCountSub].contents![0] = 103; trackEventsSub[trackEventCountSub].contents![1] = loopNumber; trackEventCountSub++; let loopCount = _readMidiByte(inView, refs, true); let currentLoopCount = _readMidiByte(inView, refs, true); let offsetToBeginningLoop = ((((((_readMidiByte(inView, refs, false) << 8) | _readMidiByte(inView, refs, false)) << 8) | _readMidiByte(inView, refs, false)) << 8) | _readMidiByte(inView, refs, false)); if ((loopCount == 0xFF) || (loopCount == 0x00)) { hasLoopPoint = true; loopEnd = absoluteTime; if (extendTracksToHighest) { if (refs.altPattern === null) { refs.position = refs.position - offsetToBeginningLoop; } } } else { let it = loopEndsWithCount.get(refs.position); if (loopEndsWithCount.has(refs.position)) { let countLeft = it!; if (countLeft == 0) { loopEndsWithCount.delete(refs.position); } else { loopEndsWithCount.set(refs.position, countLeft - 1); } } else { loopEndsWithCount.set(refs.position, loopCount - 1); } if (refs.altPattern === null) { refs.position = refs.position - offsetToBeginningLoop; } else { loopEndsWithCount.delete(refs.position); } } } else if (subType == 0x2E) { // start loop let loopNumber = _readMidiByte(inView, refs, true); let endLoop = _readMidiByte(inView, refs, true); // Always FF hasLoopPoint = true; loopStart = absoluteTime; // Fake loop start, controller 102 trackEventsSub[trackEventCountSub].type = 0xB0 | ((i / 4) & 0xF); trackEventsSub[trackEventCountSub].contentSize = 2; trackEventsSub[trackEventCountSub].contents = new Array(2); trackEventsSub[trackEventCountSub].contents![0] = 102; trackEventsSub[trackEventCountSub].contents![1] = loopNumber; trackEventCountSub++; loopNumbers.push(loopNumber); } else if (subType == 0x2F) { trackEventsSub[trackEventCountSub].type = 0xFF; trackEventsSub[trackEventCountSub].contentSize = 2; trackEventsSub[trackEventCountSub].contents = new Array(2); trackEventsSub[trackEventCountSub].contents![0] = 0x2F; trackEventsSub[trackEventCountSub].contents![1] = 0x0; trackEventCountSub++; endFlag = true; } if (!statusBit) previousEventValue = eventVal; } else if ((eventVal >= 0x90 && eventVal < 0xA0) || (statusBit && (previousEventValue >= 0x90) && (previousEventValue < 0xA0))) { let curEventVal; let noteNumber: number; if (statusBit) { trackEventsSub[trackEventCountSub].type = previousEventValue; noteNumber = eventVal; curEventVal = previousEventValue; } else { trackEventsSub[trackEventCountSub].type = eventVal; noteNumber = _readMidiByte(inView, refs, true); curEventVal = eventVal; } let velocity = _readMidiByte(inView, refs, true); let timeDuration = _getVLBytes(inView, refs, true); trackEventsSub[trackEventCountSub].durationTime = timeDuration; // to be filled in trackEventsSub[trackEventCountSub].contentSize = 2; trackEventsSub[trackEventCountSub].contents = new Array(2); trackEventsSub[trackEventCountSub].contents![0] = noteNumber; trackEventsSub[trackEventCountSub].contents![1] = velocity; trackEventCountSub++; if (!statusBit) previousEventValue = eventVal; } else if (((eventVal >= 0xB0) && (eventVal < 0xC0)) || (statusBit && (previousEventValue >= 0xB0) && (previousEventValue < 0xC0))) // controller change { let controllerTypeText = ""; let controllerType; if (statusBit) { controllerType = eventVal; trackEventsSub[trackEventCountSub].type = previousEventValue; } else { controllerType = _readMidiByte(inView, refs, true); trackEventsSub[trackEventCountSub].type = eventVal; } let controllerValue = _readMidiByte(inView, refs, true); trackEventsSub[trackEventCountSub].contentSize = 2; trackEventsSub[trackEventCountSub].contents = new Array(2); trackEventsSub[trackEventCountSub].contents![0] = controllerType; trackEventsSub[trackEventCountSub].contents![1] = controllerValue; trackEventCountSub++; if (!statusBit) previousEventValue = eventVal; } else if (((eventVal >= 0xC0) && (eventVal < 0xD0)) || (statusBit && (previousEventValue >= 0xC0) && (previousEventValue < 0xD0))) // change instrument { let instrument; if (statusBit) { instrument = eventVal; trackEventsSub[trackEventCountSub].type = previousEventValue; } else { instrument = _readMidiByte(inView, refs, true); trackEventsSub[trackEventCountSub].type = eventVal; } trackEventsSub[trackEventCountSub].contentSize = 1; trackEventsSub[trackEventCountSub].contents = [instrument]; if (instrument >= numInstruments) { numInstruments = (instrument + 1); } trackEventCountSub++; if (!statusBit) previousEventValue = eventVal; } else if (((eventVal >= 0xD0) && (eventVal < 0xE0)) || (statusBit && (previousEventValue >= 0xD0) && (previousEventValue < 0xE0))) // channel aftertouch { let amount; if (statusBit) { amount = eventVal; trackEventsSub[trackEventCountSub].type = previousEventValue; } else { amount = _readMidiByte(inView, refs, true); trackEventsSub[trackEventCountSub].type = eventVal; } trackEventsSub[trackEventCountSub].contentSize = 1; trackEventsSub[trackEventCountSub].contents = [amount]; trackEventCountSub++; if (!statusBit) previousEventValue = eventVal; } else if (((eventVal >= 0xE0) && (eventVal < 0xF0)) || (statusBit && (previousEventValue >= 0xE0) && (previousEventValue < 0xF0))) // pitch bend { let valueLSB; if (statusBit) { valueLSB = eventVal; trackEventsSub[trackEventCountSub].type = previousEventValue; } else { valueLSB = _readMidiByte(inView, refs, true); trackEventsSub[trackEventCountSub].type = eventVal; } let valueMSB = _readMidiByte(inView, refs, true); trackEventsSub[trackEventCountSub].contentSize = 2; trackEventsSub[trackEventCountSub].contents = [valueLSB, valueMSB]; trackEventCountSub++; if (!statusBit) previousEventValue = eventVal; } else if (eventVal == 0xFE) { // repeat operation // should not be here... // no prev event set } else { console.error(`${eventVal} ERROR MISSING PARSE OF TYPE`); } } for (let eventCount = 0; eventCount < trackEventCountSub; eventCount++) { if (trackEventCountSub >= 0x30000) { for (let eventCount = 0; eventCount < trackEventCountSub; eventCount++) { if (trackEventsSub[eventCount].contents !== null) { //delete [] trackEventsSub[eventCount].contents; trackEventsSub[eventCount].contents = null; } } //delete [] trackEventsSub; console.error("Overflow 2? trackEventCountSub >= 0x30000"); return out; } let trackEvent = trackEventsSub[eventCount]; if ((trackEvent.type >= 0x90) && (trackEvent.type < 0xA0)) { // need to split out if (trackEvent.durationTime > 0) { let shutoffTime = (trackEvent.absoluteTime + trackEvent.durationTime); if (eventCount != (trackEventCountSub - 1)) { for (let e = (eventCount+1); e < trackEventCountSub; e++) { if ((trackEventsSub[e].absoluteTime >= shutoffTime) && (e != (trackEventCountSub - 1))) { for (let j = (trackEventCountSub - 1); j >= e; j--) { trackEventsSub[j+1].absoluteTime = trackEventsSub[j].absoluteTime; trackEventsSub[j+1].contentSize = trackEventsSub[j].contentSize; if (trackEventsSub[j+1].contents !== null) { //delete [] trackEventsSub[j+1].contents; trackEventsSub[j+1].contents = null; } trackEventsSub[j+1].contents = new Array(trackEventsSub[j].contentSize); for (let r = 0; r < trackEventsSub[j].contentSize; r++) { trackEventsSub[j+1].contents![r] = trackEventsSub[j].contents![r]; } trackEventsSub[j+1].deltaTime = trackEventsSub[j].deltaTime; trackEventsSub[j+1].durationTime = trackEventsSub[j].durationTime; trackEventsSub[j+1].obsoleteEvent = trackEventsSub[j].obsoleteEvent; trackEventsSub[j+1].type = trackEventsSub[j].type; } trackEventsSub[e].type = trackEventsSub[eventCount].type; trackEventsSub[e].absoluteTime = shutoffTime; trackEventsSub[e].deltaTime = (trackEventsSub[e].absoluteTime - trackEventsSub[e - 1].absoluteTime); trackEventsSub[e].contentSize = trackEventsSub[eventCount].contentSize; trackEventsSub[e].durationTime = 0; trackEventsSub[e].contents = new Array(trackEventsSub[e].contentSize); trackEventsSub[e].contents![0] = trackEventsSub[eventCount].contents![0]; trackEventsSub[e].contents![1] = 0; trackEventsSub[e + 1].deltaTime = (trackEventsSub[e + 1].absoluteTime - trackEventsSub[e].absoluteTime); if (trackEventsSub[e].deltaTime > 0xFF000000) { let a = 1; } trackEventCountSub++; break; } else if (e == (trackEventCountSub - 1)) { trackEventsSub[e + 1].absoluteTime = shutoffTime; // move end to end trackEventsSub[e + 1].contentSize = trackEventsSub[e].contentSize; if (trackEventsSub[e + 1].contents !== null) { trackEventsSub[e + 1].contents = null; } trackEventsSub[e + 1].contents = new Array(trackEventsSub[e].contentSize); for (let r = 0; r < trackEventsSub[e].contentSize; r++) { trackEventsSub[e + 1].contents![r] = trackEventsSub[e].contents![r]; } trackEventsSub[e + 1].deltaTime = trackEventsSub[e].deltaTime; trackEventsSub[e + 1].durationTime = trackEventsSub[e].durationTime; trackEventsSub[e + 1].obsoleteEvent = trackEventsSub[e].obsoleteEvent; trackEventsSub[e + 1].type = trackEventsSub[e].type; trackEventsSub[e].type = trackEventsSub[eventCount].type; trackEventsSub[e].absoluteTime = shutoffTime; trackEventsSub[e].deltaTime = (trackEventsSub[e].absoluteTime - trackEventsSub[e - 1].absoluteTime); trackEventsSub[e].contentSize = trackEventsSub[eventCount].contentSize; trackEventsSub[e].durationTime = 0; trackEventsSub[e].contents = new Array(trackEventsSub[e].contentSize); trackEventsSub[e].contents![0] = trackEventsSub[eventCount].contents![0]; trackEventsSub[e].contents![1] = 0; trackEventsSub[e + 1].deltaTime = (trackEventsSub[e + 1].absoluteTime - trackEventsSub[e].absoluteTime); trackEventCountSub++; break; } } } else { trackEventsSub[eventCount+1].absoluteTime = shutoffTime; // move end to end trackEventsSub[eventCount+1].contentSize = trackEventsSub[eventCount].contentSize; if (trackEventsSub[eventCount+1].contents !== null) { //delete [] trackEventsSub[eventCount+1].contents; trackEventsSub[eventCount+1].contents = null; } trackEventsSub[eventCount+1].contents = new Array(trackEventsSub[eventCount].contentSize); for (let r = 0; r < trackEventsSub[eventCount].contentSize; r++) { trackEventsSub[eventCount+1].contents![r] = trackEventsSub[eventCount].contents![r]; } trackEventsSub[eventCount+1].deltaTime = trackEventsSub[eventCount].deltaTime; trackEventsSub[eventCount+1].durationTime = trackEventsSub[eventCount].durationTime; trackEventsSub[eventCount+1].obsoleteEvent = trackEventsSub[eventCount].obsoleteEvent; trackEventsSub[eventCount+1].type = trackEventsSub[eventCount].type; trackEventsSub[eventCount].type = trackEventsSub[eventCount].type; trackEventsSub[eventCount].absoluteTime = shutoffTime; if ((trackEventsSub[eventCount].absoluteTime - trackEventsSub[eventCount - 1].absoluteTime) > 0xFF000000) { let a =1; } trackEventsSub[eventCount].deltaTime = (trackEventsSub[eventCount].absoluteTime - trackEventsSub[eventCount - 1].absoluteTime); trackEventsSub[eventCount].contentSize = trackEventsSub[eventCount].contentSize; trackEventsSub[eventCount].durationTime = 0; trackEventsSub[eventCount].contents = new Array(trackEventsSub[eventCount].contentSize); trackEventsSub[eventCount].contents![0] = trackEventsSub[eventCount].contents![0]; trackEventsSub[eventCount].contents![1] = 0; trackEventsSub[eventCount+1].deltaTime = (trackEventsSub[eventCount+1].absoluteTime - trackEventsSub[eventCount].absoluteTime); if (trackEventsSub[eventCount].deltaTime > 0xFF000000) { let a = 1; } trackEventCountSub++; } } } } let timeOffset = 0; let sizeData = 0; let previousTrackEvent = 0x0; for (let j = 0; j < trackEventCountSub; j++) { let trackEvent = trackEventsSub[j]; if (trackEvent.obsoleteEvent) { timeOffset += trackEvent.deltaTime; } else { let [timeDelta, lengthTimeDelta] = _returnVLBytes(trackEvent.deltaTime + timeOffset); timeOffset = 0; sizeData += lengthTimeDelta; if ((trackEvent.type !== previousTrackEvent) || (trackEvent.type === 0xFF)) { sizeData += 1; } sizeData += trackEvent.contentSize; previousTrackEvent = trackEvent.type; } } outView.setUint32(outPos, sizeData); outPos += 4; timeOffset = 0; previousTrackEvent = 0x0; for (let eventCount = 0; eventCount < trackEventCountSub; eventCount++) { let trackEvent = trackEventsSub[eventCount]; if (trackEvent.obsoleteEvent) { timeOffset += trackEvent.deltaTime; } else { let [timeDelta, lengthTimeDelta] = _returnVLBytes(trackEvent.deltaTime + timeOffset); timeOffset = 0; outPos = _writeVLBytes(outView, outPos, timeDelta, lengthTimeDelta, true); if ((trackEvent.type != previousTrackEvent) || (trackEvent.type == 0xFF)) { outView.setUint8(outPos, trackEvent.type); outPos++; } for (let z = 0; z < trackEvent.contentSize; z++) { outView.setUint8(outPos, trackEvent.contents![z]); outPos++; } previousTrackEvent = trackEvent.type; } } } else { } for (let eventCount = 0; eventCount < trackEventCountSub; eventCount++) { if (trackEventsSub[eventCount].contents !== null) { // delete [] trackEventsSub[eventCount].contents; trackEventsSub[eventCount].contents = null; } } counterTrack++; //delete [] trackEventsSub; } return out.slice(0, outPos); } interface ICreateGameMidiOptions { loop?: boolean; } /** * Converts a normal midi file to a midi that can be put in the game. * * https://github.com/derselbst/N64SoundTools/blob/master/N64MidiTool/N64MidiLibrary/MidiParse.cpp#L12837 * * @param midiFile Normal midi file. */ export function createGameMidi(midiFile: ArrayBuffer, options?: ICreateGameMidiOptions): ArrayBuffer | null { const loop = options?.loop || false; const loopPoint = 0; const useRepeaters = false; let trackEventCount: number[] = []; let trackEvents: TrackEvent[][] = []; for (let x = 0; x < 32; x++) { trackEvents.push([]); trackEventCount.push(0); } const dataView = new DataView(midiFile); if (dataView.getUint32(0) !== MIDI_HEADER_MAGIC) { return null; } const headerLength = dataView.getUint32(4); const type = dataView.getUint16(8); let numTracks = dataView.getUint16(10); const tempo = dataView.getUint16(12); if (numTracks > 16) { console.log("Too many tracks, truncating to 16."); numTracks = 16; } if (type !== 0 && type !== 1) { console.log("Invalid midi type"); return null; } let refs: IRefs = { altPattern: null, altOffset: 0, altLength: 0, position: 0xE, original: 0, }; let unknownsHit = false; let highestAbsoluteTime = 0; let highestAbsoluteTimeByTrack = []; for (let x = 0; x < 16; x++) { highestAbsoluteTimeByTrack[x] = 0; } for (let trackNum = 0; trackNum < numTracks; trackNum++) { let absoluteTime = 0; if (dataView.getUint32(refs.position) !== MIDI_TRACK_MAGIC) { console.log("Invalid track midi header"); return null; } const trackLength = dataView.getUint32(refs.position + 4); refs.position += 8; let previousEventValue = 0xFF; let endFlag = false; while (!endFlag && (refs.position < midiFile.byteLength)) { refs.original = 0; let timeTag = _getVLBytes(dataView, refs, false); absoluteTime += timeTag; let eventVal = _readMidiByte(dataView, refs, false); let statusBit = eventVal <= 0x7F ? true : false; if (eventVal === 0xFF) { // meta event. let subType = _readMidiByte(dataView, refs, false); if (subType === 0x2F) { // End of Track Event. absoluteTime -= timeTag; endFlag = true; let length = _readMidiByte(dataView, refs, false); // end 00 in real mid } else if (subType === 0x51) { // Set Tempo Event. let length = _readMidiByte(dataView, refs, false); _readMidiByte(dataView, refs, false); _readMidiByte(dataView, refs, false); _readMidiByte(dataView, refs, false); } else if (subType < 0x7F && !(subType === 0x51 || subType === 0x2F)) { // Various Unused Meta Events. let length = _getVLBytes(dataView, refs, false); // Was _readMidiByte in Subdrag code. for (let i = 0; i < length; i++) { _readMidiByte(dataView, refs, false); } } else if (subType === 0x7F) { // Unused Sequencer Specific Event let length = _getVLBytes(dataView, refs, false); for (let i = 0; i < length; i++) { _readMidiByte(dataView, refs, false); } } previousEventValue = eventVal; } else if ((eventVal >= 0x80 && eventVal < 0x90) || (statusBit && (previousEventValue >= 0x80 && previousEventValue < 0x90))) { let curEventVal; let noteNumber; if (statusBit) { noteNumber = eventVal; curEventVal = previousEventValue; } else { noteNumber = _readMidiByte(dataView, refs, false); curEventVal = eventVal; } let velocity = _readMidiByte(dataView, refs, false); if (!statusBit) { previousEventValue = eventVal; } } else if ((eventVal >= 0x90 && eventVal < 0xA0) || (statusBit && (previousEventValue >= 0x90 && previousEventValue < 0xA0))) { let curEventVal; let noteNumber; if (statusBit) { noteNumber = eventVal; curEventVal = previousEventValue; } else { noteNumber = _readMidiByte(dataView, refs, false); curEventVal = eventVal; } let velocity = _readMidiByte(dataView, refs, false); if (!statusBit) previousEventValue = eventVal; } else if (((eventVal >= 0xB0) && (eventVal < 0xC0)) || (statusBit && (previousEventValue >= 0xB0 && previousEventValue < 0xC0))) // controller change { let controllerType; if (statusBit) { controllerType = eventVal; } else { controllerType = _readMidiByte(dataView, refs, false); } let controllerValue = _readMidiByte(dataView, refs, false); if (!statusBit) previousEventValue = eventVal; } else if (((eventVal >= 0xC0) && (eventVal < 0xD0)) || (statusBit && (previousEventValue >= 0xC0 && previousEventValue < 0xD0))) // change instrument { let instrument; if (statusBit) { instrument = eventVal; } else { instrument = _readMidiByte(dataView, refs, false); } if (!statusBit) previousEventValue = eventVal; } else if (((eventVal >= 0xD0) && (eventVal < 0xE0)) || (statusBit && (previousEventValue >= 0xD0 && previousEventValue < 0xE0))) // channel aftertouch { let amount; if (statusBit) { amount = eventVal; } else { amount = _readMidiByte(dataView, refs, false); } if (!statusBit) previousEventValue = eventVal; } else if (((eventVal >= 0xE0) && (eventVal < 0xF0)) || (statusBit && (previousEventValue >= 0xE0 && previousEventValue < 0xF0))) // pitch bend { let valueLSB; if (statusBit) { valueLSB = eventVal; } else { valueLSB = _readMidiByte(dataView, refs, false); } let valueMSB = _readMidiByte(dataView, refs, false); if (!statusBit) previousEventValue = eventVal; } else if (eventVal == 0xF0 || eventVal == 0xF7) { let length = _getVLBytes(dataView, refs, false); // subtract length for (let i = 0; i < length; i++) { _readMidiByte(dataView, refs, false); } } else { if (!unknownsHit) { console.warn("Invalid midi character found"); unknownsHit = true; } } } if (absoluteTime > highestAbsoluteTime) { highestAbsoluteTime = absoluteTime; } if (absoluteTime > highestAbsoluteTimeByTrack[trackNum]) { highestAbsoluteTimeByTrack[trackNum] = absoluteTime; } } refs = { altPattern: null, altOffset: 0, altLength: 0, position: 0xE, original: 0, }; for (let trackNum = 0; trackNum < numTracks; trackNum++) { let absoluteTime = 0; if (dataView.getUint32(refs.position) !== MIDI_TRACK_MAGIC) { console.log("Invalid track midi header"); return null; } const trackLength = dataView.getUint32(refs.position + 4); refs.position += 8; let previousEventValue = 0xFF; let endFlag = false; let didLoop = false; if (loop && loopPoint === 0 && highestAbsoluteTimeByTrack[trackNum] > 0) { const newTrackEvent = trackEvents[trackNum][trackEventCount[trackNum]] = new TrackEvent(); newTrackEvent.type = 0xFF; newTrackEvent.absoluteTime = 0; newTrackEvent.contentSize = 3; newTrackEvent.contents = [0x2E, 0x00, 0xFF]; newTrackEvent.deltaTime = 0; newTrackEvent.obsoleteEvent = false; trackEventCount[trackNum]++; didLoop = true; } while (!endFlag && (refs.position < midiFile.byteLength)) { refs.original = 0; let timeTag = _getVLBytes(dataView, refs, false); absoluteTime += timeTag; let newTrackEvent = trackEvents[trackNum][trackEventCount[trackNum]] = new TrackEvent(); newTrackEvent.deltaTime = timeTag; newTrackEvent.obsoleteEvent = false; newTrackEvent.contents = null; newTrackEvent.absoluteTime = absoluteTime; if (loop && !didLoop && highestAbsoluteTimeByTrack[trackNum] > loopPoint) { if (absoluteTime == loopPoint) { newTrackEvent.type = 0xFF; newTrackEvent.absoluteTime = absoluteTime; newTrackEvent.contentSize = 3; newTrackEvent.contents = [0x2E, 0x00, 0xFF]; newTrackEvent.deltaTime = timeTag; newTrackEvent.obsoleteEvent = false; trackEventCount[trackNum]++; newTrackEvent = trackEvents[trackNum][trackEventCount[trackNum]] = new TrackEvent(); newTrackEvent.deltaTime = timeTag; newTrackEvent.obsoleteEvent = false; newTrackEvent.contents = null; newTrackEvent.absoluteTime = absoluteTime; didLoop = true; } else if (absoluteTime > loopPoint) { newTrackEvent.type = 0xFF; newTrackEvent.absoluteTime = loopPoint; newTrackEvent.contentSize = 3; newTrackEvent.contents = [0x2E, 0x00, 0xFF]; if (trackEventCount[trackNum] > 0) newTrackEvent.deltaTime = loopPoint - trackEvents[trackNum][trackEventCount[trackNum] - 1].absoluteTime; else newTrackEvent.deltaTime = loopPoint; newTrackEvent.obsoleteEvent = false; trackEventCount[trackNum]++; newTrackEvent = trackEvents[trackNum][trackEventCount[trackNum]] = new TrackEvent(); newTrackEvent.deltaTime = absoluteTime - loopPoint; newTrackEvent.obsoleteEvent = false; newTrackEvent.contents = null; newTrackEvent.absoluteTime = absoluteTime; didLoop = true; } } let eventVal = _readMidiByte(dataView, refs, false); let statusBit = eventVal <= 0x7F ? true : false; if (eventVal === 0xFF) { let subType = _readMidiByte(dataView, refs, false); if (subType === 0x2F) { endFlag = true; if (loop && highestAbsoluteTimeByTrack[trackNum] > loopPoint) { let prevEvent = trackEvents[trackNum][trackEventCount[trackNum] - 1]; if (prevEvent.type === 0xFF && prevEvent.contentSize > 0 && prevEvent.contents![0] === 0x2E) { newTrackEvent = prevEvent; newTrackEvent.type = 0xFF; newTrackEvent.contentSize = 1; newTrackEvent.contents = [0x2F]; } else { let newTrackEventLast = trackEvents[trackNum][trackEventCount[trackNum] + 1] = new TrackEvent(); newTrackEventLast.absoluteTime = highestAbsoluteTime; newTrackEventLast.deltaTime = 0; newTrackEventLast.durationTime = newTrackEvent.durationTime; newTrackEventLast.obsoleteEvent = newTrackEvent.obsoleteEvent; newTrackEventLast.type = 0xFF; newTrackEventLast.contentSize = 1; newTrackEventLast.contents = [0x2F]; newTrackEvent.type = 0xFF; if (highestAbsoluteTime > (prevEvent.absoluteTime + prevEvent.durationTime)) { newTrackEvent.deltaTime = (highestAbsoluteTime - (prevEvent.absoluteTime + prevEvent.durationTime)); newTrackEvent.absoluteTime = highestAbsoluteTime; } else { newTrackEvent.deltaTime = 0; newTrackEvent.absoluteTime = prevEvent.absoluteTime; } newTrackEvent.contentSize = 7; newTrackEvent.contents = [ 0x2D, 0xFF, 0xFF, 0x0, // todo write location 0x0, 0x0, 0x0 ]; newTrackEvent.obsoleteEvent = false; trackEventCount[trackNum]++; } } else { newTrackEvent.type = 0xFF; newTrackEvent.contentSize = 1; newTrackEvent.contents = [0x2F]; } let length = _readMidiByte(dataView, refs, false); // end 00 in real midi } else if (subType === 0x51) { let length = _readMidiByte(dataView, refs, false); newTrackEvent.type = 0xFF; newTrackEvent.contentSize = 4; newTrackEvent.contents = [ 0x51, _readMidiByte(dataView, refs, false), _readMidiByte(dataView, refs, false), _readMidiByte(dataView, refs, false) ]; } else if (subType < 0x7F && !(subType == 0x51 || subType == 0x2F)) { newTrackEvent.type = 0xFF; let length = _getVLBytes(dataView, refs, false); // Was _readMidiByte in Subdrag code. for (let i = 0; i < length; i++) { _readMidiByte(dataView, refs, false); } newTrackEvent.obsoleteEvent = true; } else if (subType === 0x7F) { // Unused sequencer specific event. newTrackEvent.type = 0xFF; let length = _getVLBytes(dataView, refs, false); for (let i = 0; i < length; i++) { _readMidiByte(dataView, refs, false); } newTrackEvent.obsoleteEvent = true; } previousEventValue = eventVal; } else if ((eventVal >= 0x80 && eventVal < 0x90) || (statusBit && (previousEventValue >= 0x80 && previousEventValue < 0x90))) { let curEventVal; let noteNumber; if (statusBit) { newTrackEvent.type = previousEventValue; noteNumber = eventVal; curEventVal = previousEventValue; } else { newTrackEvent.type = eventVal; noteNumber = _readMidiByte(dataView, refs, false); curEventVal = eventVal; } let velocity = _readMidiByte(dataView, refs, false); for (let testBackwards = (trackEventCount[trackNum] - 1); testBackwards >= 0; testBackwards--) { if ((trackEvents[trackNum][testBackwards].type == (0x90 | (curEventVal & 0xF))) && !(trackEvents[trackNum][testBackwards].obsoleteEvent)) { if (trackEvents[trackNum][testBackwards].contents![0] == noteNumber) { trackEvents[trackNum][testBackwards].durationTime = (absoluteTime - trackEvents[trackNum][testBackwards].absoluteTime); break; } } } newTrackEvent.durationTime = 0; newTrackEvent.contentSize = 2; newTrackEvent.contents = [noteNumber, velocity]; newTrackEvent.obsoleteEvent = true; if (!statusBit) previousEventValue = eventVal; } else if ((eventVal >= 0x90 && eventVal < 0xA0) || (statusBit && (previousEventValue >= 0x90 && previousEventValue < 0xA0))) { let curEventVal; let noteNumber; if (statusBit) { newTrackEvent.type = previousEventValue; noteNumber = eventVal; curEventVal = previousEventValue; } else { newTrackEvent.type = eventVal; noteNumber = _readMidiByte(dataView, refs, false); curEventVal = eventVal; } let velocity = _readMidiByte(dataView, refs, false); if (velocity === 0) { // simulate note off for (let testBackwards = (trackEventCount[trackNum] - 1); testBackwards >= 0; testBackwards--) { if (((trackEvents[trackNum][testBackwards].type == curEventVal)) && !(trackEvents[trackNum][testBackwards].obsoleteEvent)) { if (trackEvents[trackNum][testBackwards].contents![0] == noteNumber) { trackEvents[trackNum][testBackwards].durationTime = (absoluteTime - trackEvents[trackNum][testBackwards].absoluteTime); break; } } } newTrackEvent.durationTime = 0; newTrackEvent.contentSize = 2; newTrackEvent.contents = [noteNumber, velocity]; newTrackEvent.obsoleteEvent = true; } else { // check if no note off received, if so, turn it off and restart note for (let testBackwards = (trackEventCount[trackNum] - 1); testBackwards >= 0; testBackwards--) { if (((trackEvents[trackNum][testBackwards].type == curEventVal)) && !(trackEvents[trackNum][testBackwards].obsoleteEvent)) { if (trackEvents[trackNum][testBackwards].contents![0] == noteNumber) { if (trackEvents[trackNum][testBackwards].durationTime == 0) // means unfinished note trackEvents[trackNum][testBackwards].durationTime = (absoluteTime - trackEvents[trackNum][testBackwards].absoluteTime); break; } } } newTrackEvent.durationTime = 0; // to be filled in newTrackEvent.contentSize = 2; newTrackEvent.contents = [noteNumber, velocity]; } if (!statusBit) previousEventValue = eventVal; } else if (((eventVal >= 0xB0) && (eventVal < 0xC0)) || (statusBit && (previousEventValue >= 0xB0 && previousEventValue < 0xC0))) // controller change { let controllerType; if (statusBit) { controllerType = eventVal; newTrackEvent.type = previousEventValue; } else { controllerType = _readMidiByte(dataView, refs, false); newTrackEvent.type = eventVal; } let controllerValue = _readMidiByte(dataView, refs, false); newTrackEvent.contentSize = 2; newTrackEvent.contents = [controllerType, controllerValue]; if (!statusBit) previousEventValue = eventVal; } else if (((eventVal >= 0xC0) && (eventVal < 0xD0)) || (statusBit && (previousEventValue >= 0xC0 && previousEventValue < 0xD0))) // change instrument { let instrument; if (statusBit) { instrument = eventVal; newTrackEvent.type = previousEventValue; } else { instrument = _readMidiByte(dataView, refs, false); newTrackEvent.type = eventVal; } if ((eventVal & 0xF) === 9) // Drums in GM instrument = instrument; else instrument = instrument; newTrackEvent.contentSize = 1; newTrackEvent.contents = [instrument]; if (!statusBit) previousEventValue = eventVal; } else if (((eventVal >= 0xD0) && (eventVal < 0xE0)) || (statusBit && (previousEventValue >= 0xD0 && previousEventValue < 0xE0))) // channel aftertouch { newTrackEvent.type = eventVal; let amount; if (statusBit) { amount = eventVal; newTrackEvent.type = previousEventValue; } else { amount = _readMidiByte(dataView, refs, false); newTrackEvent.type = eventVal; } newTrackEvent.contentSize = 1; newTrackEvent.contents = [amount]; //newTrackEvent.obsoleteEvent = true; // temporary? if (!statusBit) previousEventValue = eventVal; } else if (((eventVal >= 0xE0) && (eventVal < 0xF0)) || (statusBit && (previousEventValue >= 0xE0 && previousEventValue < 0xF0))) // pitch bend { newTrackEvent.type = eventVal; let valueLSB; if (statusBit) { valueLSB = eventVal; newTrackEvent.type = previousEventValue; } else { valueLSB = _readMidiByte(dataView, refs, false); newTrackEvent.type = eventVal; } let valueMSB = _readMidiByte(dataView, refs, false); newTrackEvent.contentSize = 2; newTrackEvent.contents = [valueLSB, valueMSB]; //newTrackEvent.obsoleteEvent = true; // temporary? if (!statusBit) previousEventValue = eventVal; } else if (eventVal == 0xF0 || eventVal == 0xF7) { newTrackEvent.type = eventVal; let length = _getVLBytes(dataView, refs, false); // subtract length for (let i = 0; i < length; i++) { _readMidiByte(dataView, refs, false); } newTrackEvent.obsoleteEvent = true; } else { if (!unknownsHit) { console.error("Invalid midi character found"); unknownsHit = true; } } trackEventCount[trackNum]++; } } let outFile = new ArrayBuffer(0x100000); // TOOD: What size? let outView = new DataView(outFile); let outPos = 0; let timeOffset = 0; let startPosition = 0x44; for (let i = 0; i < numTracks; i++) { let sizeData = 0; let loopStartPosition = 0; let foundLoopStart = false; let previousTrackEvent = 0; if (trackEventCount[i] > 0) { outView.setUint32(outPos, startPosition); outPos += 4; for (let j = 0; j < trackEventCount[i]; j++) { const trackEvent = trackEvents[i][j]; let [timeDelta, lengthTimeDelta] = _returnVLBytes(trackEvent.deltaTime + timeOffset); if (trackEvent.obsoleteEvent) { timeOffset += trackEvent.deltaTime; } else { if (trackEvent.type === 0xFF && trackEvent.contents![0] === 0x2E) { foundLoopStart = true; loopStartPosition = startPosition + sizeData + 1 + trackEvent.contentSize + lengthTimeDelta; } timeOffset = 0; sizeData += lengthTimeDelta; if (trackEvent.type === 0xFF && trackEvent.contents![0] === 0x2D) { let offsetBack = ((startPosition + sizeData) - loopStartPosition + 8); trackEvent.contents![3] = ((offsetBack >> 24) & 0xFF); trackEvent.contents![4] = ((offsetBack >> 16) & 0xFF); trackEvent.contents![5] = ((offsetBack >> 8) & 0xFF); trackEvent.contents![6] = ((offsetBack >> 0) & 0xFF); } if ((trackEvent.type !== previousTrackEvent) || (trackEvent.type === 0xFF)) { sizeData += 1; } sizeData += trackEvent.contentSize; if ((trackEvent.type >= 0x90) && (trackEvent.type < 0xA0)) { let [duration, lengthDurationBytes] = _returnVLBytes(trackEvent.durationTime); sizeData += lengthDurationBytes; } previousTrackEvent = trackEvent.type; } } startPosition += sizeData; } else { outView.setUint32(outPos, 0); outPos += 4; } } for (let i = numTracks; i < 16; i++) { outView.setUint32(outPos, 0); outPos += 4; } outView.setUint32(outPos, tempo); outPos += 4; for (let i = 0; i < numTracks; i++) { if (trackEventCount[i] > 0) { let previousTrackEvent = 0; for (let j = 0; j < trackEventCount[i]; j++) { let trackEvent = trackEvents[i][j]; if (trackEvent.obsoleteEvent) { timeOffset += trackEvent.deltaTime; } else { let [timeDelta, lengthTimeDelta] = _returnVLBytes(trackEvent.deltaTime + timeOffset); timeOffset = 0; outPos = _writeVLBytes(outView, outPos, timeDelta, lengthTimeDelta, false); if (trackEvent.type !== previousTrackEvent || trackEvent.type === 0xFF) { outView.setUint8(outPos, trackEvent.type); outPos++; } copyRange(outView, trackEvent.contents!, outPos, 0, trackEvent.contentSize); outPos += trackEvent.contentSize; if ((trackEvent.type >= 0x90) && (trackEvent.type < 0xA0)) { let [duration, lengthDurationBytes] = _returnVLBytes(trackEvent.durationTime); outPos = _writeVLBytes(outView, outPos, duration, lengthDurationBytes, false); } previousTrackEvent = trackEvent.type; } } } } const inArray = outFile.slice(0, outPos); const inArrayDataView = new DataView(inArray); let offsetheader = []; let extraOffsets = []; for (let x = 0; x < 0x40; x += 4) { offsetheader[x / 4] = ((((((inArrayDataView.getUint8(x) << 8) | inArrayDataView.getUint8(x+1)) << 8) | inArrayDataView.getUint8(x+2)) << 8) | inArrayDataView.getUint8(x+3)); extraOffsets[x / 4] = 0; } for (let x = 0; x < outPos; x++) { if (x > 0x44) { if (inArrayDataView.getUint8(x) === 0xFE) // need to write twice { for (let y = 0; y < numTracks; y++) { if (offsetheader[y] > x) { extraOffsets[y]++; } } } } } for (let x = 0; x < 16; x++) { inArrayDataView.setUint32(x * 4, offsetheader[x] + extraOffsets[x]); } let outPosNew = 0; for (let x = 0; x < outPos; x++) { outView.setUint8(outPosNew, inArrayDataView.getUint8(x)); outPosNew++; if (x > 0x44) { if (inArrayDataView.getUint8(x) === 0xFE) { // need to write twice outView.setUint8(outPosNew, inArrayDataView.getUint8(x)); outPosNew++; } } } assert(outPosNew >= outPos); // if (useRepeaters) // TODO? return outFile.slice(0, outPosNew); } /** * The start of the MIDI data in the ROM is a bunch of * offsets to track data. This counts these offsets. */ function _getTrackCount(inView: DataView): number { let trackCount = 0; // -4 because the last number in the header is the "division" // which is not an offset. for (let i = 0; i < LENGTH_HEADER - 4; i += 4) { const trackOffset = inView.getUint32(i); // At some point the offsets end and there are zeroes. if (trackOffset !== 0) { trackCount++; } } return trackCount; } function _writeMidiHeader(outView: DataView, trackCount: number, division: number): void { // Write magic "MThd" outView.setUint32(0, 0x4D546864); // Write header length outView.setUint32(4, 0x00000006); // Write MIDI format, always 1 (multi-track) outView.setUint16(8, 1); // Write track count outView.setUint16(10, trackCount); // Write division outView.setUint16(12, division); } function _getVLBytes(inView: DataView, refs: IRefs, includeFERepeats: boolean) { let VLVal = 0; let tempByte = 0; while (true) { if (refs.altPattern !== null) { tempByte = refs.altPattern[refs.altOffset]; refs.altOffset++; if (refs.altOffset === refs.altLength) { refs.altPattern = null; refs.altOffset = 0; refs.altLength = 0; } } else { tempByte = inView.getUint8(refs.position); refs.position++; const byteAtPosition = inView.getUint8(refs.position); if (includeFERepeats && tempByte === 0xFE) { if (byteAtPosition !== 0xFE) { let repeatFirstByte = byteAtPosition; refs.position++; const repeatDistanceFromBeginningMarker = (repeatFirstByte << 8) | inView.getUint8(refs.position); refs.position++; const repeatCount = inView.getUint8(refs.position); refs.position++; refs.altPattern = new Array(repeatCount); const altPatternStart = (refs.position - 4) - repeatDistanceFromBeginningMarker; const altPatternEnd = altPatternStart + repeatCount; for (let copy = altPatternStart; copy < altPatternEnd; copy++) { refs.altPattern[copy - altPatternStart] = inView.getUint8(copy); } refs.altOffset = 0; refs.altLength = repeatCount; tempByte = refs.altPattern[refs.altOffset]; refs.altOffset++; } else { // byteAtPosition === 0xFE // Skip duplicate 0xFE refs.position++; } if (refs.altOffset === refs.altLength && refs.altPattern !== null) { refs.altPattern = null; refs.altOffset = 0; refs.altLength = 0; } } } if ((tempByte >> 7) === 0x1) { VLVal += tempByte; VLVal = VLVal << 8; } else { VLVal += tempByte; break; } } refs.original = VLVal; let Vlength = 0; for (let c = 0, a = 0; ; c += 8, a += 7) { Vlength += (((VLVal >> c) & 0x7F) << a); if (c == 24) break; } return Vlength; } function _readMidiByte(inView: DataView, refs: IRefs, includeFERepeats: boolean) { let returnByte: number; if (refs.altPattern !== null) { returnByte = refs.altPattern[refs.altOffset]; refs.altOffset++; } else { returnByte = inView.getUint8(refs.position); refs.position++; if (includeFERepeats && returnByte === 0xFE) { const byteAtPosition = inView.getUint8(refs.position); if (byteAtPosition !== 0xFE) { let repeatFirstByte = byteAtPosition; refs.position++; const repeatDistanceFromBeginningMarker = (repeatFirstByte << 8) | inView.getUint8(refs.position); refs.position++; const repeatCount = inView.getUint8(refs.position); refs.position++; refs.altPattern = new Array(repeatCount); const altPatternStart = (refs.position - 4) - repeatDistanceFromBeginningMarker; const altPatternEnd = altPatternStart + repeatCount; for (let copy = altPatternStart; copy < altPatternEnd; copy++) { refs.altPattern[copy - altPatternStart] = inView.getUint8(copy); } refs.altOffset = 0; refs.altLength = repeatCount; returnByte = refs.altPattern[refs.altOffset]; refs.altOffset++; } else { // Skip duplicate 0xFE refs.position++; } } } if (refs.altOffset === refs.altLength && refs.altPattern !== null) { refs.altPattern = null; refs.altOffset = 0; refs.altLength = 0; } return returnByte; } /** * Writes variable-length bytes to DataView. * @param outView * @param outPos * @param value * @param len * @param includeFERepeats * @returns New outPos value. */ function _writeVLBytes(outView: DataView, outPos: number, value: number, len: number, includeFERepeats: boolean) { let tempByte: number; if (len === 1) { tempByte = value & 0xFF; outView.setUint8(outPos, tempByte); outPos += 1; } else if (len === 2) { tempByte = (value >> 8) & 0xFF; outView.setUint8(outPos, tempByte); outPos += 1; tempByte = value & 0xFF; outView.setUint8(outPos, tempByte); outPos += 1; } else if (len === 3) { tempByte = (value >> 16) & 0xFF; outView.setUint8(outPos, tempByte); outPos += 1; tempByte = (value >> 8) & 0xFF; outView.setUint8(outPos, tempByte); outPos += 1; tempByte = value & 0xFF; outView.setUint8(outPos, tempByte); outPos += 1; } else { tempByte = (value >> 24) & 0xFF; outView.setUint8(outPos, tempByte); outPos += 1; tempByte = (value >> 8) & 0xFF; outView.setUint8(outPos, tempByte); outPos += 1; tempByte = value & 0xFF; outView.setUint8(outPos, tempByte); outPos += 1; } return outPos; } function _returnVLBytes(value: number): [number, number] { let subValue1 = (value >> 21) & 0x7F; let subValue2 = (value >> 14) & 0x7F; let subValue3 = (value >> 7) & 0x7F; let subValue4 = (value >> 0) & 0x7F; if (subValue1 > 0) { let newValue = 0x80808000; newValue |= (subValue1 << 24); newValue |= (subValue2 << 16); newValue |= (subValue3 << 8); newValue |= subValue4; const length = 4; return [newValue, length]; } else if (subValue2 > 0) { let newValue = 0x00808000; newValue |= (subValue2 << 16); newValue |= (subValue3 << 8); newValue |= subValue4; const length = 3; return [newValue, length]; } else if (subValue3 > 0) { let newValue = 0x00008000; newValue |= (subValue3 << 8); newValue |= subValue4; const length = 2; return [newValue, length]; } else { const length = 1; return [value, length]; } } class TrackEvent { obsoleteEvent: boolean = false; deltaTime: number = 0; durationTime: number = 0; absoluteTime: number = 0; type: number = 0x00; contents: number[] | null = null; contentSize: number = 0; }
the_stack
export enum PromoState { PENDING = "PENDING", ACTIVE = "ACTIVE", INACTIVE = "INACTIVE", REJECTED = "REJECTED" } export enum NotificationType { FOLLOW = "FOLLOW", REACTION = "REACTION", COMMENT = "COMMENT", FLARE = "FLARE" } export enum SponsoringType { ONE_TIME = "ONE_TIME", MONTHLY = "MONTHLY", ANNUALLY = "ANNUALLY" } export enum HeaderType { DEFAULT = "DEFAULT", PROMO = "PROMO" } export interface CurrencyInput { symbol: string; code: string; } export interface CreateFlareInput { blocks: CreateBlockInput[]; jobId?: Nullable<string>; } export interface CreateBlockInput { type: string; content: JSON; } export interface AddCommentInput { flareId: string; text: string; } export interface AddLikeInput { flareId: string; reaction: string; } export interface RemoveCommentInput { flareId: string; commentId: string; } export interface RemoveLikeInput { flareId: string; likeId: string; } export interface HeaderPromoInput { title: string; userId: string; description?: Nullable<string>; price: JSON; } export interface HeaderPromoUpdateInput { title?: Nullable<string>; description?: Nullable<string>; price?: Nullable<JSON>; } export interface NotificationInput { to: string; type: NotificationType; followee?: Nullable<string>; comment?: Nullable<string>; flare?: Nullable<string>; read?: Nullable<boolean>; content?: Nullable<JSON>; } export interface SponsorInput { type: SponsoringType; amount: number; currency: CurrencyInput; user: string; paymentDetails: PaymentDetailsInput; } export interface PaymentDetailsInput { type: string; } export interface TipInput { amount: number; note?: Nullable<string>; currency: CurrencyInput; user: string; flare: string; } export interface CreateUserInput { firstName: string; image?: Nullable<string>; lastName: string; email: string; password: string; bio?: Nullable<UserBioInput>; } export interface UpdateUserInput { image?: Nullable<string>; firstName?: Nullable<string>; username?: Nullable<string>; lastName?: Nullable<string>; password?: Nullable<string>; bio?: Nullable<UserBioInput>; preferences?: Nullable<UserPreferencesInput>; } export interface UserBioInput { id?: Nullable<string>; description?: Nullable<string>; github?: Nullable<string>; twitter?: Nullable<string>; linkedin?: Nullable<string>; facebook?: Nullable<string>; hashnode?: Nullable<string>; instagram?: Nullable<string>; devto?: Nullable<string>; } export interface UserPreferencesInput { kudos?: Nullable<JSON>; blogs?: Nullable<JSON>; header?: Nullable<JSON>; } export interface PreferenceKudosInput { enabled: boolean; } export interface PreferenceBlogsInput { enabled: boolean; } export interface PreferenceHeaderInput { enabled: boolean; type: HeaderType; image?: Nullable<JSON>; } export interface GiveKudosInput { userId: string; content: JSON; } export interface UpdateHeaderImageInput { jobId: string; preferenceId: string; } export interface Currency { __typename?: 'Currency'; symbol: string; code: string; } export interface Success { __typename?: 'Success'; success: boolean; } export interface IQuery { __typename?: 'IQuery'; flares(): Nullable<Nullable<Flare>[]> | Promise<Nullable<Nullable<Flare>[]>>; popularFlares(): Nullable<Nullable<Flare>[]> | Promise<Nullable<Nullable<Flare>[]>>; flare(id: string): Nullable<Flare> | Promise<Nullable<Flare>>; bookmarkedFlares(): Nullable<Nullable<Flare>[]> | Promise<Nullable<Nullable<Flare>[]>>; allHeaderPromos(): Nullable<Nullable<HeaderPromo>[]> | Promise<Nullable<Nullable<HeaderPromo>[]>>; headerPromoById(id: string): Nullable<HeaderPromo> | Promise<Nullable<HeaderPromo>>; notifications(): Notification[] | Promise<Notification[]>; sponsors(): Nullable<Nullable<Sponsor>[]> | Promise<Nullable<Nullable<Sponsor>[]>>; sponsor(id: string): Nullable<Sponsor> | Promise<Nullable<Sponsor>>; mySponsors(): Nullable<Nullable<Sponsor>[]> | Promise<Nullable<Nullable<Sponsor>[]>>; tips(): Nullable<Nullable<Tip>[]> | Promise<Nullable<Nullable<Tip>[]>>; tip(id: string): Nullable<Tip> | Promise<Nullable<Tip>>; users(): Nullable<Nullable<User>[]> | Promise<Nullable<Nullable<User>[]>>; user(id: string): Nullable<User> | Promise<Nullable<User>>; userByUsername(username: string): Nullable<User> | Promise<Nullable<User>>; me(): Nullable<User> | Promise<Nullable<User>>; getTopUsers(): Nullable<Nullable<User>[]> | Promise<Nullable<Nullable<User>[]>>; isUsernameAvailable(username: string): Nullable<UserNameAvailability> | Promise<Nullable<UserNameAvailability>>; } export interface IMutation { __typename?: 'IMutation'; createFlare(input: CreateFlareInput): Nullable<Flare> | Promise<Nullable<Flare>>; deleteFlare(id: string): Nullable<Success> | Promise<Nullable<Success>>; addComment(input: AddCommentInput): Nullable<Flare> | Promise<Nullable<Flare>>; addLike(input: AddLikeInput): Nullable<Flare> | Promise<Nullable<Flare>>; removeComment(input: RemoveCommentInput): Nullable<Flare> | Promise<Nullable<Flare>>; removeLike(input: RemoveLikeInput): Nullable<Flare> | Promise<Nullable<Flare>>; bookmark(flareId: string): Nullable<Bookmark> | Promise<Nullable<Bookmark>>; removeBookmark(id: string): Nullable<Success> | Promise<Nullable<Success>>; createHeaderPromo(input: HeaderPromoInput, jobId: string): Nullable<HeaderPromo> | Promise<Nullable<HeaderPromo>>; updateHeaderPromo(id: string, input: HeaderPromoUpdateInput, jobId?: Nullable<string>): Nullable<HeaderPromo> | Promise<Nullable<HeaderPromo>>; deleteHeaderPromo(id: string): Nullable<HeaderPromo> | Promise<Nullable<HeaderPromo>>; applyHeaderPromo(id: string): Nullable<Success> | Promise<Nullable<Success>>; sponsor(input?: Nullable<SponsorInput>): Nullable<Sponsor> | Promise<Nullable<Sponsor>>; cancelSponsorship(id: string): Nullable<Sponsor> | Promise<Nullable<Sponsor>>; tip(input?: Nullable<TipInput>): Nullable<Tip> | Promise<Nullable<Tip>>; createUser(input?: Nullable<CreateUserInput>): Nullable<User> | Promise<Nullable<User>>; updateUser(input?: Nullable<UpdateUserInput>): Nullable<User> | Promise<Nullable<User>>; completeProfile(input?: Nullable<UpdateUserInput>): Nullable<User> | Promise<Nullable<User>>; completeOnboarding(): Nullable<Success> | Promise<Nullable<Success>>; deleteUser(id: string): Nullable<User> | Promise<Nullable<User>>; follow(userId: string): Nullable<User> | Promise<Nullable<User>>; unfollow(userId: string): Nullable<User> | Promise<Nullable<User>>; giveKudos(input?: Nullable<GiveKudosInput>): Nullable<User> | Promise<Nullable<User>>; removeKudos(id: string): Nullable<User> | Promise<Nullable<User>>; updateHeaderImage(input: UpdateHeaderImageInput): Nullable<Success> | Promise<Nullable<Success>>; } export interface Flare { __typename?: 'Flare'; id: string; blocks: Block[]; author: User; deleted?: Nullable<boolean>; tags: string; likes: Like[]; bookmarks: Bookmark[]; _count?: Nullable<JSON>; comments: Nullable<Comment>[]; createdAt: string; } export interface Comment { __typename?: 'Comment'; id: string; text?: Nullable<string>; author: User; createdAt: string; } export interface Block { __typename?: 'Block'; id: string; type: string; content: JSON; } export interface Like { __typename?: 'Like'; id: string; reaction: string; createdAt: string; author: User; } export interface Bookmark { __typename?: 'Bookmark'; id: string; flare: Flare; author: User; createdAt: string; } export interface HeaderPromo { __typename?: 'HeaderPromo'; id: string; title: string; description: string; image: JSON; createdAt: string; user: User; sponsor: User; price: JSON; state?: Nullable<PromoState>; } export interface Notification { __typename?: 'Notification'; id: string; to: User; type: NotificationType; followee?: Nullable<User>; comment?: Nullable<Comment>; flare?: Nullable<Flare>; content?: Nullable<JSON>; createdAt: string; read: boolean; } export interface Sponsor { __typename?: 'Sponsor'; id: string; type: SponsoringType; amount: number; currency: Currency; user: User; sponsoredBy: User; createdAt: string; } export interface Tip { __typename?: 'Tip'; id: string; amount: number; note?: Nullable<string>; currency: Currency; tippedBy: User; user: User; createdAt: string; flare: Flare; } export interface User { __typename?: 'User'; id: string; image?: Nullable<string>; firstName: string; lastName?: Nullable<string>; email?: Nullable<string>; username?: Nullable<string>; password?: Nullable<string>; bio?: Nullable<UserBio>; _count?: Nullable<JSON>; followers?: Nullable<Nullable<User>[]>; following?: Nullable<Nullable<User>[]>; kudos?: Nullable<Nullable<Kudos>[]>; kudosGiven?: Nullable<Nullable<Kudos>[]>; isFollowing: boolean; preferences: UserPreferences; isOnboarded: boolean; onboardingState?: Nullable<JSON>; } export interface UserBio { __typename?: 'UserBio'; id: string; description?: Nullable<string>; github?: Nullable<string>; twitter?: Nullable<string>; linkedin?: Nullable<string>; facebook?: Nullable<string>; hashnode?: Nullable<string>; instagram?: Nullable<string>; devto?: Nullable<string>; } export interface UserPreferences { __typename?: 'UserPreferences'; id: string; user: User; kudos: PreferenceKudos; blogs: PreferenceBlogs; header: PreferenceHeader; } export interface PreferenceKudos { __typename?: 'PreferenceKudos'; enabled: boolean; } export interface PreferenceBlogs { __typename?: 'PreferenceBlogs'; enabled: boolean; } export interface PreferenceHeader { __typename?: 'PreferenceHeader'; enabled: boolean; type: HeaderType; image?: Nullable<JSON>; } export interface Kudos { __typename?: 'Kudos'; id: string; user: User; kudosBy: User; content: JSON; createdAt: string; } export interface UserNameAvailability { __typename?: 'UserNameAvailability'; available: boolean; } export type JSON = any; type Nullable<T> = T | null;
the_stack
export interface Size { // Docs: https://electronjs.org/docs/api/structures/size height: number width: number } export interface Point { // Docs: https://electronjs.org/docs/api/structures/point x: number y: number } export interface Rectangle { // Docs: https://electronjs.org/docs/api/structures/rectangle /** * The height of the rectangle (must be an integer). */ height: number /** * The width of the rectangle (must be an integer). */ width: number /** * The x coordinate of the origin of the rectangle (must be an integer). */ x: number /** * The y coordinate of the origin of the rectangle (must be an integer). */ y: number } export interface Display { // Docs: https://electronjs.org/docs/api/structures/display /** * Can be `available`, `unavailable`, `unknown`. */ accelerometerSupport: | "available" | "unavailable" | "unknown" /** * the bounds of the display in DIP points. */ bounds: Rectangle /** * The number of bits per pixel. */ colorDepth: number /** * represent a color space (three-dimensional object which contains all realizable * color combinations) for the purpose of color conversions */ colorSpace: string /** * The number of bits per color component. */ depthPerComponent: number /** * The display refresh rate. */ displayFrequency: number /** * Unique identifier associated with the display. */ id: number /** * `true` for an internal display and `false` for an external display */ internal: boolean /** * Whether or not the display is a monochrome display. */ monochrome: boolean /** * Can be 0, 90, 180, 270, represents screen rotation in clock-wise degrees. */ rotation: number /** * Output device's pixel scale factor. */ scaleFactor: number size: Size /** * Can be `available`, `unavailable`, `unknown`. */ touchSupport: "available" | "unavailable" | "unknown" /** * the work area of the display in DIP points. */ workArea: Rectangle workAreaSize: Size } interface BrowserWindowConstructorOptions { /** * Window's width in pixels. Default is `800`. */ width?: number /** * Window's height in pixels. Default is `600`. */ height?: number /** * (**required** if y is used) Window's left offset from screen. Default is to * center the window. */ x?: number /** * (**required** if x is used) Window's top offset from screen. Default is to * center the window. */ y?: number /** * The `width` and `height` would be used as web page's size, which means the * actual window's size will include window frame's size and be slightly larger. * Default is `false`. */ useContentSize?: boolean /** * Show window in the center of the screen. */ center?: boolean /** * Window's minimum width. Default is `0`. */ minWidth?: number /** * Window's minimum height. Default is `0`. */ minHeight?: number /** * Window's maximum width. Default is no limit. */ maxWidth?: number /** * Window's maximum height. Default is no limit. */ maxHeight?: number /** * Whether window is resizable. Default is `true`. */ resizable?: boolean /** * Whether window is movable. This is not implemented on Linux. Default is `true`. */ movable?: boolean /** * Whether window is minimizable. This is not implemented on Linux. Default is * `true`. */ minimizable?: boolean /** * Whether window is maximizable. This is not implemented on Linux. Default is * `true`. */ maximizable?: boolean /** * Whether window is closable. This is not implemented on Linux. Default is `true`. */ closable?: boolean /** * Whether the window can be focused. Default is `true`. On Windows setting * `focusable: false` also implies setting `skipTaskbar: true`. On Linux setting * `focusable: false` makes the window stop interacting with wm, so the window will * always stay on top in all workspaces. */ focusable?: boolean /** * Whether the window should always stay on top of other windows. Default is * `false`. */ alwaysOnTop?: boolean /** * Whether the window should show in fullscreen. When explicitly set to `false` the * fullscreen button will be hidden or disabled on macOS. Default is `false`. */ fullscreen?: boolean /** * Whether the window can be put into fullscreen mode. On macOS, also whether the * maximize/zoom button should toggle full screen mode or maximize window. Default * is `true`. */ fullscreenable?: boolean /** * Use pre-Lion fullscreen on macOS. Default is `false`. */ simpleFullscreen?: boolean /** * Whether to show the window in taskbar. Default is `false`. */ skipTaskbar?: boolean /** * Whether the window is in kiosk mode. Default is `false`. */ kiosk?: boolean /** * Default window title. Default is `"Electron"`. If the HTML tag `<title>` is * defined in the HTML file loaded by `loadURL()`, this property will be ignored. */ title?: string /** * The window icon. On Windows it is recommended to use `ICO` icons to get best * visual effects, you can also leave it undefined so the executable's icon will be * used. */ icon?: string /** * Whether window should be shown when created. Default is `true`. */ show?: boolean /** * Whether the renderer should be active when `show` is `false` and it has just * been created. In order for `document.visibilityState` to work correctly on * first load with `show: false` you should set this to `false`. Setting this to * `false` will cause the `ready-to-show` event to not fire. Default is `true`. */ paintWhenInitiallyHidden?: boolean /** * Specify `false` to create a frameless window. Default is `true`. */ frame?: boolean /** * Whether this is a modal window. This only works when the window is a child * window. Default is `false`. */ modal?: boolean /** * Whether clicking an inactive window will also click through to the web contents. * Default is `false` on macOS. This option is not configurable on other platforms. */ acceptFirstMouse?: boolean /** * Whether to hide cursor when typing. Default is `false`. */ disableAutoHideCursor?: boolean /** * Auto hide the menu bar unless the `Alt` key is pressed. Default is `false`. */ autoHideMenuBar?: boolean /** * Enable the window to be resized larger than screen. Only relevant for macOS, as * other OSes allow larger-than-screen windows by default. Default is `false`. */ enableLargerThanScreen?: boolean /** * Window's background color as a hexadecimal value, like `#66CD00` or `#FFF` or * `#80FFFFFF` (alpha in #AARRGGBB format is supported if `transparent` is set to * `true`). Default is `#FFF` (white). */ backgroundColor?: string /** * Whether window should have a shadow. Default is `true`. */ hasShadow?: boolean /** * Set the initial opacity of the window, between 0.0 (fully transparent) and 1.0 * (fully opaque). This is only implemented on Windows and macOS. */ opacity?: number /** * Forces using dark theme for the window, only works on some GTK+3 desktop * environments. Default is `false`. */ darkTheme?: boolean /** * Makes the window transparent. Default is `false`. On Windows, does not work * unless the window is frameless. */ transparent?: boolean /** * The type of window, default is normal window. See more about this below. */ type?: string /** * Specify how the material appearance should reflect window activity state on * macOS. Must be used with the `vibrancy` property. Possible values are: */ visualEffectState?: "followWindow" | "active" | "inactive" /** * The style of window title bar. Default is `default`. Possible values are: * * @platform darwin,win32 */ titleBarStyle?: | "default" | "hidden" | "hiddenInset" | "customButtonsOnHover" /** * Set a custom position for the traffic light buttons in frameless windows. */ trafficLightPosition?: Point /** * Whether frameless window should have rounded corners on macOS. Default is * `true`. */ roundedCorners?: boolean /** * Shows the title in the title bar in full screen mode on macOS for `hiddenInset` * titleBarStyle. Default is `false`. * * @deprecated */ fullscreenWindowTitle?: boolean /** * Use `WS_THICKFRAME` style for frameless windows on Windows, which adds standard * window frame. Setting it to `false` will remove window shadow and window * animations. Default is `true`. */ thickFrame?: boolean /** * Add a type of vibrancy effect to the window, only on macOS. Can be * `appearance-based`, `light`, `dark`, `titlebar`, `selection`, `menu`, `popover`, * `sidebar`, `medium-light`, `ultra-dark`, `header`, `sheet`, `window`, `hud`, * `fullscreen-ui`, `tooltip`, `content`, `under-window`, or `under-page`. Please * note that `appearance-based`, `light`, `dark`, `medium-light`, and `ultra-dark` * are deprecated and have been removed in macOS Catalina (10.15). */ vibrancy?: | "appearance-based" | "light" | "dark" | "titlebar" | "selection" | "menu" | "popover" | "sidebar" | "medium-light" | "ultra-dark" | "header" | "sheet" | "window" | "hud" | "fullscreen-ui" | "tooltip" | "content" | "under-window" | "under-page" /** * Controls the behavior on macOS when option-clicking the green stoplight button * on the toolbar or by clicking the Window > Zoom menu item. If `true`, the window * will grow to the preferred width of the web page when zoomed, `false` will cause * it to zoom to the width of the screen. This will also affect the behavior when * calling `maximize()` directly. Default is `false`. */ zoomToPageWidth?: boolean /** * Tab group name, allows opening the window as a native tab on macOS 10.12+. * Windows with the same tabbing identifier will be grouped together. This also * adds a native new tab button to your window's tab bar and allows your `app` and * window to receive the `new-window-for-tab` event. */ tabbingIdentifier?: string /** * Settings of web page's features. */ webPreferences?: WebPreferences /** * When using a frameless window in conjuction with * `win.setWindowButtonVisibility(true)` on macOS or using a `titleBarStyle` so * that the standard window controls ("traffic lights" on macOS) are visible, this * property enables the Window Controls Overlay JavaScript APIs and CSS Environment * Variables. Specifying `true` will result in an overlay with default system * colors. Default is `false`. */ titleBarOverlay?: TitleBarOverlay | boolean }
the_stack
import { aTimeout } from '@open-wc/testing/index-no-side-effects'; import { assert } from 'chai'; import * as sinon from 'sinon'; import { setAuthStateCache } from '../auth_state_cache'; import { PrpcClientExt } from '../libs/prpc_client_ext'; import { BUILD_FIELD_MASK, BuildsService } from '../services/buildbucket'; import { queryAuthState } from '../services/milo_internal'; import { getInvIdFromBuildId, getInvIdFromBuildNum, ResultDb } from '../services/resultdb'; import { Prefetcher } from './prefetch'; describe('prefetch', () => { let fetchStub: sinon.SinonStub<[RequestInfo, RequestInit | undefined], Promise<Response>>; let respondWithStub: sinon.SinonStub<[Response | Promise<Response>], void>; let prefetcher: Prefetcher; // Helps generate fetch requests that are identical to the ones generated // by the pRPC Clients. let fetchInterceptor: sinon.SinonStub<[RequestInfo, RequestInit | undefined], Promise<Response>>; let buildsService: BuildsService; let resultdb: ResultDb; beforeEach(async () => { await setAuthStateCache({ accessToken: 'access-token', identity: 'user:user-id' }); fetchStub = sinon.stub<[RequestInfo, RequestInit | undefined], Promise<Response>>(); respondWithStub = sinon.stub<[Response | Promise<Response>], void>(); prefetcher = new Prefetcher(CONFIGS, fetchStub); fetchInterceptor = sinon.stub<[RequestInfo, RequestInit | undefined], Promise<Response>>(); buildsService = new BuildsService( new PrpcClientExt({ host: CONFIGS.BUILDBUCKET.HOST, fetchImpl: fetchInterceptor }, () => 'access-token') ); resultdb = new ResultDb( new PrpcClientExt({ host: CONFIGS.RESULT_DB.HOST, fetchImpl: fetchInterceptor }, () => 'access-token') ); }); it('prefetches build page resources', async () => { const authResponse = new Response(JSON.stringify({})); const buildResponse = new Response(JSON.stringify({})); const invResponse = new Response(JSON.stringify({})); const testVariantsResponse = new Response(JSON.stringify({})); fetchStub.onCall(0).resolves(authResponse); fetchStub.onCall(1).resolves(buildResponse); fetchStub.onCall(2).resolves(invResponse); fetchStub.onCall(3).resolves(testVariantsResponse); const invName = 'invocations/' + (await getInvIdFromBuildNum( { project: 'chromium', bucket: 'ci', builder: 'Win7 Tests (1)', }, 116372 )); await prefetcher.prefetchResources( new URL('https://luci-milo-dev.appspot.com/ui/p/chromium/builders/ci/Win7%20Tests%20(1)/116372') ); await aTimeout(100); const requestedUrls = fetchStub.getCalls().map((c) => new Request(...c.args).url); assert.strictEqual(requestedUrls.length, 4); assert.includeMembers(requestedUrls, [ `https://${self.location.host}/auth-state`, `https://${CONFIGS.BUILDBUCKET.HOST}/prpc/buildbucket.v2.Builds/GetBuild`, `https://${CONFIGS.RESULT_DB.HOST}/prpc/luci.resultdb.v1.ResultDB/GetInvocation`, `https://${CONFIGS.RESULT_DB.HOST}/prpc/luci.resultdb.v1.ResultDB/QueryTestVariants`, ]); // Check whether the auth state was prefetched. queryAuthState(fetchInterceptor); let cacheHit = prefetcher.respondWithPrefetched({ request: new Request(...fetchInterceptor.getCall(0).args), respondWith: respondWithStub, } as Partial<FetchEvent> as FetchEvent); let cachedRes = await respondWithStub.getCall(0).args[0]; assert.isTrue(cacheHit); assert.strictEqual(cachedRes, authResponse); assert.strictEqual(fetchStub.callCount, 4); // Check whether the build was prefetched. buildsService.getBuild({ builder: { project: 'chromium', bucket: 'ci', builder: 'Win7 Tests (1)', }, buildNumber: 116372, fields: BUILD_FIELD_MASK, }); cacheHit = prefetcher.respondWithPrefetched({ request: new Request(...fetchInterceptor.getCall(1).args), respondWith: respondWithStub, } as Partial<FetchEvent> as FetchEvent); cachedRes = await respondWithStub.getCall(1).args[0]; assert.isTrue(cacheHit); assert.strictEqual(cachedRes, buildResponse); assert.strictEqual(fetchStub.callCount, 4); // Check whether the invocation was prefetched. resultdb.getInvocation({ name: invName }); cacheHit = prefetcher.respondWithPrefetched({ request: new Request(...fetchInterceptor.getCall(2).args), respondWith: respondWithStub, } as Partial<FetchEvent> as FetchEvent); cachedRes = await respondWithStub.getCall(2).args[0]; assert.isTrue(cacheHit); assert.strictEqual(cachedRes, invResponse); assert.strictEqual(fetchStub.callCount, 4); // Check whether the test variants was prefetched. resultdb.queryTestVariants({ invocations: [invName] }); cacheHit = prefetcher.respondWithPrefetched({ request: new Request(...fetchInterceptor.getCall(3).args), respondWith: respondWithStub, } as Partial<FetchEvent> as FetchEvent); cachedRes = await respondWithStub.getCall(3).args[0]; assert.isTrue(cacheHit); assert.strictEqual(cachedRes, testVariantsResponse); assert.strictEqual(fetchStub.callCount, 4); }); it('prefetches build page resources when visiting a short build page url', async () => { const authResponse = new Response(JSON.stringify({})); const buildResponse = new Response(JSON.stringify({})); const invResponse = new Response(JSON.stringify({})); const testVariantsResponse = new Response(JSON.stringify({})); fetchStub.onCall(0).resolves(authResponse); fetchStub.onCall(1).resolves(buildResponse); fetchStub.onCall(2).resolves(invResponse); fetchStub.onCall(3).resolves(testVariantsResponse); const invName = 'invocations/' + getInvIdFromBuildId('123456789'); await prefetcher.prefetchResources(new URL('https://luci-milo-dev.appspot.com/ui/b/123456789')); await aTimeout(100); const requestedUrls = fetchStub.getCalls().map((c) => new Request(...c.args).url); assert.strictEqual(requestedUrls.length, 4); assert.includeMembers(requestedUrls, [ `https://${self.location.host}/auth-state`, `https://${CONFIGS.BUILDBUCKET.HOST}/prpc/buildbucket.v2.Builds/GetBuild`, `https://${CONFIGS.RESULT_DB.HOST}/prpc/luci.resultdb.v1.ResultDB/GetInvocation`, `https://${CONFIGS.RESULT_DB.HOST}/prpc/luci.resultdb.v1.ResultDB/QueryTestVariants`, ]); // Check whether the auth state was prefetched. queryAuthState(fetchInterceptor); let cacheHit = prefetcher.respondWithPrefetched({ request: new Request(...fetchInterceptor.getCall(0).args), respondWith: respondWithStub, } as Partial<FetchEvent> as FetchEvent); let cachedRes = await respondWithStub.getCall(0).args[0]; assert.isTrue(cacheHit); assert.strictEqual(cachedRes, authResponse); assert.strictEqual(fetchStub.callCount, 4); // Check whether the build was prefetched. buildsService.getBuild({ id: '123456789', fields: BUILD_FIELD_MASK, }); cacheHit = prefetcher.respondWithPrefetched({ request: new Request(...fetchInterceptor.getCall(1).args), respondWith: respondWithStub, } as Partial<FetchEvent> as FetchEvent); cachedRes = await respondWithStub.getCall(1).args[0]; assert.isTrue(cacheHit); assert.strictEqual(cachedRes, buildResponse); assert.strictEqual(fetchStub.callCount, 4); // Check whether the invocation was prefetched. resultdb.getInvocation({ name: invName }); cacheHit = prefetcher.respondWithPrefetched({ request: new Request(...fetchInterceptor.getCall(2).args), respondWith: respondWithStub, } as Partial<FetchEvent> as FetchEvent); cachedRes = await respondWithStub.getCall(2).args[0]; assert.isTrue(cacheHit); assert.strictEqual(cachedRes, invResponse); assert.strictEqual(fetchStub.callCount, 4); // Check whether the test variants was prefetched. resultdb.queryTestVariants({ invocations: [invName] }); cacheHit = prefetcher.respondWithPrefetched({ request: new Request(...fetchInterceptor.getCall(3).args), respondWith: respondWithStub, } as Partial<FetchEvent> as FetchEvent); cachedRes = await respondWithStub.getCall(3).args[0]; assert.isTrue(cacheHit); assert.strictEqual(cachedRes, testVariantsResponse); assert.strictEqual(fetchStub.callCount, 4); }); it('prefetches artifact page resources', async () => { const authResponse = new Response(JSON.stringify({})); const artifactResponse = new Response( JSON.stringify({ name: 'invocations/inv-id/tests/test-id/results/result-id/artifacts/artifact-id', artifactId: 'artifact-id', }) ); fetchStub.onCall(0).resolves(authResponse); fetchStub.onCall(1).resolves(artifactResponse); await prefetcher.prefetchResources( new URL( // eslint-disable-next-line max-len 'https://luci-milo-dev.appspot.com/ui/artifact/raw/invocations/inv-id/tests/test-id/results/result-id/artifacts/artifact-id' ) ); await aTimeout(100); const requestedUrls = fetchStub.getCalls().map((c) => new Request(...c.args).url); assert.strictEqual(requestedUrls.length, 2); assert.includeMembers(requestedUrls, [ `https://${self.location.host}/auth-state`, `https://${CONFIGS.RESULT_DB.HOST}/prpc/luci.resultdb.v1.ResultDB/GetArtifact`, ]); // Check whether the auth state was prefetched. queryAuthState(fetchInterceptor); let cacheHit = prefetcher.respondWithPrefetched({ request: new Request(...fetchInterceptor.getCall(0).args), respondWith: respondWithStub, } as Partial<FetchEvent> as FetchEvent); let cachedRes = await respondWithStub.getCall(0).args[0]; assert.isTrue(cacheHit); assert.strictEqual(cachedRes, authResponse); assert.strictEqual(fetchStub.callCount, 2); // Check whether the artifact was prefetched. resultdb.getArtifact({ name: 'invocations/inv-id/tests/test-id/results/result-id/artifacts/artifact-id', }); cacheHit = prefetcher.respondWithPrefetched({ request: new Request(...fetchInterceptor.getCall(1).args), respondWith: respondWithStub, } as Partial<FetchEvent> as FetchEvent); cachedRes = await respondWithStub.getCall(1).args[0]; assert.isTrue(cacheHit); assert.strictEqual(fetchStub.callCount, 2); assert.strictEqual(cachedRes, artifactResponse); }); });
the_stack
import { entries, groupBy, pickBy } from 'lodash'; import { Browser } from 'tests/end-to-end/common/browser'; import { launchBrowser } from 'tests/end-to-end/common/browser-factory'; import { NestedIframeTargetPage, NestedIframeWindowMessageRecord, sortMessages, } from 'tests/end-to-end/common/page-controllers/nested-iframe-target-page'; import { PopupPage } from 'tests/end-to-end/common/page-controllers/popup-page'; import { DEFAULT_E2E_TEST_TIMEOUT_MS, DEFAULT_TARGET_PAGE_SCAN_TIMEOUT_MS, } from 'tests/end-to-end/common/timeouts'; // This file constitutes the success criteria for feat(web-postmessage) describe('Target Page window.postMessage behavior', () => { let browser: Browser; let targetPage: NestedIframeTargetPage; let popupPage: PopupPage; beforeEach(async () => { browser = await launchBrowser({ suppressFirstTimeDialog: true, addExtraPermissionsToManifest: 'all-origins', }); targetPage = await browser.newNestedIframeTargetPage(); popupPage = await browser.newPopupPage(targetPage); await popupPage.gotoAdhocPanel(); }); afterEach(async () => { await browser?.close(); }); // We're doing one combined test rather than an it.each(spoofingScenarios) only for performance // and reliability's sake; this test is unusually slow because it requires that we wait for a // duration rather than a specific event. it( 'does not respond to spoofed messages', async () => { await enableSomeCrossFrameVisualizer(); await targetPage.resetWindowMessageRecording(); for (const message of spoofingScenarios) { await targetPage.sendWindowPostMessage(message); } await targetPage.waitForTimeout(DEFAULT_TARGET_PAGE_SCAN_TIMEOUT_MS); // We should see the messages we spoofed in each corresponding receiver window, but no // additional response messages. const recordedMessages = await targetPage.getRecordedWindowMessages(); expect(sortMessages(recordedMessages)).toEqual(sortMessages(spoofingScenarios)); }, DEFAULT_E2E_TEST_TIMEOUT_MS + DEFAULT_TARGET_PAGE_SCAN_TIMEOUT_MS, ); it( 'does not respond to replay attacks', async () => { await targetPage.resetWindowMessageRecording(); await enableSomeCrossFrameVisualizer(); const messagesToEnableVisualizer = await targetPage.getRecordedWindowMessages(); await targetPage.resetWindowMessageRecording(); for (const message of messagesToEnableVisualizer) { await targetPage.sendWindowPostMessage(message); } await targetPage.waitForTimeout(DEFAULT_TARGET_PAGE_SCAN_TIMEOUT_MS); // We should see the messages we spoofed in each corresponding receiver window, but no // additional response messages. const messagesRecordedDuringSpoofing = await targetPage.getRecordedWindowMessages(); expect(sortMessages(messagesRecordedDuringSpoofing)).toEqual( sortMessages(messagesToEnableVisualizer), ); }, DEFAULT_E2E_TEST_TIMEOUT_MS + DEFAULT_TARGET_PAGE_SCAN_TIMEOUT_MS, ); it( 'does not respond to reflected replay attacks', async () => { await targetPage.resetWindowMessageRecording(); await enableSomeCrossFrameVisualizer(); const legitimateMessages = await targetPage.getRecordedWindowMessages(); await targetPage.resetWindowMessageRecording(); const reflectedMessages = legitimateMessages.map(m => ({ source: m.dest, dest: m.source, data: m.data, })); for (const message of reflectedMessages) { await targetPage.sendWindowPostMessage(message); } await targetPage.waitForTimeout(DEFAULT_TARGET_PAGE_SCAN_TIMEOUT_MS); // We should see the messages we spoofed in each corresponding receiver window, but no // additional response messages. const messagesRecordedDuringSpoofing = await targetPage.getRecordedWindowMessages(); expect(sortMessages(messagesRecordedDuringSpoofing)).toEqual( sortMessages(reflectedMessages), ); }, DEFAULT_E2E_TEST_TIMEOUT_MS + DEFAULT_TARGET_PAGE_SCAN_TIMEOUT_MS, ); // This is a regression test for a known-bad case, and verifies that we aren't sending any // problematic "raw" axe-core messages through window.postMessage. This intentionally doesn't // verify a full snapshot of each message (unit tests cover that) it('avoids leaking page contents in window messages', async () => { await targetPage.resetWindowMessageRecording(); await enableSomeCrossFrameVisualizer(); const recordedMessages = await targetPage.getRecordedWindowMessages(); // Smoke test to ensure we're successfully recording at all. // // For each of [axe.ping, axe.start-scan, insights.draw], there // should be a request-response pair (2 messages) for each of the top-child and // child-grandchild relationships, ie, 3 * 2 * 2 = 12. expect(recordedMessages.length).toBe(12); // The important test (that no messages contain HTML snippets) const mayContainHtmlSnippet = (msg: NestedIframeWindowMessageRecord) => JSON.stringify(msg.data).includes('<'); expect(recordedMessages.filter(mayContainHtmlSnippet)).toEqual([]); }); // We have some customers that normally intercept and drop unrecognized window messages. To // enable them to avoid dropping legitimate messages from us, we guarantee that all of our // messages should use a very specific signature pattern that they recognize. If this pattern // were to change, it would be a breaking change for those customers. it('includes the required stable signature in all messages', async () => { await targetPage.resetWindowMessageRecording(); await enableSomeCrossFrameVisualizer(); const recordedMessages = await targetPage.getRecordedWindowMessages(); for (const message of recordedMessages) { expect(tryJsonParse(message.data)).toHaveProperty( 'messageStableSignature', 'e467510c-ca1f-47df-ace1-a39f7f0678c9', ); } }); it('does not reuse the same message data twice, even across frames', async () => { await targetPage.resetWindowMessageRecording(); await enableSomeCrossFrameVisualizer(); const recordedMessages = await targetPage.getRecordedWindowMessages(); // The rest of this is just verifying that each element of recordedMessages.map(m => m.data) // is unique in a way that presents the complete set of errors if the test fails. const messagesByData = groupBy(recordedMessages, m => m.data); const repeatedMessagesByData = pickBy(messagesByData, messages => messages.length > 1); const pickDirectionFromMessage = (message: NestedIframeWindowMessageRecord) => ({ source: message.source, dest: message.dest, }); const repeatedMessagesWithDirections = entries(repeatedMessagesByData).map( ([data, messages]) => ({ data, directions: messages.map(pickDirectionFromMessage), }), ); expect(repeatedMessagesWithDirections).toEqual([]); }); const spoofedAxeMessage = JSON.stringify({ uuid: '00000000-0000-0000-0000-0000000000001', topic: 'axe.start', message: { options: { runOnly: ['hidden-content'], excludeHidden: false, resultTypes: ['passes', 'violations', 'incomplete', 'inapplicable'], }, command: 'rules', parameter: null, context: { initiator: false, page: true, include: [], exclude: [], }, }, _respondable: true, _source: 'axeAPI.x.y.z', _axeuuid: '00000000-0000-0000-0000-0000000000002', }); const spoofedInsightsPingMessage = JSON.stringify({ messageId: '00000000-0000-0000-0000-0000000000001', command: 'insights.ping', message: null, messageStableSignature: 'e467510c-ca1f-47df-ace1-a39f7f0678c9', messageSourceId: 'Accessibility Insights for Web - Dev', messageVersion: '1.0.4', }); const spoofedInsightsDrawMessage = JSON.stringify({ messageId: '00000000-0000-0000-0000-0000000000001', command: 'insights.draw', message: { elementResults: [], isEnabled: false, featureFlagStoreData: {}, configId: 'headings', }, messageStableSignature: 'e467510c-ca1f-47df-ace1-a39f7f0678c9', messageSourceId: 'Accessibility Insights for Web - Dev', messageVersion: '1.0.4', }); // The cases are based on which sending patterns legitimate messages follow const spoofingScenarios: NestedIframeWindowMessageRecord[] = [ { source: 'top', dest: 'child', data: spoofedInsightsPingMessage }, { source: 'top', dest: 'child', data: spoofedInsightsDrawMessage }, { source: 'child', dest: 'top', data: spoofedInsightsDrawMessage }, { source: 'grandchild', dest: 'top', data: spoofedInsightsDrawMessage }, { source: 'top', dest: 'child', data: spoofedAxeMessage }, { source: 'child', dest: 'top', data: spoofedAxeMessage }, ]; async function enableSomeCrossFrameVisualizer() { await popupPage.enableToggleByAriaLabel('Headings'); await Promise.all( targetPage.allFrames().map( async frame => await frame.waitForSelector('#insights-shadow-host .insights-highlight-box', { timeout: DEFAULT_TARGET_PAGE_SCAN_TIMEOUT_MS, }), ), ); } function tryJsonParse(maybeJsonString: any): any | null { if (typeof maybeJsonString !== 'string') { return null; } try { return JSON.parse(maybeJsonString); } catch { return null; } } });
the_stack
* @packageDocumentation * @module std.internal */ //================================================================ import { XTreeNode } from "./XTreeNode"; import { Color } from "./Color"; import { Comparator } from "../functional/Comparator"; /** * Red-Black Tree * * @reference https://en.wikipedia.org/w/index.php?title=Red%E2%80%93black_tree * @inventor Rudolf Bayer * @author Jeongho Nam - https://github.com/samchon */ export abstract class XTree<T> { protected root_: XTreeNode<T> | null; private comp_: Comparator<T>; private equal_: Comparator<T>; /* --------------------------------------------------------- CONSTRUCTOR --------------------------------------------------------- */ protected constructor(comp: Comparator<T>) { this.root_ = null; this.comp_ = comp; this.equal_ = function (x: T, y: T): boolean { return !comp(x, y) && !comp(y, x); }; } public clear(): void { this.root_ = null; } /* ========================================================= ACCESSORS - GETTERS - COMPARISON ============================================================ GETTERS --------------------------------------------------------- */ public root(): XTreeNode<T> | null { return this.root_; } public get(val: T): XTreeNode<T> | null { const ret = this.nearest(val); if (ret === null || !this.equal_(val, ret.value)) return null; else return ret; } public nearest(val: T): XTreeNode<T> | null { // NEED NOT TO ITERATE if (this.root_ === null) return null; //---- // ITERATE //---- let ret: XTreeNode<T> | null = this.root_; while (true) // UNTIL MEET THE MATCHED VALUE OR FINAL BRANCH { let my_node: XTreeNode<T> | null = null; // COMPARE if (this.comp_(val, ret.value)) my_node = ret.left; else if (this.comp_(ret.value, val)) my_node = ret.right; else return ret; // MATCHED VALUE // FINAL BRANCH? OR KEEP GOING if (my_node !== null) ret = my_node; else break; } return ret; // DIFFERENT NODE } private _Fetch_maximum(node: XTreeNode<T>): XTreeNode<T> { while (node.right !== null) node = node.right; return node; } /* ========================================================= ELEMENTS I/O - INSERT - ERASE - COLOR - ROTATION ============================================================ INSERT --------------------------------------------------------- */ public insert(val: T): void { const parent = this.nearest(val); const node = new XTreeNode<T>(val, Color.RED); if (parent === null) this.root_ = node; else { node.parent = parent; if (this.comp_(node.value, parent.value)) parent.left = node; else parent.right = node; } this._Insert_case1(node); } private _Insert_case1(n: XTreeNode<T>): void { if (n.parent === null) n.color = Color.BLACK; else this._Insert_case2(n); } private _Insert_case2(n: XTreeNode<T>): void { if (this._Fetch_color(n.parent) === Color.BLACK) return; else this._Insert_case3(n); } private _Insert_case3(n: XTreeNode<T>): void { if (this._Fetch_color(n.uncle) === Color.RED) { n.parent!.color = Color.BLACK; n.uncle!.color = Color.BLACK; n.grand!.color = Color.RED; this._Insert_case1(n.grand!); } else this._Insert_case4(n); } private _Insert_case4(n: XTreeNode<T>): void { if (n === n.parent!.right && n.parent === n.grand!.left) { this._Rotate_left(n.parent!); n = n.left!; } else if (n === n.parent!.left && n.parent === n.grand!.right) { this._Rotate_right(n.parent!); n = n.right!; } this._Insert_case5(n); } private _Insert_case5(n: XTreeNode<T>): void { n.parent!.color = Color.BLACK; n.grand!.color = Color.RED; if (n === n.parent!.left && n.parent === n.grand!.left) this._Rotate_right(n.grand!); else this._Rotate_left(n.grand!); } /* --------------------------------------------------------- ERASE --------------------------------------------------------- */ public erase(val: T): void { let node: XTreeNode<T> | null = this.get(val); if (node === null) return; // UNABLE TO FIND THE MATCHED NODE if (node.left !== null && node.right !== null) { const pred: XTreeNode<T> = this._Fetch_maximum(node.left); node.value = pred.value; node = pred; } const child = (node.right === null) ? node.left : node.right; if (this._Fetch_color(node) === Color.BLACK) { node.color = this._Fetch_color(child); this._Erase_case1(node); } this._Replace_node(node, child); if (this._Fetch_color(this.root_) === Color.RED) this.root_!.color = Color.BLACK; } private _Erase_case1(n: XTreeNode<T>): void { if (n.parent === null) return; else this._Erase_case2(n); } private _Erase_case2(n: XTreeNode<T>): void { if (this._Fetch_color(n.sibling) === Color.RED) { n.parent!.color = Color.RED; n.sibling!.color = Color.BLACK; if (n === n.parent!.left) this._Rotate_left(n.parent!); else this._Rotate_right(n.parent!); } this._Erase_case3(n); } private _Erase_case3(n: XTreeNode<T>): void { if (this._Fetch_color(n.parent) === Color.BLACK && this._Fetch_color(n.sibling) === Color.BLACK && this._Fetch_color(n.sibling!.left) === Color.BLACK && this._Fetch_color(n.sibling!.right) === Color.BLACK) { n.sibling!.color = Color.RED; this._Erase_case1(n.parent!); } else this._Erase_case4(n); } private _Erase_case4(N: XTreeNode<T>): void { if (this._Fetch_color(N.parent) === Color.RED && N.sibling !== null && this._Fetch_color(N.sibling) === Color.BLACK && this._Fetch_color(N.sibling.left) === Color.BLACK && this._Fetch_color(N.sibling.right) === Color.BLACK) { N.sibling.color = Color.RED; N.parent!.color = Color.BLACK; } else this._Erase_case5(N); } private _Erase_case5(n: XTreeNode<T>): void { if (n === n.parent!.left && n.sibling !== null && this._Fetch_color(n.sibling) === Color.BLACK && this._Fetch_color(n.sibling.left) === Color.RED && this._Fetch_color(n.sibling.right) === Color.BLACK) { n.sibling.color = Color.RED; n.sibling.left!.color = Color.BLACK; this._Rotate_right(n.sibling); } else if (n === n.parent!.right && n.sibling !== null && this._Fetch_color(n.sibling) === Color.BLACK && this._Fetch_color(n.sibling.left) === Color.BLACK && this._Fetch_color(n.sibling.right) === Color.RED) { n.sibling.color = Color.RED; n.sibling.right!.color = Color.BLACK; this._Rotate_left(n.sibling); } this._Erase_case6(n); } private _Erase_case6(n: XTreeNode<T>): void { n.sibling!.color = this._Fetch_color(n.parent); n.parent!.color = Color.BLACK; if (n === n.parent!.left) { n.sibling!.right!.color = Color.BLACK; this._Rotate_left(n.parent!); } else { n.sibling!.left!.color = Color.BLACK; this._Rotate_right(n.parent!); } } /* --------------------------------------------------------- ROTATION --------------------------------------------------------- */ private _Rotate_left(node: XTreeNode<T>): void { const right = node.right; this._Replace_node(node, right); node.right = right!.left; if (right!.left !== null) right!.left!.parent = node; right!.left = node; node.parent = right; } private _Rotate_right(node: XTreeNode<T>): void { const left = node.left; this._Replace_node(node, left); node.left = left!.right; if (left!.right !== null) left!.right!.parent = node; left!.right = node; node.parent = left; } private _Replace_node(oldNode: XTreeNode<T>, newNode: XTreeNode<T> | null): void { if (oldNode.parent === null) this.root_ = newNode; else { if (oldNode === oldNode.parent.left) oldNode.parent.left = newNode; else oldNode.parent.right = newNode; } if (newNode !== null) newNode.parent = oldNode.parent; } /* --------------------------------------------------------- COLOR --------------------------------------------------------- */ private _Fetch_color(node: XTreeNode<T> | null): Color { if (node === null) return Color.BLACK; else return node.color; } }
the_stack
import { Vector3, Quaternion, EventDispatcher, PerspectiveCamera, OrthographicCamera, Vector2, MOUSE } from 'three' const STATE = { NONE: -1, ROTATE: 0, ZOOM: 1, PAN: 2, TOUCH_ROTATE: 3, TOUCH_ZOOM_PAN: 4 } const CHANGE_EVENT = { type: 'change' } const START_EVENT = { type: 'start' } const END_EVENT = { type: 'end' } const EPS = 0.000001 const LAST_POSITION = new Vector3() const LAST_ZOOM = { value: 1 } export class THREETrackballControls extends EventDispatcher { camera: PerspectiveCamera | OrthographicCamera domElement: HTMLElement window: Window // API enabled: boolean screen: any rotateSpeed: number zoomSpeed: number panSpeed: number noRotate: boolean noZoom: boolean noPan: boolean staticMoving: boolean dynamicDampingFactor: number minDistance: number maxDistance: number keys: number[] mouseButtons: any target: Vector3 private _state: number private _keyState: number private _eye: Vector3 private _movePrev: Vector2 private _moveCurr: Vector2 private _lastAxis: Vector3 private _lastAngle: number private _zoomStart: Vector2 private _zoomEnd: Vector2 private _touchZoomDistanceStart: number private _touchZoomDistanceEnd: number private _panStart: Vector2 private _panEnd: Vector2 private target0: Vector3 private position0: Vector3 private up0: Vector3 private zoom0: number private keydown: EventListener private keyup: EventListener private mousedown: EventListener private mouseup: EventListener private mousemove: EventListener private mousewheel: EventListener private touchstart: EventListener private touchmove: EventListener private touchend: EventListener private contextmenu: EventListener constructor(camera: PerspectiveCamera | OrthographicCamera, domElement: HTMLElement, domWindow?: Window) { super() if (domElement === undefined) console.warn('TrackballControls: The second parameter "domElement" is now mandatory.') this.camera = camera this.domElement = domElement this.window = domWindow !== undefined ? domWindow : window // Set to false to disable this control this.enabled = true this.screen = { left: 0, top: 0, width: 0, height: 0 } this.rotateSpeed = 1.0 this.zoomSpeed = 1.2 this.panSpeed = 0.3 this.noRotate = false this.noZoom = false this.noPan = false this.staticMoving = false this.dynamicDampingFactor = 0.2 // How far you can dolly in and out ( PerspectiveCamera only ) this.minDistance = 0 this.maxDistance = Infinity this.keys = [65 /*A*/, 83 /*S*/, 68 /*D*/] // Replace ZOOM by DOLLY (threejs r111) this.mouseButtons = { LEFT: MOUSE.ROTATE, MIDDLE: MOUSE.DOLLY, RIGHT: MOUSE.PAN } // "target" sets the location of focus, where the camera orbits around this.target = new Vector3() this._state = STATE.NONE this._keyState = STATE.NONE this._eye = new Vector3() this._movePrev = new Vector2() this._moveCurr = new Vector2() this._lastAxis = new Vector3() this._lastAngle = 0 this._zoomStart = new Vector2() this._zoomEnd = new Vector2() this._touchZoomDistanceStart = 0 this._touchZoomDistanceEnd = 0 this._panStart = new Vector2() this._panEnd = new Vector2() this.target0 = this.target.clone() this.position0 = this.camera.position.clone() this.up0 = this.camera.up.clone() this.zoom0 = this.camera.zoom // event handlers - FSM: listen for events and reset state this.keydown = (event: KeyboardEvent) => { if (this.enabled === false) return this.window.removeEventListener('keydown', this.keydown) if (this._keyState !== STATE.NONE) { return } else if (event.keyCode === this.keys[STATE.ROTATE] && !this.noRotate) { this._keyState = STATE.ROTATE } else if (event.keyCode === this.keys[STATE.ZOOM] && !this.noZoom) { this._keyState = STATE.ZOOM } else if (event.keyCode === this.keys[STATE.PAN] && !this.noPan) { this._keyState = STATE.PAN } } this.keyup = () => { if (this.enabled === false) { return } this._keyState = STATE.NONE this.window.addEventListener('keydown', this.keydown, false) } this.mousedown = (event: MouseEvent) => { if (this.enabled === false) { return } event.preventDefault() event.stopPropagation() if (this._state === STATE.NONE) { switch (event.button) { case this.mouseButtons.LEFT: this._state = STATE.ROTATE break case this.mouseButtons.MIDDLE: this._state = STATE.ZOOM break case this.mouseButtons.RIGHT: this._state = STATE.PAN break default: this._state = STATE.NONE } } const state = this._keyState !== STATE.NONE ? this._keyState : this._state if (state === STATE.ROTATE && !this.noRotate) { this._moveCurr.copy(this.getMouseOnCircle(event.pageX, event.pageY)) this._movePrev.copy(this._moveCurr) } else if (state === STATE.ZOOM && !this.noZoom) { this._zoomStart.copy(this.getMouseOnScreen(event.pageX, event.pageY)) this._zoomEnd.copy(this._zoomStart) } else if (state === STATE.PAN && !this.noPan) { this._panStart.copy(this.getMouseOnScreen(event.pageX, event.pageY)) this._panEnd.copy(this._panStart) } document.addEventListener('mousemove', this.mousemove, false) document.addEventListener('mouseup', this.mouseup, false) ;(this as any).dispatchEvent(START_EVENT) } this.mousemove = (event: MouseEvent) => { if (this.enabled === false) { return } event.preventDefault() event.stopPropagation() const state = this._keyState !== STATE.NONE ? this._keyState : this._state if (state === STATE.ROTATE && !this.noRotate) { this._movePrev.copy(this._moveCurr) this._moveCurr.copy(this.getMouseOnCircle(event.pageX, event.pageY)) } else if (state === STATE.ZOOM && !this.noZoom) { this._zoomEnd.copy(this.getMouseOnScreen(event.pageX, event.pageY)) } else if (state === STATE.PAN && !this.noPan) { this._panEnd.copy(this.getMouseOnScreen(event.pageX, event.pageY)) } } this.mouseup = (event: MouseEvent) => { if (this.enabled === false) { return } event.preventDefault() event.stopPropagation() this._state = STATE.NONE document.removeEventListener('mousemove', this.mousemove) document.removeEventListener('mouseup', this.mouseup) ;(this as any).dispatchEvent(END_EVENT) } this.mousewheel = (event: WheelEvent) => { if (this.enabled === false) { return } if (this.noZoom === true) return event.preventDefault() event.stopPropagation() switch (event.deltaMode) { case 2: // Zoom in pages this._zoomStart.y -= event.deltaY * 0.025 break case 1: // Zoom in lines this._zoomStart.y -= event.deltaY * 0.01 break default: // undefined, 0, assume pixels this._zoomStart.y -= event.deltaY * 0.00025 break } ;(this as any).dispatchEvent(START_EVENT) ;(this as any).dispatchEvent(END_EVENT) } this.touchstart = (event: TouchEvent) => { if (this.enabled === false) { return } event.preventDefault() switch (event.touches.length) { case 1: this._state = STATE.TOUCH_ROTATE this._moveCurr.copy(this.getMouseOnCircle(event.touches[0].pageX, event.touches[0].pageY)) this._movePrev.copy(this._moveCurr) break default: // 2 or more this._state = STATE.TOUCH_ZOOM_PAN const dx = event.touches[0].pageX - event.touches[1].pageX const dy = event.touches[0].pageY - event.touches[1].pageY this._touchZoomDistanceEnd = this._touchZoomDistanceStart = Math.sqrt(dx * dx + dy * dy) const x = (event.touches[0].pageX + event.touches[1].pageX) / 2 const y = (event.touches[0].pageY + event.touches[1].pageY) / 2 this._panStart.copy(this.getMouseOnScreen(x, y)) this._panEnd.copy(this._panStart) break } ;(this as any).dispatchEvent(START_EVENT) } this.touchmove = (event: TouchEvent) => { if (this.enabled === false) { return } event.preventDefault() event.stopPropagation() switch (event.touches.length) { case 1: this._movePrev.copy(this._moveCurr) this._moveCurr.copy(this.getMouseOnCircle(event.touches[0].pageX, event.touches[0].pageY)) break default: // 2 or more const dx = event.touches[0].pageX - event.touches[1].pageX const dy = event.touches[0].pageY - event.touches[1].pageY this._touchZoomDistanceEnd = Math.sqrt(dx * dx + dy * dy) const x = (event.touches[0].pageX + event.touches[1].pageX) / 2 const y = (event.touches[0].pageY + event.touches[1].pageY) / 2 this._panEnd.copy(this.getMouseOnScreen(x, y)) break } } this.touchend = (event: TouchEvent) => { if (this.enabled === false) { return } switch (event.touches.length) { case 0: this._state = STATE.NONE break case 1: this._state = STATE.TOUCH_ROTATE this._moveCurr.copy(this.getMouseOnCircle(event.touches[0].pageX, event.touches[0].pageY)) this._movePrev.copy(this._moveCurr) break } ;(this as any).dispatchEvent(END_EVENT) } this.contextmenu = (event: MouseEvent) => { if (this.enabled === false) { return } event.preventDefault() } this.domElement.addEventListener('contextmenu', this.contextmenu, false) this.domElement.addEventListener('mousedown', this.mousedown, false) this.domElement.addEventListener('wheel', this.mousewheel, false) this.domElement.addEventListener('touchstart', this.touchstart, false) this.domElement.addEventListener('touchend', this.touchend, false) this.domElement.addEventListener('touchmove', this.touchmove, false) this.window.addEventListener('keydown', this.keydown, false) this.window.addEventListener('keyup', this.keyup, false) this.handleResize() // force an update at start this.update() } dispose(): void { this.domElement.removeEventListener('contextmenu', this.contextmenu, false) this.domElement.removeEventListener('mousedown', this.mousedown, false) this.domElement.removeEventListener('wheel', this.mousewheel, false) this.domElement.removeEventListener('touchstart', this.touchstart, false) this.domElement.removeEventListener('touchend', this.touchend, false) this.domElement.removeEventListener('touchmove', this.touchmove, false) document.removeEventListener('mousemove', this.mousemove, false) document.removeEventListener('mouseup', this.mouseup, false) this.window.removeEventListener('keydown', this.keydown, false) this.window.removeEventListener('keyup', this.keyup, false) } // ------------------------------------------------ handleResize(): void { const box = this.domElement.getBoundingClientRect() // adjustments come from similar code in the jquery offset() function const d = this.domElement.ownerDocument.documentElement this.screen.left = box.left + this.window.pageXOffset - d.clientLeft this.screen.top = box.top + this.window.pageYOffset - d.clientTop this.screen.width = box.width this.screen.height = box.height } getMouseOnScreen = (pageX: number, pageY: number) => { const vector = new Vector2() return vector.set((pageX - this.screen.left) / this.screen.width, (pageY - this.screen.top) / this.screen.height) } getMouseOnCircle = (pageX: number, pageY: number) => { const vector = new Vector2() return vector.set( (pageX - this.screen.width * 0.5 - this.screen.left) / (this.screen.width * 0.5), (this.screen.height + 2 * (this.screen.top - pageY)) / this.screen.width ) } rotateCamera = () => { const axis: Vector3 = new Vector3() const quaternion: Quaternion = new Quaternion() const eyeDirection: Vector3 = new Vector3() const cameraUpDirection: Vector3 = new Vector3() const cameraSidewaysDirection: Vector3 = new Vector3() const moveDirection: Vector3 = new Vector3() let angle: number moveDirection.set(this._moveCurr.x - this._movePrev.x, this._moveCurr.y - this._movePrev.y, 0) angle = moveDirection.length() if (angle) { this._eye.copy(this.camera.position).sub(this.target) eyeDirection.copy(this._eye).normalize() cameraUpDirection.copy(this.camera.up).normalize() cameraSidewaysDirection.crossVectors(cameraUpDirection, eyeDirection).normalize() cameraUpDirection.setLength(this._moveCurr.y - this._movePrev.y) cameraSidewaysDirection.setLength(this._moveCurr.x - this._movePrev.x) moveDirection.copy(cameraUpDirection.add(cameraSidewaysDirection)) axis.crossVectors(moveDirection, this._eye).normalize() angle *= this.rotateSpeed quaternion.setFromAxisAngle(axis, angle) this._eye.applyQuaternion(quaternion) this.camera.up.applyQuaternion(quaternion) this._lastAxis.copy(axis) this._lastAngle = angle } else if (!this.staticMoving && this._lastAngle) { this._lastAngle *= Math.sqrt(1.0 - this.dynamicDampingFactor) this._eye.copy(this.camera.position).sub(this.target) quaternion.setFromAxisAngle(this._lastAxis, this._lastAngle) this._eye.applyQuaternion(quaternion) this.camera.up.applyQuaternion(quaternion) } this._movePrev.copy(this._moveCurr) } zoomCamera = () => { let factor = 0 if (this._state === STATE.TOUCH_ZOOM_PAN) { factor = this._touchZoomDistanceStart / this._touchZoomDistanceEnd this._touchZoomDistanceStart = this._touchZoomDistanceEnd if (this.camera['isPerspectiveCamera']) { this._eye.multiplyScalar(factor) } else if (this.camera['isOrthographicCamera']) { this.camera.zoom *= factor this.camera.updateProjectionMatrix() } else { console.warn('TrackballControls: Unsupported camera type') } } else { factor = 1.0 + (this._zoomEnd.y - this._zoomStart.y) * this.zoomSpeed if (factor !== 1.0 && factor > 0.0) { if (this.camera['isPerspectiveCamera']) { this._eye.multiplyScalar(factor) } else if (this.camera['isOrthographicCamera']) { this.camera.zoom /= factor this.camera.updateProjectionMatrix() } else { console.warn('TrackballControls: Unsupported camera type') } } if (this.staticMoving) { this._zoomStart.copy(this._zoomEnd) } else { this._zoomStart.y += (this._zoomEnd.y - this._zoomStart.y) * this.dynamicDampingFactor } } } panCamera = () => { const mouseChange: Vector2 = new Vector2() const cameraUp: Vector3 = new Vector3() const pan: Vector3 = new Vector3() mouseChange.copy(this._panEnd).sub(this._panStart) if (mouseChange.lengthSq()) { if (this.camera['isOrthographicCamera']) { const scale_x = ((<OrthographicCamera>this.camera).right - (<OrthographicCamera>this.camera).left) / this.camera.zoom / this.domElement.clientWidth const scale_y = ((<OrthographicCamera>this.camera).top - (<OrthographicCamera>this.camera).bottom) / this.camera.zoom / this.domElement.clientWidth mouseChange.x *= scale_x mouseChange.y *= scale_y } mouseChange.multiplyScalar(this._eye.length() * this.panSpeed) pan.copy(this._eye).cross(this.camera.up).setLength(mouseChange.x) pan.add(cameraUp.copy(this.camera.up).setLength(mouseChange.y)) this.camera.position.add(pan) this.target.add(pan) if (this.staticMoving) { this._panStart.copy(this._panEnd) } else { this._panStart.add( mouseChange.subVectors(this._panEnd, this._panStart).multiplyScalar(this.dynamicDampingFactor) ) } } } checkDistances(): void { if (!this.noZoom || !this.noPan) { if (this._eye.lengthSq() > this.maxDistance * this.maxDistance) { this.camera.position.addVectors(this.target, this._eye.setLength(this.maxDistance)) this._zoomStart.copy(this._zoomEnd) } if (this._eye.lengthSq() < this.minDistance * this.minDistance) { this.camera.position.addVectors(this.target, this._eye.setLength(this.minDistance)) this._zoomStart.copy(this._zoomEnd) } } } update(): void { this._eye.subVectors(this.camera.position, this.target) if (!this.noRotate) { this.rotateCamera() } if (!this.noZoom) { this.zoomCamera() } if (!this.noPan) { this.panCamera() } this.camera.position.addVectors(this.target, this._eye) if (this.camera['isPerspectiveCamera']) { this.checkDistances() this.camera.lookAt(this.target) if (LAST_POSITION.distanceToSquared(this.camera.position) > EPS) { ;(this as any).dispatchEvent(CHANGE_EVENT) LAST_POSITION.copy(this.camera.position) } } else if (this.camera['isOrthographicCamera']) { this.camera.lookAt(this.target) if (LAST_POSITION.distanceToSquared(this.camera.position) > EPS || LAST_ZOOM.value !== this.camera.zoom) { ;(this as any).dispatchEvent(CHANGE_EVENT) LAST_POSITION.copy(this.camera.position) LAST_ZOOM.value = this.camera.zoom } else { console.warn('TrackballControls: Unsupported camera type') } } } reset(): void { this._state = STATE.NONE this._keyState = STATE.NONE this.target.copy(this.target0) this.camera.position.copy(this.position0) this.camera.up.copy(this.up0) this.camera.zoom = this.zoom0 this._eye.subVectors(this.camera.position, this.target) this.camera.lookAt(this.target) ;(this as any).dispatchEvent(CHANGE_EVENT) LAST_POSITION.copy(this.camera.position) LAST_ZOOM.value = this.camera.zoom } }
the_stack
import stringify = require('json-stringify'); import { ConsoleUtils } from './consoleUtils'; import "reflect-metadata"; import "es6-shim"; import { plainToClass } from "class-transformer"; import { ForceOrgListResult, ForceOrgListCommandResponse, ForceOrgDisplayResult } from './helper_classes'; import { IOrgConnectionData, IPackageJson, IAppSettings, IFileEntry } from './helper_interfaces'; import { CONSTANTS, OPERATION } from './statics'; import { Org } from '../models/org'; import { SObjectDescribe } from '../models/sobjectDescribe'; import jsforce = require('jsforce'); import { QueryResult } from 'jsforce/lib/query'; import deepEqual from 'deep-equal'; import { SFieldDescribe } from '../models/sfieldDescribe'; import { DescribeSObjectResult } from 'jsforce'; import { RESOURCES } from './resources'; import { OpenDialogSyncOptions } from 'electron'; import path from "path"; import fs = require('fs'); let dialog = require('electron').remote.dialog; let ncp = require('ncp').ncp; const openExplorer = require('open-file-explorer'); const fse = require('fs-extra') const { readdirSync } = require('fs') const { distance, closest } = require('fastest-levenshtein') var request = require("request") ////////////////////////////////////////////// // Prototype Extensions ////////////////////// ////////////////////////////////////////////// declare global { interface String { format(...args: string[]): string; } } String.prototype.format = function () { var args = arguments; return this.replace(/{(\d+)}/g, function (match: any, number: any) { return typeof args[number] != 'undefined' ? args[number] : match; }); }; ////////////////////////////////////////////// // Decorators //////////////////////////////// ////////////////////////////////////////////// export function SerializableGetter(tags?: Array<string>) { return function (target: object, propertyKey: string | symbol, descriptor?: PropertyDescriptor) { let enumProperty = "____emum____" + String(propertyKey); let p = Object.getOwnPropertyDescriptor(target, '_serializableKeys'); if (!p) { Object.defineProperty(target, "_serializableKeys", { enumerable: false, value: [{ propertyKey, enumProperty, tags }], writable: true }); } else { target["_serializableKeys"].push({ propertyKey, enumProperty, tags }); } if (descriptor) { descriptor.enumerable = true; Object.defineProperty(target, enumProperty, descriptor); } }; } export function NonSerializable(tags?: Array<string>) { return function (target: object, propertyKey: string | symbol) { let p = Object.getOwnPropertyDescriptor(target, '_nonSerializableKeys'); if (!p) { Object.defineProperty(target, "_nonSerializableKeys", { enumerable: false, value: [{ propertyKey, tags }], writable: true }); } else { target["_nonSerializableKeys"].push({ propertyKey, tags }); } } } export function NonSerializableIfDefault($default: any, tags?: Array<string>) { return function (target: object, propertyKey: string | symbol) { let p = Object.getOwnPropertyDescriptor(target, '_nonSerializableDefaults'); if (!p) { Object.defineProperty(target, "_nonSerializableDefaults", { enumerable: false, value: [{ propertyKey, tags, $default }], writable: true }); } else { target["_nonSerializableDefaults"].push({ propertyKey, tags, $default }); } } } ////////////////////////////////////////////// // Utilities ///////////////////////////////// ////////////////////////////////////////////// export class AppUtils { public static makeId(length: Number = 10) { var result = ''; var characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'; var charactersLength = characters.length; for (var i = 0; i < length; i++) { result += characters.charAt(Math.floor(Math.random() * charactersLength)); } return result; } public static stringifyObj(obj: any, tag?: string): string { return stringify(obj, (key: any, value: any) => { if (value instanceof Map) { let obj = Object.create(null); for (let [k, v] of value) { obj[k] = v; } return obj; } else { try { if (typeof value == 'object') { let _serializableKeys = value.__proto__ && value.__proto__._serializableKeys; let _nonSerializableKeys = value.__proto__ && value.__proto__._nonSerializableKeys; let _nonSerializableDefaults = value.__proto__ && value.__proto__._nonSerializableDefaults; if (_serializableKeys) { let values = {}; _serializableKeys.forEach((key: { propertyKey: string, enumProperty: string }) => { values[key.propertyKey] = value[key.enumProperty]; }); value = Object.assign({}, value); _serializableKeys.forEach((key: { propertyKey: string, enumProperty: string, tags?: Array<string> }) => { if (typeof values[key.propertyKey] != 'undefined') { if (!key.tags || key.tags.length == 0 || key.tags.indexOf(tag) >= 0) value[key.propertyKey] = values[key.propertyKey]; } delete value[key.enumProperty]; }); } if (_nonSerializableKeys) { value = Object.assign({}, value); _nonSerializableKeys.forEach((key: { propertyKey: string, tags: Array<string> }) => { if (tag && key.tags) { if (key.tags.indexOf(tag) >= 0) { delete value[key.propertyKey]; } } else { if (!key.tags || key.tags.length == 0) { delete value[key.propertyKey]; } } }); } if (_nonSerializableDefaults) { value = Object.assign({}, value); _nonSerializableDefaults.forEach((key: { propertyKey: string, tags: Array<string>, $default: any }) => { if (typeof key.$default != 'undefined' // Equals && (key.$default == value[key.propertyKey] // Empty array || Array.isArray(key.$default) && Array.isArray(value[key.propertyKey]) && value[key.propertyKey].length == 0 // Empty object || !Array.isArray(key.$default) && (typeof key.$default == 'object') && Object.keys(value[key.propertyKey]).length == 0)) { if (tag && key.tags && key.tags.indexOf(tag) >= 0 || !key.tags) { delete value[key.propertyKey]; } } }); } } } catch (e) { } return value; } }); } public static execAsyncSync(fn: () => Promise<any>, timeout?: number): Promise<any> { return new Promise<any>((resolve, reject) => { setTimeout(async function () { if (!fn) { resolve(); } else { try { let result = await fn(); resolve(result); } catch (err) { reject(err.message); } } }, timeout || 0); }); } public static objectApply(thisObj: any, ...appliedObjs: any[]) { appliedObjs.forEach(obj => { Object.keys(obj).forEach(key => { if (obj[key]) { thisObj[key] = obj[key]; } }); }); } public static async execSfdxCommand(command: String, targetusername: String, killProcessOnFirstConsoleOutput: boolean = true): Promise<{ commandOutput: string, cliCommand: string }> { let commandOutput: string = ""; let callback = (data: { message: string, isError: boolean, exitCode: number }): boolean => { if (!data.isError && typeof data.exitCode == "undefined" && data.message) { commandOutput += data.message; } if (killProcessOnFirstConsoleOutput) { return true; } return false; } let cliCommand = ""; if (typeof targetusername != "undefined") { cliCommand = `sfdx ${command} --targetusername ${targetusername}`; } else { cliCommand = `sfdx ${command}`; } await ConsoleUtils.callConsoleCommand(cliCommand, callback); return { cliCommand, commandOutput }; }; public static async execForceOrgList(): Promise<{ orgs: Array<ForceOrgListResult>, commandOutput: string }> { try { //let responseString = SfdxUtils.execSfdx("force:org:list --json", undefined); let response = await AppUtils.execSfdxCommand("force:org:list --json", undefined); let jsonObject = JSON.parse(response.commandOutput); let responseObject = plainToClass(ForceOrgListCommandResponse, jsonObject, { enableImplicitConversion: true, excludeExtraneousValues: true }); if (responseObject.status == 0) { return { orgs: [ ...responseObject.result.nonScratchOrgs, ...responseObject.result.scratchOrgs.map(x => { x.isScratchOrg = true; return x; })], commandOutput: response.commandOutput }; } } catch (ex) { } return { orgs: new Array<ForceOrgListResult>(), commandOutput: RESOURCES.Home_Error_ExecuteSFDXFailed }; } public static async execForceOrgDisplay(userName: string, asJson?: boolean): Promise<ForceOrgDisplayResult> { if (!asJson) { let response = await AppUtils.execSfdxCommand("force:org:display", userName); return this._parseForceOrgDisplayResult(response.cliCommand, response.commandOutput); } let response = await AppUtils.execSfdxCommand("force:org:display --json", userName); let result = new ForceOrgDisplayResult(JSON.parse(response.commandOutput)); result.cliCommand = response.cliCommand; result.commandOutput = response.commandOutput; return result; } public static createOrgConnection(connectionData: IOrgConnectionData): any { return new jsforce.Connection({ instanceUrl: connectionData.instanceUrl, accessToken: connectionData.accessToken, version: connectionData.apiVersion, maxRequest: CONSTANTS.MAX_CONCURRENT_PARALLEL_REQUESTS }); } public static getStrOperation(operation: OPERATION | string): string { operation = typeof operation == 'undefined' || operation == null ? '' : operation; if ((typeof operation != "string") == true) { if (typeof OPERATION[operation] == 'undefined') { return OPERATION.Unknown.toString(); } return OPERATION[operation].toString(); } return operation.toString(); } public static getOperation(operation: OPERATION | string): OPERATION { operation = typeof operation == 'undefined' || operation == null ? '' : operation; if ((typeof operation == "string") == true) { if (typeof OPERATION[operation.toString()] == 'undefined') { return OPERATION.Unknown; } return OPERATION[operation.toString()]; } return <OPERATION>operation; } public static async queryAsync(org: Org, soql: string, useBulkQueryApi: boolean): Promise<QueryResult<object>> { const makeQueryAsync = (soql: string) => new Promise((resolve, reject) => { let conn = org.getConnection(); let records = []; if (useBulkQueryApi && conn.bulk) { conn.bulk.pollTimeout = CONSTANTS.BULK_QUERY_API_POLL_TIMEOUT; conn.bulk.query(soql).on("record", function (record: any) { records.push(record); }).on("end", function () { ___fixRecords(records); resolve(<QueryResult<object>>{ done: true, records: records, totalSize: records.length }); }).on("error", function (error: any) { reject(error); }); } else { let query = conn.query(soql).on("record", function (record: any) { records.push(record); }).on("end", function () { ___fixRecords(records); resolve(<QueryResult<object>>{ done: true, records: records, totalSize: query.totalSize }); }).on("error", function (error: any) { reject(error); }).run({ autoFetch: true, maxFetch: CONSTANTS.MAX_FETCH_SIZE }); } }); return <QueryResult<object>>(await makeQueryAsync(soql)); function ___fixRecords(records: Array<any>) { if (records.length == 0) return; let props = Object.keys(records[0]); records.forEach(record => { props.forEach(prop => { if (record[prop] === "") { record[prop] = null; } }); delete record.attributes; }); } } public static async getOrgObjectsList(org: Org): Promise<Array<SObjectDescribe>> { let queryNoCustom = `SELECT QualifiedApiName, Label, IsEverUpdatable, IsEverCreatable, IsEverDeletable FROM EntityDefinition WHERE IsRetrieveable = true AND IsQueryable = true AND IsIdEnabled = true AND IsDeprecatedAndHidden = false and IsCustomizable = false`; let queryWithCustom = `SELECT QualifiedApiName, Label, IsEverUpdatable, IsEverCreatable, IsEverDeletable FROM EntityDefinition WHERE IsRetrieveable = true AND IsQueryable = true AND IsIdEnabled = true AND IsDeprecatedAndHidden = false and IsCustomizable = true`; let recordsWithNoCustom = await this.queryAsync(org, queryNoCustom, false); let recordsWithCustom = await this.queryAsync(org, queryWithCustom, false); let records = [...recordsWithNoCustom.records, ...recordsWithCustom.records]; return records.filter((record: any) => { return (record.IsEverUpdatable && record.IsEverCreatable && record.IsEverDeletable) || record.QualifiedApiName == 'RecordType' || record.QualifiedApiName == 'ContentVersion' }) .sort((a, b) => b.QualifiedApiName - a.QualifiedApiName) .map((record: any) => { return new SObjectDescribe({ label: String(record["Label"]), name: String(record["QualifiedApiName"]), createable: true, updateable: true, custom: this.isCustomObject(String(record["QualifiedApiName"])) }); }); } public static async describeSObjectAsync(org: Org, objectName: string, sObjectDescribe?: SObjectDescribe): Promise<SObjectDescribe> { var conn = org.getConnection(); const describeAsync = (name: string) => new Promise((resolve, reject) => conn.sobject(name).describe(function (err: any, meta: any) { if (err) reject(err); else resolve(meta); })); let describeResult: DescribeSObjectResult = <DescribeSObjectResult>(await describeAsync(objectName)); sObjectDescribe = sObjectDescribe || new SObjectDescribe({ name: objectName, createable: describeResult.createable, custom: describeResult.custom, label: describeResult.label, updateable: describeResult.createable && describeResult.updateable }); describeResult.fields.forEach((field: any) => { let f = new SFieldDescribe({ name: field.name, objectName: objectName, nameField: field.nameField, unique: field.unique, type: field.type, label: field.label, custom: field.custom, updateable: field.updateable, autoNumber: field["autoNumber"], creatable: field.createable, calculated: field.calculated, cascadeDelete: field.cascadeDelete, lookup: field.referenceTo != null && field.referenceTo.length > 0, referencedObjectType: field.referenceTo[0], namePointing: field.namePointing, referenceTo: field.referenceTo }); sObjectDescribe.fieldsMap.set(f.name, f); }); return sObjectDescribe; }; public static async connectOrg(org: Org): Promise<void> { let result = await this.execForceOrgDisplay(org.orgName); if (result.isConnected) { org.instanceUrl = result.InstanceUrl; org.accessToken = result.AccessToken; } else { throw new Error(RESOURCES.Home_Error_UnableToConnect); } } public static isCustomObject(objectName: string): boolean { if (!objectName) return false; return objectName.endsWith('__c') || objectName.endsWith('__pc') || objectName.endsWith('__s'); } public static isEquals(object1: any, object2: any): boolean { return deepEqual(object1, object2); } public static intersect(array1: any[], array2: any[], propertyName: string): any[] { return array1.filter(function (obj1) { return array2.some(function (obj2) { return obj2[propertyName] == obj1[propertyName]; }); }); } public static exclude(array1: any[], array2: any[], propertyName?: string): any[] { return array1.filter(function (obj1) { return !array2.some(function (obj2) { if (typeof obj2 == 'object' && typeof obj1 == 'object') return obj2[propertyName] == obj1[propertyName]; return obj2 == obj1; }); }); } public static objectAssignSafeDefined(target: any, ...sources: Array<any>): any { for (const source of sources) { for (const key of Object.keys(source)) { const val = source[key]; if (val !== undefined && val != null) { target[key] = val; } } } return target; } public static objectAssignSafe(target: any, source: any): any { Object.getOwnPropertyNames(source).forEach(function (prop) { Object.defineProperty( target, prop, Object.getOwnPropertyDescriptor(source, prop) ); }); return target; } public static removeBy(array: Array<any>, propertyName: string, propertyValue: string) { if (!array) return array; return array.filter(it => it[propertyName] != propertyValue); } public static remove(array: Array<any>, item: any) { if (!array) return array; return array.filter(it => it != item); } public static distinctArray<T>(array: Array<T>, propName: string): Array<T> { if (!array) return array; var resArr = []; array.forEach(item => { if (!resArr.some(x => x[propName] == item[propName])) { resArr.push(item); } }); return resArr; } public static uniqueArray(array: Array<any>): Array<any> { if (!array) return array; return [...new Set(array)]; } public static sortArray(array: Array<any>, ...propNames: string[]): Array<any> { // --------------- Local functions ------------------- // const ___fieldSorter = (propNames: Array<string>) => (a: any, b: any) => propNames.map(propName => { let dir = 1; if (propName[0] === '-') { dir = -1; propName = propName.substring(1); } return a[propName] > b[propName] || (String(a[propName]) || "").startsWith("**") ? dir : a[propName] < b[propName] ? -(dir) : 0; }).reduce((p, n) => p ? p : n, 0); if (!array) return array; return array.sort(___fieldSorter(propNames)); } public static selectFolder(defaultPath: string): string[] { let options = <OpenDialogSyncOptions>{ properties: ["openDirectory"], defaultPath }; return dialog.showOpenDialogSync(options); } public static readPackageJson(): IPackageJson { let filePath = path.join(process.cwd(), 'package.json'); let jsonObj: IPackageJson = require(filePath); return jsonObj; } public static readUserJson(): IAppSettings { let filePath = path.join(process.cwd(), CONSTANTS.USER_SETTINGS_FILE_NAME); if (!fs.existsSync(filePath)) { fs.writeFileSync(filePath, '{}'); } let jsonObj: IAppSettings = require(filePath); return jsonObj; } public static writeUserJson(settings: IAppSettings): void { let filePath = path.join(process.cwd(), CONSTANTS.USER_SETTINGS_FILE_NAME); fs.writeFileSync(filePath, AppUtils.pretifyJson(settings)); } public static async readRemoveJsonAsync(url: string): Promise<any> { return new Promise((resolve) => { request({ url, json: true }, function (error: any, response: any, body: any) { if (!error && response.statusCode === 200) { resolve(body); return; } resolve({}); }); }); } public static async copyDirAsync(source: string, destination: string): Promise<void> { return new Promise((resolve, reject) => { ncp.limit = 16; AppUtils.emptyDirs([destination]); ncp(source, destination, function (err: any) { if (err) { reject(err); } resolve(); }); }); } public static deleteDirs(filePaths: string[]) { filePaths.forEach(path => { fse.removeSync(path); }); } public static emptyDirs(filePaths: string[]) { filePaths.forEach(path => { if (fs.existsSync(path)) fse.emptyDirSync(path); }); } public static openExplorer(filePath: string) { openExplorer(filePath); } public static getListOfDirs(filePath: string): IFileEntry[] { if (!fs.existsSync(filePath)) return new Array<IFileEntry>(); return readdirSync(filePath, { withFileTypes: true }) .filter((dirent: any) => dirent.isDirectory()) .map((dirent: any) => { return <IFileEntry>{ name: dirent.name, fullPath: path.join(filePath, dirent.name), isDirectory: true } }); } public static textToHtmlString(text: string): string { return text.replace(new RegExp('\n', 'gi'), "<br/>").replace(/\r/g, '').replace(/\s/g, '&nbsp;'); } public static pretifyJson(json: any): string { if (typeof json == 'string') { return JSON.stringify(JSON.parse(json), null, 4); } return JSON.stringify(json, null, 4); } public static transposeArray(array: Array<any>): any { if (!array) return {}; let result = {}; for (let row of array) { for (let [key, value] of Object.entries(row)) { result[key] = result[key] || []; result[key].push(value); } } return result; } public static transposeArrayMany(array: Array<any>, headerName: string, valuesArrayNamne: string): Array<any> { if (!array || array.length == 0) return []; let items = []; let propIndex = {}; for (let prop in array[0]) { propIndex[prop] = items.length; items.push({ [headerName]: prop, [valuesArrayNamne]: [] }) } array.forEach((item, index) => { for (let prop in item) { items[propIndex[prop]][valuesArrayNamne].push(item[prop]); } }); return items; } /** * Pivot the array * * @static * @param {Array<any>} array Array to be converted * @param {number} rowIndex Index of column in array which is to be kept as first column * @param {number} colIndex Index of column whose values to be converted as columns in the output array * @param {number} dataIndex Index of column whose values to be used as data (displayed in tabular/grid format) * @returns {Array<any>} * @memberof AppUtils */ public static getPivotArray(array: Array<any>, rowIndex: number, colIndex: number, dataIndex: number): Array<any> { var result = {}, ret = []; var newCols = []; for (var i = 0; i < array.length; i++) { if (!result[array[i][rowIndex]]) { result[array[i][rowIndex]] = {}; } result[array[i][rowIndex]][array[i][colIndex]] = array[i][dataIndex]; //To get column names if (newCols.indexOf(array[i][colIndex]) == -1) { newCols.push(array[i][colIndex]); } } newCols.sort(); var item = []; //Add Header Row item.push('Item'); item.push.apply(item, newCols); ret.push(item); //Add content for (var key in result) { item = []; item.push(key); for (var i = 0; i < newCols.length; i++) { item.push(result[key][newCols[i]] || "-"); } ret.push(item); } return ret; } public static searchClosest(itemToSearchFor: string, arrayToSearchIn: Array<string>): string { if (!itemToSearchFor) return itemToSearchFor; return closest(itemToSearchFor, arrayToSearchIn); } public static createSoqlKeywords(query: string, ...keywords: string[]): { query: string, keywords: Array<string> } { keywords = keywords && keywords.length > 0 ? keywords : CONSTANTS.SOQL_KEYWRDS; keywords = keywords.map(keyword => { let regex = keyword.split('|')[0]; let key = keyword.split('|')[1]; query = query.replace(new RegExp(regex, 'gi'), key); return key; }); return { query, keywords }; } public static parseSoql(soqlKeywords: { query: string, keywords: Array<string> }): Array<{ index: number, word: string, text?: string }> { var found = new Array<{ index: number, word: string, text?: string }>(); soqlKeywords.keywords.forEach(function (word) { var idx = soqlKeywords.query.indexOf(word); while (idx !== -1) { found.push({ word: word, index: idx }); idx = soqlKeywords.query.indexOf(word, idx + 1); } }); found.sort(function (x, y) { return x.index - y.index }); found.forEach(function (x, i, xs) { if (i < xs.length - 1) { x.text = soqlKeywords.query.substring(x.index, xs[i + 1].index).replace(xs[i].word, "").trim(); } else { x.text = soqlKeywords.query.substring(x.index).replace(xs[i].word, "").trim(); } }); return found; } public static listEnum(enumType: any): string[] { return Object.keys(enumType).filter(key => !isNaN(Number(enumType[key]))); } public static sleepAsync(ms: number): Promise<void> { return new Promise(resolve => setTimeout(resolve, ms)); } // ------------------------ Private members --------------------------------// private static _parseForceOrgDisplayResult(cliCommand: string, commandResult: string): ForceOrgDisplayResult { if (!commandResult) return null; let lines = commandResult.split('\n'); let output: ForceOrgDisplayResult = new ForceOrgDisplayResult(); output.commandOutput = commandResult; output.cliCommand = cliCommand; lines.forEach(line => { if (line.startsWith("Access Token")) output.AccessToken = line.split(' ').pop(); if (line.startsWith("Client Id")) output.ClientId = line.split(' ').pop(); if (line.startsWith("Connected Status")) output.ConnectedStatus = line.split(' ').pop(); if (line.startsWith("Status")) output.Status = line.split(' ').pop(); if (line.startsWith("Id")) output.OrgId = line.split(' ').pop(); if (line.startsWith("Instance Url")) output.InstanceUrl = line.split(' ').pop(); if (line.startsWith("Username")) output.Username = line.split(' ').pop(); }); return output; }; }
the_stack
import 'jasmine'; import {ConformancePatternRule, ErrorCode, PatternKind} from '../rules/conformance_pattern_rule'; import {compileAndCheck, customMatchers} from './testing/test_support'; describe('AbsoluteMatcher', () => { beforeEach(() => { jasmine.addMatchers(customMatchers); }); it('requires a matcher scope', () => { const config = { errorCode: ErrorCode.CONFORMANCE_PATTERN, errorMessage: 'banned name with no scope', kind: PatternKind.BANNED_NAME, values: ['exec'] }; const sources = [`eval('alert("hi");');`]; const check = () => compileAndCheck(new ConformancePatternRule(config), ...sources); expect(check).toThrowError('Malformed matcher selector.'); }); describe('file scope', () => { it('matches a file path', () => { const config = { errorCode: ErrorCode.CONFORMANCE_PATTERN, errorMessage: 'banned name with file path', kind: PatternKind.BANNED_NAME, values: ['./file_0|Foo.bar'] }; const sources = [ `export class Foo { static bar(s: string) {return s + "abc";} }`, `import {Foo} from './file_0'; var a = Foo.bar("123");` ]; const results = compileAndCheck(new ConformancePatternRule(config), ...sources); expect(results).toHaveFailuresMatching( {matchedCode: `bar`, messageText: 'banned name with file path'}); }); it('ignores an exported symbol defined in an unmatched file path', () => { const config = { errorCode: ErrorCode.CONFORMANCE_PATTERN, errorMessage: 'banned name with file path', kind: PatternKind.BANNED_NAME, values: ['./file_0|Foo.bar'] }; // test exported symbols const sources = [ `export class Foo { static bar(s: string) {return s + "abc";} }`, `export class Foo { static bar(s: string) {return s + "abc";} }`, `import {Foo} from './file_1'; var a = Foo.bar("123");` ]; const results = compileAndCheck(new ConformancePatternRule(config), ...sources); expect(results).toHaveNoFailures(); }); it('ignores an un-exported symbol defined in an unmatched file path', () => { const config = { errorCode: ErrorCode.CONFORMANCE_PATTERN, errorMessage: 'banned name with file path', kind: PatternKind.BANNED_NAME, values: ['./file_0|Foo.bar'] }; // test non-exported symbols const sources = [ `export class Foo { static bar(s: string) {return s + "abc";} }`, `class Foo { static bar(s: string) {return s + "abc";} } var a = Foo.bar("123");` ]; const results = compileAndCheck(new ConformancePatternRule(config), ...sources); expect(results).toHaveNoFailures(); }); it('matches a local exported definition', () => { // This is a match because Foo.bar is an exported symbol. const config = { errorCode: ErrorCode.CONFORMANCE_PATTERN, errorMessage: 'banned name with file path', kind: PatternKind.BANNED_NAME, values: ['./file_0|Foo.bar'] }; const sources = [`export class Foo { static bar(s: string) {return s + "abc";} } var a = Foo.bar("123");`]; const results = compileAndCheck(new ConformancePatternRule(config), ...sources); expect(results).toHaveFailuresMatching( {matchedCode: `bar`, messageText: 'banned name with file path'}); }); it('matches names in import statement', () => { const config = { errorCode: ErrorCode.CONFORMANCE_PATTERN, errorMessage: 'banned name with file path', kind: PatternKind.BANNED_NAME, values: ['./file_0|foo', 'ANY_SYMBOL|bar'] }; const sources = [ `export function foo(s: string) {return s + "abc";} function bar() {} export {bar};`, `import {foo} from './file_0'; import {bar} from './file_0';`, `import {foo as okFoo} from './file_0'; import {bar as okBar} from './file_0';`, ]; const results = compileAndCheck(new ConformancePatternRule(config), ...sources); expect(results).toHaveFailuresMatching( {matchedCode: `foo`, messageText: 'banned name with file path'}, {matchedCode: `bar`, messageText: 'banned name with file path'}, ); }); }); describe('global scope', () => { it('matches an in-stock library method', () => { const config = { errorCode: ErrorCode.CONFORMANCE_PATTERN, errorMessage: 'banned ambient name', kind: PatternKind.BANNED_NAME, values: ['GLOBAL|eval'] }; const sources = [`eval('alert("hi");');`]; const results = compileAndCheck(new ConformancePatternRule(config), ...sources); expect(results).toHaveFailuresMatching( {matchedCode: `eval`, messageText: 'banned ambient name'}); }); it('does not match a custom exported method with the same name', () => { const config = { errorCode: ErrorCode.CONFORMANCE_PATTERN, errorMessage: 'banned ambient name', kind: PatternKind.BANNED_NAME, values: ['GLOBAL|eval'] }; const sources = [`export class Foo { static eval(s: string) { return s + "abc";} } var a = Foo.eval("123");`]; const results = compileAndCheck(new ConformancePatternRule(config), ...sources); expect(results).toHaveNoFailures(); }); it('does not match a custom non-exported method with the same name', () => { const config = { errorCode: ErrorCode.CONFORMANCE_PATTERN, errorMessage: 'banned global name', kind: PatternKind.BANNED_NAME, values: ['GLOBAL|Foo.bar'] }; const sources = [`class Foo { static bar(s: string) {return s + "abc";} } var a = Foo.bar("123");`]; const results = compileAndCheck(new ConformancePatternRule(config), ...sources); expect(results).toHaveNoFailures(); }); it('matches an initializer in a named declaration', () => { const config = { errorCode: ErrorCode.CONFORMANCE_PATTERN, errorMessage: 'banned ambient name', kind: PatternKind.BANNED_NAME, values: ['GLOBAL|open'], }; const sources = ['const op = open;']; const results = compileAndCheck(new ConformancePatternRule(config), ...sources); expect(results).toHaveFailuresMatching( {matchedCode: 'open', messageText: 'banned ambient name'}); }); }); describe('properties', () => { it('matches a static property', () => { const config = { errorCode: ErrorCode.CONFORMANCE_PATTERN, errorMessage: 'banned name with file path', kind: PatternKind.BANNED_NAME, values: ['./file_0|Foo.s'] }; const sources = [ `export class Foo { static s : string; }`, `import {Foo} from './file_0'; var a = Foo.s;`, ]; const results = compileAndCheck(new ConformancePatternRule(config), ...sources); expect(results).toHaveFailuresMatching( {matchedCode: `s`, messageText: 'banned name with file path'}); }); it('does not match a property with a name overlapping an in-stock library', () => { const config = { errorCode: ErrorCode.CONFORMANCE_PATTERN, errorMessage: 'banned name without file path', kind: PatternKind.BANNED_NAME, values: ['GLOBAL|open'] }; const sources = [ 'const elem = new XMLHttpRequest();', 'elem.open("get", "url");', // FQN of elem.open is // XMLHttpRequest.open and shouldn't be // banned ]; const results = compileAndCheck(new ConformancePatternRule(config), ...sources); expect(results).toHaveNoFailures(); }); }); describe('inheritance', () => { it('matches an inherited static property', () => { // This is a match because Moo inherits s from Foo. const config = { errorCode: ErrorCode.CONFORMANCE_PATTERN, errorMessage: 'banned name with file path', kind: PatternKind.BANNED_NAME, values: ['./file_0|Foo.s'] }; const sources = [ `export class Foo { static s : string; }`, `import {Foo} from './file_0'; export class Moo extends Foo { static t : string; }`, `import {Moo} from './file_1'; var a = Moo.s;`, ]; const results = compileAndCheck(new ConformancePatternRule(config), ...sources); expect(results).toHaveFailuresMatching( {matchedCode: `s`, messageText: 'banned name with file path'}); }); it('matches an inherited static method', () => { // This is a match because Moo inherits bar from Foo. const config = { errorCode: ErrorCode.CONFORMANCE_PATTERN, errorMessage: 'banned name with file path', kind: PatternKind.BANNED_NAME, values: ['./file_0|Foo.bar'] }; const sources = [ `export class Foo { static bar(s: string) {return s + "abc";} }`, `import {Foo} from './file_0'; export class Moo extends Foo { static far(s: string) {return s + "def";} }`, `import {Moo} from './file_1'; Moo.bar("abc");` ]; const results = compileAndCheck(new ConformancePatternRule(config), ...sources); expect(results).toHaveFailuresMatching( {matchedCode: `bar`, messageText: 'banned name with file path'}); }); it('does not match a redefined inherited static property', () => { // This is not a match because Moo redefines s. const config = { errorCode: ErrorCode.CONFORMANCE_PATTERN, errorMessage: 'banned name with file path', kind: PatternKind.BANNED_NAME, values: ['./file_0|Foo.s'] }; const sources = [ `export class Foo { static s : string; }`, `import {Foo} from './file_0'; export class Moo extends Foo { static s : string; }`, `import {Moo} from './file_1'; var a = Moo.s;`, ]; const results = compileAndCheck(new ConformancePatternRule(config), ...sources); expect(results).toHaveNoFailures(); }); it('does not match a redefined inherited static method', () => { // This is not a match because Moo redefines bar. const config = { errorCode: ErrorCode.CONFORMANCE_PATTERN, errorMessage: 'banned name with file path', kind: PatternKind.BANNED_NAME, values: ['./file_0|Foo.bar'] }; const sources = [ `export class Foo { static bar(s: string) {return s + "abc";} } export class Moo extends Foo { static bar(s: string) {return s + "def";} }`, `import {Foo, Moo} from './file_0'; Moo.bar("abc");` ]; const results = compileAndCheck(new ConformancePatternRule(config), ...sources); expect(results).toHaveNoFailures(); }); it('does not match an interface\'s static method', () => { // This is not a match because even though bar specified is interface Moo, // its actual definition is in class Boo. const config = { errorCode: ErrorCode.CONFORMANCE_PATTERN, errorMessage: 'banned name with file path', kind: PatternKind.BANNED_NAME, values: ['./file_1|Moo.bar'] }; const sources = [ `export class Foo { static bar(s: string) {return s + "abc";} }`, `import {Foo} from './file_0'; export interface Moo extends Foo { }`, `import {Moo} from './file_1'; export class Boo implements Moo { static bar(s: string) {return s + "def";} }`, `import {Boo} from './file_2'; Boo.bar("abc");`, ]; const results = compileAndCheck(new ConformancePatternRule(config), ...sources); expect(results).toHaveNoFailures(); }); }); });
the_stack
import { FloatArray, Epsilon } from './types' import { Matrix } from './Matrix' import { Scalar } from './Scalar' import { Vector3 } from './Vector3' /** @public */ export type ReadOnlyVector4 = { readonly y: number readonly x: number readonly z: number readonly w: number } /** * Vector4 class created for EulerAngle class conversion to Quaternion * @public */ export class Vector4 { /** * Creates a Vector4 object from the given floats. * @param x - x value of the vector * @param y - y value of the vector * @param z - z value of the vector * @param w - w value of the vector */ constructor( /** x value of the vector */ public x: number, /** y value of the vector */ public y: number, /** z value of the vector */ public z: number, /** w value of the vector */ public w: number ) {} // Statics /** * Returns a new Vector4 as the result of the addition of the two given vectors. * @param vector1 - the first vector * @param vector2 - the second vector * @returns the resulting vector */ public static Add(vector1: ReadOnlyVector4, vector2: ReadOnlyVector4): Vector4 { return new Vector4(vector1.x, vector1.y, vector1.z, vector1.w).addInPlace(vector2) } /** * Returns a new Vector4 set from the starting index of the given array. * @param array - the array to pull values from * @param offset - the offset into the array to start at * @returns the new vector */ public static FromArray(array: ArrayLike<number>, offset: number = 0): Vector4 { return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]) } /** * Updates the given vector "result" from the starting index of the given array. * @param array - the array to pull values from * @param offset - the offset into the array to start at * @param result - the vector to store the result in */ public static FromArrayToRef(array: ArrayLike<number>, offset: number, result: Vector4): void { result.x = array[offset] result.y = array[offset + 1] result.z = array[offset + 2] result.w = array[offset + 3] } /** * Updates the given vector "result" from the starting index of the given FloatArray. * @param array - the array to pull values from * @param offset - the offset into the array to start at * @param result - the vector to store the result in */ public static FromFloatArrayToRef(array: FloatArray, offset: number, result: Vector4): void { Vector4.FromArrayToRef(array, offset, result) } /** * Updates the given vector "result" coordinates from the given floats. * @param x - float to set from * @param y - float to set from * @param z - float to set from * @param w - float to set from * @param result - the vector to the floats in */ public static FromFloatsToRef(x: number, y: number, z: number, w: number, result: Vector4): void { result.x = x result.y = y result.z = z result.w = w } /** * Returns a new Vector4 set to (0.0, 0.0, 0.0, 0.0) * @returns the new vector */ public static Zero(): Vector4 { return new Vector4(0.0, 0.0, 0.0, 0.0) } /** * Returns a new Vector4 set to (1.0, 1.0, 1.0, 1.0) * @returns the new vector */ public static One(): Vector4 { return new Vector4(1.0, 1.0, 1.0, 1.0) } /** * Returns a new normalized Vector4 from the given one. * @param vector - the vector to normalize * @returns the vector */ public static Normalize(vector: ReadOnlyVector4): Vector4 { let result = Vector4.Zero() Vector4.NormalizeToRef(vector, result) return result } /** * Updates the given vector "result" from the normalization of the given one. * @param vector - the vector to normalize * @param result - the vector to store the result in */ public static NormalizeToRef(vector: ReadOnlyVector4, result: Vector4): void { result.copyFrom(vector) result.normalize() } /** * Returns a vector with the minimum values from the left and right vectors * @param left - left vector to minimize * @param right - right vector to minimize * @returns a new vector with the minimum of the left and right vector values */ public static Minimize(left: ReadOnlyVector4, right: ReadOnlyVector4): Vector4 { let min = new Vector4(left.x, left.y, left.z, left.w) min.minimizeInPlace(right) return min } /** * Returns a vector with the maximum values from the left and right vectors * @param left - left vector to maximize * @param right - right vector to maximize * @returns a new vector with the maximum of the left and right vector values */ public static Maximize(left: ReadOnlyVector4, right: ReadOnlyVector4): Vector4 { let max = new Vector4(left.x, left.y, left.z, left.w) max.maximizeInPlace(right) return max } /** * Returns the distance (float) between the vectors "value1" and "value2". * @param value1 - value to calulate the distance between * @param value2 - value to calulate the distance between * @returns the distance between the two vectors */ public static Distance(value1: ReadOnlyVector4, value2: ReadOnlyVector4): number { return Math.sqrt(Vector4.DistanceSquared(value1, value2)) } /** * Returns the squared distance (float) between the vectors "value1" and "value2". * @param value1 - value to calulate the distance between * @param value2 - value to calulate the distance between * @returns the distance between the two vectors squared */ public static DistanceSquared(value1: ReadOnlyVector4, value2: ReadOnlyVector4): number { let x = value1.x - value2.x let y = value1.y - value2.y let z = value1.z - value2.z let w = value1.w - value2.w return x * x + y * y + z * z + w * w } /** * Returns a new Vector4 located at the center between the vectors "value1" and "value2". * @param value1 - value to calulate the center between * @param value2 - value to calulate the center between * @returns the center between the two vectors */ public static Center(value1: ReadOnlyVector4, value2: ReadOnlyVector4): Vector4 { let center = Vector4.Add(value1, value2) center.scaleInPlace(0.5) return center } /** * Returns a new Vector4 set with the result of the normal transformation by the given matrix of the given vector. * This methods computes transformed normalized direction vectors only. * @param vector - the vector to transform * @param transformation - the transformation matrix to apply * @returns the new vector */ public static TransformNormal(vector: ReadOnlyVector4, transformation: Matrix): Vector4 { let result = Vector4.Zero() Vector4.TransformNormalToRef(vector, transformation, result) return result } /** * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given vector. * This methods computes transformed normalized direction vectors only. * @param vector - the vector to transform * @param transformation - the transformation matrix to apply * @param result - the vector to store the result in */ public static TransformNormalToRef(vector: ReadOnlyVector4, transformation: Matrix, result: Vector4): void { const m = transformation.m let x = vector.x * m[0] + vector.y * m[4] + vector.z * m[8] let y = vector.x * m[1] + vector.y * m[5] + vector.z * m[9] let z = vector.x * m[2] + vector.y * m[6] + vector.z * m[10] result.x = x result.y = y result.z = z result.w = vector.w } /** * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given floats (x, y, z, w). * This methods computes transformed normalized direction vectors only. * @param x - value to transform * @param y - value to transform * @param z - value to transform * @param w - value to transform * @param transformation - the transformation matrix to apply * @param result - the vector to store the results in */ public static TransformNormalFromFloatsToRef( x: number, y: number, z: number, w: number, transformation: Matrix, result: Vector4 ): void { const m = transformation.m result.x = x * m[0] + y * m[4] + z * m[8] result.y = x * m[1] + y * m[5] + z * m[9] result.z = x * m[2] + y * m[6] + z * m[10] result.w = w } /** * Returns the string with the Vector4 coordinates. * @returns a string containing all the vector values */ public toString(): string { return '{X: ' + this.x + ' Y:' + this.y + ' Z:' + this.z + ' W:' + this.w + '}' } /** * Returns the string "Vector4". * @returns "Vector4" */ public getClassName(): string { return 'Vector4' } /** * Returns the Vector4 hash code. * @returns a unique hash code */ public getHashCode(): number { let hash = this.x || 0 hash = (hash * 397) ^ (this.y || 0) hash = (hash * 397) ^ (this.z || 0) hash = (hash * 397) ^ (this.w || 0) return hash } // Operators /** * Returns a new array populated with 4 elements : the Vector4 coordinates. * @returns the resulting array */ public asArray(): number[] { let result = new Array<number>() this.toArray(result, 0) return result } /** * Populates the given array from the given index with the Vector4 coordinates. * @param array - array to populate * @param index - index of the array to start at (default: 0) * @returns the Vector4. */ public toArray(array: FloatArray, index: number = 0): Vector4 { array[index] = this.x array[index + 1] = this.y array[index + 2] = this.z array[index + 3] = this.w return this } /** * Adds the given vector to the current Vector4. * @param otherVector - the vector to add * @returns the updated Vector4. */ public addInPlace(otherVector: ReadOnlyVector4): Vector4 { this.x += otherVector.x this.y += otherVector.y this.z += otherVector.z this.w += otherVector.w return this } /** * Returns a new Vector4 as the result of the addition of the current Vector4 and the given one. * @param otherVector - the vector to add * @returns the resulting vector */ public add(otherVector: ReadOnlyVector4): Vector4 { return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w) } /** * Updates the given vector "result" with the result of the addition of the current Vector4 and the given one. * @param otherVector - the vector to add * @param result - the vector to store the result * @returns the current Vector4. */ public addToRef(otherVector: ReadOnlyVector4, result: Vector4): Vector4 { result.x = this.x + otherVector.x result.y = this.y + otherVector.y result.z = this.z + otherVector.z result.w = this.w + otherVector.w return this } /** * Subtract in place the given vector from the current Vector4. * @param otherVector - the vector to subtract * @returns the updated Vector4. */ public subtractInPlace(otherVector: ReadOnlyVector4): Vector4 { this.x -= otherVector.x this.y -= otherVector.y this.z -= otherVector.z this.w -= otherVector.w return this } /** * Returns a new Vector4 with the result of the subtraction of the given vector from the current Vector4. * @param otherVector - the vector to add * @returns the new vector with the result */ public subtract(otherVector: ReadOnlyVector4): Vector4 { return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w) } /** * Sets the given vector "result" with the result of the subtraction of the given vector from the current Vector4. * @param otherVector - the vector to subtract * @param result - the vector to store the result * @returns the current Vector4. */ public subtractToRef(otherVector: ReadOnlyVector4, result: Vector4): Vector4 { result.x = this.x - otherVector.x result.y = this.y - otherVector.y result.z = this.z - otherVector.z result.w = this.w - otherVector.w return this } /** * Returns a new Vector4 set with the result of the subtraction of the given floats from the current Vector4 coordinates. */ /** * Returns a new Vector4 set with the result of the subtraction of the given floats from the current Vector4 coordinates. * @param x - value to subtract * @param y - value to subtract * @param z - value to subtract * @param w - value to subtract * @returns new vector containing the result */ public subtractFromFloats(x: number, y: number, z: number, w: number): Vector4 { return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w) } /** * Sets the given vector "result" set with the result of the subtraction of the given floats from the current Vector4 coordinates. * @param x - value to subtract * @param y - value to subtract * @param z - value to subtract * @param w - value to subtract * @param result - the vector to store the result in * @returns the current Vector4. */ public subtractFromFloatsToRef(x: number, y: number, z: number, w: number, result: Vector4): Vector4 { result.x = this.x - x result.y = this.y - y result.z = this.z - z result.w = this.w - w return this } /** * Returns a new Vector4 set with the current Vector4 negated coordinates. * @returns a new vector with the negated values */ public negate(): Vector4 { return new Vector4(-this.x, -this.y, -this.z, -this.w) } /** * Multiplies the current Vector4 coordinates by scale (float). * @param scale - the number to scale with * @returns the updated Vector4. */ public scaleInPlace(scale: number): Vector4 { this.x *= scale this.y *= scale this.z *= scale this.w *= scale return this } /** * Returns a new Vector4 set with the current Vector4 coordinates multiplied by scale (float). * @param scale - the number to scale with * @returns a new vector with the result */ public scale(scale: number): Vector4 { return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale) } /** * Sets the given vector "result" with the current Vector4 coordinates multiplied by scale (float). * @param scale - the number to scale with * @param result - a vector to store the result in * @returns the current Vector4. */ public scaleToRef(scale: number, result: Vector4): Vector4 { result.x = this.x * scale result.y = this.y * scale result.z = this.z * scale result.w = this.w * scale return this } /** * Scale the current Vector4 values by a factor and add the result to a given Vector4 * @param scale - defines the scale factor * @param result - defines the Vector4 object where to store the result * @returns the unmodified current Vector4 */ public scaleAndAddToRef(scale: number, result: Vector4): Vector4 { result.x += this.x * scale result.y += this.y * scale result.z += this.z * scale result.w += this.w * scale return this } /** * Boolean : True if the current Vector4 coordinates are stricly equal to the given ones. * @param otherVector - the vector to compare against * @returns true if they are equal */ public equals(otherVector: ReadOnlyVector4): boolean { return ( otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w ) } /** * Boolean : True if the current Vector4 coordinates are each beneath the distance "epsilon" from the given vector ones. * @param otherVector - vector to compare against * @param epsilon - (Default: very small number) * @returns true if they are equal */ public equalsWithEpsilon(otherVector: ReadOnlyVector4, epsilon: number = Epsilon): boolean { return ( otherVector && Scalar.WithinEpsilon(this.x, otherVector.x, epsilon) && Scalar.WithinEpsilon(this.y, otherVector.y, epsilon) && Scalar.WithinEpsilon(this.z, otherVector.z, epsilon) && Scalar.WithinEpsilon(this.w, otherVector.w, epsilon) ) } /** * Boolean : True if the given floats are strictly equal to the current Vector4 coordinates. * @param x - x value to compare against * @param y - y value to compare against * @param z - z value to compare against * @param w - w value to compare against * @returns true if equal */ public equalsToFloats(x: number, y: number, z: number, w: number): boolean { return this.x === x && this.y === y && this.z === z && this.w === w } /** * Multiplies in place the current Vector4 by the given one. * @param otherVector - vector to multiple with * @returns the updated Vector4. */ public multiplyInPlace(otherVector: ReadOnlyVector4): Vector4 { this.x *= otherVector.x this.y *= otherVector.y this.z *= otherVector.z this.w *= otherVector.w return this } /** * Returns a new Vector4 set with the multiplication result of the current Vector4 and the given one. * @param otherVector - vector to multiple with * @returns resulting new vector */ public multiply(otherVector: ReadOnlyVector4): Vector4 { return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w) } /** * Updates the given vector "result" with the multiplication result of the current Vector4 and the given one. * @param otherVector - vector to multiple with * @param result - vector to store the result * @returns the current Vector4. */ public multiplyToRef(otherVector: ReadOnlyVector4, result: Vector4): Vector4 { result.x = this.x * otherVector.x result.y = this.y * otherVector.y result.z = this.z * otherVector.z result.w = this.w * otherVector.w return this } /** * Returns a new Vector4 set with the multiplication result of the given floats and the current Vector4 coordinates. * @param x - x value multiply with * @param y - y value multiply with * @param z - z value multiply with * @param w - w value multiply with * @returns resulting new vector */ public multiplyByFloats(x: number, y: number, z: number, w: number): Vector4 { return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w) } /** * Returns a new Vector4 set with the division result of the current Vector4 by the given one. * @param otherVector - vector to devide with * @returns resulting new vector */ public divide(otherVector: ReadOnlyVector4): Vector4 { return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w) } /** * Updates the given vector "result" with the division result of the current Vector4 by the given one. * @param otherVector - vector to devide with * @param result - vector to store the result * @returns the current Vector4. */ public divideToRef(otherVector: ReadOnlyVector4, result: Vector4): Vector4 { result.x = this.x / otherVector.x result.y = this.y / otherVector.y result.z = this.z / otherVector.z result.w = this.w / otherVector.w return this } /** * Divides the current Vector3 coordinates by the given ones. * @param otherVector - vector to devide with * @returns the updated Vector3. */ public divideInPlace(otherVector: ReadOnlyVector4): Vector4 { return this.divideToRef(otherVector, this) } /** * Updates the Vector4 coordinates with the minimum values between its own and the given vector ones * @param other - defines the second operand * @returns the current updated Vector4 */ public minimizeInPlace(other: ReadOnlyVector4): Vector4 { if (other.x < this.x) { this.x = other.x } if (other.y < this.y) { this.y = other.y } if (other.z < this.z) { this.z = other.z } if (other.w < this.w) { this.w = other.w } return this } /** * Updates the Vector4 coordinates with the maximum values between its own and the given vector ones * @param other - defines the second operand * @returns the current updated Vector4 */ public maximizeInPlace(other: ReadOnlyVector4): Vector4 { if (other.x > this.x) { this.x = other.x } if (other.y > this.y) { this.y = other.y } if (other.z > this.z) { this.z = other.z } if (other.w > this.w) { this.w = other.w } return this } /** * Gets a new Vector4 from current Vector4 floored values * @returns a new Vector4 */ public floor(): Vector4 { return new Vector4(Math.floor(this.x), Math.floor(this.y), Math.floor(this.z), Math.floor(this.w)) } /** * Gets a new Vector4 from current Vector3 floored values * @returns a new Vector4 */ public fract(): Vector4 { return new Vector4( this.x - Math.floor(this.x), this.y - Math.floor(this.y), this.z - Math.floor(this.z), this.w - Math.floor(this.w) ) } // Properties /** * Returns the Vector4 length (float). * @returns the length */ public length(): number { return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w) } /** * Returns the Vector4 squared length (float). * @returns the length squared */ public lengthSquared(): number { return this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w } // Methods /** * Normalizes in place the Vector4. * @returns the updated Vector4. */ public normalize(): Vector4 { let len = this.length() if (len === 0) { return this } return this.scaleInPlace(1.0 / len) } /** * Returns a new Vector3 from the Vector4 (x, y, z) coordinates. * @returns this converted to a new vector3 */ public toVector3(): Vector3 { return new Vector3(this.x, this.y, this.z) } /** * Returns a new Vector4 copied from the current one. * @returns the new cloned vector */ public clone(): Vector4 { return new Vector4(this.x, this.y, this.z, this.w) } /** * Updates the current Vector4 with the given one coordinates. * @param source - the source vector to copy from * @returns the updated Vector4. */ public copyFrom(source: ReadOnlyVector4): Vector4 { this.x = source.x this.y = source.y this.z = source.z this.w = source.w return this } /** * Updates the current Vector4 coordinates with the given floats. * @param x - float to copy from * @param y - float to copy from * @param z - float to copy from * @param w - float to copy from * @returns the updated Vector4. */ public copyFromFloats(x: number, y: number, z: number, w: number): Vector4 { this.x = x this.y = y this.z = z this.w = w return this } /** * Updates the current Vector4 coordinates with the given floats. * @param x - float to set from * @param y - float to set from * @param z - float to set from * @param w - float to set from * @returns the updated Vector4. */ public set(x: number, y: number, z: number, w: number): Vector4 { return this.copyFromFloats(x, y, z, w) } /** * Copies the given float to the current Vector3 coordinates * @param v - defines the x, y, z and w coordinates of the operand * @returns the current updated Vector3 */ public setAll(v: number): Vector4 { this.x = this.y = this.z = this.w = v return this } }
the_stack
import { IPdfPrimitive } from './../../interfaces/i-pdf-primitives'; import { IPdfWriter } from './../../interfaces/i-pdf-writer'; import { ObjectStatus } from './../input-output/enum'; import { PdfCrossTable } from './../input-output/pdf-cross-table'; /** * `PdfString` class is used to perform string related primitive operations. * @private */ export namespace InternalEnum { //Internals /** * public Enum for `ForceEncoding`. * @private */ export enum ForceEncoding { /** * Specifies the type of `None`. * @private */ None, /** * Specifies the type of `Ascii`. * @private */ Ascii, /** * Specifies the type of `Unicode`. * @private */ Unicode } /** * public Enum for `SourceType`. * @private */ enum SourceType { /** * Specifies the type of `StringValue`. * @private */ StringValue, /** * Specifies the type of `ByteBuffer`. * @private */ ByteBuffer, } } export class PdfString implements IPdfPrimitive { //constants = ; /** * `General markers` for string. * @private */ public static readonly stringMark : string = '()'; /** * `Hex markers` for string. * @private */ public static readonly hexStringMark : string = '<>'; /** * Format of password data. * @private */ private static readonly hexFormatPattern : string = '{0:X2}'; //Fields /** * Value of the object. * @private */ private stringValue : string; /** * The byte data of the string. * @private */ private data : number[]; /** * Value indicating whether the string was converted to hex. * @default false * @private */ private bHex : boolean = false; /** * Shows the type of object `status` whether it is object registered or other status; * @private */ private status1 : ObjectStatus; /** * Indicates if the object is currently in `saving state or not`. * @private */ private isSaving1 : boolean; /** * Internal variable to store the `position`. * @default -1 * @private */ private position1 : number = -1; /** * Internal variable to hold `PdfCrossTable` reference. * @private */ private crossTable : PdfCrossTable; /** * Internal variable to hold `cloned object`. * @default null * @private */ private clonedObject1 : PdfString = null; /** * Indicates whether to check if the value `has unicode characters`. * @private */ private bConverted : boolean; /** * Indicates whether we should convert `data to Unicode`. * @private */ private bForceEncoding : InternalEnum.ForceEncoding; /** * `Shows` if the data of the stream was decrypted. * @default false * @private */ private bDecrypted : boolean = false; /** * Holds the `index` number of the object. * @private */ private index1 : number; /** * Shows if the data of the stream `was decrypted`. * @default false * @private */ private isParentDecrypted : boolean = false; /** * Gets a value indicating whether the object is `packed or not`. * @default false * @private */ private isPacked : boolean = false; /** * @hidden * @private */ public isFormField : boolean = false; /** * @hidden * @private */ public isColorSpace : boolean = false; /** * @hidden * @private */ public isHexString : boolean = true; /** * @hidden * @private */ private encodedBytes : number[]; //constructor /** * Initializes a new instance of the `PdfString` class. * @private */ public constructor() /** * Initializes a new instance of the `PdfString` class. * @private */ public constructor(value : string) public constructor(value? : string) { if (typeof value === 'undefined') { this.bHex = false; } else { if (!(value.length > 0 && value[0] === '0xfeff')) { this.stringValue = value; this.data = []; for (let i : number = 0; i < value.length; ++i) { this.data.push(value.charCodeAt(i)); } } } } //Property /** * Gets a value indicating whether string is in `hex`. * @private */ public get hex() : boolean { return this.bHex; } /** * Gets or sets string `value` of the object. * @private */ public get value() : string { return this.stringValue; } public set value(value : string) { this.stringValue = value; this.data = null; } /** * Gets or sets the `Status` of the specified object. * @private */ public get status() : ObjectStatus { return this.status1; } public set status(value : ObjectStatus) { this.status1 = value; } /** * Gets or sets a value indicating whether this document `is saving` or not. * @private */ public get isSaving() : boolean { return this.isSaving1; } public set isSaving(value : boolean) { this.isSaving1 = value; } /** * Gets or sets the `index` value of the specified object. * @private */ public get objectCollectionIndex() : number { return this.index1; } public set objectCollectionIndex(value : number) { this.index1 = value; } /** * Returns `cloned object`. * @private */ public get clonedObject() : IPdfPrimitive { return this.clonedObject1; } /** * Gets or sets the `position` of the object. * @private */ public get position() : number { return this.position1; } public set position(value : number) { this.position1 = value; } /** * Returns `PdfCrossTable` associated with the object. * @private */ public get CrossTable() : PdfCrossTable { return this.crossTable; } /** * Gets a value indicating whether to check if the value has unicode characters. * @private */ public get converted() : boolean { return this.bConverted; } /** * sets a value indicating whether to check if the value has unicode characters. * @private */ public set converted(value : boolean) { this.bConverted = value; } /** * Gets value indicating whether we should convert data to Unicode. */ public get encode() : InternalEnum.ForceEncoding { return this.bForceEncoding; } public set encode(value : InternalEnum.ForceEncoding) { this.bForceEncoding = value; } //Methods /** * Converts `bytes to string using hex format` for representing string. * @private */ public static bytesToHex(bytes : number[]) : string { if (bytes == null) { return ''; } let builder : string = ''; return builder; } /** * `Saves` the object using the specified writer. * @private */ public save(writer : IPdfWriter) : void { if (writer === null) { throw new Error('ArgumentNullException : writer'); } if (this.encode !== undefined && this.encode === InternalEnum.ForceEncoding.Ascii) { writer.write(this.pdfEncode()); } else { writer.write(PdfString.stringMark[0] + this.value + PdfString.stringMark[1]); } } public pdfEncode() : string { let result : string = ''; if (this.encode !== undefined && this.encode === InternalEnum.ForceEncoding.Ascii) { let data : number[] = this.escapeSymbols(this.value); for (let i : number = 0; i < data.length; i++) { result += String.fromCharCode(data[i]); } result = PdfString.stringMark[0] + result + PdfString.stringMark[1]; } else { result = this.value; } return result; } private escapeSymbols(value : string) : number[] { let data : number[] = []; for (let i : number = 0; i < value.length; i++) { let currentData : number = value.charCodeAt(i); switch (currentData) { case 40: case 41: data.push(92); data.push(currentData); break; case 13: data.push(92); data.push(114); break; case 92: data.push(92); data.push(currentData); break; default: data.push(currentData); break; } } return data; } /** * Creates a `copy of PdfString`. * @private */ public clone(crossTable : PdfCrossTable) : IPdfPrimitive { if (this.clonedObject1 !== null && this.clonedObject1.CrossTable === crossTable) { return this.clonedObject1; } else { this.clonedObject1 = null; } let newString : PdfString = new PdfString(this.stringValue); newString.bHex = this.bHex; newString.crossTable = crossTable; newString.isColorSpace = this.isColorSpace; this.clonedObject1 = newString; return newString; } /** * Converts string to array of unicode symbols. */ public static toUnicodeArray(value : string, bAddPrefix : boolean) : number[] { if (value == null) { throw new Error('Argument Null Exception : value'); } let startIndex : number = 0; let output : number[] = []; for (let i : number = 0; i < value.length; i++) { let code : number = value.charCodeAt(i); output.push(code / 256 >>> 0); output.push(code & 0xff); } return output; } /** * Converts byte data to string. */ public static byteToString(data : number[]) : string { if (data == null) { throw new Error('Argument Null Exception : stream'); } let result : string = ''; for (let i : number = 0; i < data.length; ++i) { result += String.fromCharCode(data[i]); } return result; } }
the_stack
import { getImage } from "./images"; export class spaces { static drawUnknown(ctx: CanvasRenderingContext2D, x: number, y: number) { ctx.save(); ctx.beginPath(); ctx.arc(x, y, 8, 0, 2 * Math.PI); ctx.fillStyle = "orange"; ctx.lineWidth = 2; ctx.stroke(); ctx.fill(); ctx.restore(); } static drawOther(ctx: CanvasRenderingContext2D, x: number, y: number) { spaces._drawOther(ctx, x, y, 8); } static drawOther3(ctx: CanvasRenderingContext2D, x: number, y: number) { spaces._drawOther(ctx, x, y, 12); } static _drawOther(ctx: CanvasRenderingContext2D, x: number, y: number, radius: number) { ctx.save(); ctx.beginPath(); ctx.arc(x, y, radius, 0, 2 * Math.PI); ctx.lineWidth = radius / 6; ctx.strokeStyle = "rgba(255, 255, 255, 0.4)"; ctx.stroke(); ctx.lineWidth = radius / 4; ctx.fillStyle = "rgba(255, 255, 255, 0.2)"; ctx.strokeStyle = "black"; ctx.setLineDash([radius / 2, 3]); ctx.stroke(); ctx.fill(); ctx.restore(); } static drawBlue(ctx: CanvasRenderingContext2D, x: number, y: number) { ctx.save(); ctx.beginPath(); ctx.arc(x, y, 8, 0, 2 * Math.PI); ctx.lineWidth = 2; ctx.fillStyle = "#0039ff"; ctx.strokeStyle = "#001281"; ctx.stroke(); ctx.fill(); ctx.restore(); } static drawBlue3(ctx: CanvasRenderingContext2D, x: number, y: number) { ctx.save(); ctx.drawImage(getImage("spaceBlue3"), x - 14, y - 14); ctx.restore(); } static drawRed(ctx: CanvasRenderingContext2D, x: number, y: number) { ctx.save(); ctx.beginPath(); ctx.arc(x, y, 8, 0, 2 * Math.PI); ctx.lineWidth = 2; ctx.fillStyle = "#ff3131"; ctx.strokeStyle = "#611515"; ctx.stroke(); ctx.fill(); ctx.restore(); } static drawRed3(ctx: CanvasRenderingContext2D, x: number, y: number) { ctx.save(); ctx.drawImage(getImage("spaceRed3"), x - 14, y - 14); ctx.restore(); } static drawMiniGame(ctx: CanvasRenderingContext2D, x: number, y: number) { // Same as blue ctx.save(); ctx.beginPath(); ctx.arc(x, y, 8, 0, 2 * Math.PI); ctx.lineWidth = 2; ctx.fillStyle = "#0039ff"; ctx.strokeStyle = "#001281"; ctx.stroke(); ctx.fill(); // Add star on top. ctx.fillStyle = "#A4FFFF"; spaces._drawStar(ctx, x, y, 8, 5, 0.45); ctx.restore(); } static drawMiniGameDuel3(ctx: CanvasRenderingContext2D, x: number, y: number) { ctx.save(); ctx.drawImage(getImage("spaceMiniGameDuel3"), x - 14, y - 14); ctx.restore(); } static drawHappening(ctx: CanvasRenderingContext2D, x: number, y: number) { ctx.save(); ctx.beginPath(); ctx.arc(x, y, 8, 0, 2 * Math.PI); ctx.lineWidth = 2; ctx.fillStyle = "#099f0a"; ctx.strokeStyle = "#2e681e"; ctx.stroke(); ctx.fill(); // Add ? on top ctx.fillStyle = "white"; ctx.font = 'bold 19px monospace'; ctx.fillText("?", x - 6, y + 6); ctx.restore(); } static drawHappening3(ctx: CanvasRenderingContext2D, x: number, y: number) { ctx.save(); ctx.drawImage(getImage("spaceHappening3"), x - 14, y - 14); ctx.restore(); } static drawHappeningDuel3(ctx: CanvasRenderingContext2D, x: number, y: number) { ctx.save(); ctx.drawImage(getImage("spaceHappeningDuel3"), x - 14, y - 14); ctx.restore(); } static drawStar(ctx: CanvasRenderingContext2D, x: number, y: number) { spaces._drawStarSpace(ctx, x, y, 8); } static drawStar3(ctx: CanvasRenderingContext2D, x: number, y: number) { spaces._drawStarSpace(ctx, x, y, 12); } static _drawStarSpace(ctx: CanvasRenderingContext2D, x: number, y: number, radius: number) { ctx.save(); // Transparent base circle ctx.beginPath(); ctx.arc(x, y, radius, 0, 2 * Math.PI); ctx.lineWidth = radius / 8; ctx.fillStyle = "rgba(0, 0, 0, 0.2)"; ctx.strokeStyle = "rgba(0, 0, 0, 0.3)"; ctx.stroke(); ctx.fill(); // Add yellow star on top ctx.fillStyle = "yellow"; spaces._drawStar(ctx, x, y, radius + 1, 5, 0.45); ctx.restore(); } static drawChance(ctx: CanvasRenderingContext2D, x: number, y: number) { ctx.save(); ctx.beginPath(); ctx.arc(x, y, 8, 0, 2 * Math.PI); ctx.lineWidth = 2; ctx.fillStyle = "#0039ff"; ctx.strokeStyle = "#001281"; ctx.stroke(); ctx.fill(); // Add '!' ctx.fillStyle = "#ff3131"; ctx.font = "bold 19px monospace"; ctx.fillText("!", x - 6, y + 6); ctx.restore(); } static drawChance2(ctx: CanvasRenderingContext2D, x: number, y: number) { ctx.save(); ctx.beginPath(); ctx.arc(x, y, 8, 0, 2 * Math.PI); ctx.lineWidth = 2; ctx.fillStyle = "#099f0a"; ctx.strokeStyle = "#2e681e"; ctx.stroke(); ctx.fill(); // Add '!' ctx.fillStyle = "white"; ctx.font = "bold 19px monospace"; ctx.fillText("!", x - 6, y + 6); ctx.restore(); } static drawChance3(ctx: CanvasRenderingContext2D, x: number, y: number) { ctx.save(); ctx.drawImage(getImage("spaceChance3"), x - 14, y - 14); ctx.restore(); } static drawStart(ctx: CanvasRenderingContext2D, x: number, y: number) { spaces._drawStart(ctx, x, y, 8, "black"); } static drawStart3(ctx: CanvasRenderingContext2D, x: number, y: number) { spaces._drawStart(ctx, x, y, 12, "black"); } static drawStartDuelRed(ctx: CanvasRenderingContext2D, x: number, y: number) { spaces._drawStart(ctx, x, y, 12, "red"); } static drawStartDuelBlue(ctx: CanvasRenderingContext2D, x: number, y: number) { spaces._drawStart(ctx, x, y, 12, "blue"); } static _drawStart(ctx: CanvasRenderingContext2D, x: number, y: number, radius: number, color: string) { ctx.save(); ctx.beginPath(); ctx.arc(x, y, radius, 0, 2 * Math.PI); ctx.lineWidth = 1; ctx.fillStyle = color; ctx.strokeStyle = "rgba(255, 255, 255, 0.5)"; ctx.stroke(); ctx.fill(); // Write the word "START" ctx.fillStyle = "white"; ctx.strokeStyle = "black"; ctx.lineWidth = 2; ctx.font = "bold 12px monospace"; ctx.textAlign = "center"; ctx.strokeText("START", x, y + 12); ctx.fillText("START", x, y + 12); ctx.restore(); } static drawShroom(ctx: CanvasRenderingContext2D, x: number, y: number) { ctx.save(); ctx.beginPath(); if (ctx.ellipse) { ctx.ellipse(x, y, 8, 6, 0, 0, 2 * Math.PI); } else { ctx.arc(x, y, 8, 0, 2 * Math.PI); } ctx.lineWidth = 2; ctx.fillStyle = "#0039ff"; ctx.strokeStyle = "#001281"; ctx.stroke(); ctx.fill(); // Add dots ctx.beginPath(); ctx.fillStyle = "#D3FDFC"; ctx.arc(x, y + 5, 4, 0, 2 * Math.PI); ctx.fill(); ctx.beginPath(); ctx.arc(x - 5, y, 2, 0, 2 * Math.PI); ctx.fill(); ctx.beginPath(); ctx.arc(x + 5, y, 2, 0, 2 * Math.PI); ctx.fill(); ctx.beginPath(); ctx.arc(x, y - 2, 3, 0, 2 * Math.PI); ctx.fill(); ctx.restore(); } static drawBowser(ctx: CanvasRenderingContext2D, x: number, y: number) { ctx.save(); ctx.drawImage(getImage("spaceBowser"), x - 9, y - 9); ctx.restore(); } static drawBowser3(ctx: CanvasRenderingContext2D, x: number, y: number) { ctx.save(); ctx.drawImage(getImage("spaceBowser3"), x - 14, y - 14); ctx.restore(); } static drawItem2(ctx: CanvasRenderingContext2D, x: number, y: number) { ctx.save(); ctx.drawImage(getImage("spaceItem2"), x - 9, y - 9); ctx.restore(); } static drawItem3(ctx: CanvasRenderingContext2D, x: number, y: number) { ctx.save(); ctx.drawImage(getImage("spaceItem3"), x - 14, y - 14); ctx.restore(); } static drawBattle2(ctx: CanvasRenderingContext2D, x: number, y: number) { ctx.save(); ctx.beginPath(); ctx.arc(x, y, 8, 0, 2 * Math.PI); ctx.lineWidth = 2; ctx.fillStyle = "#099f0a"; ctx.strokeStyle = "#2e681e"; ctx.stroke(); ctx.fill(); // Zip zap ctx.beginPath(); ctx.fillStyle = "white"; ctx.translate(x - 10, y - 10); ctx.moveTo(14, 3); // Top point ctx.lineTo(4, 11); // Left point ctx.lineTo(9, 11); // Go inward ctx.lineTo(7, 18); // Bottom point ctx.lineTo(16, 9); // Right point ctx.lineTo(12, 9); // Go inward ctx.lineTo(14, 3); // Back to top point ctx.fill(); ctx.restore(); } static drawBattle3(ctx: CanvasRenderingContext2D, x: number, y: number) { ctx.save(); ctx.drawImage(getImage("spaceBattle3"), x - 14, y - 14); ctx.restore(); } static drawBank2(ctx: CanvasRenderingContext2D, x: number, y: number) { ctx.save(); ctx.beginPath(); ctx.arc(x, y, 8, 0, 2 * Math.PI); ctx.lineWidth = 2; ctx.fillStyle = "#099f0a"; ctx.strokeStyle = "#2e681e"; ctx.stroke(); ctx.fill(); // Add fancy drawing of coin bag ctx.fillStyle = "#EEF700"; ctx.translate(x - 10, y - 10); ctx.beginPath(); ctx.arc(10, 12, 5, 0, 2 * Math.PI); ctx.fill(); ctx.beginPath(); ctx.moveTo(8, 7); ctx.lineTo(7, 5); ctx.lineTo(8, 4); ctx.lineTo(12, 4); ctx.lineTo(13, 5); ctx.lineTo(12, 7); ctx.fill(); ctx.fillStyle = "#099f0a"; spaces._drawStar(ctx, 10, 12, 4, 5, 0.45); ctx.restore(); } static drawBank3(ctx: CanvasRenderingContext2D, x: number, y: number) { ctx.save(); ctx.drawImage(getImage("spaceBank3"), x - 14, y - 14); ctx.restore(); } static drawArrow(ctx: CanvasRenderingContext2D, x: number, y: number, game: number) { ctx.save(); ctx.beginPath(); ctx.fillStyle = "#F647A0"; ctx.strokeStyle = "#94305B"; if (game === 3) { ctx.translate(x - 12, y - 12); ctx.scale(1.25, 1.25); } else { ctx.translate(x - 10, y - 10); } ctx.moveTo(10, 1); // Top point ctx.lineTo(1, 10); // Left point ctx.lineTo(5, 10); // Go inward ctx.lineTo(5, 18); // Bottom left ctx.lineTo(15, 18); // Bottom right ctx.lineTo(15, 10); // Inner right ctx.lineTo(19, 10); // Right point ctx.lineTo(10, 1); // Back to top ctx.stroke(); ctx.fill(); ctx.restore(); } static drawBlackStar2(ctx: CanvasRenderingContext2D, x: number, y: number) { ctx.save(); // Transparent base circle ctx.beginPath(); ctx.arc(x, y, 8, 0, 2 * Math.PI); ctx.lineWidth = 1; ctx.fillStyle = "rgba(0, 0, 0, 0.2)"; ctx.strokeStyle = "rgba(0, 0, 0, 0.3)"; ctx.stroke(); ctx.fill(); // Add black star on top ctx.fillStyle = "black"; spaces._drawStar(ctx, x, y, 9, 5, 0.45); ctx.restore(); } static drawGameGuy3(ctx: CanvasRenderingContext2D, x: number, y: number) { ctx.save(); ctx.drawImage(getImage("spaceGameGuy3"), x - 14, y - 14); ctx.restore(); } static drawGameGuyDuel3(ctx: CanvasRenderingContext2D, x: number, y: number) { ctx.save(); ctx.drawImage(getImage("spaceGameGuyDuel3"), x - 14, y - 14); ctx.restore(); } static drawDuelBasic(ctx: CanvasRenderingContext2D, x: number, y: number) { ctx.save(); ctx.drawImage(getImage("spaceDuelBasic3"), x - 14, y - 14); ctx.restore(); } static drawDuelPowerup(ctx: CanvasRenderingContext2D, x: number, y: number) { ctx.save(); ctx.drawImage(getImage("spaceDuelPowerup3"), x - 14, y - 14); ctx.restore(); } static drawDuelReverse(ctx: CanvasRenderingContext2D, x: number, y: number) { ctx.save(); ctx.drawImage(getImage("spaceDuelReverse3"), x - 14, y - 14); ctx.restore(); } // Draws any star shape, helper method. static _drawStar(ctx: CanvasRenderingContext2D, x: number, y: number, r: number, numPoints: number, radiusInsetFraction: number) { ctx.save(); ctx.beginPath(); ctx.translate(x, y); ctx.moveTo(0, 0 - r); for (let i = 0; i < numPoints; i++) { ctx.rotate(Math.PI / numPoints); ctx.lineTo(0, 0 - (r * radiusInsetFraction)); ctx.rotate(Math.PI / numPoints); ctx.lineTo(0, 0 - r); } ctx.fill(); ctx.restore(); } }
the_stack
import { Buffer, Sockets, Network, PageHub } from '../../src/index' import { PageHubServer } from '../../src/hub/page' import { expect } from 'chai' import * as support from '../support' async function use(func: (sockets: Sockets) => void) { const hubServer = new PageHubServer({}) hubServer.listen(0) const hub = new PageHub(0) const net = new Network(hub) const sockets = new Sockets(net) await func(sockets) sockets.dispose() net.dispose() hub.dispose() hubServer.dispose() } type RunCallback<T=any> = (resolve: (value: T) => void, reject: (error: any) => void) => void function run<T=any>(callback: RunCallback<T>) { return new Promise<T>((resolve, reject) => callback(resolve, reject)) } describe('Sockets', () => { // #region events it("'client' should receive 'open', 'message' and 'close' events.", async () => { await use(async sockets => { sockets.createServer(socket => { socket.send('1') socket.close() }).listen(5000) const [opened, messaged, closed] = await run(resolve => { const socket = sockets.connect('localhost', 5000) let opened = false let messaged = false let closed = false socket.on('open', () => { opened = true }) socket.on('message', () => { messaged = true }) socket.on('close', () => { closed = true resolve([opened, messaged, closed]) }) }) expect(opened).to.be.true expect(messaged).to.be.true expect(closed).to.be.true }) }) it("'client' should 'error' and 'close' on non-resolvable server", async () => { await use(async sockets => { const socket = sockets.connect('localhost', 5000) let opened = false let messaged = false let errored = false let closed = false socket.on('open', () => { opened = true }) socket.on('message', () => { messaged = true }) socket.on('error', () => { errored = true }) socket.on('close', () => { closed = true }) await support.wait(() => closed) expect(opened).to.be.false expect(messaged).to.be.false expect(errored).to.be.true expect(closed).to.be.true }) }) it("'server' should 'message' and 'close' events but not 'open'.", async () => { await use(async sockets => { let opened = false let messaged = false let closed = false sockets.createServer(socket => { socket.on('open', () => { opened = true }) socket.on('message', () => { messaged = true }) socket.on('close', () => { closed = true }) }).listen(5000) const socket = sockets.connect('localhost', 5000) socket.on('open', () => { socket.send('1') socket.close() }) await support.wait(() => closed) expect(opened).to.be.false expect(messaged).to.be.true expect(closed).to.be.true }) }) // #region server > client messaging it("'client' should receive 'message' from server then 'close'.", async () => { await use(async sockets => { const input = support.createRandomBuffer(1024) sockets.createServer(socket => { socket.send(input) socket.close() }).listen(5000) const output = await run((resolve, reject) => { const socket = sockets.connect('localhost', 5000) let output: Buffer; socket.on('close', () => resolve(output)) socket.on('message', message => { output = Buffer.from(message.data) }) }) const match = input.equals(output) expect(match).to.be.true }) }) // #region client > server messaging it("'server' should receive 'message' from client then 'close'.", async () => { await use(async sockets => { const input = support.createRandomBuffer(1024) let output: Buffer let closed = false sockets.createServer(socket => { socket.on('message', message => { output = Buffer.from(message.data) }) socket.on('close', () => { closed = true }) }).listen(5000) await run(resolve => { const socket = sockets.connect('localhost', 5000) socket.on('open', async () => { socket.send(input) socket.close() await support.wait(() => closed) resolve(null) }) }) const match = input.equals(output!) expect(match).to.be.true expect(closed).to.be.true }) }) // #region echo it("'server' should echo 'client' message.", async () => { await use(async sockets => { const input = support.createRandomBuffer(1024) let closed = false sockets.createServer(socket => { socket.on('message', message => socket.send(message.data)) socket.on('close', () => { closed = true }) }).listen(5000) const output = await run(resolve => { const socket = sockets.connect('localhost', 5000) let output: Buffer socket.on('open', async () => { socket.on('message', message => { output = Buffer.from(message.data) socket.close() }) socket.send(input) await support.wait(() => closed) resolve(output) }) }) const match = input.equals(output) expect(match).to.be.true }) }) it("'client' should echo 'server' message.", async () => { await use(async sockets => { const input = support.createRandomBuffer(1024) let closed = false let output: Buffer sockets.createServer(socket => { socket.send(input) socket.on('message', message => { output = Buffer.from(message.data) socket.close() closed = true }) }).listen(5000) const socket = sockets.connect('localhost', 5000) socket.on('message', message => socket.send(message.data)) await support.wait(() => closed) const match = input.equals(output!) expect(match).to.be.true }) }) // #region throw conditions it("'client' should 'throw' sending to an un-opened socket.", async () => { await use(async sockets => { const input = support.createRandomBuffer(1024) sockets.createServer(socket => { }).listen(5000) await support.shouldThrow(async () => { const socket = sockets.connect('localhost', 5000) socket.send('1') }) }) }) // #region streaming it("'server' should send 128 messages in sequence then close.", async () => { await use(async sockets => { const COUNT = 128 const inputs = support.range(COUNT).map(() => support.createRandomBuffer(1024)) sockets.createServer(socket => { for(const buffer of inputs) { socket.send(buffer) } socket.close() }).listen(5000) const outputs: Buffer[] = [] let closed = false const socket = sockets.connect('localhost', 5000) socket.on('close', () => { closed = true }) socket.on('message', message => { outputs.push(Buffer.from(message.data)) }) await support.wait(() => closed) expect(outputs.length).to.be.eq(inputs.length) for(let i = 0; i < inputs.length; i++) { const match = outputs[i].equals(inputs[i]) expect(match).to.be.true } }) }) it("'client' should send 128 messages in sequence then close.", async () => { await use(async sockets => { const COUNT = 128 const inputs = support.range(COUNT).map(() => support.createRandomBuffer(1024)) let closed = false sockets.createServer(socket => { socket.on('close', () => { closed = true }) socket.on('message', message => { outputs.push(Buffer.from(message.data)) }) }).listen(5000) const outputs: Buffer[] = [] const socket = sockets.connect('localhost', 5000) socket.on('open', () => { for(const buffer of inputs) { socket.send(buffer) } socket.close() }) await support.wait(() => closed) expect(outputs.length).to.be.eq(inputs.length) for(let i = 0; i < inputs.length; i++) { const match = outputs[i].equals(inputs[i]) expect(match).to.be.true } }) }) // #region message size it('should send and receive 100_000 byte message payloads', async () => { await use(async sockets => { const input = support.createRandomBuffer(100_000) sockets.createServer(socket => { socket.send(input) socket.close() }).listen(5000) const socket = sockets.connect('localhost', 5000) let output: Buffer; let closed = false socket.on('message', message => { output = message.data }) socket.on('close', () => { closed = true }) await support.wait(() => closed) const match = input.equals(output!) expect(match).to.be.true }) }) // #region message size it('should throw when sending greater than 1_000_000 byte message payloads', async () => { await use(async sockets => { sockets.createServer(_ => {}).listen(5000) const socket = sockets.connect('localhost', 5000) await support.shouldThrow(async () => { await run((resolve, reject) => { socket.on('open', () => { try { socket.send(Buffer.alloc(1_000_001)) resolve(null) } catch(error) { reject(error) } }) }) }) }) }) // #region concurrency it("'server' should accept 128 sockets, 'send' one to each then 'close'", async () => { await use(async sockets => { const COUNT = 128 const input = support.createRandomBuffer(1024) let openCount = 0 let connectCount = 0 let closedCount = 0 sockets.createServer(socket => { connectCount += 1 socket.send(input) socket.close() }).listen(5000) const outputs: Buffer[] = [] support.range(COUNT).forEach(() => { const socket = sockets.connect('localhost', 5000) socket.on('open', () => { openCount += 1}) socket.on('close', () => { closedCount += 1}) socket.on('message', message => { outputs.push(Buffer.from(message.data)) }) }) await support.wait(() => closedCount === COUNT) expect(connectCount).to.be.eq(COUNT) expect(openCount).to.be.eq(COUNT) expect(closedCount).to.be.eq(COUNT) expect(outputs).to.have.lengthOf(COUNT) for(const buffer of outputs) { expect(buffer.equals(input)).to.be.true } }) }) })
the_stack
import resolveParentPathBy = require( './index' ); /** * Callback to invoke after processing a path. * * @param error - error object or null * @param result - test result */ type Callback = ( error: Error | null, result: boolean ) => void; /** * Checks whether a path passes a test. * * @param path - resolved path * @param next - callback */ function predicate( path: string, next: Callback ): void { next( null, ( path === path ) ); } /** * Checks whether a path passes a test. * * @param path - resolved path */ function predicateSync( path: string ): boolean { return ( path === path ); } /** * Callback invoked upon resolving a path. * * @param error - error object * @param path - resolved path */ function done( error: Error | null, path: string | null ): void { if ( error || path === null ) { throw new Error( 'beep' ); } } // TESTS // // The function returns void... { resolveParentPathBy( 'package.json', predicate, done ); // $ExpectType void resolveParentPathBy( 'package.json', {}, predicate, done ); // $ExpectType void } // The compiler throws an error if the function is provided a first argument which is not a string... { resolveParentPathBy( 123, predicate, done ); // $ExpectError resolveParentPathBy( false, predicate, done ); // $ExpectError resolveParentPathBy( true, predicate, done ); // $ExpectError resolveParentPathBy( null, predicate, done ); // $ExpectError resolveParentPathBy( undefined, predicate, done ); // $ExpectError resolveParentPathBy( [], predicate, done ); // $ExpectError resolveParentPathBy( {}, predicate, done ); // $ExpectError resolveParentPathBy( ( x: number ): number => x, predicate, done ); // $ExpectError resolveParentPathBy( 123, {}, predicate, done ); // $ExpectError resolveParentPathBy( false, {}, predicate, done ); // $ExpectError resolveParentPathBy( true, {}, predicate, done ); // $ExpectError resolveParentPathBy( null, {}, predicate, done ); // $ExpectError resolveParentPathBy( undefined, {}, predicate, done ); // $ExpectError resolveParentPathBy( [], {}, predicate, done ); // $ExpectError resolveParentPathBy( {}, {}, predicate, done ); // $ExpectError resolveParentPathBy( ( x: number ): number => x, {}, predicate, done ); // $ExpectError } // The compiler throws an error if the function is provided a predicate function argument which is not a function with the expected signature... { resolveParentPathBy( '/var/log/', 1, done ); // $ExpectError resolveParentPathBy( '/var/log/', false, done ); // $ExpectError resolveParentPathBy( '/var/log/', true, done ); // $ExpectError resolveParentPathBy( '/var/log/', null, done ); // $ExpectError resolveParentPathBy( '/var/log/', undefined, done ); // $ExpectError resolveParentPathBy( '/var/log/', [], done ); // $ExpectError resolveParentPathBy( '/var/log/', {}, done ); // $ExpectError resolveParentPathBy( '/var/log/', ( x: number ): number => x, done ); // $ExpectError resolveParentPathBy( '/var/log/', {}, 1, done ); // $ExpectError resolveParentPathBy( '/var/log/', {}, false, done ); // $ExpectError resolveParentPathBy( '/var/log/', {}, true, done ); // $ExpectError resolveParentPathBy( '/var/log/', {}, null, done ); // $ExpectError resolveParentPathBy( '/var/log/', {}, undefined, done ); // $ExpectError resolveParentPathBy( '/var/log/', {}, [], done ); // $ExpectError resolveParentPathBy( '/var/log/', {}, {}, done ); // $ExpectError resolveParentPathBy( '/var/log/', {}, ( x: number ): number => x, done ); // $ExpectError } // The compiler throws an error if the function is provided a "done" callback argument which is not a function with the expected signature... { resolveParentPathBy( '/var/log/', predicate, 1 ); // $ExpectError resolveParentPathBy( '/var/log/', predicate, false ); // $ExpectError resolveParentPathBy( '/var/log/', predicate, true ); // $ExpectError resolveParentPathBy( '/var/log/', predicate, null ); // $ExpectError resolveParentPathBy( '/var/log/', predicate, undefined ); // $ExpectError resolveParentPathBy( '/var/log/', predicate, [] ); // $ExpectError resolveParentPathBy( '/var/log/', predicate, {} ); // $ExpectError resolveParentPathBy( '/var/log/', predicate, ( x: number ): number => x ); // $ExpectError resolveParentPathBy( '/var/log/', {}, predicate, 1 ); // $ExpectError resolveParentPathBy( '/var/log/', {}, predicate, false ); // $ExpectError resolveParentPathBy( '/var/log/', {}, predicate, true ); // $ExpectError resolveParentPathBy( '/var/log/', {}, predicate, null ); // $ExpectError resolveParentPathBy( '/var/log/', {}, predicate, undefined ); // $ExpectError resolveParentPathBy( '/var/log/', {}, predicate, [] ); // $ExpectError resolveParentPathBy( '/var/log/', {}, predicate, {} ); // $ExpectError resolveParentPathBy( '/var/log/', {}, predicate, ( x: number ): number => x ); // $ExpectError } // The compiler throws an error if the function is provided an options argument which is not an object... { resolveParentPathBy( 'package.json', null, predicate, done ); // $ExpectError } // The compiler throws an error if the function is provided an `dir` option which is not a string... { resolveParentPathBy( 'package.json', { 'dir': 123 }, predicate, done ); // $ExpectError resolveParentPathBy( 'package.json', { 'dir': true }, predicate, done ); // $ExpectError resolveParentPathBy( 'package.json', { 'dir': false }, predicate, done ); // $ExpectError resolveParentPathBy( 'package.json', { 'dir': null }, predicate, done ); // $ExpectError resolveParentPathBy( 'package.json', { 'dir': [] }, predicate, done ); // $ExpectError resolveParentPathBy( 'package.json', { 'dir': {} }, predicate, done ); // $ExpectError resolveParentPathBy( 'package.json', { 'dir': ( x: number ): number => x }, predicate, done ); // $ExpectError } // The compiler throws an error if the function is provided an unsupported number of arguments... { resolveParentPathBy(); // $ExpectError resolveParentPathBy( 'C:\\foo\\bar\\baz' ); // $ExpectError resolveParentPathBy( 'C:\\foo\\bar\\baz', {} ); // $ExpectError resolveParentPathBy( 'C:\\foo\\bar\\baz', predicate ); // $ExpectError resolveParentPathBy( 'C:\\foo\\bar\\baz', {}, predicate ); // $ExpectError resolveParentPathBy( 'C:\\foo\\bar\\baz', {}, predicate, done, {} ); // $ExpectError } // Attached to the main export is a `sync` method which returns a string or null... { resolveParentPathBy.sync( 'package.json', predicateSync ); // $ExpectType string | null resolveParentPathBy.sync( 'package.json', {}, predicateSync ); // $ExpectType string | null } // The compiler throws an error if the `sync` method is provided a first argument which is not a string... { resolveParentPathBy.sync( 123, predicateSync ); // $ExpectError resolveParentPathBy.sync( false, predicateSync ); // $ExpectError resolveParentPathBy.sync( true, predicateSync ); // $ExpectError resolveParentPathBy.sync( null, predicateSync ); // $ExpectError resolveParentPathBy.sync( undefined, predicateSync ); // $ExpectError resolveParentPathBy.sync( [], predicateSync ); // $ExpectError resolveParentPathBy.sync( {}, predicateSync ); // $ExpectError resolveParentPathBy.sync( ( x: number ): number => x, predicateSync ); // $ExpectError resolveParentPathBy.sync( 123, {}, predicateSync ); // $ExpectError resolveParentPathBy.sync( false, {}, predicateSync ); // $ExpectError resolveParentPathBy.sync( true, {}, predicateSync ); // $ExpectError resolveParentPathBy.sync( null, {}, predicateSync ); // $ExpectError resolveParentPathBy.sync( undefined, {}, predicateSync ); // $ExpectError resolveParentPathBy.sync( [], {}, predicateSync ); // $ExpectError resolveParentPathBy.sync( {}, {}, predicateSync ); // $ExpectError resolveParentPathBy.sync( ( x: number ): number => x, {}, predicateSync ); // $ExpectError } // The compiler throws an error if the `sync` method is provided a predicate function argument which is not a function with the expected signature... { resolveParentPathBy.sync( 'package.json', 123 ); // $ExpectError resolveParentPathBy.sync( 'package.json', false ); // $ExpectError resolveParentPathBy.sync( 'package.json', true ); // $ExpectError resolveParentPathBy.sync( 'package.json', null ); // $ExpectError resolveParentPathBy.sync( 'package.json', undefined ); // $ExpectError resolveParentPathBy.sync( 'package.json', [] ); // $ExpectError resolveParentPathBy.sync( 'package.json', {} ); // $ExpectError resolveParentPathBy.sync( 'package.json', {}, 123 ); // $ExpectError resolveParentPathBy.sync( 'package.json', {}, false ); // $ExpectError resolveParentPathBy.sync( 'package.json', {}, true ); // $ExpectError resolveParentPathBy.sync( 'package.json', {}, null ); // $ExpectError resolveParentPathBy.sync( 'package.json', {}, undefined ); // $ExpectError resolveParentPathBy.sync( 'package.json', {}, [] ); // $ExpectError resolveParentPathBy.sync( 'package.json', {}, {} ); // $ExpectError } // The compiler throws an error if the `sync` method is provided an options argument which is not an object... { resolveParentPathBy.sync( 'package.json', null, predicateSync ); // $ExpectError } // The compiler throws an error if the `sync` method is provided an `dir` option which is not a string... { resolveParentPathBy.sync( 'package.json', { 'dir': 123 }, predicateSync ); // $ExpectError resolveParentPathBy.sync( 'package.json', { 'dir': true }, predicateSync ); // $ExpectError resolveParentPathBy.sync( 'package.json', { 'dir': false }, predicateSync ); // $ExpectError resolveParentPathBy.sync( 'package.json', { 'dir': null }, predicateSync ); // $ExpectError resolveParentPathBy.sync( 'package.json', { 'dir': [] }, predicateSync ); // $ExpectError resolveParentPathBy.sync( 'package.json', { 'dir': {} }, predicateSync ); // $ExpectError resolveParentPathBy.sync( 'package.json', { 'dir': ( x: number ): number => x }, predicateSync ); // $ExpectError } // The compiler throws an error if the `sync` method is provided an unsupported number of arguments... { resolveParentPathBy.sync(); // $ExpectError resolveParentPathBy.sync( 'package.json' ); // $ExpectError resolveParentPathBy.sync( 'package.json', {}, predicateSync, {} ); // $ExpectError }
the_stack
import {testResultsCache} from "../../clientTestResultsCache"; import * as events from "../../../common/events"; import * as utils from "../../../common/utils"; import * as types from "../../../common/types"; import * as json from "../../../common/json"; import * as typestyle from "typestyle"; import * as styles from "../../styles/styles"; import {Icon} from "../../components/icon"; import * as React from "react"; import * as ReactDOM from "react-dom"; type IDisposable = events.Disposable; type Editor = monaco.editor.ICodeEditor; import Position = monaco.Position; type ICodeEditor = monaco.editor.ICodeEditor; const keyForMonacoDifferentiation = "alm_tested" const lineSeperator = '\n———————————————\n'; namespace TestedMonacoStyles { const overlayCommon: typestyle.types.NestedCSSProperties = { padding: '0px 10px', whiteSpace: 'pre', pointerEvents: 'none', /** * This is to match the line height for a line in monaco * Inspected a line in monaco to figure this out * On mac it was 24px * On windows it was 22px. * Going with the small value globally instead of trying to figure it out */ lineHeight: '22px', } export const logOverlayClassName = typestyle.style( overlayCommon, { color: styles.monokaiTextColor, } ); export const errorStackOverlayClassName = typestyle.style( overlayCommon, { color: styles.errorColor, } ); } export function setup(editor: Editor): { dispose: () => void } { // if (editor) return { dispose: () => null }; // DEBUG : while the feature isn't complete used to disable it let hadSomeTestsResults = false; type WidgetDispose = { dispose(): void }; const deltaLogWidgets = new DeltaList<types.TestLog, WidgetDispose>({ getId: (log: types.TestLog) => { return `${keyForMonacoDifferentiation} - ${JSON.stringify(log)}`; }, onAdd:(log) => { const argsStringifiedAndJoined = log.args.map((a) => json.stringify(a).trim()) .join(lineSeperator); let nodeRendered = <div className={TestedMonacoStyles.logOverlayClassName}> {argsStringifiedAndJoined} </div>; let node = document.createElement('div'); ReactDOM.render(nodeRendered, node); const widgetDispose = MonacoInlineWidget.add({ editor, frameColor: styles.monokaiTextColor, domNode: node, position: log.testLogPosition.lastPositionInFile, heightInLines: argsStringifiedAndJoined.split('\n').length + 1, }); return widgetDispose; }, onRemove: (log, state) => state.dispose(), }); const deltaTestResultsWidgets = new DeltaList<types.TestResult, WidgetDispose>({ getId: (result: types.TestResult) => { return `${keyForMonacoDifferentiation} - ${JSON.stringify(result)}`; }, onAdd: (result) => { const disposible = new events.CompositeDisposible(); /** * Show pass fail in the editor. * Would prefer in gutter but monaco doesn't allow multiple gutters. * So adding them inline as circles. * They move to the gutter based on our column setting ;) */ let dotRendered = <div className={`hint--right ${ result.status === types.TestStatus.Success ? "hint--success" : result.status === types.TestStatus.Fail ? "hint--error" : "hint--info" }`} style={{ cursor: 'pointer', padding: '0px 5px', color: result.status === types.TestStatus.Success ? styles.successColor : result.status === types.TestStatus.Fail ? styles.errorColor : styles.highlightColor }} data-hint={ result.status === types.TestStatus.Success ? "Test Success" : result.status === types.TestStatus.Fail ? `Test Fail: ${result.error.message}` : "Test Skipped" }> <Icon name={styles.icons.tested}/> </div>; let dotNode = document.createElement('div'); ReactDOM.render(dotRendered, dotNode); const widget: monaco.editor.IContentWidget = { allowEditorOverflow: false, getId: () => `${keyForMonacoDifferentiation} - dot - ${JSON.stringify(result)}`, getDomNode: () => dotNode, getPosition: () => { return { position: { lineNumber: result.testLogPosition.lastPositionInFile.line + 1, column: /** Show in start of line to keep it easier to scan with eye */ 1 }, preference: [ monaco.editor.ContentWidgetPositionPreference.EXACT ] } } } editor.addContentWidget(widget); disposible.add({ dispose: () => editor.removeContentWidget(widget) }) /** * Show stacks for error ones */ if (!result.error) { // No stack for passing ones :) return disposible; } let trailingStackStringifiedAndJoined = result.error.stack /** Remove the first one as that is where we will show the error */ .slice(1) .map((a) => `${a.filePath}:${a.position.line + 1}:${a.position.ch + 1}`) .join(lineSeperator); const detailsStringifiedAndJoined = result.error.message + (trailingStackStringifiedAndJoined ? `${lineSeperator}${trailingStackStringifiedAndJoined}` : ''); let nodeRendered = <div className={TestedMonacoStyles.errorStackOverlayClassName}> {detailsStringifiedAndJoined} </div>; let node = document.createElement('div'); ReactDOM.render(nodeRendered, node); const widgetDispose = MonacoInlineWidget.add({ editor, frameColor: styles.errorColor, domNode: node, position: result.error.testLogPosition.lastPositionInFile, heightInLines: detailsStringifiedAndJoined.split('\n').length + 1, }); disposible.add(widgetDispose); return disposible; }, onRemove: (result, state) => state.dispose(), }); const performLogRefresh = utils.debounce((): void => { let filePath: string = editor.filePath; let model: monaco.editor.IModel = editor.getModel(); const allResults = testResultsCache.getResults(); const thisModule = allResults[filePath]; if (!thisModule) { if (hadSomeTestsResults) { deltaLogWidgets.delta([]); deltaTestResultsWidgets.delta([]); } hadSomeTestsResults = false; return; } hadSomeTestsResults = true; /** * Update logs for this file * For those found update them * For those not found delete them * For those new add them. * * show logs in this file inline * show logs in external files still inline */ deltaLogWidgets.delta(thisModule.logs); /** Also show the test results */ deltaTestResultsWidgets.delta(thisModule.testResults); // console.log(thisModule.logs); // DEBUG }, 500); // Perform an initial lint performLogRefresh(); const disposible = new events.CompositeDisposible(); // Subscribe for future updates disposible.add(testResultsCache.testResultsDelta.on(performLogRefresh)); return disposible; } /** * Imagine a data structure that takes `T[]` * and given `getId(): T` * * Calls these on delta for `T[]` * * onAdd => do stuff and give me some state I will call for onRemove * onRemove => do stuff */ class DeltaList<T,State> { constructor(private config: { getId: (item: T) => string; onAdd: (item: T) => State; onRemove: (item: T, state: State) => void; }) { } private map: { [id: string]: { item: T, state: State, } } = Object.create(null); delta(items: T[]) { /** for quick lookup */ const quickNewItemLookup = utils.createMap(items.map(this.config.getId)); /** New dict */ let newDict = this.map; newDict = Object.create(null); /** old dict */ const oldDict = this.map; items.forEach(item => { const id = this.config.getId(item); /** Added? */ if (!oldDict[id]) { const state = this.config.onAdd(item); newDict[id] = { item, state } } /** Just copy over */ else { newDict[id] = oldDict[id]; } }); /** Removed? */ Object.keys(oldDict).forEach(id => { if (!quickNewItemLookup[id]){ this.config.onRemove(oldDict[id].item, oldDict[id].state); } }); this.map = newDict; } } namespace MonacoInlineWidget { declare class _ZoneWidget { constructor(...args: any[]); create(): void; show(pos: Position, heightInLines: number): void; dispose(): void; }; const ZoneWidget: typeof _ZoneWidget = monacoRequire('vs/editor/contrib/zoneWidget/browser/zoneWidget').ZoneWidget; type Config = { editor: Editor, frameColor: string, domNode: HTMLDivElement, position: { line: number, ch: number }, /** * Consider removing this and using height measuring * e.g. https://github.com/wnr/element-resize-detector * which is used by https://github.com/souporserious/react-measure/blob/db00f18922a0934544751c56c536689f675da9fa/src/Measure.jsx#L38 */ heightInLines: number, } /** For reference see `gotoError.ts` in monaco source code */ class MyMarkerWidget extends ZoneWidget { private _editor: ICodeEditor; private _parentContainer: HTMLElement; constructor(private config: Config) { super(config.editor, { frameColor: config.frameColor, }); this.create(); const position = new Position(config.position.line + 1, config.position.ch + 1); this.show(position, config.heightInLines); } protected _fillContainer(container: HTMLElement): void { this._parentContainer = container; this._parentContainer.tabIndex = 0; this._parentContainer.setAttribute('role', 'tooltip'); this._parentContainer.appendChild(this.config.domNode); /** Because sometimes monaco is leaving text hanging around */ this._parentContainer.style.backgroundColor = styles.monokaiBackgroundColor; } public dispose() { super.dispose(); } } export function add(config: Config): { dispose: () => void } { const editor = config.editor; const position = editor.getPosition(); const revealPosition = editor.revealPosition; const revealLine = editor.revealLine; editor.revealPosition = () => null; editor.revealLine = () => null; /** Add */ const widget = new MyMarkerWidget(config); /** * Our inline log widgets jump the scroll position. So we needed disable and restore these functions :-/ * Also some of these are called asyncly for some reason. * See code in ZoneWidget._showImpl */ editor.setPosition(position); editor.revealPosition = revealPosition; editor.revealLine = revealLine; return widget; } }
the_stack
import React, { useEffect, useImperativeHandle, useRef } from "react"; import { DARK_GREY, GREEN } from "../../playground/lesson1/colours"; import Zdog from "zdog"; import Zfont from "zfont"; import { useSelector } from "react-redux"; Zfont.init(Zdog); const DOSIS = new Zdog.Font({ src: "/open-sans-lat_cyr-600.ttf" }); const TAU = Zdog.TAU; const viewRotation = new Zdog.Vector(); viewRotation.add({ x: TAU / 6 }); viewRotation.add({ z: TAU / 16 }); let dragStartRX, dragStartRZ; const animation_speed_factor = 1; const createNodeLabel = (addTo) => new Zdog.Text({ addTo, font: DOSIS, value: ":)", fill: true, fontSize: 16, stroke: false, textAlign: "center", textBaseline: "bottom", color: DARK_GREY.string(), }); const createPacketLabel = (addTo) => new Zdog.Text({ addTo, font: DOSIS, value: ":)", fill: true, fontSize: 12, stroke: false, textAlign: "center", textBaseline: "middle", color: DARK_GREY.string(), }); function randomInterval(min, max) { return Math.random() * (max - min + 1) + min; } const linkNodes = (state, nodes) => { function get_connection_point(node, node_b) { let point = { x: node.translate.x, y: node.translate.y, }; // if (node.translate.x > node_b.translate.x) { // point.x -= node.width/2; // } else { // point.x += node.width/2; // } if (node.translate.y > node_b.translate.y) { point.y -= node.height / 2; } else { point.y += node.height / 2; } return point; } let link1 = link.copy(); let a = get_connection_point(nodes[0], nodes[1]); let b = get_connection_point(nodes[1], nodes[0]); link1.path = [ a, // First node { bezier: [ { x: a.x, y: b.y }, // First control point { x: b.x, y: a.y }, // Second control point b, // Second node ], }, ]; link1.updatePath(); state.links.push(link1); state.illo.addChild(link1); }; const addNode = (state, name, coords = { x: 0, y: 0, z: 0 }, color = GREEN) => { let node = network_node.copy(); let label = createNodeLabel(state.illo); label.value = name; label.rotate.x = -TAU / 4; label.translate = { x: coords.x, y: coords.y, z: coords.z + node.height * 1.9, }; node.leftFace = color.darken(0.3).alpha(0.8).string(); node.rightFace = color.alpha(0.8).string(); node.topFace = color.alpha(0.8).string(); node.bottomFace = color.darken(0.3).alpha(0.8).string(); node.color = color.darken(0.1).alpha(0.8).string(); node.name = name; node.translate = coords; node.translate.z += node.height / 1.5; node.label = label; state.illo.addChild(node); state.networkNodes.push(node); state.textElements.push(label); }; // Cubic bezier pct — 0..1 function getCubicBezierXY(pct, startPt, controlPt1, controlPt2, endPt) { var x = CubicN(pct, startPt.x, controlPt1.x, controlPt2.x, endPt.x); var y = CubicN(pct, startPt.y, controlPt1.y, controlPt2.y, endPt.y); return { x: x, y: y, }; } function CubicN(pct, a, b, c, d) { var t2 = pct * pct; var t3 = t2 * pct; return ( a + (-a * 3 + pct * (3 * a - a * pct)) * pct + (3 * b + pct * (-6 * b + b * 3 * pct)) * pct + (c * 3 - c * 3 * pct) * t2 + d * t3 ); } // Packet format: packet = {progress: 0..1, coords: {x:0, y:0}, speed_factor: 1, link: link object, reverse: true} // increment = amount in percents (0..1) of the full packet's path // Returns `false` when the packet has been successfully transferred. const transferPacket = (packet, increment) => { let path = packet.link.path; increment = increment * packet.speed_factor * animation_speed_factor; if (!packet.reverse && packet.progress + increment > 1) { return false; } if (packet.reverse && packet.progress - increment < 0) { return false; } if (packet.reverse) { if (packet.progress > 0) { packet.progress -= increment; } } else { if (packet.progress < 1) { packet.progress += increment; } } let coords = getCubicBezierXY( // Refreshing coords packet.progress, path[0], // start path[1].bezier[0], // cp1 path[1].bezier[1], // cp2 path[1].bezier[2] // end ); packet.label.translate = { x: coords.x, y: coords.y, z: packet.height * 2.3 }; packet.translate = coords; return true; }; const emitPacket = ( state: State, link, name: string, speed_factor = 1, color = DARK_GREY, size = 8, reverse = false, transferredCallback ) => { const packet = network_packet.copy(); const label = createPacketLabel(state.illo); label.value = name; label.rotate.x = -TAU / 4; label.translate = { x: 0, y: 0, z: 0 }; packet.width = size; packet.height = size; packet.depth = size; packet.progress = reverse ? 1 : 0; packet.speed_factor = speed_factor; packet.link = link; packet.leftFace = color.alpha(0.5).string(); packet.rightFace = color.alpha(0.5).string(); packet.topFace = color.darken(0.1).alpha(0.5).string(); packet.bottomFace = color.darken(0.2).alpha(0.5).string(); packet.color = color.darken(0.2).alpha(0.5).string(); packet.reverse = reverse; packet.name = name; packet.label = label; packet.transferredCallback = transferredCallback; transferPacket(packet, 0.01); state.illo.addChild(packet); state.packets.push(packet); state.textElements.push(label); }; const link = new Zdog.Shape({ stroke: 2, color: DARK_GREY.string(), closed: false, }); const network_packet = new Zdog.Box({ width: 8, height: 8, depth: 8, stroke: 1, fill: true, }); const network_node = new Zdog.Box({ width: 40, height: 40, depth: 60, stroke: 1, fill: true, }); const animate = (state) => { state.illo.rotate.set(viewRotation); // viewRotation.add({ z: 0.00005 }); // illo.zoom += 0.0005; for (let i = 0; i < state.packets.length; i++) { const packet = state.packets[i]; if (transferPacket(packet, 0.01) == false) { state.illo.removeChild(packet); state.illo.removeChild(packet.label); state.packets.splice(i, 1); state.textElements.splice(state.textElements.indexOf(packet.label), 1); if (packet.transferredCallback) { packet.transferredCallback(); } } } state.illo.updateRenderGraph(); if (!state.stopAnimation) { requestAnimationFrame(animate.bind(this, state)); } }; function initZdog(element) { const illo = new Zdog.Illustration({ element, resize: true, dragRotate: true, }); new Zdog.Dragger({ startElement: illo.element, onDragStart: function () { dragStartRX = viewRotation.x; dragStartRZ = viewRotation.z; }, onDragMove: function (pointer, moveX, moveY) { const moveRX = (moveY / illo.width) * Zdog.TAU * -1; const moveRY = (moveX / illo.width) * Zdog.TAU * -1; viewRotation.x = dragStartRX; viewRotation.z = dragStartRZ + moveRY / 2; // viewRotation.y = dragStartRY + moveRY; }, }); return illo; } const visRender = (domElement, props: VNetVisualizeProps, vnetState: State) => { vnetState.illo = initZdog(domElement); for (const node of props.nodes) { addNode( vnetState, node.name, { x: node.x, y: node.y, z: node.z }, node.colour ); } for (const link of props.links) { linkNodes(vnetState, [ vnetState.networkNodes[link[0]], vnetState.networkNodes[link[1]], ]); } animate(vnetState); vnetState.illo.updateRenderGraph(); }; interface NodeProps { name: string; x: number; y: number; z: number; colour: string; } interface VNetVisualizeProps { nodes: Array<NodeProps>; links?: Array<any>; } export interface VNetInterface { emitPacket: CallableFunction; } // Internal state interface State { illo?: any; stopAnimation: boolean; networkNodes: Array<any>; packets: Array<any>; links: Array<any>; textElements: Array<any>; nodes: Array<any>; } const VNetVisualize: React.ForwardRefRenderFunction< VNetInterface, VNetVisualizeProps > = (props, ref) => { let currentPage = useSelector((state: any) => parseInt(state.navigation.lessonPage, 10) ); const canvasRef = useRef(null); const vnetState: React.MutableRefObject<State> = useRef({ illo: null, networkNodes: [], packets: [], links: [], textElements: [], nodes: [], stopAnimation: false, }); useImperativeHandle(ref, () => ({ getLink: (num) => vnetState.current.links[num], // Emits a new packet in the network visualisation. // Returns a promise that's resolved once the packet has been transferred. // TODO: change this to take an object/interface emitPacket: ( originLink, isReverseDirection: boolean, packetNum, speed, colour, size ) => { const promise = new Promise((resolve, _reject) => { emitPacket( vnetState.current, originLink, packetNum.toString(), speed || 2, colour || DARK_GREY, size || 8, isReverseDirection, resolve ); }); return promise; }, stopAnimation: () => { vnetState.current.stopAnimation = true; }, })); const resized = () => { // Reinitialize Zdog if the canvas element is resized. if (vnetState.current.illo) { vnetState.current.illo.updateRenderGraph(); } }; React.useEffect(() => { window.addEventListener("resize", resized); return () => window.removeEventListener("resize", resized); }); useEffect(() => { if (canvasRef.current && canvasRef.current.offsetParent != null) { // make sure the canvas element is visible before we start rendering it. visRender(canvasRef.current, props, vnetState.current); } }, [ currentPage, canvasRef, canvasRef.current && canvasRef.current.offsetParent != null, ]); return <canvas ref={canvasRef} id="zdog-canvas" className="vnet-vis" />; }; export default React.forwardRef(VNetVisualize);
the_stack
'use strict'; import { parseToMillisecond } from 'chord/base/common/time'; import { IListOption } from 'chord/music/api/listOption'; import { IAudio } from 'chord/music/api/audio'; import { IEpisode } from 'chord/sound/api/episode'; import { IPodcast } from 'chord/sound/api/podcast'; import { IRadio } from "chord/sound/api/radio"; import { getEpisodeId, getPodcastId, getRadioId, getRadioUrl, } from "chord/sound/common/origin"; import { getAbsolutUrl } from "chord/base/node/url"; import { makeLyric as _makeLyric } from 'chord/music/utils/lyric'; import { getDemoAudioUrl } from 'chord/sound/ximalaya/crypto'; const _origin = 'ximalaya'; const _getEpisodeId: (id: string) => string = getEpisodeId.bind(null, _origin); const _getPodcastId: (id: string) => string = getPodcastId.bind(null, _origin); const _getRadioId: (id: string) => string = getRadioId.bind(null, _origin); const _getRadioUrl: (id: string) => string = getRadioUrl.bind(null, _origin); const DOMAIN = 'https://www.ximalaya.com'; const IMG_DOMAIN = 'http://imagev2.xmcdn.com'; function _makeAudio(url: string): IAudio { return { url, kbps: 64, format: 'm4a', size: 1, }; } export function makeDemoAudio(info: any): IAudio { let url = getDemoAudioUrl(info); if (!url) return null; return _makeAudio(url); } export function makeAudio(url: any): IAudio { if (!url) return null; return _makeAudio(url); } export function makeEpisode(info: any): IEpisode { let episodeInfo = info['trackInfo'] || info; let podcastInfo = info['albumInfo'] || info; let radioInfo = info['userInfo'] || info; let episodeOriginalId = (episodeInfo['trackId'] || info['id']).toString(); let episodeName = episodeInfo['title'] || episodeInfo['trackName']; let url = DOMAIN + (episodeInfo['link'] || episodeInfo['trackUrl'] || episodeInfo['url']); let t = url.split('/').slice(-2)[0]; let podcastOriginalId = (podcastInfo['albumId'] || info['album_id'] || t).toString(); let podcastName = podcastInfo['albumId'] ? (podcastInfo['title'] || info['albumTitle']) : podcastInfo['albumName'] || info['album_title']; let podcastCoverUrl = podcastInfo['coverPath'] || podcastInfo['trackCoverPath'] || info['cover_path']; podcastCoverUrl = podcastCoverUrl ? getAbsolutUrl(podcastCoverUrl, IMG_DOMAIN) : null; let radioOriginalId = radioInfo['uid'] || radioInfo['anchorId'] || radioInfo['anchorUid']; radioOriginalId = radioOriginalId ? radioOriginalId.toString() : null; let radioName = radioInfo['nickname']; let radioCoverUrl = getAbsolutUrl(radioInfo['coverPath'] || info['cover'] || info['logoPic'], IMG_DOMAIN); let lyricUrl = episodeInfo['lyric']; let tags = info['tags'] ? info['tags'].split(',').map(name => ({ name, id: null })) : null; let duration = episodeInfo['duration'] ? episodeInfo['duration'] * 1000 : episodeInfo['durationAsString'] ? parseToMillisecond(episodeInfo['durationAsString']) : null; let audio = makeAudio(episodeInfo['src']); let audios = audio ? [audio] : []; if (info['play_path_64']) { audio = makeAudio(episodeInfo['play_path_64']); audio.kbps = 64; audios.push(audio); } if (info['play_path_32']) { audio = makeAudio(episodeInfo['play_path_32']); audio.kbps = 32; audios.push(audio); } let releaseDate = episodeInfo['lastUpdate'] ? Date.parse(episodeInfo['lastUpdate']) : info['updated_at'] ? info['updated_at'] : episodeInfo['updateTime'] || episodeInfo['createTime'] || episodeInfo['createDateFormat'] || info['createTimeAsString']; let episode: IEpisode = { episodeId: _getEpisodeId(episodeOriginalId), type: 'episode', origin: _origin, episodeOriginalId, url, episodeName, podcastId: _getPodcastId(podcastOriginalId), podcastOriginalId, podcastName, podcastCoverUrl, radioId: _getRadioId(radioOriginalId), radioOriginalId, radioName, radioCoverUrl, description: episodeInfo['richIntro'] || episodeInfo['intro'], composer: episodeInfo['compose'], tags, lyricUrl, track: episodeInfo['index'] ? episodeInfo['index'] - 1 : null, // millisecond duration, // millisecond releaseDate, playCountWeb: episodeInfo['playCount'] || info['count_play'] || null, playCount: 0, likeCount: info['count_like'], audios, }; return episode; } export function makeEpisodes(info: any): Array<IEpisode> { return (info || []).map(episodeInfo => makeEpisode(episodeInfo)); } export function makePodcast(info: any): IPodcast { let podcastInfo = info['mainInfo'] || info; let radioInfo = info['anchorInfo'] || info['anchor'] || info; let episodeListInfo = info['tracksInfo'] || info; let metas = podcastInfo['metas'] || info; let podcastOriginalId = (podcastInfo['albumId'] || info['albumId'] || info['id']).toString(); let podcastId = _getPodcastId(podcastOriginalId); let podcastName = podcastInfo['albumTitle'] || info['title']; let podcastCoverUrl = podcastInfo['cover'] || podcastInfo['coverPath'] || info['cover_path']; podcastCoverUrl = podcastCoverUrl ? getAbsolutUrl(podcastCoverUrl.split('!')[0], IMG_DOMAIN) : null; let radioOriginalId = (radioInfo['anchorId'] || radioInfo['anchorUid'] || radioInfo['uid']).toString(); let radioId = _getRadioId(radioOriginalId); let radioName = radioInfo['anchorName'] || radioInfo['anchorNickName'] || radioInfo['nickname']; let tags = info['tags'] ? info['tags'].split(',').map(name => ({ name, id: null })) : null; let category = metas[0] ? metas[0]['categoryName'] : null; let url = category ? (DOMAIN + '/' + category + '/' + podcastOriginalId) : info['albumUrl'] ? (DOMAIN + info['albumUrl']) : info['url'] ? (DOMAIN + info['url']) : info['link'] ? (DOMAIN + info['link']) : null; // let episodeList = episodeListInfo['tracks']; // 'tracks' can be number // let episodes = (episodeList && episodeList.length) ? (episodeList || []).map(j => { // let episode = makeEpisode(j); // episode = { // ...episode, // url: url + '/' + episode.episodeOriginalId, // podcastOriginalId, // podcastId, // podcastName, // podcastCoverUrl, // radioOriginalId, // radioId: radioId, // radioName: radioName, // }; // return episode; // }) : []; let podcast: IPodcast = { podcastId, type: 'podcast', origin: _origin, podcastOriginalId, url, podcastName, podcastCoverUrl, radioId, radioName, description: podcastInfo['richIntro'] || podcastInfo['description'] || info['intro'], tags, releaseDate: Date.parse(podcastInfo['updateDate']) || info['updated_at'] || 0, episodes: [], episodeCount: episodeListInfo['trackTotalCount'] || info['trackCount'] || info['tracks'], playCount: podcastInfo['playCount'] || info['play'], likeCount: null, }; return podcast; } export function makePodcasts(info: any): Array<IPodcast> { return (info || []).map(episodeInfo => makePodcast(episodeInfo)); } export function makeRadio(info: any): IRadio { let radioOriginalId = info['uid'].toString(); let radioCoverUrl = getAbsolutUrl(info['cover'] || info['logoPic'] || info['coverPath'], IMG_DOMAIN); let radioName = info['nickName'] || info['anchorNickName'] || info['nickname']; let followerCount = info['fansCount'] || info['followers_counts'] || info['followerCount']; let followingCount = info['followingCount'] || info['followings_counts']; let url = _getRadioUrl(radioOriginalId); let radio = { radioId: _getRadioId(radioOriginalId), type: 'radio', origin: _origin, radioOriginalId: radioOriginalId, url, radioName: radioName, radioCoverUrl, followerCount, followingCount, episodeCount: info['tracks_counts'] || info['trackCount'], podcastCount: info['album_counts'] || info['albumCount'], description: info['personalSignature'] || info['description'], }; return radio; } export function makeRadios(info: any): Array<IRadio> { return (info || []).map(radio => makeRadio(radio)); } export function makePodcastListOptions(info: any): Array<IListOption> { let options = []; for (let i of info) { for (let category of i.categories) { let option = { id: category.id, name: category.displayName, type: category.name, items: category.subcategories.map(subInfo => ({ id: subInfo.id, name: subInfo.displayValue, type: subInfo.code, items: [], info: { metaId: subInfo.metadataId, metaValue: subInfo.metadataValue, // this is category.id category: subInfo.categoryId, }, })), }; options.push(option); } } return options; } export function makePodcastOptionSubs(info: any): Array<IListOption> { let options = []; let list = [...info.currentSubcategory.metas, ...info.metadata]; for (let meta of list) { let option = { id: meta.id, name: meta.name, type: 'meta', items: meta.metaValues.map(val => ({ id: val.id, name: val.name, type: val.code, })), }; options.push(option); } return options; }
the_stack
import { Spreadsheet, locale, dialog, mouseDown, renderFilterCell, initiateFilterUI, FilterInfoArgs, getStartEvent, duplicateSheetOption } from '../index'; import { reapplyFilter, filterCellKeyDown, DialogBeforeOpenEventArgs } from '../index'; import { getFilteredColumn, cMenuBeforeOpen, filterByCellValue, clearFilter, getFilterRange, applySort, getCellPosition } from '../index'; import { filterRangeAlert, getFilteredCollection, beforeDelete, sheetsDestroyed, initiateFilter, duplicateSheetFilterHandler } from '../../workbook/common/event'; import { FilterCollectionModel, getRangeIndexes, getCellAddress, updateFilter, ColumnModel, beforeInsert } from '../../workbook/index'; import { getIndexesFromAddress, getSwapRange, getColumnHeaderText, CellModel, getDataRange, getSheetIndex } from '../../workbook/index'; import { getData, Workbook, getTypeFromFormat, getCell, getCellIndexes, getRangeAddress, getSheet, inRange } from '../../workbook/index'; import { SheetModel, sortImport, clear, getColIndex, SortCollectionModel, setRow, ExtendedRowModel, hideShow } from '../../workbook/index'; import { beginAction, FilterOptions, BeforeFilterEventArgs, FilterEventArgs, ClearOptions, getValueFromFormat } from '../../workbook/index'; import { isFilterHidden } from '../../workbook/index'; import { getComponent, EventHandler, isUndefined, isNullOrUndefined, Browser, KeyboardEventArgs, removeClass, detach } from '@syncfusion/ej2-base'; import { L10n } from '@syncfusion/ej2-base'; import { Dialog } from '../services'; import { IFilterArgs, PredicateModel, ExcelFilterBase, beforeFltrcMenuOpen, CheckBoxFilterBase, getUid } from '@syncfusion/ej2-grids'; import { filterCmenuSelect, filterCboxValue, filterDialogCreated, filterDialogClose, createCboxWithWrap } from '@syncfusion/ej2-grids'; import { parentsUntil } from '@syncfusion/ej2-grids'; import { Query, DataManager, Predicate, Deferred } from '@syncfusion/ej2-data'; import { SortOrder, MenuItemModel, NodeKeyPressEventArgs, NodeClickEventArgs, NodeCheckEventArgs } from '@syncfusion/ej2-navigations'; import { TreeView } from '@syncfusion/ej2-navigations'; import { BeforeOpenEventArgs } from '@syncfusion/ej2-popups'; import { completeAction, contentLoaded, beforeCheckboxRender, FilterCheckboxArgs, refreshCheckbox } from '../../spreadsheet/index'; /** * `Filter` module is used to handle the filter action in Spreadsheet. */ export class Filter { private parent: Spreadsheet; private filterRange: Map<number, { useFilterRange: boolean, range: number[] }>; private filterCollection: Map<number, PredicateModel[]>; private filterBtn: HTMLElement; /** * Constructor for filter module. * * @param {Spreadsheet} parent - Specifies the Spreadsheet. */ constructor(parent: Spreadsheet) { this.parent = parent; this.filterCollection = new Map(); this.filterRange = new Map(); this.filterBtn = parent.createElement('div', { className: 'e-filter-btn e-control e-btn e-lib e-filter-iconbtn e-icon-btn' }); this.filterBtn.appendChild(parent.createElement('span', { className: 'e-btn-icon e-icons e-filter-icon' })); this.addEventListener(); } /** * To destroy the filter module. * * @returns {void} - To destroy the filter module. */ protected destroy(): void { this.removeEventListener(); this.filterRange = null; this.filterCollection = null; this.parent = null; } private addEventListener(): void { this.parent.on(filterRangeAlert, this.filterRangeAlertHandler, this); this.parent.on(initiateFilterUI, this.initiateFilterUIHandler, this); this.parent.on(mouseDown, this.filterMouseDownHandler, this); this.parent.on(renderFilterCell, this.renderFilterCellHandler, this); this.parent.on(beforeFltrcMenuOpen, this.beforeFilterMenuOpenHandler, this); this.parent.on(filterCmenuSelect, this.closeDialog, this); this.parent.on(reapplyFilter, this.reapplyFilterHandler, this); this.parent.on(filterByCellValue, this.filterByCellValueHandler, this); this.parent.on(clearFilter, this.clearFilterHandler, this); this.parent.on(getFilteredColumn, this.getFilteredColumnHandler, this); this.parent.on(cMenuBeforeOpen, this.cMenuBeforeOpenHandler, this); this.parent.on(filterCboxValue, this.filterCboxValueHandler, this); this.parent.on(getFilterRange, this.getFilterRangeHandler, this); this.parent.on(filterCellKeyDown, this.filterCellKeyDownHandler, this); this.parent.on(getFilteredCollection, this.getFilteredCollection, this); this.parent.on(contentLoaded, this.updateFilter, this); this.parent.on(updateFilter, this.updateFilter, this); this.parent.on(beforeInsert, this.beforeInsertHandler, this); this.parent.on(beforeDelete, this.beforeDeleteHandler, this); this.parent.on(sheetsDestroyed, this.deleteSheetHandler, this); this.parent.on(clear, this.clearHandler, this); this.parent.on(filterDialogCreated, this.filterDialogCreatedHandler, this); this.parent.on(filterDialogClose, this.removeFilterClass, this); this.parent.on(duplicateSheetFilterHandler, this.duplicateSheetFilterHandler, this); } private removeEventListener(): void { if (!this.parent.isDestroyed) { this.parent.off(filterRangeAlert, this.filterRangeAlertHandler); this.parent.off(initiateFilterUI, this.initiateFilterUIHandler); this.parent.off(mouseDown, this.filterMouseDownHandler); this.parent.off(renderFilterCell, this.renderFilterCellHandler); this.parent.off(beforeFltrcMenuOpen, this.beforeFilterMenuOpenHandler); this.parent.off(filterCmenuSelect, this.closeDialog); this.parent.off(reapplyFilter, this.reapplyFilterHandler); this.parent.off(filterByCellValue, this.filterByCellValueHandler); this.parent.off(clearFilter, this.clearFilterHandler); this.parent.off(getFilteredColumn, this.getFilteredColumnHandler); this.parent.off(cMenuBeforeOpen, this.cMenuBeforeOpenHandler); this.parent.on(filterCboxValue, this.filterCboxValueHandler); this.parent.off(getFilterRange, this.getFilterRangeHandler); this.parent.off(filterCellKeyDown, this.filterCellKeyDownHandler); this.parent.off(getFilteredCollection, this.getFilteredCollection); this.parent.off(contentLoaded, this.updateFilter); this.parent.off(updateFilter, this.updateFilter); this.parent.off(beforeInsert, this.beforeInsertHandler); this.parent.off(beforeDelete, this.beforeDeleteHandler); this.parent.off(sheetsDestroyed, this.deleteSheetHandler); this.parent.off(clear, this.clearHandler); this.parent.off(filterDialogCreated, this.filterDialogCreatedHandler); this.parent.off(filterDialogClose, this.removeFilterClass); this.parent.off(duplicateSheetFilterHandler, this.duplicateSheetFilterHandler); } } /** * Gets the module name. * * @returns {string} - Gets the module name. */ protected getModuleName(): string { return 'filter'; } /** * Validates the range and returns false when invalid. * * @param {SheetModel} sheet - Specify the sheet. * @param {string} range - Specify the range. * @returns {void} - Validates the range and returns false when invalid. */ private isInValidFilterRange(sheet: SheetModel, range?: string): boolean { const selectedRange: number[] = range ? getSwapRange(getIndexesFromAddress(range)) : getSwapRange(getIndexesFromAddress(sheet.selectedRange)); return selectedRange[0] > sheet.usedRange.rowIndex || selectedRange[1] > sheet.usedRange.colIndex; } /** * Shows the range error alert dialog. * * @param {any} args - Specifies the args * @param {string} args.error - range error string. * @returns {void} - Shows the range error alert dialog. */ private filterRangeAlertHandler(args: { error: string }): void { const dialogInst: Dialog = (this.parent.serviceLocator.getService(dialog) as Dialog); dialogInst.show({ content: args.error, isModal: true, height: 180, width: 400, showCloseIcon: true, beforeOpen: (args: BeforeOpenEventArgs): void => { const dlgArgs: DialogBeforeOpenEventArgs = { dialogName: 'FilterRangeDialog', element: args.element, target: args.target, cancel: args.cancel }; this.parent.trigger('dialogBeforeOpen', dlgArgs); if (dlgArgs.cancel) { args.cancel = true; } } }); this.parent.hideSpinner(); } /** * Triggers before filter context menu opened and used to add sorting items. * * @param {any} args - Specifies the args * @param {HTMLElement} args.element - Specify the element * @returns {void} - Triggers before filter context menu opened and used to add sorting items. */ private beforeFilterMenuOpenHandler(args: { element: HTMLElement }): void { const l10n: L10n = this.parent.serviceLocator.getService(locale); args.element.classList.add('e-spreadsheet-contextmenu'); // to show sort icons const ul: Element = args.element.querySelector('ul'); this.addMenuItem(ul, l10n.getConstant('SortDescending'), 'e-filter-sortdesc', 'e-sort-desc'); this.addMenuItem(ul, l10n.getConstant('SortAscending'), 'e-filter-sortasc', 'e-sort-asc'); args.element.appendChild(ul); } /** * Creates new menu item element * * @param {Element} ul - Specify the element. * @param {string} text - Specify the text. * @param {string} className - Specify the className * @param {string} iconCss - Specify the iconCss * @returns {void} - Creates new menu item element */ private addMenuItem(ul: Element, text: string, className?: string, iconCss?: string): void { const li: Element = this.parent.createElement('li', { className: className + ' e-menu-item' }); li.innerHTML = text; li.insertBefore(this.parent.createElement('span', { className: 'e-menu-icon e-icons ' + iconCss }), li.firstChild); ul.insertBefore(li, ul.firstChild); } /** * Initiates the filter UI for the selected range. * * @param {any} args - Specifies the args * @param {PredicateModel[]} args.predicates - Specify the predicates. * @param {number} args.range - Specify the range. * @param {Promise<FilterEventArgs>} args.promise - Spefify the promise. * @param {number} args.sIdx - Specify the sIdx * @param {boolean} args.isCut - Specify the bool value * @param {boolean} args.isUndoRedo - Specify the bool value * @param {boolean} args.isInternal - Spefify the isInternal. * @returns {void} - Initiates the filter UI for the selected range. */ private initiateFilterUIHandler( args: { predicates?: PredicateModel[], range?: string, promise?: Promise<FilterEventArgs>, sIdx?: number, isCut?: boolean, isInternal?: boolean, useFilterRange?: boolean }): void { const predicates: PredicateModel[] = args ? args.predicates : null; let sheetIdx: number = args.sIdx; if (!sheetIdx && sheetIdx !== 0) { sheetIdx = this.parent.activeSheetIndex; } let deferred: Deferred; if (args.promise) { deferred = new Deferred(); args.promise = deferred.promise; } const resolveFn: Function = (): void => { if (deferred) { deferred.resolve(); } }; const isInternal: boolean = args.isInternal || args.isCut; if (this.filterRange.size > 0 && this.filterRange.has(sheetIdx) && !this.parent.isOpen && !predicates) { //disable filter this.removeFilter(sheetIdx, isInternal, false); resolveFn(); return; } const sheet: SheetModel = getSheet(this.parent as Workbook, sheetIdx); if (this.isInValidFilterRange(sheet, args.range)) { const l10n: L10n = this.parent.serviceLocator.getService(locale); this.filterRangeAlertHandler({ error: l10n.getConstant('FilterOutOfRangeError') }); resolveFn(); return; } let selectedRange: string = args.range || sheet.selectedRange; let eventArgs: { range: string, filterOptions?: FilterOptions, predicates?: PredicateModel[], previousPredicates?: PredicateModel[], cancel: boolean, useFilterRange?: boolean, sheetIndex: number }; let actionArgs: { [key: string]: Object }; if (!isInternal) { eventArgs = { range: selectedRange, sheetIndex: sheetIdx, cancel: false }; if (args.predicates) { eventArgs.predicates = args.predicates; eventArgs.previousPredicates = this.filterCollection.get(sheetIdx) && [].slice.call(this.filterCollection.get(sheetIdx)); } else { eventArgs.filterOptions = { predicates: args.predicates as Predicate[] }; } eventArgs.useFilterRange = false; actionArgs = { action: 'filter', eventArgs: eventArgs }; this.parent.notify(beginAction, actionArgs); if (eventArgs.cancel) { resolveFn(); return; } delete eventArgs.cancel; args.useFilterRange = eventArgs.useFilterRange; } if (!args.range && (isInternal || selectedRange === eventArgs.range)) { let rangeIdx: number[] = getRangeIndexes(selectedRange); if (rangeIdx[0] === rangeIdx[2] && rangeIdx[1] === rangeIdx[3]) { rangeIdx = getDataRange(rangeIdx[0], rangeIdx[1], sheet); selectedRange = getRangeAddress(rangeIdx); if (!isInternal) { eventArgs.range = selectedRange; } } } else if (!isInternal) { selectedRange = eventArgs.range; } if (predicates) { if (predicates.length) { const filterRange: { useFilterRange: boolean, range: number[] } = this.filterRange.get(sheetIdx); if (filterRange) { args.useFilterRange = filterRange.useFilterRange; } this.processRange(sheet, sheetIdx, selectedRange, true, args.useFilterRange); const range: number[] = this.filterRange.get(sheetIdx).range.slice(); range[0] = range[0] + 1; // to skip first row. if (!args.useFilterRange) { range[2] = sheet.usedRange.rowIndex; //filter range should be till used range. } range[1] = range[3] = getColIndex(predicates[0].field); const addr: string = `${sheet.name}!${this.getPredicateRange(range, predicates.slice(1, predicates.length))}`; const fullAddr: string = getRangeAddress(range); getData( this.parent, addr, true, true, null, true, null, null, false, fullAddr).then( (jsonData: { [key: string]: CellModel }[]) => { this.filterSuccessHandler( new DataManager(jsonData), { action: 'filtering', filterCollection: predicates, field: predicates[0].field, sIdx: args.sIdx, isInternal: isInternal, prevPredicates: eventArgs && eventArgs.previousPredicates }); resolveFn(); }); return; } else { this.clearFilterHandler({ sheetIndex: sheetIdx }); resolveFn(); } } else { this.processRange(sheet, sheetIdx, selectedRange, false, args.useFilterRange); resolveFn(); } if (!isInternal) { this.parent.notify(completeAction, actionArgs); } } /** * Processes the range if no filter applied. * * @param {SheetModel} sheet - Specify the sheet. * @param {number} sheetIdx - Specify the sheet index. * @param {string} filterRange - Specify the filterRange. * @param {boolean} preventRefresh - To prevent refreshing the filter buttons. * @param {boolean} useFilterRange - Specifies whether to consider filtering range or used range during filering. * @returns {void} - Processes the range if no filter applied. */ private processRange( sheet: SheetModel, sheetIdx: number, filterRange?: string, preventRefresh?: boolean, useFilterRange?: boolean): void { const range: number[] = getSwapRange(getIndexesFromAddress(filterRange || sheet.selectedRange)); if (range[0] === range[2] && range[1] === range[3]) { //if selected range is a single cell range[0] = 0; range[1] = 0; range[2] = sheet.usedRange.rowIndex; range[3] = sheet.usedRange.colIndex; } else if (range[3] > sheet.usedRange.colIndex) { range[3] = sheet.usedRange.colIndex; } this.filterRange.set(sheetIdx, { useFilterRange: useFilterRange, range: range }); this.filterCollection.set(sheetIdx, []); if (!preventRefresh) { this.refreshFilterRange(range, false, sheetIdx); } } /** * Removes all the filter related collections for the active sheet. * * @param {number} sheetIdx - Specify the sheet index. * @param {boolean} isCut - Specify the bool value. * @param {boolean} preventRefresh - Specify the preventRefresh. * @param {boolean} isUndoRedo - Specify the isUndoRedo. * @returns {void} - Removes all the filter related collections for the active sheet. */ private removeFilter(sheetIdx: number, isCut?: boolean, preventRefresh?: boolean): void { const range: number[] = this.filterRange.get(sheetIdx).range.slice(); const rangeAddr: string = getRangeAddress(range); let args: { [key: string]: Object }; if (!isCut) { args = { action: 'filter', eventArgs: { range: rangeAddr, sheetIndex: sheetIdx, cancel: false } }; this.parent.notify(beginAction, args); if ((args.eventArgs as { cancel: boolean }).cancel) { return; } delete (args.eventArgs as { cancel: boolean }).cancel; } if (this.filterCollection.get(sheetIdx).length || preventRefresh) { this.clearFilterHandler({ preventRefresh: preventRefresh, sheetIndex: sheetIdx }); } this.filterRange.delete(sheetIdx); this.filterCollection.delete(sheetIdx); this.refreshFilterRange(range, true, sheetIdx); if (this.parent.filterCollection) { let count: number = 0; let filterColl: FilterCollectionModel; for (let i: number = 0, len: number = this.parent.filterCollection.length; i < len; i++) { filterColl = this.parent.filterCollection[count]; if (filterColl.sheetIndex === sheetIdx && filterColl.filterRange === rangeAddr) { this.parent.filterCollection.splice(count, 1); } else { count++; } } } if (!isCut) { this.parent.notify(completeAction, args); } } /** * Handles filtering cell value based on context menu. * * @returns {void} - Handles filtering cell value based on context menu. */ private filterByCellValueHandler(): void { const sheetIdx: number = this.parent.activeSheetIndex; const sheet: SheetModel = this.parent.getActiveSheet(); if (this.isInValidFilterRange(sheet)) { const l10n: L10n = this.parent.serviceLocator.getService(locale); this.filterRangeAlertHandler({ error: l10n.getConstant('FilterOutOfRangeError') }); return; } const cell: number[] = getRangeIndexes(sheet.activeCell); if (!this.isFilterRange(sheetIdx, cell[0], cell[1])) { this.processRange(sheet, sheetIdx); } const range: number[] = this.filterRange.get(sheetIdx).range.slice(); range[0] = range[0] + 1; // to skip first row. range[2] = sheet.usedRange.rowIndex; //filter range should be till used range. range[1] = range[3] = cell[1]; const field: string = getColumnHeaderText(cell[1] + 1); const type: string = this.getColumnType(sheet, cell[1], cell).type; const predicates: PredicateModel[] = [{ field: field, operator: 'equal', matchCase: false, type: type, value: getValueFromFormat(this.parent, cell[0], cell[1], getSheetIndex(this.parent, sheet.name), sheet) }]; const addr: string = `${sheet.name}!${this.getPredicateRange(range, this.filterCollection.get(sheetIdx))}`; const fullAddr: string = getRangeAddress(range); getData(this.parent, addr, true, true, null, true, null, null, false, fullAddr).then((jsonData: { [key: string]: CellModel }[]) => { this.filterSuccessHandler( new DataManager(jsonData), { action: 'filtering', filterCollection: predicates, field: field, isFilterByValue: true }); }); } /** * Creates filter buttons and renders the filter applied cells. * * @param { any} args - Specifies the args * @param { HTMLElement} args.td - specify the element * @param { number} args.rowIndex - specify the rowIndex * @param { number} args.colIndex - specify the colIndex * @param { number} args.sIdx - specify the sIdx * @returns {void} - Creates filter buttons and renders the filter applied cells. */ private renderFilterCellHandler(args: { td: HTMLElement, rowIndex: number, colIndex: number, sIdx?: number }): void { const sheetIdx: number = !isNullOrUndefined(args.sIdx) ? args.sIdx : this.parent.activeSheetIndex; if (sheetIdx === this.parent.activeSheetIndex && this.isFilterCell(sheetIdx, args.rowIndex, args.colIndex)) { if (!args.td) { return; } let filterButton: HTMLElement = args.td.querySelector('.e-filter-icon'); if (filterButton) { filterButton.className = 'e-btn-icon e-icons e-filter-icon' + this.getFilterSortClassName(args.colIndex, sheetIdx); } else { filterButton = this.filterBtn.cloneNode(true) as HTMLElement; filterButton.firstElementChild.className += this.getFilterSortClassName(args.colIndex, sheetIdx); args.td.insertBefore(filterButton, args.td.firstChild); } } } private getFilterSortClassName(colIdx: number, sheetIdx: number): string { const field: string = getColumnHeaderText(colIdx + 1); let className: string = ''; const predicates: PredicateModel[] = this.filterCollection.get(sheetIdx); const sortCollection: SortCollectionModel[] = this.parent.sortCollection; for (let i: number = 0; i < predicates.length; i++) { if (predicates[i].field === field) { className = ' e-filtered'; break; } } if (sortCollection) { for (let i: number = 0; i < sortCollection.length; i++) { if (sortCollection[i].sheetIndex === sheetIdx && sortCollection[i].columnIndex === colIdx) { className += sortCollection[i].order === 'Ascending' ? ' e-sortasc-filter' : ' e-sortdesc-filter'; break; } } } return className; } /** * Refreshes the filter header range. * * @param {number[]} filterRange - Specify the filterRange. * @param {boolean} remove - Specify the bool value * @param {number} sIdx - Specify the index. * @returns {void} - Refreshes the filter header range. */ private refreshFilterRange(filterRange?: number[], remove?: boolean, sIdx?: number): void { let sheetIdx: number = sIdx; if (!sheetIdx && sheetIdx !== 0) { sheetIdx = this.parent.activeSheetIndex; } if (!filterRange && !this.filterRange.get(sheetIdx)) { filterRange = [0, 0, 0, 0]; } const range: number[] = filterRange || this.filterRange.get(sheetIdx).range.slice(); for (let index: number = range[1]; index <= range[3]; index++) { const cell: HTMLElement = this.parent.getCell(range[0], index); if (remove) { if (cell && cell.hasChildNodes()) { const element: Element = cell.querySelector('.e-filter-btn'); if (element) { element.parentElement.removeChild(element); } } } else { this.renderFilterCellHandler({ td: cell, rowIndex: range[0], colIndex: index, sIdx: sheetIdx }); } } if (this.parent.sortCollection) { this.parent.notify(sortImport, null); } } /** * Checks whether the provided cell is a filter cell. * * @param {number} sheetIdx - Specify the sheet index. * @param {number} rowIndex - Specify the row index * @param {number} colIndex - Specify the col index. * @returns {boolean} - Checks whether the provided cell is a filter cell. */ private isFilterCell(sheetIdx: number, rowIndex: number, colIndex: number): boolean { const range: number[] = this.filterRange.get(sheetIdx) && this.filterRange.get(sheetIdx).range; return (range && range[0] === rowIndex && range[1] <= colIndex && range[3] >= colIndex); } /** * Checks whether the provided cell is in a filter range * * @param {number} sheetIdx - Specify the sheet index. * @param {number} rowIndex - Specify the row index * @param {number} colIndex - Specify the col index. * @returns {boolean} - Checks whether the provided cell is in a filter range */ private isFilterRange(sheetIdx: number, rowIndex: number, colIndex: number): boolean { const range: number[] = this.filterRange.get(sheetIdx) && this.filterRange.get(sheetIdx).range; return (range && range[0] <= rowIndex && range[2] >= rowIndex && range[1] <= colIndex && range[3] >= colIndex); } /** * Gets the filter information from active cell * * @param {any} args - Specifies the args * @param {string} args.field - Specify the field * @param {string} args.clearFilterText - Specify the clearFilterText * @param {boolean} args.isFiltered - Specify the isFiltered * @param {boolean} args.isClearAll - Specify the isClearAll * @returns {void} - Triggers before context menu created to enable or disable items. */ private getFilteredColumnHandler(args: { field?: string, clearFilterText?: string, isFiltered?: boolean, isClearAll?: boolean, sheetIndex?: number }): void { const sheetIdx: number = isUndefined(args.sheetIndex) ? this.parent.activeSheetIndex : args.sheetIndex; const l10n: L10n = this.parent.serviceLocator.getService(locale); args.clearFilterText = l10n.getConstant('ClearFilter'); if (this.filterRange.has(sheetIdx)) { const filterCollection: PredicateModel[] = this.filterCollection.get(sheetIdx); if (args.isClearAll) { args.isFiltered = filterCollection && filterCollection.length > 0; return; } const range: number[] = this.filterRange.get(sheetIdx).range.slice(); const sheet: SheetModel = getSheet(this.parent, sheetIdx); const cell: number[] = getCellIndexes(sheet.activeCell); if (this.isFilterRange(sheetIdx, cell[0], cell[1])) { args.field = getColumnHeaderText(cell[1] + 1); const headerCell: CellModel = getCell(range[0], cell[1], sheet); const cellValue: string = this.parent.getDisplayText(headerCell); args.clearFilterText = l10n.getConstant('ClearFilterFrom') + '\"' + (cellValue ? cellValue.toString() : 'Column ' + args.field) + '\"'; filterCollection.some((value: PredicateModel) => { args.isFiltered = value.field === args.field; return args.isFiltered; }); } } } /** * Triggers before context menu created to enable or disable items. * * @param {any} e - Specifies the args * @param {HTMLElement} e.element - Specify the element * @param {MenuItemModel[]} e.items - Specify the items * @param {MenuItemModel} e.parentItem - Specify the parentItem * @param {string} e.target - Specify the target * @returns {void} - Triggers before context menu created to enable or disable items. */ private cMenuBeforeOpenHandler(e: { element: HTMLElement, items: MenuItemModel[], parentItem: MenuItemModel, target: string }): void { const id: string = this.parent.element.id + '_cmenu'; if (e.parentItem && e.parentItem.id === id + '_filter' && e.target === '') { const args: { [key: string]: boolean } = { isFiltered: false }; this.getFilteredColumnHandler(args); this.parent.enableContextMenuItems([id + '_clearfilter', id + '_reapplyfilter'], !!args.isFiltered, true); } } /** * Closes the filter popup. * * @returns {void} - Closes the filter popup. */ private closeDialog(): void { const filterPopup: HTMLElement = document.querySelector('.e-filter-popup'); if (filterPopup && filterPopup.id.includes(this.parent.element.id)) { const excelFilter: Dialog = getComponent(filterPopup, 'dialog'); EventHandler.remove(filterPopup, getStartEvent(), this.filterMouseDownHandler); if (excelFilter) { excelFilter.hide(); } this.parent.notify(filterDialogClose, null); } } private removeFilterClass(): void { if (this.parent.element.style.position === 'relative') { this.parent.element.style.position = ''; } if (this.parent.element.classList.contains('e-filter-open')) { this.parent.element.classList.remove('e-filter-open'); } } /** * Returns true if the filter popup is opened. * * @returns {boolean} - Returns true if the filter popup is opened. */ private isPopupOpened(): boolean { const filterPopup: HTMLElement = document.getElementsByClassName('e-filter-popup')[0] as HTMLElement; return filterPopup && filterPopup.id.includes(this.parent.element.id) && filterPopup.style.display !== 'none'; } private filterCellKeyDownHandler(args: { isFilterCell: boolean, closePopup?: boolean }): void { const sheet: SheetModel = this.parent.getActiveSheet(); const indexes: number[] = getCellIndexes(sheet.activeCell); if (this.isFilterCell(this.parent.activeSheetIndex, indexes[0], indexes[1])) { if (args.closePopup) { this.closeDialog(); } else { args.isFilterCell = true; if (!this.isPopupOpened()) { const target: HTMLElement = this.parent.getCell(indexes[0], indexes[1]); if (target) { this.openDialog(target); } } } } } private filterMouseDownHandler(e: MouseEvent & TouchEvent): void { if ((Browser.isDevice && e.type === 'mousedown') || this.parent.getActiveSheet().isProtected) { return; } const target: HTMLElement = e.target as HTMLElement; if (target.classList.contains('e-filter-icon') || target.classList.contains('e-filter-btn')) { if (this.isPopupOpened()) { this.closeDialog(); } this.openDialog(parentsUntil(target, 'e-cell') as HTMLElement); } else if (this.isPopupOpened()) { const offsetEle: Element = target.offsetParent; if (!target.classList.contains('e-searchinput') && !target.classList.contains('e-searchclear') && (offsetEle && !offsetEle.classList.contains('e-filter-popup') && !offsetEle.classList.contains('e-text-content') && !offsetEle.classList.contains('e-checkboxtree') && !offsetEle.classList.contains('e-checkbox-wrapper'))) { this.closeDialog(); } else { this.selectSortItemHandler(target); } } } private initTreeView(args: FilterCheckboxArgs, excelFilter: ExcelFilterBase): void { let checkedNodes: string[] = []; const allNodes: string[] = []; const idColl: { [key: string]: boolean } = {}; let groupedYears: { [key: string]: Object }[] = []; let groupedMonths: { [key: string]: Object }[] = []; let groupedData: { [key: string]: Object }[] = []; let otherData: { [key: string]: Object }[] = []; let value: string; let month: string; let day: number; let date: Date; let mId: string; let dId: string; let monthNum: number; const months: string[] = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December']; let grpObj: { [key: string]: Object }; let indeterminate: boolean = false; const sheet: SheetModel = this.parent.getActiveSheet(); const addNodes: (data: { [key: string]: Object }) => void = (data: { [key: string]: Object }): void => { idColl[dId] = true; if (isFilterHidden(sheet, Number(data['__rowIndex']) - 1)) { indeterminate = true; } else { checkedNodes.push(dId); } allNodes.push(dId); }; args.dataSource.forEach((data: { [key: string]: Object }): void => { date = data[args.column.field] as Date; if (typeof date === 'object' && !!Date.parse(date.toString())) { value = date.getFullYear().toString(); if (!idColl[value]) { grpObj = { __rowIndex: value, hasChild: true }; grpObj[args.column.field] = value; groupedYears.push(grpObj); idColl[value] = true; } monthNum = date.getMonth(); month = months[monthNum]; mId = value + ' ' + month; if (!idColl[mId]) { grpObj = { __rowIndex: mId, pId: value, hasChild: true, month: monthNum }; grpObj[args.column.field] = month; groupedMonths.push(grpObj); idColl[mId] = true; } day = date.getDate(); dId = mId + ' ' + day.toString(); if (!idColl[dId]) { grpObj = { __rowIndex: dId, pId: mId }; grpObj[args.column.field] = day; groupedData.push(grpObj); addNodes(data); } } else { if (!data[args.column.field] && data[args.column.field] !== 0) { dId = 'blanks'; value = this.parent.serviceLocator.getService<L10n>(locale).getConstant('Blanks'); } else { dId = 'text ' + data[args.column.field].toString().toLowerCase(); value = <string>data[args.column.field]; } if (!idColl[dId]) { grpObj = { __rowIndex: dId }; grpObj[args.column.field] = value; otherData.push(grpObj); addNodes(data); } } }); groupedYears = new DataManager( groupedYears).executeLocal(new Query().sortBy(args.column.field, 'decending')) as { [key: string]: Object }[]; groupedMonths = new DataManager( groupedMonths).executeLocal(new Query().sortBy('month', 'ascending')) as { [key: string]: Object }[]; groupedData = new DataManager( groupedData).executeLocal(new Query().sortBy(args.column.field, 'ascending')) as { [key: string]: Object }[]; groupedData = groupedYears.concat(groupedMonths.concat(groupedData)); if (otherData.length) { otherData = new DataManager( otherData).executeLocal(new Query().sortBy(args.column.field, 'ascending')) as { [key: string]: Object }[]; groupedData = groupedData.concat(otherData); } const nodeClick: Function = (args: NodeKeyPressEventArgs | NodeClickEventArgs ): void => { let checkedNode: HTMLLIElement[] = [args.node]; if ((args.event.target as Element).classList.contains('e-fullrow') || (args.event as KeyboardEventArgs).key == 'Enter') { let getNodeDetails: { [key: string]: Object } = treeViewObj.getNode(args.node); if (getNodeDetails.isChecked == 'true') { treeViewObj.uncheckAll(checkedNode); } else { treeViewObj.checkAll(checkedNode); } } } const selectAllClick: Function = (): void => { cBox.indeterminate = false; if (cBoxFrame.classList.contains('e-check')) { treeViewObj.uncheckAll(); cBoxFrame.classList.add('e-uncheck'); cBox.checked = false; } else { treeViewObj.checkAll(); cBoxFrame.classList.add('e-check'); cBox.checked = true; } }; const updateState: Function = (): void => { removeClass([cBoxFrame], ['e-check', 'e-stop', 'e-uncheck']); if ((args.btnObj.element as HTMLButtonElement).disabled) { (args.btnObj.element as HTMLButtonElement).disabled = false; } if (indeterminate) { if (treeViewObj.checkedNodes.length) { cBoxFrame.classList.add('e-stop'); } else { cBoxFrame.classList.add('e-uncheck'); (args.btnObj.element as HTMLButtonElement).disabled = true; } } else { cBoxFrame.classList.add('e-check'); } cBox.indeterminate = indeterminate; cBox.checked = !indeterminate; } const selectAllObj: { [key: string]: Object } = {}; selectAllObj[args.column.field] = this.parent.serviceLocator.getService<L10n>(locale).getConstant('SelectAll'); const selectAll: Element = createCboxWithWrap( getUid('cbox'), (excelFilter as any).createCheckbox(selectAllObj[args.column.field], false, selectAllObj), 'e-ftrchk'); selectAll.classList.add('e-spreadsheet-ftrchk') const cBoxFrame: Element = selectAll.querySelector('.e-frame'); cBoxFrame.classList.add('e-selectall'); selectAll.addEventListener('click', selectAllClick.bind(this)); args.element.appendChild(selectAll); const cBox: HTMLInputElement = selectAll.querySelector('.e-chk-hidden') as HTMLInputElement; const treeViewEle = this.parent.createElement('div'); const treeViewObj: TreeView = new TreeView({ fields: { dataSource: groupedData, id: '__rowIndex', parentID: 'pId', text: args.column.field, hasChildren: 'hasChild' }, enableRtl: this.parent.enableRtl, showCheckBox: true, cssClass: 'e-checkboxtree', checkedNodes: checkedNodes, nodeClicked: nodeClick.bind(this), keyPress: nodeClick.bind(this), nodeChecked: (args: NodeCheckEventArgs): void => { if (args.action !== 'indeterminate') { indeterminate = treeViewObj.checkedNodes.length !== (treeViewObj.fields.dataSource as Object[]).length; updateState(); } } }); treeViewObj.createElement = this.parent.createElement; treeViewObj.appendTo(treeViewEle); args.element.appendChild(treeViewEle); checkedNodes = treeViewObj.checkedNodes; updateState(); const applyBtnClickHandler: Function = (): void => { if (treeViewObj.checkedNodes.length === groupedData.length) { this.filterSuccessHandler(new DataManager(args.dataSource), { action: 'clear-filter', field: args.column.field }); } else { this.generatePredicate( treeViewObj.checkedNodes, args.type, args.column.field, excelFilter, allNodes, treeViewObj.checkedNodes.length > groupedData.length / 2); } }; args.btnObj.element.addEventListener('click', applyBtnClickHandler.bind(this)); const refreshCheckboxes: Function = this.refreshCheckbox.bind(this, groupedData, treeViewObj, checkedNodes); const filterDlgCloseHandler: Function = (): void => { this.parent.off(refreshCheckbox, refreshCheckboxes); this.parent.off(filterDialogClose, filterDlgCloseHandler); }; this.parent.on(filterDialogClose, filterDlgCloseHandler, this); this.parent.on(refreshCheckbox, refreshCheckboxes, this); } private generatePredicate( checkedNodes: string[], type: string, field: string, excelFilter: ExcelFilterBase, allNodes: string[], isNotEqual: boolean): void { const predicates: PredicateModel[] = []; let predicate: PredicateModel; const months: { [key: string]: number } = { 'January': 0, 'February': 1, 'March': 2, 'April': 3, 'May': 4, 'June': 5, 'July': 6, 'August': 7, 'September': 8, 'October': 9, 'November': 10, 'December': 11 }; let valArr: string[]; let date: Date; let val: string | number; let otherType: string; const updateOtherPredicate: Function = (): void => { if (valArr[0] === 'blanks') { predicates.push(Object.assign({ value: '', type: type }, predicate)); } else if (valArr[0] === 'text') { valArr.splice(0, 1) val = valArr.join(' '); if (isNaN(Number(val))) { otherType = 'string'; } else { val = Number(val); otherType = 'number'; } predicates.push(Object.assign({ value: val, type: otherType }, predicate)); } }; const setDate: () => void = (): void => { date = new Date(Number(valArr[0]), months[valArr[1]], Number(valArr[2])); if (date.getDay()) { predicates.push(Object.assign({ value: date, type: type }, predicate)); } else { updateOtherPredicate(); } }; if (isNotEqual) { predicate = { field: field, ignoreAccent: false, matchCase: false, predicate: 'and', operator: 'notequal' }; for (let i: number = 0, len: number = allNodes.length; i < len; i++) { if (checkedNodes.indexOf(allNodes[i]) === -1) { valArr = allNodes[i].split(' '); setDate(); } } } else { predicate = { field: field, ignoreAccent: false, matchCase: false, predicate: 'or', operator: 'equal' }; for (let i: number = 0, len: number = checkedNodes.length; i < len; i++) { valArr = checkedNodes[i].split(' '); if (valArr.length === 3) { setDate(); } else { updateOtherPredicate(); } } } excelFilter.initiateFilter(predicates); } private refreshCheckbox( groupedData: { [key: string]: Object }[], treeViewObj: TreeView, checkedNodes: string[], args: { event: KeyboardEvent }): void { let searchValue: string; if (args.event.type === 'keyup') { searchValue = (args.event.target as HTMLInputElement).value; } else if ((args.event.target as Element).classList.contains('e-search-icon')) { return; } let filteredList: Object[]; const changeData: Function = (): void => { if (filteredList.length && !(treeViewObj.fields.dataSource as Object[]).length) { const wrapper: Element = treeViewObj.element.parentElement; wrapper.getElementsByClassName('e-spreadsheet-ftrchk')[0].classList.remove('e-hide'); detach(wrapper.getElementsByClassName('e-checkfltrnmdiv')[0]); } treeViewObj.fields.dataSource = <{ [key: string]: Object }[]>filteredList; treeViewObj.dataBind(); }; if (searchValue) { filteredList = new DataManager(groupedData).executeLocal(new Query().where( new Predicate(treeViewObj.fields.text, 'contains', searchValue, true))); const filterId: { [key: string]: boolean } = {}; const predicates = []; let key: string; let initList: Object[]; const strFilter: boolean = isNaN(Number(searchValue)); let expandId: string[]; let level: number; if (strFilter) { for (let i: number = 0; i < filteredList.length; i++) { if (!filteredList[i]['hasChild']) { continue; } predicates.push(new Predicate('pId', 'equal', filteredList[i]['__rowIndex'], false)); key = filteredList[i]['pId']; if (!filterId[key]) { predicates.push(new Predicate('__rowIndex', 'equal', key, false)); filterId[key] = true; } } initList = filteredList; level = 1; } else { let year: string; const filterParentId: { [key: string]: boolean } = {}; expandId = []; for (let i: number = 0; i < filteredList.length; i++) { key = filteredList[i]['pId']; if (key) { year = key.split(' ')[0]; if (!filterId[key]) { predicates.push(new Predicate('__rowIndex', 'equal', key, false)); filterId[key] = true; expandId.push(year); expandId.push(key); } if (!filterParentId[year]) { if (!filterId[year]) { predicates.push(new Predicate('__rowIndex', 'equal', year, false)); filterId[year] = true; } predicates.push(new Predicate('__rowIndex', 'equal', filteredList[i]['__rowIndex'], false)); } } else { key = filteredList[i]['__rowIndex']; if (!filterParentId[key]) { predicates.push(new Predicate('__rowIndex', 'contains', key, false)); filterParentId[key] = true; } } } initList = []; } if (filteredList.length) { if (predicates.length) { filteredList = initList.concat(new DataManager(groupedData).executeLocal(new Query().where(Predicate.or(predicates)))); } changeData(); treeViewObj.checkAll(); const duration: number = treeViewObj.animation.expand.duration; treeViewObj.animation.expand.duration = 0; treeViewObj.expandAll(expandId, level); treeViewObj.animation.expand.duration = duration; } else if ((treeViewObj.fields.dataSource as Object[]).length) { changeData(); const wrapper: Element = treeViewObj.element.parentElement; wrapper.getElementsByClassName('e-spreadsheet-ftrchk')[0].classList.add('e-hide'); const noRecordEle: Element = this.parent.createElement('div', { className: 'e-checkfltrnmdiv' }); noRecordEle.appendChild(this.parent.createElement( 'span', { innerHTML: this.parent.serviceLocator.getService<L10n>(locale).getConstant('NoResult') })); wrapper.appendChild(noRecordEle); } } else { filteredList = groupedData; changeData(); treeViewObj.setProperties({ checkedNodes: checkedNodes }); } } private openDialog(cell: HTMLElement): void { const colIndex: number = parseInt(cell.getAttribute('aria-colindex'), 10); const field: string = getColumnHeaderText(colIndex); this.parent.showSpinner(); const sheetIdx: number = this.parent.activeSheetIndex; const filterRange: { useFilterRange: boolean, range: number[] } = this.filterRange.get(sheetIdx); const range: number[] = filterRange.range.slice(); const sheet: SheetModel = this.parent.getActiveSheet(); const filterCell: CellModel = getCell(range[0], colIndex - 1, sheet); const displayName: string = this.parent.getDisplayText(filterCell); range[0] = range[0] + 1; // to skip first row. if (!filterRange.useFilterRange) { range[2] = sheet.usedRange.rowIndex; //filter range should be till used range. } const fullRange: number[] = [range[0], colIndex - 1, range[2], colIndex - 1]; const totalRange: { address: string, filteredCol: boolean, otherColPredicate: PredicateModel[] } = this.getPredicateRange( fullRange, this.filterCollection.get(sheetIdx), colIndex - 1) as { address: string, filteredCol: boolean, otherColPredicate: PredicateModel[] }; const otherColPredicate: PredicateModel[] = totalRange.otherColPredicate; const addr: string = `${sheet.name}!${totalRange.address}`; const fullAddr: string = getRangeAddress(fullRange); const col: { type: string, isDateAvail: boolean } = this.getColumnType(sheet, colIndex - 1, range); const type: string = col.type; let dateColData: { [key: string]: Object }[]; const isDateCol: boolean = type.includes('date') || col.isDateAvail; if (isDateCol && !totalRange.filteredCol) { dateColData = []; } getData(this.parent, addr, true, true, null, true, null, null, false, fullAddr, null, dateColData).then((jsonData: { [key: string]: CellModel }[]) => { let checkBoxData: DataManager; this.parent.element.style.position = 'relative'; this.parent.element.classList.add('e-filter-open'); if (isDateCol) { if (dateColData || !otherColPredicate.length) { checkBoxData = new DataManager(dateColData || jsonData); } else { const data: Object[] = new DataManager(jsonData).executeLocal(new Query().where(Predicate.and(this.getPredicates(otherColPredicate)))); checkBoxData = new DataManager(data); } const beforeCboxRender: Function = (args: FilterCheckboxArgs): void => { this.parent.off(beforeCheckboxRender, beforeCboxRender); args.isCheckboxFilterTemplate = true; this.initTreeView(args, excelFilter); }; this.parent.on(beforeCheckboxRender, beforeCboxRender, this); } else { //to avoid undefined array data jsonData.some((value: { [key: string]: CellModel }, index: number) => { if (value) { checkBoxData = new DataManager(jsonData.slice(index)); } return !!value; }); } const target: HTMLElement = cell.querySelector('.e-filter-btn'); const options: IFilterArgs = { type: type, field: field, format: (type === 'date' ? this.getDateFormatFromColumn(sheet, colIndex, range) : null), displayName: displayName || 'Column ' + field, dataSource: checkBoxData, height: this.parent.element.classList.contains('e-bigger') ? 800 : 500, columns: [], hideSearchbox: false, filteredColumns: this.filterCollection.get(sheetIdx), column: { 'field': field, 'filter': {} }, handler: this.filterSuccessHandler.bind(this, new DataManager(jsonData)), target: target, position: { X: 0, Y: 0 }, localeObj: this.parent.serviceLocator.getService(locale) }; const excelFilter: ExcelFilterBase = new ExcelFilterBase(this.parent, this.getLocalizedCustomOperators()); excelFilter.openDialog(options); const filterPopup: HTMLElement = document.querySelector('.e-filter-popup'); if (filterPopup && filterPopup.id.includes(this.parent.element.id)) { EventHandler.add(filterPopup, getStartEvent(), this.filterMouseDownHandler, this); const parentOff: DOMRect = this.parent.element.getBoundingClientRect() as DOMRect; const cellOff: DOMRect = target.getBoundingClientRect() as DOMRect; const popupOff: DOMRect = filterPopup.getBoundingClientRect() as DOMRect; let left: number = (cellOff.right - parentOff.left) - popupOff.width; if (left < 0) { // Left collision wrt spreadsheet left left = cellOff.left - parentOff.left; } filterPopup.style.left = `${left}px`; filterPopup.style.top = '0px'; filterPopup.style.visibility = 'hidden'; if (filterPopup.classList.contains('e-hide')) { filterPopup.classList.remove('e-hide'); } let top: number = cellOff.bottom - parentOff.top; if (popupOff.height - (parentOff.bottom - cellOff.bottom) > 0) { // Bottom collision wrt spreadsheet bottom top -= popupOff.height - (parentOff.bottom - cellOff.bottom); if (top < 0) { top = 0; } } filterPopup.style.top = `${top}px`; filterPopup.style.visibility = ''; } this.parent.hideSpinner(); }); } private getPredicateRange( range: number[], predicates: PredicateModel[], col?: number): string | { address: string, filteredCol: boolean, otherColPredicate: PredicateModel[] } { let addr: string = getRangeAddress(range); let filteredCol: boolean; const otherColPredicate: PredicateModel[] = []; if (predicates && predicates.length) { let predicateRange: string; let colIdx: number; predicates.forEach((predicate: PredicateModel): void => { if (predicate.field) { predicateRange = `${predicate.field}${range[0] + 1}:${predicate.field}${range[2] + 1}`; colIdx = getColIndex(predicate.field); if (!addr.includes(predicateRange)) { addr += `,${predicateRange}`; if (colIdx < range[1]) { range[1] = colIdx; } if (colIdx > range[3]) { range[3] = colIdx; } } if (col !== undefined) { if (colIdx === col) { filteredCol = true; } else { otherColPredicate.push(predicate); } } } }); } else { filteredCol = true; } return col === undefined ? addr : { address: addr, filteredCol: filteredCol, otherColPredicate: otherColPredicate }; } private filterDialogCreatedHandler(): void { const filterPopup: HTMLElement = document.querySelector('.e-filter-popup'); if (filterPopup && filterPopup.id.includes(this.parent.element.id) && filterPopup.classList.contains('e-popup-close')) { filterPopup.classList.add('e-hide'); } } /** * Formats cell value for listing it in filter popup. * * @param {any} args - Specifies the args * @param {string | number} args.value - Specify the value * @param {object} args.column - Specify the column * @param {object} args.data - Specify the data * @returns {void} - Formats cell value for listing it in filter popup. */ private filterCboxValueHandler(args: { value: string | number, column: object, data: object }): void { if (args.column && args.data) { const fieldKey: string = 'field'; const field: string = args.column[fieldKey] as string; const dataKey: string = 'dataObj'; const rowKey: string = '__rowIndex'; if (args.value) { const indexes: number[] = getCellIndexes(field + args.data[dataKey][rowKey]); const cell: CellModel = getCell(indexes[0], indexes[1], this.parent.getActiveSheet()); if (cell && cell.format) { args.value = this.parent.getDisplayText(cell); } } } } /** * Triggers when sorting items are chosen on context menu of filter popup. * * @param {HTMLElement} target - Specify the element. * @returns {void} - Triggers when sorting items are chosen on context menu of filter popup. */ private selectSortItemHandler(target: HTMLElement): void { const sortOrder: SortOrder = target.classList.contains('e-filter-sortasc') ? 'Ascending' : target.classList.contains('e-filter-sortdesc') ? 'Descending' : null; if (!sortOrder) { return; } const sheet: SheetModel = this.parent.getActiveSheet(); const sheetIdx: number = this.parent.activeSheetIndex; const filterRange: { useFilterRange: boolean, range: number[] } = this.filterRange.get(sheetIdx); const range: number[] = filterRange.range.slice(); range[0] = range[0] + 1; // to skip first row. if (!filterRange.useFilterRange) { range[2] = sheet.usedRange.rowIndex; //filter range should be till used range. } this.parent.sortCollection = this.parent.sortCollection ? this.parent.sortCollection : []; let prevSort: SortCollectionModel; for (let i: number = 0; i < this.parent.sortCollection.length; i++) { if (this.parent.sortCollection[i] && this.parent.sortCollection[i].sheetIndex === sheetIdx) { prevSort = this.parent.sortCollection[i]; this.parent.sortCollection.splice(i, 1); } } this.parent.sortCollection.push( { sortRange: getRangeAddress(range), columnIndex: getIndexesFromAddress(sheet.activeCell)[1], order: sortOrder, sheetIndex: sheetIdx }); if (!prevSort) { prevSort = { order: '' }; } this.parent.notify( applySort, { sortOptions: { sortDescriptors: { order: sortOrder }, containsHeader: false }, previousSort: prevSort, range: getRangeAddress(range) }); this.refreshFilterRange(); this.closeDialog(); } /** * Triggers when OK button or clear filter item is selected * * @param {DataManager} dataSource - Specify the data source * @param {Object} args - Specify the data source * @param {string} args.action - Specify the action * @param {PredicateModel[]} args.filterCollection - Specify the filter collection. * @param {string} args.field - Specify the field. * @param {number} args.sIdx - Specify the index. * @param {boolean} args.isUndoRedo - Specify the bool. * @param {boolean} args.isInternal - Specify the isInternal. * @param {boolean} args.isFilterByValue - Specify the isFilterByValue. * @param {PredicateModel[]} args.prevPredicates - Specify the prevPredicates. * @returns {void} - Triggers when OK button or clear filter item is selected */ private filterSuccessHandler( dataSource: DataManager, args: { action: string, filterCollection?: PredicateModel[], field: string, sIdx?: number, isInternal?: boolean, isFilterByValue?: boolean, prevPredicates?: PredicateModel[] }): void { let sheetIdx: number = args.sIdx; if (!sheetIdx && sheetIdx !== 0) { sheetIdx = this.parent.activeSheetIndex; } let prevPredicates: PredicateModel[] = args.prevPredicates || [].slice.call(this.filterCollection.get(sheetIdx)); if (args.isFilterByValue && !prevPredicates.length) { prevPredicates = undefined; } let predicates: PredicateModel[] = this.filterCollection.get(sheetIdx); this.updatePredicate(predicates, args.field); if (args.action === 'clear-filter' && predicates.length === prevPredicates.length) { return; } if (args.action === 'filtering') { predicates = predicates.concat(args.filterCollection); if (predicates.length) { for (let i: number = 0; i < predicates.length; i++) { args.field = predicates[i].field; } } } this.filterCollection.set(sheetIdx, predicates); const filterOptions: FilterOptions = { datasource: dataSource, predicates: this.getPredicates(this.filterCollection.get(sheetIdx)) }; const filterRange: { useFilterRange: boolean, range: number[] } = this.filterRange.get(sheetIdx); if (!filterRange.useFilterRange) { filterRange.range[2] = getSheet(this.parent as Workbook, sheetIdx).usedRange.rowIndex; //extend the range if filtered } this.applyFilter( filterOptions, getRangeAddress(filterRange.range), sheetIdx, prevPredicates, false, args.isInternal); } private updatePredicate(predicates: PredicateModel[], field: string): void { const dataManager: DataManager = new DataManager(predicates as JSON[]); const query: Query = new Query(); const fields: { field: string }[] = dataManager.executeLocal(query.where('field', 'equal', field)) as { field: string }[]; for (let index: number = 0; index < fields.length; index++) { let sameIndex: number = -1; for (let filterIndex: number = 0; filterIndex < predicates.length; filterIndex++) { if (predicates[filterIndex].field === fields[index].field) { sameIndex = filterIndex; break; } } if (sameIndex !== -1) { predicates.splice(sameIndex, 1); } } } /** * Triggers events for filtering and applies filter. * * @param {FilterOptions} filterOptions - Specify the filteroptions. * @param {string} range - Specify the range. * @param {number} sheetIdx - Specify the sheet index. * @param {PredicateModel[]} prevPredicates - Specify the predicates. * @param {boolean} isUndoRedo - Specify the undo redo. * @param {boolean} refresh - Spefify the refresh. * @param {boolean} isInternal - Specify the isInternal. * @returns {void} - Triggers events for filtering and applies filter. */ private applyFilter( filterOptions: FilterOptions, range: string, sheetIdx: number, prevPredicates?: PredicateModel[], refresh?: boolean, isInternal?: boolean): void { const eventArgs: { range: string, predicates: PredicateModel[], previousPredicates: PredicateModel[], sheetIndex: number, cancel: boolean } = { range: range, predicates: [].slice.call(this.filterCollection.get(sheetIdx)), previousPredicates: prevPredicates, sheetIndex: sheetIdx, cancel: false }; if (!isInternal) { this.parent.notify(beginAction, { action: 'filter', eventArgs: eventArgs }); if (eventArgs.cancel) { return; } } if (range.indexOf('!') < 0) { range = this.parent.sheets[sheetIdx].name + '!' + range; } this.parent.showSpinner(); // eslint-disable-next-line @typescript-eslint/no-unused-vars const promise: Promise<FilterEventArgs> = new Promise((resolve: Function, reject: Function) => { resolve((() => { /** */ })()); }); const filterArgs: { [key: string]: BeforeFilterEventArgs | Promise<FilterEventArgs> | boolean } = { args: { range: range, filterOptions: filterOptions }, promise: promise, refresh: refresh }; this.parent.notify(initiateFilter, filterArgs); (filterArgs.promise as Promise<FilterEventArgs>).then((args: FilterEventArgs) => { this.refreshFilterRange(); this.parent.notify(getFilteredCollection, null); this.parent.hideSpinner(); if (!isInternal) { delete eventArgs.cancel; this.parent.notify(completeAction, { action: 'filter', eventArgs: eventArgs }); } return Promise.resolve(args); }).catch((error: string) => { this.filterRangeAlertHandler({ error: error }); return Promise.reject(error); }); } /** * Gets the predicates for the sheet * * @param {number} sheetIdx - Specify the sheetindex * @returns {Predicate[]} - Gets the predicates for the sheet */ private getPredicates(predicateModel: PredicateModel[]): Predicate[] { const predicateList: Predicate[] = []; const excelPredicate: Predicate = CheckBoxFilterBase.getPredicate(predicateModel); for (const prop of Object.keys(excelPredicate)) { predicateList.push(<Predicate>excelPredicate[prop]); } return predicateList; } /** * Gets the column type to pass it into the excel filter options. * * @param {SheetModel} sheet - Specify the sheet. * @param {number} colIndex - Specify the colindex * @param {number[]} range - Specify the range. * @returns {string} - Gets the column type to pass it into the excel filter options. */ private getColumnType(sheet: SheetModel, colIndex: number, range: number[]): { type: string, isDateAvail: boolean } { let num: number = 0; let str: number = 0; let date: number = 0; const time: number = 0; for (let i: number = range[0]; i <= range[2]; i++) { const cell: CellModel = getCell(i, colIndex, sheet); if (cell) { if (cell.format) { const type: string = getTypeFromFormat(cell.format).toLowerCase(); switch (type) { case 'number': case 'currency': case 'accounting': case 'percentage': num++; break; case 'shortdate': case 'longdate': date++; break; case 'time': num++; break; default: str++; break; } } else { if (typeof cell.value === 'string' || cell.value === undefined || cell.value === null) { str++; } else { num++; } } } else { str++; } } return { type: (num > str && num > date && num > time) ? 'number' : (str > num && str > date && str > time) ? 'string' : (date > num && date > str && date > time) ? 'date' : 'datetime', isDateAvail: !!date }; } private getDateFormatFromColumn(sheet: SheetModel, colIndex: number, range: number[]): string { let format: string; for (let i: number = range[0]; i <= range[2]; i++) { const cell: CellModel = getCell(i, colIndex - 1, sheet); if (cell && cell.format) { format = cell.format; break; } } return format; } /** * Clear filter from the field. * * @param {any} args - Specifies the args * @param {{ field: string }} args.field - Specify the args * @param {boolean} args.isAction - Specify the isAction. * @param {boolean} args.preventRefresh - Specify the preventRefresh. * @returns {void} - Clear filter from the field. */ private clearFilterHandler(args?: { field?: string, isAction?: boolean, preventRefresh?: boolean, sheetIndex?: number }): void { const sheetIndex: number = args && args.sheetIndex !== undefined ? args.sheetIndex : this.parent.activeSheetIndex; if (args && args.field) { let predicates: PredicateModel[] = [].slice.call(this.filterCollection.get(sheetIndex)); if (predicates && predicates.length) { this.updatePredicate(predicates, args.field); this.initiateFilterUIHandler( { predicates: predicates, range: getRangeAddress(this.filterRange.get(sheetIndex).range), sIdx: sheetIndex }); } } else { const isAction: boolean = args && args.isAction; const filterArgs: { [key: string]: boolean | number } = { isFiltered: false, isClearAll: true, sheetIndex: sheetIndex }; this.getFilteredColumnHandler(filterArgs); if (filterArgs.isFiltered || (args && args.preventRefresh)) { let eventArgs: { range: string, predicates: PredicateModel[], previousPredicates: PredicateModel[], sheetIndex: number, cancel: boolean }; const sheet: SheetModel = getSheet(this.parent, sheetIndex); const filterRange: { useFilterRange: boolean, range: number[] } = this.filterRange.get(sheetIndex); const range: number[] = filterRange.range; if (isAction) { eventArgs = { range: getRangeAddress(range), predicates: [], previousPredicates: this.filterCollection.get(sheetIndex), sheetIndex: sheetIndex, cancel: false }; this.parent.notify(beginAction, { action: 'filter', eventArgs: eventArgs }); if (eventArgs.cancel) { return; } } this.filterCollection.set(sheetIndex, []); const filterColl: FilterCollectionModel[] = this.parent.filterCollection; for (let i: number = 0, len: number = filterColl && filterColl.length; i < len; i++) { if (filterColl[i].sheetIndex === sheetIndex) { filterColl.splice(i, 1); break; } } const len: number = filterRange.useFilterRange ? range[2] : sheet.usedRange.rowIndex; if (this.parent.scrollSettings.enableVirtualization && ((len - range[0]) + 1 > (this.parent.viewport.rowCount + (this.parent.getThreshold('row') * 2)))) { for (let i: number = 0; i <= len; i++) { setRow(sheet, i, <ExtendedRowModel>{ hidden: false, isFiltered: false }); } if (!args || !args.preventRefresh) { this.parent.renderModule.refreshSheet(false, false, true); } } else { this.refreshFilterRange(null, null, sheetIndex); const evtArgs: { [key: string]: number | boolean } = { startIndex: range[0], hide: false, isFiltering: true, refreshUI: false, endIndex: filterRange.useFilterRange ? range[2] : sheet.usedRange.rowIndex, sheetIndex: sheetIndex }; this.parent.notify(hideShow, evtArgs); if (evtArgs.refreshUI && (!args || !args.preventRefresh)) { this.parent.renderModule.refreshSheet(false, false, true); } } if (isAction) { delete eventArgs.cancel; this.parent.notify(completeAction, { action: 'filter', eventArgs: eventArgs }); } } } } /** * Reapplies the filter. * * @param {boolean} isInternal - Specifies the isInternal. * @param {boolean} refresh - Specifies the refresh. * @returns {void} - Reapplies the filter. */ private reapplyFilterHandler(isInternal?: boolean, refresh?: boolean): void { const sheetIdx: number = this.parent.activeSheetIndex; if (this.filterRange.has(sheetIdx)) { const predicates: PredicateModel[] = this.filterCollection.get(sheetIdx); if (predicates && predicates.length) { const sheet: SheetModel = getSheet(this.parent, sheetIdx); const filterRange: { useFilterRange: boolean, range: number[] } = this.filterRange.get(this.parent.activeSheetIndex); const range: number[] = filterRange.range.slice(); range[0] = range[0] + 1; if (!filterRange.useFilterRange) { range[2] = sheet.usedRange.rowIndex; } range[1] = range[3] = getColIndex(predicates[0].field); const addr: string = `${sheet.name}!${this.getPredicateRange(range, predicates.slice(1, predicates.length))}`; getData( this.parent, addr, true, true, null, true, null, null, false, getRangeAddress(range)).then( (jsonData: { [key: string]: CellModel }[]) => { const predicate: Predicate[] = this.getPredicates(this.filterCollection.get(sheetIdx)); this.applyFilter( { predicates: predicate, datasource: new DataManager(jsonData) }, getRangeAddress(filterRange.range), sheetIdx, [].slice.call(predicates), refresh, isInternal); }); } } } /** * Gets the filter information of the sheet. * * @param {FilterInfoArgs} args - Specify the args * @returns {void} - Gets the filter information of the sheet. */ private getFilterRangeHandler(args: FilterInfoArgs): void { const sheetIdx: number = args.sheetIdx; if (this.filterRange && this.filterRange.has(sheetIdx)) { args.hasFilter = true; args.filterRange = this.filterRange.get(sheetIdx).range; } else { args.hasFilter = false; args.filterRange = null; } } /** * Returns the custom operators for filter items. * * @returns {Object} - Returns the custom operators for filter items. */ private getLocalizedCustomOperators(): Object { const l10n: L10n = this.parent.serviceLocator.getService(locale); const numOptr: Object[] = [ { value: 'equal', text: l10n.getConstant('Equal') }, { value: 'greaterthan', text: l10n.getConstant('GreaterThan') }, { value: 'greaterthanorequal', text: l10n.getConstant('GreaterThanOrEqual') }, { value: 'lessthan', text: l10n.getConstant('LessThan') }, { value: 'lessthanorequal', text: l10n.getConstant('LessThanOrEqual') }, { value: 'notequal', text: l10n.getConstant('NotEqual') } ]; const customOperators: Object = { stringOperator: [ { value: 'startswith', text: l10n.getConstant('StartsWith') }, { value: 'endswith', text: l10n.getConstant('EndsWith') }, { value: 'contains', text: l10n.getConstant('Contains') }, { value: 'equal', text: l10n.getConstant('Equal') }, { value: 'notequal', text: l10n.getConstant('NotEqual') }], numberOperator: numOptr, dateOperator: numOptr, datetimeOperator: numOptr, booleanOperator: [ { value: 'equal', text: l10n.getConstant('Equal') }, { value: 'notequal', text: l10n.getConstant('NotEqual') } ] }; return customOperators; } /** * To get filtered range and predicates collections * * @returns {void} - To get filtered range and predicates collections */ private getFilteredCollection(): void { const sheetLen: number = this.parent.sheets.length; const col: FilterCollectionModel[] = []; let fil: FilterCollectionModel; for (let i: number = 0; i < sheetLen; i++) { let range: number[]; let hasFilter: boolean; const args: FilterInfoArgs = { sheetIdx: i, filterRange: range, hasFilter: hasFilter }; this.getFilterRangeHandler(args); if (args.hasFilter) { const colCollection: number[] = []; const condition: string[] = []; const value: (string | number | boolean | Date)[] = []; const type: string[] = []; const predi: string[] = []; const predicate: PredicateModel[] = this.filterCollection.get(args.sheetIdx); for (let i: number = 0; i < predicate.length; i++) { if (predicate[i].field && predicate[i].operator) { const colIdx: number = getCellIndexes(predicate[i].field + '1')[1]; colCollection.push(colIdx); condition.push(predicate[i].operator); value.push(isNullOrUndefined(predicate[i].value) ? '' : predicate[i].value); type.push(predicate[i].type); predi.push(predicate[i].predicate); } } const address: string = getRangeAddress(args.filterRange); fil = { sheetIndex: args.sheetIdx, filterRange: address, hasFilter: args.hasFilter, column: colCollection, criteria: condition, value: value, dataType: type, predicates: predi }; col.push(fil); } } if (fil) { this.parent.filterCollection = col; } } private updateFilter(args?: { initLoad: boolean, isOpen: boolean }): void { if (this.parent.filterCollection && (args.initLoad || args.isOpen)) { for (let i: number = 0; i < this.parent.filterCollection.length; i++) { const filterCol: FilterCollectionModel = this.parent.filterCollection[i]; let sIdx: number = filterCol.sheetIndex; if (i === 0 && !this.parent.isOpen && !args.isOpen) { sIdx = 0; } const predicates: PredicateModel[] = []; if (filterCol.column) { for (let j: number = 0; j < filterCol.column.length; j++) { const predicateCol: PredicateModel = { field: getCellAddress(0, filterCol.column[j]).charAt(0), operator: this.getFilterOperator(filterCol.criteria[j]), value: filterCol.value[j].toString().split('*').join(''), predicate: filterCol.predicates && filterCol.predicates[j], type: filterCol.dataType && filterCol.dataType[j] }; predicates.push(predicateCol); } } for (let i: number = 0; i < predicates.length - 1; i++) { if (predicates[i].field === predicates[i + 1].field) { if (!predicates[i].predicate) { predicates[i].predicate = 'or'; } if (!predicates[i + 1].predicate) { predicates[i + 1].predicate = 'or'; } } } this.parent.notify(initiateFilterUI, { predicates: predicates !== [] ? predicates : null, range: filterCol.filterRange, sIdx: sIdx, isCut: true }); } if (this.parent.sortCollection) { this.parent.notify(sortImport, null); } } } private getFilterOperator(value: string): string { switch (value) { case 'BeginsWith': value = 'startswith'; break; case 'Less': value = 'lessthan'; break; case 'EndsWith': value = 'endswith'; break; case 'Equal': value = 'equal'; break; case 'Notequal': value = 'notEqual'; break; case 'Greater': value = 'greaterthan'; break; case 'Contains': value = 'contains'; break; case 'LessOrEqual': value = 'lessthanorequal'; break; case 'GreaterOrEqual': value = 'greaterthanorequal'; break; } return value; } private beforeInsertHandler(args: { index: number, model: ColumnModel[], activeSheetIndex: number, modelType: string }): void { if (args.modelType === 'Column') { const sheetIdx: number = isUndefined(args.activeSheetIndex) ? this.parent.activeSheetIndex : args.activeSheetIndex; if (this.filterRange.size && this.filterRange.has(sheetIdx)) { const range: number[] = this.filterRange.get(sheetIdx).range; if (this.isFilterCell(sheetIdx, range[0], args.index) || args.index < range[1]) { range[3] += args.model.length; if (args.index <= range[1]) { range[1] += args.model.length; } this.filterCollection.get(sheetIdx).forEach((predicate: PredicateModel) => { const colIdx: number = getColIndex(predicate.field); if (args.index <= colIdx) { predicate.field = getColumnHeaderText(colIdx + args.model.length + 1); } }); if (this.parent.sortCollection) { this.parent.sortCollection.forEach((sortCollection: SortCollectionModel) => { if (sortCollection.sheetIndex === sheetIdx && args.index <= sortCollection.columnIndex) { sortCollection.columnIndex += args.model.length; } }); } this.getFilteredCollection(); } } } else if (args.modelType === 'Sheet') { let isChanged: boolean = false; for (const key of Array.from(this.filterRange.keys()).sort().reverse()) { if (args.index <= key) { isChanged = true; this.filterRange.set(key + args.model.length, this.filterRange.get(key)); this.filterRange.delete(key); this.filterCollection.set(key + args.model.length, this.filterCollection.get(key)); this.filterCollection.delete(key); } } if (this.parent.sortCollection) { this.parent.sortCollection.forEach((sortCollection: SortCollectionModel) => { if (args.index <= sortCollection.sheetIndex) { sortCollection.sheetIndex += args.model.length; } }); } if (isChanged) { this.getFilteredCollection(); } } } private beforeDeleteHandler(args: { start: number, end: number, modelType: string, refreshSheet?: boolean }): void { if (args.modelType === 'Column') { const sheetIdx: number = this.parent.activeSheetIndex; if (this.filterRange.size && this.filterRange.has(sheetIdx)) { let isChanged: boolean = true; const range: number[] = this.filterRange.get(sheetIdx).range; if (args.start >= range[1] && args.end <= range[3]) { // in between range[3] -= args.end - args.start + 1; } else if (args.start < range[1] && args.end < range[1]) { // before range[1] -= args.end - args.start + 1; range[3] -= args.end - args.start + 1; } else if (args.start < range[1] && args.end > range[1] && args.end < range[3]) { // from before to inbetween range[1] = args.start; range[3] -= args.end - args.start + 1; } else { isChanged = false; } if (isChanged) { const filterCollection: PredicateModel[] = this.filterCollection.get(sheetIdx); let isPredicateRemoved: boolean; for (let i: number = filterCollection.length - 1; i >= 0; i--) { const colIdx: number = getColIndex(filterCollection[i].field); if (args.end < colIdx) { filterCollection[i].field = getColumnHeaderText(colIdx - (args.end - args.start + 1) + 1); } else if (args.start <= colIdx && args.end >= colIdx) { isPredicateRemoved = true; filterCollection.splice(i, 1); } } const sortColl: SortCollectionModel[] = this.parent.sortCollection; if (sortColl) { for (let i: number = 0; i < sortColl.length; i++) { if (sortColl[i].sheetIndex === sheetIdx) { if (args.end < sortColl[i].columnIndex) { sortColl[i].columnIndex = sortColl[i].columnIndex - (args.end - args.start + 1); break; } else if (args.start <= sortColl[i].columnIndex && args.end >= sortColl[i].columnIndex) { sortColl.splice(i, 1); break; } } } } if (range.some((value: number) => value < 0)) { this.removeFilter(sheetIdx, true, true); args.refreshSheet = true; } else if (isPredicateRemoved) { if (filterCollection && filterCollection.length) { this.reapplyFilterHandler(true, true); args.refreshSheet = false; } else { this.clearFilterHandler({ preventRefresh: true }); args.refreshSheet = true; } } this.getFilteredCollection(); } } } } private deleteSheetHandler(args: { sheetIndex: number }): void { if (!isUndefined(args.sheetIndex)) { let isChanged: boolean; for (const key of Array.from(this.filterRange.keys()).sort().reverse()) { isChanged = true; if (args.sheetIndex === key) { this.filterRange.delete(key); this.filterCollection.delete(key); } else if (args.sheetIndex < key) { this.filterRange.set(key - 1, this.filterRange.get(key)); this.filterRange.delete(key); this.filterCollection.set(key - 1, this.filterCollection.get(key)); this.filterCollection.delete(key); } else { isChanged = false; } } const sortColl: SortCollectionModel[] = this.parent.sortCollection; if (sortColl) { for (let i: number = sortColl.length - 1; i >= 0; i--) { if (args.sheetIndex === sortColl[i].sheetIndex) { sortColl.splice(i, 1); } else if (args.sheetIndex < sortColl[i].sheetIndex) { sortColl[i].sheetIndex -= 1; } } } if (isChanged) { this.getFilteredCollection(); } } else if (this.filterRange.get(this.parent.activeSheetIndex)) { this.filterRange.delete(this.parent.activeSheetIndex); this.filterCollection.delete(this.parent.activeSheetIndex); } } private clearHandler(args: ClearOptions): void { const info: { sheetIndex: number, indices: number[] } = this.parent.getAddressInfo(args.range); if (this.filterRange.has(info.sheetIndex)) { const indexes: number[] = this.filterRange.get(info.sheetIndex).range.slice(); if (inRange(info.indices, indexes[0], indexes[1]) && inRange(info.indices, indexes[0], indexes[3])) { this.removeFilter(info.sheetIndex); } } } private duplicateSheetFilterHandler(args: duplicateSheetOption): void { if (this.filterCollection.has(args.sheetIndex)) { this.filterCollection.set(args.newSheetIndex, this.filterCollection.get(args.sheetIndex)); } if (this.filterRange.has(args.sheetIndex)) { this.filterRange.set(args.newSheetIndex, this.filterRange.get(args.sheetIndex)); } } }
the_stack
import UndoPlugin from '../../lib/corePlugins/UndoPlugin'; import { itChromeOnly } from '../TestHelper'; import { Position } from 'roosterjs-editor-dom'; import { IEditor, Keys, PluginEventType, SelectionRangeTypes, UndoPluginState, } from 'roosterjs-editor-types'; describe('UndoPlugin', () => { let plugin: UndoPlugin; let state: UndoPluginState; let editor: IEditor; let isInIME: jasmine.Spy; let addUndoSnapshot: jasmine.Spy; beforeEach(() => { plugin = new UndoPlugin({}); state = plugin.getState(); isInIME = jasmine.createSpy('isInIME'); addUndoSnapshot = jasmine.createSpy('addUndoSnapshot'); editor = <IEditor>(<any>{ isInIME, addUndoSnapshot, }); plugin.initialize(editor); }); afterEach(() => { plugin.dispose(); plugin = null; state = null; editor = null; isInIME = null; }); it('init', () => { expect(state.hasNewContent).toBeFalse(); expect(state.isRestoring).toBeFalse(); expect(state.isNested).toBeFalsy(); expect(state.snapshotsService).toBeDefined(); }); it('editor ready event', () => { let getUndoState = jasmine.createSpy('getUndoState').and.returnValue({ canUndo: false, canRedo: false, }); editor.getUndoState = getUndoState; plugin.onPluginEvent({ eventType: PluginEventType.EditorReady, }); expect(isInIME).toHaveBeenCalled(); expect(getUndoState).toHaveBeenCalled(); expect(addUndoSnapshot).toHaveBeenCalled(); }); it('editor ready event where can undo', () => { let getUndoState = jasmine.createSpy('getUndoState').and.returnValue({ canUndo: true, canRedo: false, }); editor.getUndoState = getUndoState; plugin.onPluginEvent({ eventType: PluginEventType.EditorReady, }); expect(isInIME).toHaveBeenCalled(); expect(getUndoState).toHaveBeenCalled(); expect(addUndoSnapshot).not.toHaveBeenCalledWith(state); }); it('editor ready event where can redo', () => { let getUndoState = jasmine.createSpy('getUndoState').and.returnValue({ canUndo: false, canRedo: true, }); editor.getUndoState = getUndoState; plugin.onPluginEvent({ eventType: PluginEventType.EditorReady, }); expect(isInIME).toHaveBeenCalled(); expect(getUndoState).toHaveBeenCalled(); expect(addUndoSnapshot).not.toHaveBeenCalledWith(state); }); itChromeOnly('key down event with BACKSPACE, add undo snapshot once', () => { editor.getSelectionRange = () => { return <any>{ collapsed: true, }; }; plugin.onPluginEvent({ eventType: PluginEventType.KeyDown, rawEvent: <any>{ which: Keys.BACKSPACE, }, }); expect(addUndoSnapshot).toHaveBeenCalledTimes(1); // Backspace again, no need to add undo snapshot now (<jasmine.Spy>addUndoSnapshot).calls.reset(); plugin.onPluginEvent({ eventType: PluginEventType.KeyDown, rawEvent: <any>{ which: Keys.BACKSPACE, }, }); expect(addUndoSnapshot).not.toHaveBeenCalled(); // Backspace again, with ctrl key pressed, addUndoSnapshot (<jasmine.Spy>addUndoSnapshot).calls.reset(); plugin.onPluginEvent({ eventType: PluginEventType.KeyDown, rawEvent: <any>{ which: Keys.BACKSPACE, ctrlKey: true, }, }); expect(addUndoSnapshot).toHaveBeenCalled(); // Backspace again, with expanded range, addUndoSnapshot (<jasmine.Spy>addUndoSnapshot).calls.reset(); editor.getSelectionRange = () => { return <any>{ collapsed: false, }; }; plugin.onPluginEvent({ eventType: PluginEventType.KeyDown, rawEvent: <any>{ which: Keys.BACKSPACE, }, }); expect(addUndoSnapshot).toHaveBeenCalled(); }); itChromeOnly('key down event with DELETE, add undo snapshot once', () => { editor.getSelectionRange = () => { return <any>{ collapsed: true, }; }; plugin.onPluginEvent({ eventType: PluginEventType.KeyDown, rawEvent: <any>{ which: Keys.DELETE, }, }); expect(addUndoSnapshot).toHaveBeenCalledTimes(1); // DELETE again, no need to add undo snapshot now (<jasmine.Spy>addUndoSnapshot).calls.reset(); plugin.onPluginEvent({ eventType: PluginEventType.KeyDown, rawEvent: <any>{ which: Keys.DELETE, }, }); expect(addUndoSnapshot).not.toHaveBeenCalled(); // DELETE again, with ctrl key pressed, addUndoSnapshot (<jasmine.Spy>addUndoSnapshot).calls.reset(); plugin.onPluginEvent({ eventType: PluginEventType.KeyDown, rawEvent: <any>{ which: Keys.DELETE, ctrlKey: true, }, }); expect(addUndoSnapshot).toHaveBeenCalled(); // DELETE again, with expanded range, addUndoSnapshot (<jasmine.Spy>addUndoSnapshot).calls.reset(); editor.getSelectionRange = () => { return <any>{ collapsed: false, }; }; plugin.onPluginEvent({ eventType: PluginEventType.KeyDown, rawEvent: <any>{ which: Keys.DELETE, }, }); expect(addUndoSnapshot).toHaveBeenCalled(); }); it('key down event with DELETE then BACKSPACE, add undo snapshot twice', () => { editor.getSelectionRange = () => { return <any>{ collapsed: true, }; }; plugin.onPluginEvent({ eventType: PluginEventType.KeyDown, rawEvent: <any>{ which: Keys.DELETE, }, }); plugin.onPluginEvent({ eventType: PluginEventType.KeyDown, rawEvent: <any>{ which: Keys.BACKSPACE, }, }); expect(addUndoSnapshot).toHaveBeenCalledTimes(2); }); it('key down event with cursor moving and has new content, add undo snapshot each time', () => { editor.getSelectionRange = () => { return <any>{ collapsed: true, }; }; const KEY_PAGEUP = 33; const KEY_DOWN = 40; for (let which = KEY_PAGEUP; which <= KEY_DOWN; which++) { state.hasNewContent = true; plugin.onPluginEvent({ eventType: PluginEventType.KeyDown, rawEvent: <any>{ which, }, }); } expect(addUndoSnapshot).toHaveBeenCalledTimes(KEY_DOWN - KEY_PAGEUP + 1); }); it('key down event with cursor moving and but no new content, no undo snapshot each time', () => { editor.getSelectionRange = () => { return <any>{ collapsed: true, }; }; const KEY_PAGEUP = 33; const KEY_DOWN = 40; for (let which = KEY_PAGEUP; which <= KEY_DOWN; which++) { state.hasNewContent = false; plugin.onPluginEvent({ eventType: PluginEventType.KeyDown, rawEvent: <any>{ which, }, }); } expect(addUndoSnapshot).not.toHaveBeenCalled(); }); it('delete, page up, delete, no new content, add undo snapshot twice', () => { editor.getSelectionRange = () => { return <any>{ collapsed: true, }; }; const KEY_PAGEUP = 33; [Keys.DELETE, KEY_PAGEUP, Keys.DELETE].forEach(which => { state.hasNewContent = false; plugin.onPluginEvent({ eventType: PluginEventType.KeyDown, rawEvent: <any>{ which, }, }); }); expect(addUndoSnapshot).toHaveBeenCalledTimes(2); }); it('key press event with expanded range', () => { editor.getSelectionRange = () => { return <any>{ collapsed: false, }; }; state.hasNewContent = false; plugin.onPluginEvent({ eventType: PluginEventType.KeyPress, rawEvent: <any>{ which: 65, }, }); expect(addUndoSnapshot).toHaveBeenCalled(); }); it('key press event with collapsed range', () => { editor.getSelectionRange = () => { return <any>{ collapsed: true, }; }; const clearRedo = jasmine.createSpy('clearRedo'); state.hasNewContent = false; state.snapshotsService.clearRedo = clearRedo; plugin.onPluginEvent({ eventType: PluginEventType.KeyPress, rawEvent: <any>{ which: 65, }, }); expect(addUndoSnapshot).not.toHaveBeenCalled(); expect(state.hasNewContent).toBeTrue(); expect(clearRedo).toHaveBeenCalled(); }); it('key press event with SPACE key in collapsed range', () => { editor.getSelectionRange = () => { return <any>{ collapsed: true, }; }; state.hasNewContent = false; plugin.onPluginEvent({ eventType: PluginEventType.KeyPress, rawEvent: <any>{ which: Keys.SPACE, }, }); expect(addUndoSnapshot).toHaveBeenCalled(); expect(state.hasNewContent).toBeFalse(); // Press SPACE again, no undo snapshot added (<jasmine.Spy>addUndoSnapshot).calls.reset(); plugin.onPluginEvent({ eventType: PluginEventType.KeyPress, rawEvent: <any>{ which: Keys.SPACE, }, }); expect(addUndoSnapshot).not.toHaveBeenCalled(); }); it('key press event with ENTER key in collapsed range', () => { editor.getSelectionRange = () => { return <any>{ collapsed: true, }; }; state.hasNewContent = false; plugin.onPluginEvent({ eventType: PluginEventType.KeyPress, rawEvent: <any>{ which: Keys.ENTER, }, }); expect(addUndoSnapshot).toHaveBeenCalled(); expect(state.hasNewContent).toBeTrue(); // Press ENTER again, add one more snapshot (<jasmine.Spy>addUndoSnapshot).calls.reset(); plugin.onPluginEvent({ eventType: PluginEventType.KeyPress, rawEvent: <any>{ which: Keys.SPACE, }, }); expect(addUndoSnapshot).toHaveBeenCalled(); }); it('CompositionEnd event', () => { plugin.onPluginEvent({ eventType: PluginEventType.CompositionEnd, rawEvent: <any>{}, }); expect(addUndoSnapshot).toHaveBeenCalled(); }); it('ContentChanged event', () => { state.hasNewContent = false; const clearRedo = jasmine.createSpy('clearRedo'); state.snapshotsService.clearRedo = clearRedo; plugin.onPluginEvent({ eventType: PluginEventType.ContentChanged, source: '', }); expect(addUndoSnapshot).not.toHaveBeenCalled(); expect(state.hasNewContent).toBeTrue(); expect(clearRedo).toHaveBeenCalled(); }); it('customized UndoSnapshotService', () => { const canMove = jasmine.createSpy('canMove'); const move = jasmine.createSpy('move'); const addSnapshot = jasmine.createSpy('addSnapshot'); const clearRedo = jasmine.createSpy('clearRedo'); const canUndoAutoComplete = jasmine.createSpy('canUndoAutoComplete'); plugin = new UndoPlugin({ undoSnapshotService: { canMove, move, addSnapshot, clearRedo, canUndoAutoComplete, }, }); plugin.initialize(<IEditor>(<any>{ getSelectionRange: () => ({ collapsed: true, }), isInIME, })); plugin.onPluginEvent({ eventType: PluginEventType.KeyPress, rawEvent: <any>{ which: 65, }, }); expect(clearRedo).toHaveBeenCalled(); }); it('can undo autoComplete', () => { state.snapshotsService.addSnapshot({ html: 'snapshot 1', metadata: null }, false); state.snapshotsService.addSnapshot({ html: 'snapshot 2', metadata: null }, true); state.snapshotsService.addSnapshot({ html: 'snapshot 3', metadata: null }, false); expect(state.snapshotsService.canUndoAutoComplete()).toBeTrue(); }); it('cannot undo autoComplete', () => { state.snapshotsService.addSnapshot({ html: 'snapshot 1', metadata: null }, false); state.snapshotsService.addSnapshot({ html: 'snapshot 2', metadata: null }, true); state.snapshotsService.addSnapshot({ html: 'snapshot 3', metadata: null }, false); state.snapshotsService.addSnapshot({ html: 'snapshot 4', metadata: null }, false); expect(state.snapshotsService.canUndoAutoComplete()).toBeFalse(); }); it('Backspace trigger undo when can undo autoComplete', () => { state.snapshotsService.addSnapshot({ html: 'snapshot 1', metadata: null }, false); state.snapshotsService.addSnapshot({ html: 'snapshot 2', metadata: null }, true); state.snapshotsService.addSnapshot({ html: 'snapshot 3', metadata: null }, false); const undo = jasmine.createSpy('undo'); const preventDefault = jasmine.createSpy('preventDefault'); const range = document.createRange(); const pos = Position.getStart(range); editor.undo = undo; editor.getSelectionRange = () => range; editor.getFocusedPosition = () => pos; state.autoCompletePosition = pos; plugin.onPluginEvent({ eventType: PluginEventType.KeyDown, rawEvent: <KeyboardEvent>(<any>{ which: Keys.BACKSPACE, preventDefault, }), }); expect(undo).toHaveBeenCalled(); expect(preventDefault).toHaveBeenCalled(); expect(state.autoCompletePosition).toBeNull(); }); it('Other key does not trigger undo auto complete', () => { state.snapshotsService.addSnapshot({ html: 'snapshot 1', metadata: null }, false); state.snapshotsService.addSnapshot({ html: 'snapshot 2', metadata: null }, true); state.snapshotsService.addSnapshot({ html: 'snapshot 3', metadata: null }, false); const undo = jasmine.createSpy('undo'); const preventDefault = jasmine.createSpy('preventDefault'); const range = document.createRange(); const pos = Position.getStart(range); editor.undo = undo; editor.getSelectionRange = () => range; editor.getFocusedPosition = () => pos; state.autoCompletePosition = pos; plugin.onPluginEvent({ eventType: PluginEventType.KeyDown, rawEvent: <KeyboardEvent>(<any>{ which: Keys.ENTER, preventDefault, }), }); expect(undo).not.toHaveBeenCalled(); expect(preventDefault).not.toHaveBeenCalled(); expect(state.autoCompletePosition).not.toBeNull(); expect(state.snapshotsService.canUndoAutoComplete()).toBeTrue(); }); it('Another undo snapshot is added, cannot undo autocomplete any more', () => { state.snapshotsService.addSnapshot({ html: 'snapshot 1', metadata: null }, false); state.snapshotsService.addSnapshot({ html: 'snapshot 2', metadata: null }, true); state.snapshotsService.addSnapshot({ html: 'snapshot 3', metadata: null }, false); const undo = jasmine.createSpy('undo'); const preventDefault = jasmine.createSpy('preventDefault'); const range = document.createRange(); const pos = Position.getStart(range); editor.undo = undo; editor.getSelectionRange = () => range; editor.getFocusedPosition = () => pos; editor.addUndoSnapshot = () => state.snapshotsService.addSnapshot({ html: 'snapshot 4', metadata: null }, false); state.autoCompletePosition = pos; plugin.onPluginEvent({ eventType: PluginEventType.KeyDown, rawEvent: <KeyboardEvent>(<any>{ which: Keys.DELETE, ctrlKey: true, preventDefault, }), }); expect(undo).not.toHaveBeenCalled(); expect(preventDefault).not.toHaveBeenCalled(); expect(state.autoCompletePosition).toBeNull(); expect(state.snapshotsService.canUndoAutoComplete()).toBeFalse(); }); it('Position changed, cannot undo autocomplete for Backspace', () => { state.snapshotsService.addSnapshot({ html: 'snapshot 1', metadata: null }, false); const undo = jasmine.createSpy('undo'); const preventDefault = jasmine.createSpy('preventDefault'); const range = document.createRange(); const pos = Position.getStart(range); editor.undo = undo; editor.getSelectionRange = () => range; const pos2 = new Position(pos); (<any>pos2).offset++; // hack, just want to make pos2 different from pos editor.getFocusedPosition = () => pos2; editor.addUndoSnapshot = () => state.snapshotsService.addSnapshot({ html: 'snapshot 4', metadata: null }, false); // Press backspace first time, to let plugin remember last pressed key plugin.onPluginEvent({ eventType: PluginEventType.KeyDown, rawEvent: <KeyboardEvent>(<any>{ which: Keys.BACKSPACE, preventDefault, }), }); state.snapshotsService.addSnapshot({ html: 'snapshot 2', metadata: null }, true); state.snapshotsService.addSnapshot({ html: 'snapshot 3', metadata: null }, false); state.autoCompletePosition = pos; plugin.onPluginEvent({ eventType: PluginEventType.KeyDown, rawEvent: <KeyboardEvent>(<any>{ which: Keys.BACKSPACE, preventDefault, }), }); expect(undo).not.toHaveBeenCalled(); expect(preventDefault).not.toHaveBeenCalled(); expect(state.autoCompletePosition).not.toBeNull(); expect(state.snapshotsService.canUndoAutoComplete()).toBeTrue(); }); it('Pass in undoSnapshotService<string>', () => { const canMove = jasmine.createSpy('canMove').and.returnValue(true); const move = jasmine.createSpy('move').and.returnValue('test'); const addSnapshot = jasmine.createSpy('addSnapshot'); const clearRedo = jasmine.createSpy('clearRedo'); const canUndoAutoComplete = jasmine.createSpy('canUndoAutoComplete').and.returnValue(true); const plugin = new UndoPlugin({ undoSnapshotService: { canMove, move, addSnapshot, clearRedo, canUndoAutoComplete }, }); const state = plugin.getState(); const canMoveResult = state.snapshotsService.canMove(1); const moveResult = state.snapshotsService.move(2); state.snapshotsService.addSnapshot( { html: 'test', metadata: { type: SelectionRangeTypes.Normal, isDarkMode: false, start: [1], end: [2], }, }, false ); state.snapshotsService.clearRedo(); const canUndoAutoCompleteResult = state.snapshotsService.canUndoAutoComplete(); expect(canMove).toHaveBeenCalledWith(1); expect(move).toHaveBeenCalledWith(2); expect(addSnapshot).toHaveBeenCalledWith( 'test<!--{"type":0,"isDarkMode":false,"start":[1],"end":[2]}-->', false ); expect(clearRedo).toHaveBeenCalled(); expect(canUndoAutoComplete).toHaveBeenCalled(); expect(canMoveResult).toBe(true); expect(moveResult).toEqual({ html: 'test', metadata: null }); expect(canUndoAutoCompleteResult).toBe(true); }); it('Pass in undoSnapshotService<Snapshot>', () => { const snapshot = <any>{ html: 'test', metadata: { type: SelectionRangeTypes.Normal, isDarkMode: false, start: [1], end: [2], }, }; const canMove = jasmine.createSpy('canMove').and.returnValue(true); const move = jasmine.createSpy('move').and.returnValue(snapshot); const addSnapshot = jasmine.createSpy('addSnapshot'); const clearRedo = jasmine.createSpy('clearRedo'); const canUndoAutoComplete = jasmine.createSpy('canUndoAutoComplete').and.returnValue(true); const plugin = new UndoPlugin({ undoMetadataSnapshotService: { canMove, move, addSnapshot, clearRedo, canUndoAutoComplete, }, }); const state = plugin.getState(); const canMoveResult = state.snapshotsService.canMove(1); const moveResult = state.snapshotsService.move(2); state.snapshotsService.addSnapshot(snapshot, false); state.snapshotsService.clearRedo(); const canUndoAutoCompleteResult = state.snapshotsService.canUndoAutoComplete(); expect(canMove).toHaveBeenCalledWith(1); expect(move).toHaveBeenCalledWith(2); expect(addSnapshot).toHaveBeenCalledWith(snapshot, false); expect(clearRedo).toHaveBeenCalled(); expect(canUndoAutoComplete).toHaveBeenCalled(); expect(canMoveResult).toBe(true); expect(moveResult).toEqual(snapshot); expect(canUndoAutoCompleteResult).toBe(true); }); it('Pass in undoSnapshotService<Snapshot> and undoSnapshotService<string>', () => { const snapshot = <any>{ html: 'test', metadata: { type: SelectionRangeTypes.Normal, isDarkMode: false, start: [1], end: [2], }, }; const canMove1 = jasmine.createSpy('canMove'); const move1 = jasmine.createSpy('move'); const addSnapshot1 = jasmine.createSpy('addSnapshot'); const clearRedo1 = jasmine.createSpy('clearRedo'); const canUndoAutoComplete1 = jasmine.createSpy('canUndoAutoComplete'); const canMove2 = jasmine.createSpy('canMove'); const move2 = jasmine.createSpy('move'); const addSnapshot2 = jasmine.createSpy('addSnapshot'); const clearRedo2 = jasmine.createSpy('clearRedo'); const canUndoAutoComplete2 = jasmine.createSpy('canUndoAutoComplete'); const plugin = new UndoPlugin({ undoMetadataSnapshotService: { canMove: canMove1, move: move1, addSnapshot: addSnapshot1, clearRedo: clearRedo1, canUndoAutoComplete: canUndoAutoComplete1, }, undoSnapshotService: { canMove: canMove2, move: move2, addSnapshot: addSnapshot2, clearRedo: clearRedo2, canUndoAutoComplete: canUndoAutoComplete2, }, }); const state = plugin.getState(); state.snapshotsService.canMove(1); state.snapshotsService.move(2); state.snapshotsService.addSnapshot(snapshot, false); state.snapshotsService.clearRedo(); state.snapshotsService.canUndoAutoComplete(); expect(canMove1).toHaveBeenCalled(); expect(move1).toHaveBeenCalled(); expect(addSnapshot1).toHaveBeenCalled(); expect(clearRedo1).toHaveBeenCalled(); expect(canUndoAutoComplete1).toHaveBeenCalled(); expect(canMove2).not.toHaveBeenCalled(); expect(move2).not.toHaveBeenCalled(); expect(addSnapshot2).not.toHaveBeenCalled(); expect(clearRedo2).not.toHaveBeenCalled(); expect(canUndoAutoComplete2).not.toHaveBeenCalled(); }); });
the_stack
import { HtmlTag } from "../src/html-tag"; describe( "Autolinker.HtmlTag", function() { it( "should be able to be instantiated with no arguments", function() { expect( function() { let tag = new HtmlTag(); } ).not.toThrow(); } ); it( "should be able to be configured via the config options", function() { let tag = new HtmlTag( { tagName : 'a', attrs : { attr1: 'value1', attr2: 'value2' }, innerHtml : "Hello" } ); expect( tag.getTagName() ).toBe( 'a' ); expect( tag.getAttrs() ).toEqual( { attr1: 'value1', attr2: 'value2' } ); expect( tag.getInnerHtml() ).toBe( "Hello" ); } ); it( "should be able to be configured via setters", function() { let tag = new HtmlTag(); tag.setTagName( 'a' ); tag.setAttrs( { attr1: 'value1', attr2: 'value2' } ); tag.setInnerHtml( "Hello" ); expect( tag.getTagName() ).toBe( 'a' ); expect( tag.getAttrs() ).toEqual( { attr1: 'value1', attr2: 'value2' } ); expect( tag.getInnerHtml() ).toBe( "Hello" ); } ); describe( 'setTagName()', function() { it( "should set, and override, the tag name", function() { let tag = new HtmlTag(); tag.setTagName( 'a' ); expect( tag.getTagName() ).toBe( 'a' ); tag.setTagName( 'button' ); expect( tag.getTagName() ).toBe( 'button' ); } ); it( "should return a reference to the HtmlTag instance, to allow method chaining", function() { let tag = new HtmlTag(); expect( tag.setTagName( 'a' ) ).toBe( tag ); // return value should be the HtmlTag itself } ); } ); describe( 'setAttr()', function() { it( "should set, then override, attribute properties", function() { let tag = new HtmlTag(); tag.setAttr( 'attr1', 'value1' ); // note: this call should lazily instantiate the `attrs` map tag.setAttr( 'attr2', 'value2' ); expect( tag.getAttrs() ).toEqual( { attr1: 'value1', attr2: 'value2' } ); tag.setAttr( 'attr1', '42' ); expect( tag.getAttrs() ).toEqual( { attr1: '42', attr2: 'value2' } ); } ); it( "should return a reference to the HtmlTag instance, to allow method chaining", function() { let tag = new HtmlTag(); expect( tag.setAttr( 'href', 'test' ) ).toBe( tag ); // return value should be the HtmlTag itself } ); } ); describe( 'setAttrs()', function() { it( "should set, then override, attribute properties", function() { let tag = new HtmlTag(); tag.setAttrs( { attr1: 'value1', attr2: 'value2' } ); // note: this call should lazily instantiate the `attrs` map expect( tag.getAttrs() ).toEqual( { attr1: 'value1', attr2: 'value2' } ); tag.setAttrs( { attr1: '42' } ); expect( tag.getAttrs() ).toEqual( { attr1: '42', attr2: 'value2' } ); } ); it( "should return a reference to the HtmlTag instance, to allow method chaining", function() { let tag = new HtmlTag(); expect( tag.setAttrs( { 'href': 'test' } ) ).toBe( tag ); // return value should be the HtmlTag itself } ); } ); describe( 'setClass()', function() { let tag: HtmlTag; beforeEach( function() { tag = new HtmlTag(); } ); it( "should set the CSS class to the tag when there are none yet", function() { tag.setClass( 'test' ); expect( tag.getClass() ).toBe( 'test' ); } ); it( "should overwrite the current CSS classes on the tag", function() { tag.setClass( 'test' ); tag.setClass( 'test_override' ); expect( tag.getClass() ).toBe( 'test_override' ); } ); it( "should return a reference to the HtmlTag instance, to allow method chaining", function() { expect( tag.setClass( 'test' ) ).toBe( tag ); // return value should be the HtmlTag itself } ); } ); describe( 'addClass()', function() { let tag: HtmlTag; beforeEach( function() { tag = new HtmlTag(); } ); it( "should add a CSS class to the tag when there are none yet", function() { tag.addClass( 'test' ); expect( tag.getClass() ).toBe( 'test' ); } ); it( "should add multiple CSS classes to the tag when there are none yet", function() { tag.addClass( 'test1 test2' ); expect( tag.getClass() ).toBe( 'test1 test2' ); } ); it( "should add a CSS class to existing CSS classes", function() { tag.addClass( 'test1' ); tag.addClass( 'test2' ); expect( tag.getClass() ).toBe( 'test1 test2' ); } ); it( "should add multiple CSS classes to existing CSS classes", function() { tag.addClass( 'test1 test2' ); tag.addClass( 'test3 test4' ); expect( tag.getClass() ).toBe( 'test1 test2 test3 test4' ); } ); it( "should not add duplicate CSS classes to the tag", function() { tag.addClass( 'test1 test2' ); tag.addClass( 'test1 test3 test4 test4' ); expect( tag.getClass() ).toBe( 'test1 test2 test3 test4' ); } ); it( "should return a reference to the HtmlTag instance, to allow method chaining", function() { expect( tag.addClass( 'test' ) ).toBe( tag ); // return value should be the HtmlTag itself } ); } ); describe( 'removeClass()', function() { let tag: HtmlTag; beforeEach( function() { tag = new HtmlTag(); } ); it( "should have no effect when removing a CSS class from an HtmlTag with no CSS classes", function() { expect( function() { tag.removeClass( 'test' ); // simply make sure an error isn't thrown } ).not.toThrow(); } ); it( "should remove a single CSS class from the HtmlTag", function() { tag.addClass( 'test1 test2 test3 test4' ); tag.removeClass( 'test1' ); expect( tag.getClass() ).toBe( 'test2 test3 test4' ); } ); it( "should remove multiple CSS classes from the HtmlTag", function() { tag.addClass( 'test1 test2 test3 test4' ); tag.removeClass( 'test1 test3' ); expect( tag.getClass() ).toBe( 'test2 test4' ); } ); it( "should return a reference to the HtmlTag instance, to allow method chaining", function() { expect( tag.removeClass( 'test' ) ).toBe( tag ); // return value should be the HtmlTag itself } ); } ); describe( 'getClass()', function() { it( "should return an empty string when there are no CSS classes on the HtmlTag", function() { let tag = new HtmlTag(); expect( tag.getClass() ).toBe( "" ); } ); it( "should return the CSS classes configured on the HtmlTag", function() { let tag = new HtmlTag( { attrs: { 'class': "test1 test2" } } ); expect( tag.getClass() ).toBe( "test1 test2" ); } ); it( "should return the CSS classes set using addClass()", function() { let tag = new HtmlTag(); tag.addClass( "test1 test2" ); expect( tag.getClass() ).toBe( "test1 test2" ); } ); } ); describe( 'hasClass()', function() { let tag: HtmlTag; beforeEach( function() { tag = new HtmlTag(); } ); it( "should return `false` when there are no CSS classes on the HtmlTag", function() { expect( tag.hasClass( 'test' ) ).toBe( false ); } ); it( "should return `true` for a CSS class that exists on the HtmlTag", function() { tag.addClass( 'test' ); expect( tag.hasClass( 'test' ) ).toBe( true ); } ); it( "should return `true` for a CSS class that exists on the HtmlTag, when there are multiple CSS classes", function() { tag.addClass( 'test1 test2' ); expect( tag.hasClass( 'test1' ) ).toBe( true ); expect( tag.hasClass( 'test2' ) ).toBe( true ); expect( tag.hasClass( 'test3' ) ).toBe( false ); } ); it( "should return `false` for a CSS class that is a substring of a CSS class on the HtmlTag", function() { tag.addClass( 'longCssClass' ); expect( tag.hasClass( 'longCss' ) ).toBe( false ); } ); } ); describe( 'setInnerHtml()', function() { it( "should set, then override, the tag's inner HTML", function() { let tag = new HtmlTag(); tag.setInnerHtml( "test" ); expect( tag.getInnerHtml() ).toBe( "test" ); tag.setInnerHtml( "test2" ); expect( tag.getInnerHtml() ).toBe( "test2" ); } ); it( "should return a reference to the HtmlTag instance, to allow method chaining", function() { let tag = new HtmlTag(); expect( tag.setInnerHtml( "test" ) ).toBe( tag ); // return value should be the HtmlTag itself } ); } ); describe( 'getInnerHtml()', function() { it( "should return an empty string if no inner HTML has been set", function() { let tag = new HtmlTag(); expect( tag.getInnerHtml() ).toBe( "" ); } ); it( "should return the inner HTML set during construction", function() { let tag = new HtmlTag( { innerHtml: "test" } ); expect( tag.getInnerHtml() ).toBe( "test" ); } ); it( "should return the inner HTML set with setInnerHtml()", function() { let tag = new HtmlTag(); tag.setInnerHtml( "test" ); expect( tag.getInnerHtml() ).toBe( "test" ); } ); } ); describe( 'toAnchorString()', function() { it( "should populate only the tag name when no attribute are set, and no inner HTML is set", function() { let tag = new HtmlTag( { tagName : 'a' } ); expect( tag.toAnchorString() ).toBe( '<a></a>' ); } ); it( "should populate only the tag name and inner HTML when no attribute are set", function() { let tag = new HtmlTag( { tagName : 'a', innerHtml : "My Site" } ); expect( tag.toAnchorString() ).toBe( '<a>My Site</a>' ); } ); it( "should populate both the tag name and attributes when set", function() { let tag = new HtmlTag( { tagName : 'a', attrs : { href: 'http://path/to/site', rel: 'nofollow' } } ); expect( tag.toAnchorString() ).toBe( '<a href="http://path/to/site" rel="nofollow"></a>' ); } ); it( "should populate all 3: tag name, attributes, and inner HTML when set", function() { let tag = new HtmlTag( { tagName : 'a', attrs : { href: 'http://path/to/site', rel: 'nofollow' }, innerHtml : "My Site" } ); expect( tag.toAnchorString() ).toBe( '<a href="http://path/to/site" rel="nofollow">My Site</a>' ); } ); it( "should properly build an HTML string from just the mutator methods", function() { let tag = new HtmlTag(); tag.setTagName( 'a' ); tag.addClass( 'test' ); tag.addClass( 'test2' ); tag.setAttr( 'href', 'http://path/to/site' ); tag.setInnerHtml( 'My Site' ); expect( tag.toAnchorString() ).toBe( '<a class="test test2" href="http://path/to/site">My Site</a>' ); } ); } ); } );
the_stack
import type {ReactElement, ReactNode} from 'react'; import type {ScaleContinuousNumeric} from 'd3-scale'; import type {SymbolType} from 'd3-shape'; import type {ColorScale, GraphicProps, Point, Series, Style} from './types'; import React from 'react'; import { symbol, symbolCircle, symbolCross, symbolDiamond, symbolSquare, symbolWye, symbolTriangle, symbolStar, } from 'd3-shape'; import {colorFunc, defaultSchemeName, isFunction, isString, value} from './helpers'; const symbolsMap = { 'circle': symbolCircle, 'cross': symbolCross, 'diamond': symbolDiamond, 'square': symbolSquare, 'triangle-down': symbolWye, 'triangle-up': symbolTriangle, 'star': symbolStar }; const methods = { dots: renderCircle, dot: renderCircle, circles: renderCircle, circle: renderCircle, ellipses: renderEllipse, ellipse: renderEllipse, symbols: renderSymbol, symbol: renderSymbol, labels: renderLabel, label: renderLabel, path: renderPath }; type DotType = keyof typeof methods; type DotSymbolType = keyof typeof symbolsMap | SymbolType; export type DotParams = { seriesIndex: number; pointIndex: number; point: Point; series: Series; props: DotsProps; }; export type DotSeriesParams = { seriesIndex: number; series: Series; props: DotsProps; }; export type DotTypeParams = DotParams & { dotType: DotType | DotType[] }; export type DotRenderProps = { key?: string | number; seriesIndex: number; pointIndex: number; point: Point; dotStyle: Style; dotAttributes: Record<string, any>; props: DotsProps; color: ColorScale; }; export type DotsProps = { /** * Possible values: `"dot"`, `"circle"`, `"ellipse"`, `"symbol"`, `"label"`, `"path"`. */ dotType?: DotType | DotType[] | ((params: DotParams) => DotType | DotType[]); dotRender?: (props: DotRenderProps) => ReactNode; circleRadius?: number | string | ((params: DotParams) => number | string); circleAttributes?: Record<string, any> | ((params: DotParams) => Record<string, any>); ellipseRadiusX?: number | string | ((params: DotParams) => number | string); ellipseRadiusY?: number | string | ((params: DotParams) => number | string); ellipseAttributes?: Record<string, any> | ((params: DotParams) => Record<string, any>); /** * Possible values: `"circle"`, `"cross"`, `"diamond"`, `"square"`, * `"triangle-down"`, `"triangle-up"` */ symbolType?: DotSymbolType | ((params: DotParams) => DotSymbolType); symbolAttributes?: Record<string, any> | ((params: DotParams) => Record<string, any>); label?: ReactNode | ((params: DotParams) => ReactNode); labelAttributes?: Record<string, any> | ((params: DotParams) => Record<string, any>); path?: string | ((params: DotParams) => string); pathAttributes?: Record<string, any> | ((params: DotParams) => Record<string, any>); seriesVisible?: boolean | ((params: DotSeriesParams) => boolean); seriesAttributes?: Record<string, any> | ((params: DotSeriesParams) => Record<string, any>); seriesStyle?: Style | ((params: DotSeriesParams) => Style); groupStyle?: Style | ((params: DotParams) => Style); dotVisible?: boolean | ((params: DotParams) => boolean); dotAttributes?: Record<string, any> | ((params: DotTypeParams) => Record<string, any>); dotStyle?: Style | ((params: DotTypeParams) => Style); } & GraphicProps; /** * Renders dots for your scatter plot. */ export function Dots(props: DotsProps): ReactElement { const {className, scaleX, scaleY, colors = defaultSchemeName} = props; const x = scaleX.factory(props); const y = scaleY.factory(props); const rotate = scaleX.swap || scaleY.swap; const color = colorFunc(colors); return <g className={className} style={props.style} opacity={props.opacity}> {props.series?.map((series, index) => { if ('seriesVisible' in props) { const seriesVisible = value(props.seriesVisible, {seriesIndex: index, series, props}); if (!seriesVisible) { return; } } const seriesAttributes = value(props.seriesAttributes, {seriesIndex: index, series, props}); const seriesStyle = value(props.seriesStyle, {seriesIndex: index, series, props}); return <g key={index} className={className && (className + '-series ' + className + '-series-' + index)} style={seriesStyle} opacity={series.opacity} {...seriesAttributes}> {series.data.map((point: Point, pointIndex) => { if (rotate) { return renderDot(props, color, y(point.y), x(point.x), index, pointIndex, point); } else { return renderDot(props, color, x(point.x), y(point.y), index, pointIndex, point); } })} </g>; })} </g>; } function renderDot( props: DotsProps, color: ColorScale, x: ScaleContinuousNumeric<any, any>, y: ScaleContinuousNumeric<any, any>, seriesIndex: number, pointIndex: number, point: Point ): ReactNode { const {className, dotType = 'circles'} = props; const series = props.series[seriesIndex]; if ('dotVisible' in props) { const dotVisible = value(props.dotVisible, {seriesIndex, pointIndex, point, series, props}); if (!dotVisible) { return; } } const groupStyle = value(props.groupStyle, {seriesIndex, pointIndex, point, series, props}); const _dotType: DotType | DotType[] = value([dotType], { seriesIndex, pointIndex, point, series, props }); const dotAttributes = value(props.dotAttributes, { seriesIndex, pointIndex, point, dotType: _dotType, series, props }); const dotStyle = value([point.style, series.style, props.dotStyle], { seriesIndex, pointIndex, point, dotType: _dotType, series, props }); let dot: ReactNode; if (isFunction(props.dotRender)) { dot = props.dotRender({seriesIndex, pointIndex, point, dotStyle, dotAttributes, props, color}); } else { if (isString(_dotType)) { dot = methods[_dotType] && methods[_dotType]({ seriesIndex, pointIndex, point, dotStyle, dotAttributes, props, color }); } else if (Array.isArray(_dotType)) { dot = _dotType.map((_dotType, key) => { return methods[_dotType]({ key, seriesIndex, pointIndex, point, dotStyle, dotAttributes, props, color }); }); } else { dot = null; } } return <g key={pointIndex} className={className && (`${className}-dot ${className}-dot-${pointIndex}`)} transform={`translate(${x} ${y})`} style={groupStyle}> {dot} </g>; } function renderCircle({key, seriesIndex, pointIndex, point, dotStyle, dotAttributes, props, color}: DotRenderProps) { const {className} = props; const series = props.series[seriesIndex]; const {circleRadius = 4} = props; const _circleRadius = value(circleRadius, {seriesIndex, pointIndex, point, series, props}); const circleAttributes = value(props.circleAttributes, {seriesIndex, pointIndex, point, series, props}); return <circle key={key} className={className && (`${className}-circle ${className}-circle-${seriesIndex}-${pointIndex}`)} cx={0} cy={0} r={_circleRadius} style={dotStyle} fill={point.color || series.color || color(seriesIndex)} fillOpacity={point.opacity} {...dotAttributes} {...circleAttributes} />; } function renderEllipse({key, seriesIndex, pointIndex, point, dotStyle, dotAttributes, props, color}: DotRenderProps) { const {className} = props; const series = props.series[seriesIndex]; const {ellipseRadiusX = 6, ellipseRadiusY = 4} = props; const _ellipseRadiusX = value(ellipseRadiusX, {seriesIndex, pointIndex, point, series, props}); const _ellipseRadiusY = value(ellipseRadiusY, {seriesIndex, pointIndex, point, series, props}); const ellipseAttributes = value(props.ellipseAttributes, {seriesIndex, pointIndex, point, series, props}); return <ellipse key={key} className={className && (className + '-ellipse ' + className + '-ellipse-' + seriesIndex + '-' + pointIndex)} cx={0} cy={0} rx={_ellipseRadiusX} ry={_ellipseRadiusY} style={dotStyle} fill={point.color || series.color || color(seriesIndex)} fillOpacity={point.opacity} {...dotAttributes} {...ellipseAttributes} />; } function renderPath({key, seriesIndex, pointIndex, point, dotStyle, dotAttributes, props, color}: DotRenderProps) { const {className} = props; const series = props.series[seriesIndex]; const path = value(props.path, {seriesIndex, pointIndex, point, series, props}); const pathAttributes = value(props.pathAttributes, {seriesIndex, pointIndex, point, series, props}); return <path key={key} className={className && (className + '-path ' + className + '-path-' + seriesIndex + '-' + pointIndex)} d={path} style={dotStyle} fill={point.color || series.color || color(seriesIndex)} fillOpacity={point.opacity} {...dotAttributes} {...pathAttributes} />; } function renderSymbol({key, seriesIndex, pointIndex, point, dotStyle, dotAttributes, props, color}: DotRenderProps) { const {className} = props; const series = props.series[seriesIndex]; const symbolType = value(props.symbolType, {seriesIndex, pointIndex, point, series, props}); const symbolAttributes = value(props.symbolAttributes, {seriesIndex, pointIndex, point, series, props}); const type = isString(symbolType) ? symbolsMap[symbolType] : symbolType; return <path key={key} className={className && (className + '-symbol ' + className + '-symbol-' + seriesIndex + '-' + pointIndex)} d={symbol().type(type)(point, pointIndex)} style={dotStyle} fill={point.color || series.color || color(seriesIndex)} fillOpacity={point.opacity} {...dotAttributes} {...symbolAttributes} />; } function renderLabel({key, seriesIndex, pointIndex, point, dotStyle, dotAttributes, props, color}: DotRenderProps) { const {className} = props; const series = props.series[seriesIndex]; const label = value(props.label, {seriesIndex, pointIndex, point, series, props}); const labelAttributes = value(props.labelAttributes, {seriesIndex, pointIndex, point, series, props}); return <text key={key} className={className && (className + '-label ' + className + '-label-' + seriesIndex + '-' + pointIndex)} style={dotStyle} fill={point.color || series.color || color(seriesIndex)} fillOpacity={point.opacity} {...dotAttributes} {...labelAttributes}> {label} </text>; }
the_stack
import * as React from 'react' import { useSelector } from 'react-redux' import { Flex, Box, Icon, Text, SecondaryBtn, Tooltip, useHoverTooltip, COLOR_ERROR, SIZE_2, SIZE_3, SPACING_1, SPACING_2, SPACING_3, ALIGN_CENTER, DIRECTION_COLUMN, JUSTIFY_START, JUSTIFY_CENTER, FONT_SIZE_BODY_1, FONT_SIZE_CAPTION, FONT_WEIGHT_SEMIBOLD, FONT_STYLE_ITALIC, TEXT_TRANSFORM_CAPITALIZE, OVERLAY_LIGHT_GRAY_50, } from '@opentrons/components' import * as Config from '../../../redux/config' import * as CustomLabware from '../../../redux/custom-labware' import { getCalibrationForPipette, getTipLengthForPipetteAndTiprack, } from '../../../redux/calibration' import { useCalibratePipetteOffset } from '../../../organisms/CalibratePipetteOffset/useCalibratePipetteOffset' import { InlineCalibrationWarning } from '../../../molecules/InlineCalibrationWarning' import { AskForCalibrationBlockModal } from '../../../organisms/CalibrateTipLength/AskForCalibrationBlockModal' import { INTENT_RECALIBRATE_PIPETTE_OFFSET, INTENT_TIP_LENGTH_OUTSIDE_PROTOCOL, } from '../../../organisms/CalibrationPanels' import { formatLastModified } from '../../../organisms/CalibrationPanels/utils' import { Portal } from '../../../App/portal' import { getDisplayNameForTipRack } from './utils' import type { Mount } from '../../../redux/pipettes/types' import type { State } from '../../../redux/types' // TODO: BC(2021-02-16): i18n const NO_PIPETTE_ATTACHED = 'No pipette attached' const PIPETTE_OFFSET_MISSING = 'Pipette offset calibration missing.' const CALIBRATE_NOW = 'Please calibrate offset now.' const CALIBRATE_OFFSET = 'Calibrate pipette offset' const RECALIBRATE_OFFSET = 'Recalibrate pipette offset' const RECALIBRATE_TIP = 'recalibrate tip length' const PIPETTE_OFFSET_CALIBRATION = 'pipette offset calibration' const TIP_LENGTH_CALIBRATION = 'tip length calibration' const TIP_NOT_CALIBRATED_BODY = "You will calibrate this tip length when you calibrate this pipette's offset." const LAST_CALIBRATED = 'Last calibrated' const TLC_INVALIDATES_POC_WARNING = 'If you recalibrate this tip length, you will need to recalibrate your pipette offset afterwards' const CAL_BLOCK_MODAL_CLOSED: 'cal_block_modal_closed' = 'cal_block_modal_closed' const CAL_BLOCK_MODAL_OPEN_WITH_REDO_TLC: 'cal_block_modal_redo' = 'cal_block_modal_redo' const CAL_BLOCK_MODAL_OPEN_WITH_KEEP_TLC: 'cal_block_modal_keep' = 'cal_block_modal_keep' type CalBlockModalState = | typeof CAL_BLOCK_MODAL_CLOSED | typeof CAL_BLOCK_MODAL_OPEN_WITH_REDO_TLC | typeof CAL_BLOCK_MODAL_OPEN_WITH_KEEP_TLC interface Props { robotName: string serialNumber: string | null mount: Mount disabledReason: string | null isChangingOrConfiguringPipette: boolean } export function PipetteCalibrationInfo(props: Props): JSX.Element { const { robotName, serialNumber, mount, disabledReason, isChangingOrConfiguringPipette, } = props const [tlcTargetProps, tlcTooltipProps] = useHoverTooltip() const [pocTargetProps, pocTooltipProps] = useHoverTooltip() const pipetteOffsetCalibration = useSelector((state: State) => serialNumber ? getCalibrationForPipette(state, robotName, serialNumber, mount) : null ) const tipLengthCalibration = useSelector((state: State) => serialNumber && pipetteOffsetCalibration ? getTipLengthForPipetteAndTiprack( state, robotName, serialNumber, pipetteOffsetCalibration?.tiprack ) : null ) const customLabwareDefs = useSelector((state: State) => { return CustomLabware.getCustomLabwareDefinitions(state) }) const [ startPipetteOffsetCalibration, PipetteOffsetCalibrationWizard, ] = useCalibratePipetteOffset(robotName, { mount }) const configHasCalibrationBlock = useSelector(Config.getHasCalibrationBlock) const [ calBlockModalState, setCalBlockModalState, ] = React.useState<CalBlockModalState>(CAL_BLOCK_MODAL_CLOSED) interface StartWizardOptions { keepTipLength: boolean hasBlockModalResponse?: boolean | null } const startPipetteOffsetPossibleTLC = (options: StartWizardOptions): void => { const { keepTipLength, hasBlockModalResponse = null } = options if (hasBlockModalResponse === null && configHasCalibrationBlock === null) { setCalBlockModalState( keepTipLength ? CAL_BLOCK_MODAL_OPEN_WITH_KEEP_TLC : CAL_BLOCK_MODAL_OPEN_WITH_REDO_TLC ) } else { startPipetteOffsetCalibration({ overrideParams: { hasCalibrationBlock: Boolean( configHasCalibrationBlock ?? hasBlockModalResponse ), shouldRecalibrateTipLength: !keepTipLength, }, withIntent: keepTipLength ? INTENT_RECALIBRATE_PIPETTE_OFFSET : INTENT_TIP_LENGTH_OUTSIDE_PROTOCOL, }) setCalBlockModalState(CAL_BLOCK_MODAL_CLOSED) } } if (!serialNumber) { return ( <Flex backgroundColor={OVERLAY_LIGHT_GRAY_50} justifyContent={JUSTIFY_CENTER} alignItems={ALIGN_CENTER} flex="1 1 auto" fontStyle={FONT_STYLE_ITALIC} fontSize={FONT_SIZE_CAPTION} minHeight={SIZE_3} > {NO_PIPETTE_ATTACHED} </Flex> ) } return ( <Flex flexDirection={DIRECTION_COLUMN} backgroundColor={OVERLAY_LIGHT_GRAY_50} padding={SPACING_3} flex="1 1 auto" > <Text fontWeight={FONT_WEIGHT_SEMIBOLD} fontSize={FONT_SIZE_BODY_1} textTransform={TEXT_TRANSFORM_CAPITALIZE} marginBottom={SPACING_2} > {PIPETTE_OFFSET_CALIBRATION} </Text> {pipetteOffsetCalibration ? ( <> {pipetteOffsetCalibration.status.markedBad && ( <InlineCalibrationWarning warningType="recommended" marginTop={0} marginBottom={SPACING_2} /> )} <Text fontStyle={FONT_STYLE_ITALIC} fontSize={FONT_SIZE_CAPTION} marginBottom={SPACING_2} > {`${LAST_CALIBRATED}: ${formatLastModified( pipetteOffsetCalibration.lastModified )}`} </Text> </> ) : ( <Flex marginBottom={SPACING_2} alignItems={ALIGN_CENTER} justifyContent={JUSTIFY_START} > <Box size={SIZE_2} paddingRight={SPACING_2} paddingY={SPACING_1}> <Icon name="alert-circle" color={COLOR_ERROR} /> </Box> <Flex marginLeft={SPACING_1} flexDirection={DIRECTION_COLUMN} justifyContent={JUSTIFY_START} > <Text fontSize={FONT_SIZE_BODY_1} color={COLOR_ERROR}> {PIPETTE_OFFSET_MISSING} </Text> <Text fontSize={FONT_SIZE_BODY_1} color={COLOR_ERROR}> {CALIBRATE_NOW} </Text> </Flex> </Flex> )} <SecondaryBtn {...pocTargetProps} title="pipetteOffsetCalButton" onClick={ pipetteOffsetCalibration ? () => startPipetteOffsetCalibration({ withIntent: INTENT_RECALIBRATE_PIPETTE_OFFSET, }) : () => startPipetteOffsetPossibleTLC({ keepTipLength: true }) } // @ts-expect-error TODO: SecondaryBtn expects disabled to be explicit boolean type, cast here? disabled={disabledReason} width="15rem" paddingX={SPACING_2} marginBottom={SPACING_1} > {pipetteOffsetCalibration ? RECALIBRATE_OFFSET : CALIBRATE_OFFSET} </SecondaryBtn> <Text fontWeight={FONT_WEIGHT_SEMIBOLD} fontSize={FONT_SIZE_BODY_1} textTransform={TEXT_TRANSFORM_CAPITALIZE} margin={`${SPACING_3} 0 ${SPACING_2}`} > {TIP_LENGTH_CALIBRATION} </Text> {pipetteOffsetCalibration && ( <Text marginBottom={SPACING_2} fontSize={FONT_SIZE_BODY_1}> {getDisplayNameForTipRack( pipetteOffsetCalibration.tiprackUri, customLabwareDefs )} </Text> )} {pipetteOffsetCalibration && tipLengthCalibration ? ( <> <Text marginBottom={SPACING_2} fontStyle={FONT_STYLE_ITALIC} fontSize={FONT_SIZE_CAPTION} > {`${LAST_CALIBRATED}: ${formatLastModified( tipLengthCalibration.lastModified )}`} </Text> {tipLengthCalibration.status.markedBad && ( <InlineCalibrationWarning warningType="recommended" /> )} <SecondaryBtn {...tlcTargetProps} title="recalibrateTipButton" onClick={() => startPipetteOffsetPossibleTLC({ keepTipLength: false }) } // @ts-expect-error TODO: SecondaryBtn expects disabled to be explicit boolean type, cast here? disabled={disabledReason} width="15rem" paddingX={SPACING_2} > {RECALIBRATE_TIP} </SecondaryBtn> <Text marginTop={SPACING_3} fontStyle={FONT_STYLE_ITALIC} fontSize={FONT_SIZE_CAPTION} > {TLC_INVALIDATES_POC_WARNING} </Text> </> ) : ( <Text marginTop={SPACING_2} fontStyle={FONT_STYLE_ITALIC} fontSize={FONT_SIZE_BODY_1} > {TIP_NOT_CALIBRATED_BODY} </Text> )} {!isChangingOrConfiguringPipette && PipetteOffsetCalibrationWizard} {calBlockModalState !== CAL_BLOCK_MODAL_CLOSED ? ( <Portal level="top"> <AskForCalibrationBlockModal onResponse={hasBlockModalResponse => { startPipetteOffsetPossibleTLC({ hasBlockModalResponse, keepTipLength: calBlockModalState === CAL_BLOCK_MODAL_OPEN_WITH_KEEP_TLC, }) }} titleBarTitle={PIPETTE_OFFSET_CALIBRATION} closePrompt={() => setCalBlockModalState(CAL_BLOCK_MODAL_CLOSED)} /> </Portal> ) : null} {disabledReason !== null && ( <> <Tooltip {...pocTooltipProps}>{disabledReason}</Tooltip> <Tooltip {...tlcTooltipProps}>{disabledReason}</Tooltip> </> )} </Flex> ) }
the_stack
import * as React from "react"; import { nanoid } from "nanoid"; import { isConfigured, config, Configuration } from "./config"; import { InitialFlagState, MissingConfigurationError, Flags, Input, Outcome, FlagUser, Traits, FlagBag, EvaluationResponseBody, SuccessOutcome, ErrorOutcome, RevalidatingAfterErrorFlagBag, EmptyFlagBag, EvaluatingFlagBag, SucceededFlagBag, RevalidatingAfterSuccessFlagBag, FailedFlagBag, } from "./types"; import { deepEqual, getCookie, serializeVisitorKeyCookie, combineRawFlagsWithDefaultFlags, ObjectMap, has, } from "./utils"; export type { FlagUser, Traits, Flags, MissingConfigurationError, InitialFlagState, Input, Outcome, FlagBag, } from "./types"; type Id = number; let getId = (() => { let id = 0; return (): Id => id++; })(); type Pending = { id: Id; // null in case the browser doesn't support it controller: AbortController | null; }; type State<F extends Flags> = // "empty" is an initial state candidate for csr | { name: "empty"; input?: never; outcome?: never; cachedOutcome?: never; pending?: never; } | { name: "evaluating"; input: Input; outcome?: never; cachedOutcome: SuccessOutcome<F> | null; pending: Pending | null; } // "succeeded" is an initial state candidate for ssr | { name: "succeeded"; input: Input; outcome: SuccessOutcome<F>; cachedOutcome?: never; pending?: never; } | { name: "revalidating-after-success"; input: Input; // the previous outcome outcome: SuccessOutcome<F>; cachedOutcome?: never; pending: Pending | null; } // "failed" is an initial state candidate for ssr | { name: "failed"; input: Input; outcome: ErrorOutcome; cachedOutcome: SuccessOutcome<F> | null; pending?: never; } | { name: "revalidating-after-failure"; input: Input; // the previous outcome outcome: ErrorOutcome; cachedOutcome: SuccessOutcome<F> | null; pending: Pending | null; }; type Action<F extends Flags> = // evaluate is for new inputs; the data and error get cleared | { type: "evaluate"; input: Input } // revalidate is for the same inputs; the data and error aren't cleared // it generally revalidates the same input, except for ssg when initial state // is passed in | { type: "revalidate"; input?: Input } | { type: "settle/success"; id: Id; input: Input; outcome: SuccessOutcome<F>; } | { type: "settle/failure"; id: Id; input: Input; outcome: ErrorOutcome; thrownError: any; }; type Effect = | { effect: "fetch"; input: Input; id: Id; controller: AbortController | null; } // revalidate generally revalidates the same input, except for ssg when // initial state is passed in | { effect: "revalidate-input"; input?: Input }; /** * Returns new effects and pending state, cancels controller of previous pending * state. * * @param input Next input * @param pending Previous pending state * @returns [Effects to execute, Next pending state] */ function createFetchEffects<F extends Flags>( input: Input, pending?: Pending | null ): [Effect[], Pending] { const id = getId(); const controller = typeof AbortController !== "undefined" ? new AbortController() : null; const fetchEffect: Effect = { effect: "fetch", id, controller, input }; if (pending?.controller) pending.controller.abort(); return [[fetchEffect], { id, controller }]; } function canSettle<F extends Flags>(state: State<F>) { return ( state.name === "evaluating" || state.name === "revalidating-after-success" || state.name === "revalidating-after-failure" ); } /** * The reducer returns a tuple of [state, effects]. * * effects is an array of effects to execute. The emitted effects are then later * executed in another hook. * * This pattern is basically a hand-rolled version of * https://github.com/davidkpiano/useEffectReducer * * We use a hand-rolled version to keep the size of this package minimal. */ function reducer<F extends Flags>( tuple: readonly [State<F>, Effect[]], action: Action<F> ): readonly [State<F>, Effect[]] { const [state /* and effects */] = tuple; switch (action.type) { case "evaluate": { const cachedOutcome = cache.get<SuccessOutcome<F>>(action.input); const [effects, pending] = createFetchEffects<F>( action.input, state.pending ); // action.input will always differ from state.input, because we do not // dispatch "evaluate" otherwise return [ { name: "evaluating", input: action.input, cachedOutcome, pending, }, effects, ]; } case "revalidate": { if (state.name === "empty") return tuple; const input = action.input || state.input; const [effects, pending] = createFetchEffects<F>(input, state.pending); if (state.name === "succeeded") return [ { name: "revalidating-after-success", input: state.input, outcome: state.outcome, cachedOutcome: state.cachedOutcome, pending, }, effects, ]; if (state.name === "failed") return [ { name: "revalidating-after-failure", input: state.input, outcome: state.outcome, cachedOutcome: state.cachedOutcome, pending, }, effects, ]; if (state.name === "evaluating") return [ { name: "evaluating", input: state.input, outcome: state.outcome, cachedOutcome: state.cachedOutcome, pending, }, effects, ]; return tuple; } case "settle/failure": { if (!canSettle(state)) return tuple; // ignore outdated responses if (state.pending?.id !== action.id) return tuple; if (action.thrownError) { console.error("@happykit/flags: Failed to load flags"); console.error(action.thrownError); } const cachedOutcome = cache.get<SuccessOutcome<F>>(action.input); return [ { name: "failed", input: action.input, outcome: action.outcome, cachedOutcome, }, [], ]; } case "settle/success": { if (!canSettle(state)) return tuple; // ignore outdated responses if (state.pending?.id !== action.id) return tuple; const visitorKey = action.outcome.data.visitor?.key; if (visitorKey) document.cookie = serializeVisitorKeyCookie(visitorKey); cache.set(action.input, action.outcome); return [ { name: "succeeded", input: action.input, outcome: action.outcome, }, [], ]; } default: return tuple; } } function getInput<F extends Flags>({ config, visitorKeyInState, generatedVisitorKey, user, traits, }: { config: Configuration<F>; visitorKeyInState: string | null | undefined; generatedVisitorKey: string; user: FlagUser | null; traits: Traits | null; }): Input { const cookie = typeof document !== "undefined" ? getCookie(document.cookie, "hkvk") : null; return { endpoint: config.endpoint, envKey: config.envKey, requestBody: { visitorKey: cookie || visitorKeyInState || generatedVisitorKey, user, traits, }, }; } function omitStaticDifferences(input: Input) { return { ...input, requestBody: { ...input.requestBody, visitorKey: null }, }; } /** * Returns true if the inputs are exactly equal... * * Or in case the current input is static, returns true when they are the same * except for the static properties ("static" and "visitorKey"). */ function isAlmostEqual( currentInput: Input | undefined, nextInput: Input ): boolean { // special treatment when the current input is static // in this case, we ignore the static and visitorKey properties return currentInput && !currentInput.requestBody.visitorKey ? deepEqual( omitStaticDifferences(currentInput), omitStaticDifferences(nextInput) ) : deepEqual(currentInput, nextInput); } let usedTimes = 0; export function useOnce() { React.useEffect(() => { usedTimes++; if (usedTimes > 1) { console.warn( [ "@happykit/flags: Simultaneous invocations of useFlags() detected", "", "See https://happykit.dev/notes/1", ].join("\n") ); } return () => { usedTimes--; }; }, []); } export const cache = new ObjectMap<Input, Outcome<Flags>>(); export type UseFlagsOptions<F extends Flags = Flags> = | { user?: FlagUser | null; traits?: Traits | null; initialState?: InitialFlagState<F>; revalidateOnFocus?: boolean; pause?: boolean; loadingTimeout?: number | false; } | undefined; export function useFlags<F extends Flags = Flags>( options: UseFlagsOptions<F> = {} ): FlagBag<F> { if (!isConfigured(config)) throw new MissingConfigurationError(); useOnce(); const staticConfig = config; const [generatedVisitorKey] = React.useState(nanoid); const currentUser = options.user || null; const currentTraits = options.traits || null; const shouldRevalidateOnFocus = options.revalidateOnFocus === undefined ? config.revalidateOnFocus : options.revalidateOnFocus; const currentLoadingTimeout = has(options, "loadingTimeout") ? options.loadingTimeout : // also account for deprecated loadingTimeout config.clientLoadingTimeout || config.loadingTimeout || 0; const [[state, effects], dispatch] = React.useReducer( reducer, options.initialState, (initialFlagState): [State<F>, Effect[]] => { if (!initialFlagState?.input) return [{ name: "empty" }, []]; const input = getInput({ config: staticConfig, visitorKeyInState: initialFlagState.input.requestBody.visitorKey, generatedVisitorKey, user: currentUser, traits: currentTraits, }); if (initialFlagState.outcome.error) return [ { name: "failed", input: initialFlagState.input, outcome: initialFlagState.outcome, cachedOutcome: cache.get<SuccessOutcome<F>>(initialFlagState.input), }, // always revalidate because the initial state failed [{ effect: "revalidate-input", input }], ]; cache.set(initialFlagState.input, initialFlagState.outcome); return [ { name: "succeeded", input: initialFlagState.input, outcome: initialFlagState.outcome, }, // revalidate only if the initial state was for a static render initialFlagState.input.requestBody.visitorKey ? [] : [{ effect: "revalidate-input", input }], ]; } ); React.useEffect(() => { const input = getInput({ config: staticConfig, visitorKeyInState: state.input?.requestBody.visitorKey, generatedVisitorKey, user: currentUser, traits: currentTraits, }); // evaluate if the input has changed, but not if the current input is // static as that will be revalidated on initialisation if (!options.pause && !isAlmostEqual(state.input, input)) { dispatch({ type: "evaluate", input }); } if (!shouldRevalidateOnFocus) return; function handleFocus() { if (document.visibilityState === "visible" && !options.pause) { dispatch({ type: "revalidate" }); } } // extracted "visibilitychange" for bundle size const visibilityChange = "visibilitychange"; document.addEventListener(visibilityChange, handleFocus); return () => { document.removeEventListener(visibilityChange, handleFocus); }; }, [ state, currentUser, currentTraits, shouldRevalidateOnFocus, options.pause, ]); const revalidate = React.useCallback( () => dispatch({ type: "revalidate" }), [dispatch] ); React.useEffect(() => { effects.forEach((effect) => { switch (effect.effect) { // execute the effect case "fetch": { const { id, input, controller } = effect; let timeoutId: ReturnType<typeof setTimeout>; if (controller && currentLoadingTimeout) { timeoutId = setTimeout( () => controller.abort(), currentLoadingTimeout ); } fetch([input.endpoint, input.envKey].join("/"), { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify(input.requestBody), signal: controller?.signal, }).then( (response) => { clearTimeout(timeoutId); if (!response.ok /* response.status is not 200-299 */) { dispatch({ type: "settle/failure", id, input, outcome: { error: "response-not-ok" }, thrownError: new Error("Response not ok"), }); return null; } return response.json().then( (data: EvaluationResponseBody<F>) => { // responses to outdated requests are skipped in the reducer dispatch({ type: "settle/success", id, input, outcome: { data }, }); }, (thrownError) => { dispatch({ type: "settle/failure", id, input, outcome: { error: "invalid-response-body" }, thrownError, }); return null; } ); }, (error) => { // aborted from controller due to timeout if ( error instanceof DOMException && error.name === "AbortError" ) { dispatch({ type: "settle/failure", id, input, outcome: { error: "request-timed-out" }, thrownError: error, }); } else { dispatch({ type: "settle/failure", id, input, outcome: { error: "network-error" }, thrownError: error, }); } return null; } ); break; } case "revalidate-input": dispatch({ type: "revalidate", input: effect.input }); break; default: return; } }); }, [effects, dispatch]); const { defaultFlags } = config; const flagBag = React.useMemo<FlagBag<F>>(() => { switch (state.name) { case "evaluating": return { flags: state.cachedOutcome?.data.flags ? combineRawFlagsWithDefaultFlags( state.cachedOutcome.data.flags, defaultFlags ) : null, data: null, error: null, fetching: true, settled: false, revalidate, visitorKey: state.input.requestBody.visitorKey, } as EvaluatingFlagBag<F>; case "succeeded": return { flags: combineRawFlagsWithDefaultFlags( state.outcome.data.flags, defaultFlags ), data: state.outcome.data, error: null, fetching: false, settled: Boolean(state.input.requestBody.visitorKey), revalidate, visitorKey: state.input.requestBody.visitorKey, } as SucceededFlagBag<F>; case "revalidating-after-success": return { flags: combineRawFlagsWithDefaultFlags( state.outcome.data.flags, defaultFlags ), data: state.outcome.data, error: null, fetching: true, settled: Boolean(state.input.requestBody.visitorKey), revalidate, visitorKey: state.input.requestBody.visitorKey, } as RevalidatingAfterSuccessFlagBag<F>; case "failed": return { flags: state.cachedOutcome?.data.flags ? combineRawFlagsWithDefaultFlags( state.cachedOutcome.data.flags, defaultFlags ) : defaultFlags || null, data: null, error: state.outcome.error, fetching: false, settled: Boolean(state.input.requestBody.visitorKey), revalidate, visitorKey: state.input.requestBody.visitorKey, } as FailedFlagBag<F>; case "revalidating-after-failure": return { flags: state.cachedOutcome?.data.flags ? combineRawFlagsWithDefaultFlags( state.cachedOutcome.data.flags, defaultFlags ) : defaultFlags || null, data: null, error: state.outcome.error, fetching: true, settled: Boolean(state.input.requestBody.visitorKey), revalidate, visitorKey: state.input.requestBody.visitorKey, } as RevalidatingAfterErrorFlagBag<F>; default: case "empty": return { flags: null, data: null, error: null, fetching: false, settled: false, revalidate, visitorKey: null, } as EmptyFlagBag; } }, [state, defaultFlags, revalidate]); return flagBag; }
the_stack
import { ChildProcess, spawn } from "child_process"; import * as path from "path"; import * as WebSocket from "ws"; import * as pty from "node-pty"; import { IPty } from "node-pty"; import PQueue from "p-queue"; import * as rpc from "vscode-jsonrpc"; import { v4 as getUUID } from "uuid"; import { LangConfig, langs } from "./langs"; import { borrowUser } from "./users"; import * as util from "./util"; import { Context, Options, bash } from "./util"; const allSessions: Set<Session> = new Set(); export class Session { ws: WebSocket; uuid: string; lang: string; tearingDown: boolean = false; // Initialized by setup() uidInfo: { uid: number; returnUID: () => Promise<void>; } | null = null; // Initialized later or never term: { pty: IPty; live: boolean } | null = null; lsp: { proc: ChildProcess; reader: rpc.StreamMessageReader; writer: rpc.StreamMessageWriter; } | null = null; daemon: { proc: ChildProcess } | null = null; formatter: { proc: ChildProcess; live: boolean; input: string; output: string; } | null = null; logPrimitive: (msg: string) => void; msgQueue: PQueue = new PQueue({ concurrency: 1 }); get homedir() { return `/tmp/riju/${this.uuid}`; } get config() { return langs[this.lang]; } get uid() { return this.uidInfo!.uid; } returnUID = async () => { this.uidInfo && (await this.uidInfo.returnUID()); }; get context() { return { uid: this.uid, uuid: this.uuid }; } log = (msg: string) => this.logPrimitive(`[${this.uuid}] ${msg}`); constructor(ws: WebSocket, lang: string, log: (msg: string) => void) { this.ws = ws; this.uuid = getUUID(); this.lang = lang; this.logPrimitive = log; this.log(`Creating session, language ${this.lang}`); } run = async (args: string[], options?: Options) => { return await util.run(args, this.log, options); }; privilegedSetup = () => util.privilegedSetup(this.context); privilegedSpawn = (args: string[]) => util.privilegedSpawn(this.context, args); privilegedUseradd = () => util.privilegedUseradd(this.uid); privilegedTeardown = () => util.privilegedTeardown(this.context); setup = async () => { try { allSessions.add(this); const { uid, returnUID } = await borrowUser(this.log); this.uidInfo = { uid, returnUID }; this.log(`Borrowed uid ${this.uid}`); await this.run(this.privilegedSetup()); if (this.config.setup) { await this.run(this.privilegedSpawn(bash(this.config.setup))); } await this.runCode(); if (this.config.daemon) { const daemonArgs = this.privilegedSpawn(bash(this.config.daemon)); const daemonProc = spawn(daemonArgs[0], daemonArgs.slice(1)); this.daemon = { proc: daemonProc, }; for (const stream of [daemonProc.stdout, daemonProc.stderr]) { stream.on("data", (data) => this.send({ event: "serviceLog", service: "daemon", output: data.toString("utf8"), }) ); daemonProc.on("close", (code, signal) => this.send({ event: "serviceFailed", service: "daemon", error: `Exited with status ${signal || code}`, }) ); daemonProc.on("error", (err) => this.send({ event: "serviceFailed", service: "daemon", error: `${err}`, }) ); } } if (this.config.lsp) { if (this.config.lsp.setup) { await this.run(this.privilegedSpawn(bash(this.config.lsp.setup))); } const lspArgs = this.privilegedSpawn(bash(this.config.lsp.start)); const lspProc = spawn(lspArgs[0], lspArgs.slice(1)); this.lsp = { proc: lspProc, reader: new rpc.StreamMessageReader(lspProc.stdout), writer: new rpc.StreamMessageWriter(lspProc.stdin), }; this.lsp.reader.listen((data: any) => { this.send({ event: "lspOutput", output: data }); }); lspProc.stderr.on("data", (data) => this.send({ event: "serviceLog", service: "lsp", output: data.toString("utf8"), }) ); lspProc.on("close", (code, signal) => this.send({ event: "serviceFailed", service: "lsp", error: `Exited with status ${signal || code}`, }) ); lspProc.on("error", (err) => this.send({ event: "serviceFailed", service: "lsp", error: `${err}` }) ); this.send({ event: "lspStarted", root: this.homedir }); } this.ws.on("message", (msg: string) => this.msgQueue.add(() => this.receive(msg)) ); this.ws.on("close", async () => { await this.teardown(); }); this.ws.on("error", async (err) => { this.log(`Websocket error: ${err}`); await this.teardown(); }); } catch (err) { this.log(`Error while setting up environment`); console.log(err); this.sendError(err); await this.teardown(); } }; send = async (msg: any) => { try { if (this.tearingDown) { return; } this.ws.send(JSON.stringify(msg)); } catch (err) { this.log(`Failed to send websocket message: ${err}`); console.log(err); await this.teardown(); } }; sendError = async (err: any) => { await this.send({ event: "terminalClear" }); await this.send({ event: "terminalOutput", output: `Riju encountered an unexpected error: ${err} \r \rYou may want to save your code and refresh the page. `, }); }; logBadMessage = (msg: any) => { this.log(`Got malformed message from client: ${JSON.stringify(msg)}`); }; receive = async (event: string) => { try { if (this.tearingDown) { return; } let msg: any; try { msg = JSON.parse(event); } catch (err) { this.log(`Failed to parse message from client: ${event}`); return; } switch (msg && msg.event) { case "terminalInput": if (typeof msg.input !== "string") { this.logBadMessage(msg); break; } if (!this.term) { this.log("terminalInput ignored because term is null"); break; } this.term!.pty.write(msg.input); break; case "runCode": if (typeof msg.code !== "string") { this.logBadMessage(msg); break; } await this.runCode(msg.code); break; case "formatCode": if (typeof msg.code !== "string") { this.logBadMessage(msg); break; } await this.formatCode(msg.code); break; case "lspInput": if (typeof msg.input !== "object" || !msg) { this.logBadMessage(msg); break; } if (!this.lsp) { this.log(`lspInput ignored because lsp is null`); break; } this.lsp.writer.write(msg.input); break; case "ensure": if (!this.config.ensure) { this.log(`ensure ignored because of missing configuration`); break; } await this.ensure(this.config.ensure); break; default: this.logBadMessage(msg); break; } } catch (err) { this.log(`Error while handling message from client`); console.log(err); this.sendError(err); } }; writeCode = async (code: string) => { if (this.config.main.includes("/")) { await this.run( this.privilegedSpawn([ "mkdir", "-p", path.dirname(`${this.homedir}/${this.config.main}`), ]) ); } await this.run( this.privilegedSpawn([ "sh", "-c", `cat > ${path.resolve(this.homedir, this.config.main)}`, ]), { input: code } ); }; runCode = async (code?: string) => { try { const { name, repl, main, suffix, createEmpty, compile, run, template, } = this.config; if (this.term) { const pid = this.term.pty.pid; const args = this.privilegedSpawn( bash(`kill -SIGTERM ${pid}; sleep 1; kill -SIGKILL ${pid}`) ); spawn(args[0], args.slice(1)); // Signal to terminalOutput message generator using closure. this.term.live = false; this.term = null; } this.send({ event: "terminalClear" }); let cmdline: string; if (code) { cmdline = run; if (compile) { cmdline = `( ${compile} ) && ( ${run} )`; } } else if (repl) { cmdline = repl; } else { cmdline = `echo '${name} has no REPL, press Run to see it in action'`; } if (code === undefined) { code = createEmpty !== undefined ? createEmpty : template; } if (code && suffix) { code += suffix; } await this.writeCode(code); const termArgs = this.privilegedSpawn(bash(cmdline)); const term = { pty: pty.spawn(termArgs[0], termArgs.slice(1), { name: "xterm-color", }), live: true, }; this.term = term; this.term.pty.on("data", (data) => { // Capture term in closure so that we don't keep sending output // from the old pty even after it's been killed (see ghci). if (term.live) { this.send({ event: "terminalOutput", output: data }); } }); this.term.pty.on("exit", (code, signal) => { if (term.live) { this.send({ event: "serviceFailed", service: "terminal", error: `Exited with status ${signal || code}`, }); } }); } catch (err) { this.log(`Error while running user code`); console.log(err); this.sendError(err); } }; formatCode = async (code: string) => { try { if (!this.config.format) { this.log("formatCode ignored because format is null"); return; } if (this.formatter) { const pid = this.formatter.proc.pid; const args = this.privilegedSpawn( bash(`kill -SIGTERM ${pid}; sleep 1; kill -SIGKILL ${pid}`) ); spawn(args[0], args.slice(1)); this.formatter.live = false; this.formatter = null; } const args = this.privilegedSpawn(bash(this.config.format.run)); const formatter = { proc: spawn(args[0], args.slice(1)), live: true, input: code, output: "", }; formatter.proc.stdin!.end(code); formatter.proc.stdout!.on("data", (data) => { if (!formatter.live) return; formatter.output += data.toString("utf8"); }); formatter.proc.stderr!.on("data", (data) => { if (!formatter.live) return; this.send({ event: "serviceLog", service: "formatter", output: data.toString("utf8"), }); }); formatter.proc.on("close", (code, signal) => { if (!formatter.live) return; if (code === 0) { this.send({ event: "formattedCode", code: formatter.output, originalCode: formatter.input, }); } else { this.send({ event: "serviceFailed", service: "formatter", error: `Exited with status ${signal || code}`, }); } }); formatter.proc.on("error", (err) => { if (!formatter.live) return; this.send({ event: "serviceFailed", service: "formatter", error: `${err}`, }); }); this.formatter = formatter; } catch (err) { this.log(`Error while running code formatter`); console.log(err); this.sendError(err); } }; ensure = async (cmd: string) => { const code = await this.run(this.privilegedSpawn(bash(cmd)), { check: false, }); this.send({ event: "ensured", code }); }; teardown = async () => { try { if (this.tearingDown) { return; } this.log(`Tearing down session`); this.tearingDown = true; allSessions.delete(this); if (this.uidInfo) { await this.run(this.privilegedTeardown()); await this.returnUID(); } this.ws.terminate(); } catch (err) { this.log(`Error during teardown`); console.log(err); } }; }
the_stack
import assert = require('assert'); import Path = require('path'); import underscore = require('underscore'); import { atob, btoa } from './base/stringutil'; import agile_keychain_crypto = require('./agile_keychain_crypto'); import asyncutil = require('./base/asyncutil'); import agile_keychain_entries = require('./agile_keychain_entries'); import crypto = require('./base/crypto'); import collectionutil = require('./base/collectionutil'); import dateutil = require('./base/dateutil'); import event_stream = require('./base/event_stream'); import item_store = require('./item_store'); import key_agent = require('./key_agent'); import stringutil = require('./base/stringutil'); import vfs = require('./vfs/vfs'); import vfs_util = require('./vfs/util'); import { defer } from '../lib/base/promise_util'; type IndexEntry = [ string, // uuid string, // typeName string, // title string, // primaryLocation number, // UNIX timestamp in milliseconds string, // folder UUID number, // unknown string // trashed ("Y" || "N") ]; var fieldKindMap = new collectionutil.BiDiMap<item_store.FieldType, string>() .add(item_store.FieldType.Text, 'string') .add(item_store.FieldType.Password, 'concealed') .add(item_store.FieldType.Address, 'address') .add(item_store.FieldType.Date, 'date') .add(item_store.FieldType.MonthYear, 'monthYear') .add(item_store.FieldType.URL, 'URL') .add(item_store.FieldType.CreditCardType, 'cctype') .add(item_store.FieldType.PhoneNumber, 'phone') .add(item_store.FieldType.Gender, 'gender') .add(item_store.FieldType.Email, 'email') .add(item_store.FieldType.Menu, 'menu'); // mapping between input element types // and the single-char codes used to represent // them in .1password files var fieldTypeCodeMap = new collectionutil.BiDiMap< item_store.FormFieldType, string >() .add(item_store.FormFieldType.Text, 'T') .add(item_store.FormFieldType.Password, 'P') .add(item_store.FormFieldType.Email, 'E') .add(item_store.FormFieldType.Checkbox, 'C') .add(item_store.FormFieldType.Input, 'I'); /** Default number of iterations to use in the PBKDF2 password * stretching function used to secure the master key. * * The default value was taken from a recent version of * the official 1Password v4 app for Mac (13/05/14) */ export var DEFAULT_VAULT_PASS_ITERATIONS = 80000; // TODO: 'SL5' is the default and only used value for items // in current versions of 1Password as far as I know but // the Agile Keychain allows multiple security levels to be defined. // This item data could perhaps be stored in a field for store-specific // data within the item_store.Item? var DEFAULT_AGILEKEYCHAIN_SECURITY_LEVEL = 'SL5'; /** Convert an item to JSON data for serialization in a .1password file. * @p encryptedData is the encrypted version of the item's content. */ export function toAgileKeychainItem( item: item_store.Item, encryptedData: string ): agile_keychain_entries.Item { var keychainItem: any = {}; keychainItem.createdAt = dateutil.unixTimestampFromDate(item.createdAt); keychainItem.updatedAt = dateutil.unixTimestampFromDate(item.updatedAt); keychainItem.title = item.title; keychainItem.securityLevel = DEFAULT_AGILEKEYCHAIN_SECURITY_LEVEL; keychainItem.encrypted = btoa(encryptedData); keychainItem.typeName = item.typeName; keychainItem.uuid = item.uuid; keychainItem.location = item.primaryLocation(); keychainItem.folderUuid = item.folderUuid; keychainItem.faveIndex = item.faveIndex; keychainItem.trashed = item.trashed; keychainItem.openContents = item.openContents; return keychainItem; } /** Parses an item_store.Item from JSON data in a .1password file. * * The item content is initially encrypted. The decrypted * contents can be retrieved using getContent() */ export function fromAgileKeychainItem( vault: Vault, data: agile_keychain_entries.Item ): item_store.Item { var item = new item_store.Item(vault); item.updatedAt = dateutil.dateFromUnixTimestamp(data.updatedAt); item.title = data.title; // These fields are not currently stored in // an item_store.Item directly. They could potentially be stored in // a Store-specific data field in the item? // // - data.securityLevel // - data.encrypted if (data.secureContents) { item.setContent(fromAgileKeychainContent(data.secureContents)); } item.typeName = data.typeName; item.uuid = data.uuid; item.createdAt = dateutil.dateFromUnixTimestamp(data.createdAt); if (data.location) { item.locations.push(data.location); } item.folderUuid = data.folderUuid; item.faveIndex = data.faveIndex; item.trashed = data.trashed; item.openContents = data.openContents; return item; } export function toAgileKeychainField( field: item_store.ItemField ): agile_keychain_entries.ItemField { var keychainField = new agile_keychain_entries.ItemField(); keychainField.k = fieldKindMap.get(field.kind); keychainField.n = field.name; keychainField.t = field.title; keychainField.v = field.value; return keychainField; } export function fromAgileKeychainField( fieldData: agile_keychain_entries.ItemField ): item_store.ItemField { return { kind: fieldKindMap.get2(fieldData.k), name: fieldData.n, title: fieldData.t, value: fieldData.v, }; } /** Convert an item_store.ItemContent entry into a `contents` blob for storage in * a 1Password item. */ function toAgileKeychainContent( content: item_store.ItemContent ): agile_keychain_entries.ItemContent { var keychainContent = new agile_keychain_entries.ItemContent(); if (content.sections) { keychainContent.sections = []; content.sections.forEach(section => { keychainContent.sections.push(toAgileKeychainSection(section)); }); } if (content.urls) { keychainContent.URLs = []; content.urls.forEach(url => { keychainContent.URLs.push(url); }); } keychainContent.notesPlain = content.notes; if (content.formFields) { keychainContent.fields = []; content.formFields.forEach(field => { keychainContent.fields.push(toAgileKeychainFormField(field)); }); } keychainContent.htmlAction = content.htmlAction; keychainContent.htmlMethod = content.htmlMethod; keychainContent.htmlID = content.htmlId; return keychainContent; } /** Convert a decrypted JSON `contents` blob from a 1Password item * into an item_store.ItemContent instance. */ function fromAgileKeychainContent( data: agile_keychain_entries.ItemContent ): item_store.ItemContent { let content = item_store.ContentUtil.empty(); if (data.sections) { data.sections.forEach(section => { content.sections.push(fromAgileKeychainSection(section)); }); } if (data.URLs) { data.URLs.forEach(url => { content.urls.push(url); }); } if (data.notesPlain) { content.notes = data.notesPlain; } if (data.fields) { data.fields.forEach(field => { content.formFields.push(fromAgileKeychainFormField(field)); }); } if (data.htmlAction) { content.htmlAction = data.htmlAction; } if (data.htmlMethod) { content.htmlMethod = data.htmlMethod; } if (data.htmlID) { content.htmlId = data.htmlID; } return content; } function toAgileKeychainSection( section: item_store.ItemSection ): agile_keychain_entries.ItemSection { var keychainSection = new agile_keychain_entries.ItemSection(); keychainSection.name = section.name; keychainSection.title = section.title; keychainSection.fields = []; section.fields.forEach(field => { keychainSection.fields.push(toAgileKeychainField(field)); }); return keychainSection; } /** Convert a section entry from the JSON contents blob for * an item into an item_store.ItemSection instance. */ function fromAgileKeychainSection( data: agile_keychain_entries.ItemSection ): item_store.ItemSection { return { name: data.name, title: data.title, fields: (data.fields || []).map(fieldData => fromAgileKeychainField(fieldData) ), }; } function toAgileKeychainFormField( field: item_store.WebFormField ): agile_keychain_entries.WebFormField { var keychainField = new agile_keychain_entries.WebFormField(); keychainField.id = field.id; keychainField.name = field.name; keychainField.type = fieldTypeCodeMap.get(field.type); keychainField.designation = field.designation; keychainField.value = field.value; return keychainField; } function fromAgileKeychainFormField( keychainField: agile_keychain_entries.WebFormField ): item_store.WebFormField { return { id: keychainField.id, name: keychainField.name, type: fieldTypeCodeMap.get2(keychainField.type), designation: keychainField.designation, value: keychainField.value, }; } export function convertKeys( keyList: agile_keychain_entries.EncryptionKeyEntry[] ): key_agent.Key[] { return keyList.map(keyEntry => { return { format: key_agent.KeyFormat.AgileKeychainKey, data: keyEntry.data, identifier: keyEntry.identifier, iterations: keyEntry.iterations, validation: keyEntry.validation, }; }); } /** Represents an Agile Keychain-format 1Password vault. */ export class Vault implements item_store.Store { /** File system which stores the vaults contents. */ fs: vfs.VFS; /** Path to the vault within the file system. */ path: string; private keyAgent: key_agent.KeyAgent; private keys: Promise<agile_keychain_entries.EncryptionKeyEntry[]>; // map of (item ID -> Item) for items that have been // modified and require the contents.js index file to be updated private pendingIndexUpdates: Map<string, item_store.Item>; // promise which is resolved when the current flush of // index updates completes private indexUpdated: Promise<{}>; private indexUpdatePending: boolean; onItemUpdated: event_stream.EventStream<item_store.Item>; /** Setup a vault which is stored at @p path in a filesystem. * @p fs is the filesystem interface through which the * files that make up the vault are accessed. */ constructor(fs: vfs.VFS, path: string, agent?: key_agent.KeyAgent) { this.fs = fs; this.path = path; this.keyAgent = agent || new key_agent.SimpleKeyAgent(agile_keychain_crypto.defaultCrypto); this.onItemUpdated = new event_stream.EventStream<item_store.Item>(); this.pendingIndexUpdates = new Map<string, item_store.Item>(); this.indexUpdated = Promise.resolve<{}>(null); this.indexUpdatePending = false; } private getKeys(): Promise<agile_keychain_entries.EncryptionKeyEntry[]> { if (!this.keys) { this.keys = this.loadKeys(); } return this.keys; } private async loadKeys(): Promise< agile_keychain_entries.EncryptionKeyEntry[] > { const content = await this.fs.read( Path.join(this.dataFolderPath(), 'encryptionKeys.js') ); var keyList: agile_keychain_entries.EncryptionKeyList = JSON.parse( content ); if (!keyList.list) { throw new Error('Missing `list` entry in encryptionKeys.js file'); } var vaultKeys: agile_keychain_entries.EncryptionKeyEntry[] = []; keyList.list.forEach(entry => { // Using 1Password v4, there are two entries in the // encryptionKeys.js file, 'SL5' and 'SL3'. // 'SL3' appears to be unused so speed up the unlock // process by skipping it if (entry.level != 'SL3') { vaultKeys.push(entry); } }); return vaultKeys; } private writeKeys( keyList: agile_keychain_entries.EncryptionKeyList, passHint: string ): Promise<{}> { // FIXME - Improve handling of concurrent attempts to update encryptionKeys.js. // If the file in the VFS has been modified since the original read, the operation // should fail. var keyJSON = collectionutil.prettyJSON(keyList); var keysSaved = this.fs.write( Path.join(this.dataFolderPath(), 'encryptionKeys.js'), keyJSON ); var hintSaved = this.fs.write( Path.join(this.dataFolderPath(), '.password.hint'), passHint ); return Promise.all([keysSaved, hintSaved]); } listKeys(): Promise<key_agent.Key[]> { return this.getKeys().then(convertKeys); } saveKeys(keys: key_agent.Key[], hint: string): Promise<void> { throw new Error('onepass.Vault.saveKeys() is not implemented'); } /** Unlock the vault using the given master password. * This must be called before item contents can be decrypted. */ unlock(pwd: string): Promise<void> { return item_store.unlockStore(this, this.keyAgent, pwd); } /** Lock the vault. This discards decrypted master keys for the vault * created via a call to unlock() */ lock(): Promise<void> { return this.keyAgent.forgetKeys(); } /** Returns true if the vault was successfully unlocked using unlock(). * Only once the vault is unlocked can item contents be retrieved using item_store.Item.getContents() */ isLocked(): Promise<boolean> { var keyIDs = this.keyAgent.listKeys(); var keyEntries = this.getKeys(); return Promise.all([keyIDs, keyEntries]).then(result => { var [keyIDs, keyEntries] = result as [ string[], agile_keychain_entries.EncryptionKeyEntry[] ]; var locked = false; keyEntries.forEach(entry => { if (keyIDs.indexOf(entry.identifier) == -1) { locked = true; } }); return locked; }); } /** Returns the path to the file containing the encrypted data * for an item. */ itemPath(uuid: string): string { return Path.join(this.path, 'data/default/' + uuid + '.1password'); } loadItem(uuid: string): Promise<item_store.ItemAndContent> { var contentInfo = this.fs.stat(this.itemPath(uuid)); var contentData = this.fs.read(this.itemPath(uuid)); var item: item_store.Item; return asyncutil .all2([contentInfo, contentData]) .then((contentData: [vfs.FileInfo, string]) => { let contentInfo = contentData[0]; let contentJSON = contentData[1]; let encryptedItem = fromAgileKeychainItem( this, JSON.parse(contentJSON) ); assert(contentInfo.revision); encryptedItem.revision = contentInfo.revision; item = encryptedItem; return encryptedItem.getContent(); }) .then(content => ({ item: item, content: content, })); } saveItem( item: item_store.Item, source?: item_store.ChangeSource ): Promise<void> { if (source !== item_store.ChangeSource.Sync) { item.updateTimestamps(); } else { assert(item.updatedAt); } // update the '<item ID>.1password' file let itemPath = this.itemPath(item.uuid); let itemSaved: Promise<void>; if (item.isTombstone()) { itemSaved = this.fs .rm(itemPath) .catch((err: Error | vfs.VfsError) => { if (err instanceof vfs.VfsError) { if (err.type === vfs.ErrorType.FileNotFound) { return; } } throw err; }); } else { itemSaved = item .getContent() .then(content => { item.updateOverviewFromContent(content); var contentJSON = JSON.stringify( toAgileKeychainContent(content) ); return this.encryptItemData( DEFAULT_AGILEKEYCHAIN_SECURITY_LEVEL, contentJSON ); }) .then(encryptedContent => { var keychainJSON = JSON.stringify( toAgileKeychainItem(item, encryptedContent) ); return this.fs.write(itemPath, keychainJSON); }) .then(fileInfo => { // update the saved revision for the item item.revision = fileInfo.revision; }); } // update the contents.js index file. The index file is not used by // Passcards as a source for item metadata, since failures in VFS // operations can cause contents.js to get out of sync with the // corresponding .1password files. contents.js is maintained and updated // by Passcards for compatibility with the official 1Password clients. // // Updates are added to a queue which is then flushed so that an update for one // entry does not clobber an update for another. This also reduces the number // of VFS requests. // this.pendingIndexUpdates.set(item.uuid, item); var indexSaved = asyncutil.until(() => { // wait for the current index update to complete return this.indexUpdated.then(() => { if (this.pendingIndexUpdates.size == 0) { // if there are no more updates to save, // we're done return true; } else { // otherwise, schedule another flush of updates // to the index, unless another save operation // has already started one if (!this.indexUpdatePending) { this.saveContentsFile(); } return false; } }); }); return <any>asyncutil.all2([itemSaved, indexSaved]).then(() => { this.onItemUpdated.publish(item); }); } // save pending changes to the contents.js index file private saveContentsFile() { var overviewSaved = defer<{}>(); var revision: string; this.indexUpdated = this.fs .stat(this.contentsFilePath()) .then(stat => { revision = stat.revision; return this.fs.read(this.contentsFilePath()); }) .then(contentsJSON => { var updatedItems: item_store.Item[] = []; this.pendingIndexUpdates.forEach(item => { updatedItems.push(item); }); this.pendingIndexUpdates.clear(); var contentEntries: IndexEntry[] = JSON.parse(contentsJSON); updatedItems.forEach(item => { var entry = underscore.find(contentEntries, entry => { return entry[0] == item.uuid; }); if (!entry) { entry = [ null, null, null, null, null, null, null, null, ]; contentEntries.push(entry); } entry[0] = item.uuid; entry[1] = <string>item.typeName; entry[2] = item.title; entry[3] = item.primaryLocation(); entry[4] = dateutil.unixTimestampFromDate(item.updatedAt); entry[5] = item.folderUuid; entry[6] = 0; // TODO - Find out what this is used for entry[7] = item.trashed ? 'Y' : 'N'; }); var newContentsJSON = JSON.stringify(contentEntries); return asyncutil.resolveWith( overviewSaved, this.fs.write(this.contentsFilePath(), newContentsJSON, { parentRevision: revision, }) ); }); this.indexUpdatePending = true; this.indexUpdated.then(() => { this.indexUpdatePending = false; }); } private dataFolderPath(): string { return Path.join(this.path, 'data/default'); } private contentsFilePath(): string { return Path.join(this.dataFolderPath(), 'contents.js'); } private async listDeletedItems() { const contents = await vfs_util.readJSON<IndexEntry[]>( this.fs, this.contentsFilePath() ); return contents .filter(entry => entry[1] === item_store.ItemTypes.TOMBSTONE) .map(entry => ({ uuid: entry[0], deleted: true })); } private async listCurrentItems() { const ID_REGEX = /^([0-9a-fA-F]+)\.1password$/; const entries = await this.fs.list(this.dataFolderPath()); return entries .filter(entry => entry.name.match(ID_REGEX) != null) .map(entry => ({ uuid: entry.name.match(ID_REGEX)[1], revision: entry.revision, deleted: false, })); } listItemStates(): Promise<item_store.ItemState[]> { return Promise.all([ this.listDeletedItems(), this.listCurrentItems(), ]).then((items: [item_store.ItemState[], item_store.ItemState[]]) => { // if an item is listed as a tombstone in the contents.js file // but a .1password file also exists then the deletion takes precedence. // // This currently does not 'repair' the vault by removing the // .1password file. let deletedItems = new Set<string>(); for (let item of items[0]) { deletedItems.add(item.uuid); } let allItems = items[0]; for (let item of items[1]) { if (!deletedItems.has(item.uuid)) { allItems.push(item); } } return allItems; }); } /** Returns a list of overview data for all items in the vault, * and tombstone markers for deleted items. */ async listItems( opts: item_store.ListItemsOptions = {} ): Promise<item_store.Item[]> { const itemStates = await this.listItemStates(); let loadedItems: Promise<item_store.ItemAndContent>[] = []; for (let state of itemStates) { if (state.deleted) { if (opts.includeTombstones) { let item = new item_store.Item(this, state.uuid); item.typeName = item_store.ItemTypes.TOMBSTONE; loadedItems.push( Promise.resolve({ item: item, content: null, }) ); } } else { loadedItems.push(this.loadItem(state.uuid)); } } const items = await Promise.all(loadedItems); // Early versions of Passcards would update .1password // files when items were removed rather than deleting them. // When listing vault items, filter out any such tombstones return items.map(item => item.item).filter(item => { return !item.isTombstone() || opts.includeTombstones; }); } // items may identify their encryption key via either the 'keyID' or // 'level' fields async decryptItemData( keyID: string, level: string, data: string ): Promise<string> { const keys = await this.getKeys(); var result: Promise<string>; for (let key of keys) { if (key.identifier === keyID || key.level === level) { var cryptoParams = new key_agent.CryptoParams( key_agent.CryptoAlgorithm.AES128_OpenSSLKey ); result = this.keyAgent.decrypt( key.identifier, data, cryptoParams ); break; } } if (result) { return result; } else { throw new Error('No key ' + level + ' found'); } } async encryptItemData(level: string, data: string): Promise<string> { const keys = await this.getKeys(); var result: Promise<string>; keys.forEach(key => { if (key.level === level) { var cryptoParams = new key_agent.CryptoParams( key_agent.CryptoAlgorithm.AES128_OpenSSLKey ); result = this.keyAgent.encrypt( key.identifier, data, cryptoParams ); return; } }); if (result) { return result; } else { throw new Error('No key ' + level + ' found'); } } /** Change the master password for the vault. * * This decrypts the existing master key and re-encrypts it with @p newPass. * * @param oldPass The current password for the vault * @param newPass The new password for the vault * @param newPassHint The user-provided hint for the new password * @param iterations The number of iterations of the key derivation function * to use when generating an encryption key from @p newPass. If not specified, * use the same number of iterations as the existing key. */ async changePassword( oldPass: string, newPass: string, newPassHint: string, iterations?: number ): Promise<{}> { const locked = await this.isLocked(); if (locked) { throw new Error( 'Vault must be unlocked before changing the password' ); } const keys = await this.getKeys(); let reencryptedKeys: Promise< agile_keychain_entries.EncryptionKeyEntry >[] = []; for (let key of keys) { reencryptedKeys.push( this.reencryptKey(key, oldPass, newPass, iterations) ); } const newKeys = await Promise.all(reencryptedKeys); let keyList = <agile_keychain_entries.EncryptionKeyList>{ list: newKeys, }; for (let key of newKeys) { keyList[key.level] = key.identifier; } this.keys = null; return this.writeKeys(keyList, newPassHint); } private async reencryptKey( key: agile_keychain_entries.EncryptionKeyEntry, oldPass: string, newPass: string, iterations?: number ) { let oldSaltCipher = agile_keychain_crypto.extractSaltAndCipherText( atob(key.data) ); let newSalt = crypto.randomBytes(8); let newKeyIterations = iterations || key.iterations; const derivedKey = await key_agent.keyFromPassword( oldPass, oldSaltCipher.salt, key.iterations ); const oldKey = await key_agent.decryptKey( derivedKey, oldSaltCipher.cipherText, atob(key.validation) ); const newDerivedKey = await key_agent.keyFromPassword( newPass, newSalt, newKeyIterations ); const newKey = await key_agent.encryptKey(newDerivedKey, oldKey); let newKeyEntry = { data: btoa('Salted__' + newSalt + newKey.key), identifier: key.identifier, iterations: newKeyIterations, level: key.level, validation: btoa(newKey.validation), }; return newKeyEntry; } /** Initialize a new empty vault in @p path with * a given master @p password. */ static async createVault( fs: vfs.VFS, path: string, password: string, hint: string, passIterations: number = DEFAULT_VAULT_PASS_ITERATIONS, keyAgent?: key_agent.KeyAgent ): Promise<Vault> { if (!stringutil.endsWith(path, '.agilekeychain')) { path += '.agilekeychain'; } let vault = new Vault(fs, path, keyAgent); // 1. Check for no existing vault at @p path // 2. Add empty contents.js, encryptionKeys.js, 1Password.keys files // 3. If this is a Dropbox folder and no file exists in the root // specifying the vault path, add one // 4. Generate new random key and encrypt with master password await fs.mkpath(vault.dataFolderPath()); const keyList = await agile_keychain_crypto.generateMasterKey( password, passIterations ); let keysSaved = vault.writeKeys(keyList, hint); let contentsSaved = fs.write(vault.contentsFilePath(), '[]'); await Promise.all([keysSaved, contentsSaved]); return vault; } passwordHint(): Promise<string> { return this.fs.read(Path.join(this.dataFolderPath(), '.password.hint')); } vaultPath(): string { return this.path; } async getRawDecryptedData(item: item_store.Item): Promise<string> { const content = await this.fs.read(this.itemPath(item.uuid)); const keychainItem = <agile_keychain_entries.Item>JSON.parse(content); return this.decryptItemData( keychainItem.keyID, keychainItem.securityLevel, atob(keychainItem.encrypted) ); } async getContent(item: item_store.Item): Promise<item_store.ItemContent> { const data = await this.getRawDecryptedData(item); const content = <agile_keychain_entries.ItemContent>JSON.parse(data); return fromAgileKeychainContent(content); } clear() { // not implemented for onepass.Vault since this is the user's // primary data source. return Promise.reject<void>( new Error('Primary vault does not support being cleared') ); } }
the_stack
import 'mocha'; import sinon from 'sinon'; import { assert } from 'chai'; import { IncomingMessage, ServerResponse } from 'http'; import { createHmac } from 'crypto'; import { ReceiverMultipleAckError, HTTPReceiverDeferredRequestError, AuthorizationError, } from '../errors'; import { HTTPModuleFunctions as func } from './HTTPModuleFunctions'; import { createFakeLogger } from '../test-helpers'; import { BufferedIncomingMessage } from './BufferedIncomingMessage'; describe('HTTPModuleFunctions', async () => { describe('Request header extraction', async () => { describe('extractRetryNumFromHTTPRequest', async () => { it('should work when the header does not exist', async () => { const req = sinon.createStubInstance(IncomingMessage) as IncomingMessage; if (req.headers === undefined) { // sinon on older Node.js may not return an object here req.headers = {}; } const result = func.extractRetryNumFromHTTPRequest(req); assert.isUndefined(result); }); it('should parse a single value header', async () => { const req = sinon.createStubInstance(IncomingMessage) as IncomingMessage; if (req.headers === undefined) { // sinon on older Node.js may not return an object here req.headers = {}; } req.headers['x-slack-retry-num'] = '2'; const result = func.extractRetryNumFromHTTPRequest(req); assert.equal(result, 2); }); it('should parse an array of value headers', async () => { const req = sinon.createStubInstance(IncomingMessage) as IncomingMessage; if (req.headers === undefined) { // sinon on older Node.js may not return an object here req.headers = {}; } req.headers['x-slack-retry-num'] = ['2']; const result = func.extractRetryNumFromHTTPRequest(req); assert.equal(result, 2); }); }); describe('extractRetryReasonFromHTTPRequest', async () => { it('should work when the header does not exist', async () => { const req = sinon.createStubInstance(IncomingMessage) as IncomingMessage; if (req.headers === undefined) { // sinon on older Node.js may not return an object here req.headers = {}; } const result = func.extractRetryReasonFromHTTPRequest(req); assert.isUndefined(result); }); it('should parse a valid header', async () => { const req = sinon.createStubInstance(IncomingMessage) as IncomingMessage; if (req.headers === undefined) { // sinon on older Node.js may not return an object here req.headers = {}; } req.headers['x-slack-retry-reason'] = 'timeout'; const result = func.extractRetryReasonFromHTTPRequest(req); assert.equal(result, 'timeout'); }); it('should parse an array of value headers', async () => { const req = sinon.createStubInstance(IncomingMessage) as IncomingMessage; if (req.headers === undefined) { // sinon on older Node.js may not return an object here req.headers = {}; } req.headers['x-slack-retry-reason'] = ['timeout']; const result = func.extractRetryReasonFromHTTPRequest(req); assert.equal(result, 'timeout'); }); }); }); describe('HTTP request parsing and verification', async () => { describe('parseHTTPRequestBody', async () => { it('should parse a JSON request body', async () => { const req = { rawBody: '{"foo":"bar"}', headers: { 'content-type': 'application/json' }, } as unknown as BufferedIncomingMessage; const result = func.parseHTTPRequestBody(req); assert.equal(result.foo, 'bar'); }); it('should parse a form request body', async () => { const req = { rawBody: `payload=${encodeURIComponent('{"foo":"bar"}')}`, headers: { 'content-type': 'application/x-www-form-urlencoded' }, } as unknown as BufferedIncomingMessage; const result = func.parseHTTPRequestBody(req); assert.equal(result.foo, 'bar'); }); }); describe('getHeader', async () => { it('should throw an exception when parsing a missing header', async () => { const req = sinon.createStubInstance(IncomingMessage) as IncomingMessage; if (req.headers === undefined) { // sinon on older Node.js may not return an object here req.headers = {}; } try { func.getHeader(req, 'Cookie'); assert.fail('Error should be thrown here'); } catch (e) { assert.isTrue((e as any).message.length > 0); } }); it('should parse a valid header', async () => { const req = sinon.createStubInstance(IncomingMessage) as IncomingMessage; if (req.headers === undefined) { // sinon on older Node.js may not return an object here req.headers = {}; } req.headers.Cookie = 'foo=bar'; const result = func.getHeader(req, 'Cookie'); assert.equal(result, 'foo=bar'); }); }); describe('parseAndVerifyHTTPRequest', async () => { it('should parse a JSON request body', async () => { const signingSecret = 'secret'; const timestamp = Math.floor(Date.now() / 1000); const rawBody = '{"foo":"bar"}'; const hmac = createHmac('sha256', signingSecret); hmac.update(`v0:${timestamp}:${rawBody}`); const signature = hmac.digest('hex'); const req = { rawBody: Buffer.from(rawBody), headers: { 'content-type': 'application/json', 'x-slack-signature': `v0=${signature}`, 'x-slack-request-timestamp': timestamp, }, } as unknown as BufferedIncomingMessage; const res: ServerResponse = sinon.createStubInstance(ServerResponse) as unknown as ServerResponse; const result = await func.parseAndVerifyHTTPRequest({ signingSecret }, req, res); assert.isDefined(result.rawBody); }); it('should detect an invalid timestamp', async () => { const signingSecret = 'secret'; const timestamp = Math.floor(Date.now() / 1000) - 600; // 10 minutes const rawBody = '{"foo":"bar"}'; const hmac = createHmac('sha256', signingSecret); hmac.update(`v0:${timestamp}:${rawBody}`); const signature = hmac.digest('hex'); const req = { rawBody: Buffer.from(rawBody), headers: { 'content-type': 'application/json', 'x-slack-signature': `v0=${signature}`, 'x-slack-request-timestamp': timestamp, }, } as unknown as BufferedIncomingMessage; const res: ServerResponse = sinon.createStubInstance(ServerResponse) as unknown as ServerResponse; try { await func.parseAndVerifyHTTPRequest({ signingSecret }, req, res); } catch (e) { assert.equal((e as any).message, 'Failed to verify authenticity: stale'); } }); it('should detect an invalid signature', async () => { const signingSecret = 'secret'; const timestamp = Math.floor(Date.now() / 1000); const rawBody = '{"foo":"bar"}'; const req = { rawBody: Buffer.from(rawBody), headers: { 'content-type': 'application/json', 'x-slack-signature': 'v0=invalid-signature', 'x-slack-request-timestamp': timestamp, }, } as unknown as BufferedIncomingMessage; const res: ServerResponse = sinon.createStubInstance(ServerResponse) as unknown as ServerResponse; try { await func.parseAndVerifyHTTPRequest({ signingSecret }, req, res); } catch (e) { assert.equal((e as any).message, 'Failed to verify authenticity: signature mismatch'); } }); it('should parse a ssl_check request body without signature verification', async () => { const signingSecret = 'secret'; const rawBody = 'ssl_check=1&token=legacy-fixed-verification-token'; const req = { rawBody: Buffer.from(rawBody), headers: { 'content-type': 'application/x-www-form-urlencoded', }, } as unknown as BufferedIncomingMessage; const res: ServerResponse = sinon.createStubInstance(ServerResponse) as unknown as ServerResponse; const result = await func.parseAndVerifyHTTPRequest({ signingSecret }, req, res); assert.isDefined(result.rawBody); }); it('should detect invalid signature for application/x-www-form-urlencoded body', async () => { const signingSecret = 'secret'; const rawBody = 'payload={}'; const timestamp = Math.floor(Date.now() / 1000); const req = { rawBody: Buffer.from(rawBody), headers: { 'content-type': 'application/json', 'x-slack-signature': 'v0=invalid-signature', 'x-slack-request-timestamp': timestamp, }, } as unknown as BufferedIncomingMessage; const res: ServerResponse = sinon.createStubInstance(ServerResponse) as unknown as ServerResponse; try { await func.parseAndVerifyHTTPRequest({ signingSecret }, req, res); } catch (e) { assert.equal((e as any).message, 'Failed to verify authenticity: signature mismatch'); } }); }); }); describe('HTTP response builder methods', async () => { it('should have buildContentResponse', async () => { const res: ServerResponse = sinon.createStubInstance(ServerResponse) as unknown as ServerResponse; const writeHead = sinon.fake(); res.writeHead = writeHead; func.buildContentResponse(res, 'OK'); assert.isTrue(writeHead.calledWith(200)); }); it('should have buildNoBodyResponse', async () => { const res: ServerResponse = sinon.createStubInstance(ServerResponse) as unknown as ServerResponse; const writeHead = sinon.fake(); res.writeHead = writeHead; func.buildNoBodyResponse(res, 500); assert.isTrue(writeHead.calledWith(500)); }); it('should have buildSSLCheckResponse', async () => { const res: ServerResponse = sinon.createStubInstance(ServerResponse) as unknown as ServerResponse; const writeHead = sinon.fake(); res.writeHead = writeHead; func.buildSSLCheckResponse(res); assert.isTrue(writeHead.calledWith(200)); }); it('should have buildUrlVerificationResponse', async () => { const res: ServerResponse = sinon.createStubInstance(ServerResponse) as unknown as ServerResponse; const writeHead = sinon.fake(); res.writeHead = writeHead; func.buildUrlVerificationResponse(res, { challenge: '3eZbrw1aBm2rZgRNFdxV2595E9CY3gmdALWMmHkvFXO7tYXAYM8P' }); assert.isTrue(writeHead.calledWith(200)); }); }); describe('Error handlers for event processing', async () => { const logger = createFakeLogger(); describe('defaultDispatchErrorHandler', async () => { it('should properly handle ReceiverMultipleAckError', async () => { const request = sinon.createStubInstance(IncomingMessage) as IncomingMessage; const response: ServerResponse = sinon.createStubInstance(ServerResponse) as unknown as ServerResponse; const writeHead = sinon.fake(); response.writeHead = writeHead; func.defaultDispatchErrorHandler({ error: new ReceiverMultipleAckError(), logger, request, response, }); assert.isTrue(writeHead.calledWith(500)); }); it('should properly handle HTTPReceiverDeferredRequestError', async () => { const request = sinon.createStubInstance(IncomingMessage) as IncomingMessage; const response: ServerResponse = sinon.createStubInstance(ServerResponse) as unknown as ServerResponse; const writeHead = sinon.fake(); response.writeHead = writeHead; func.defaultDispatchErrorHandler({ error: new HTTPReceiverDeferredRequestError('msg', request, response), logger, request, response, }); assert.isTrue(writeHead.calledWith(404)); }); }); describe('defaultProcessEventErrorHandler', async () => { it('should properly handle ReceiverMultipleAckError', async () => { const request = sinon.createStubInstance(IncomingMessage) as IncomingMessage; const response: ServerResponse = sinon.createStubInstance(ServerResponse) as unknown as ServerResponse; const writeHead = sinon.fake(); response.writeHead = writeHead; func.defaultProcessEventErrorHandler({ error: new ReceiverMultipleAckError(), storedResponse: undefined, logger, request, response, }); assert.isTrue(writeHead.calledWith(500)); }); it('should properly handle AuthorizationError', async () => { const request = sinon.createStubInstance(IncomingMessage) as IncomingMessage; const response: ServerResponse = sinon.createStubInstance(ServerResponse) as unknown as ServerResponse; const writeHead = sinon.fake(); response.writeHead = writeHead; func.defaultProcessEventErrorHandler({ error: new AuthorizationError('msg', new Error()), storedResponse: undefined, logger, request, response, }); assert.isTrue(writeHead.calledWith(401)); }); }); describe('defaultUnhandledRequestHandler', async () => { it('should properly execute', async () => { const request = sinon.createStubInstance(IncomingMessage) as IncomingMessage; const response: ServerResponse = sinon.createStubInstance(ServerResponse) as unknown as ServerResponse; const writeHead = sinon.fake(); response.writeHead = writeHead; func.defaultUnhandledRequestHandler({ logger, request, response, }); }); }); }); });
the_stack
import R from 'ramda'; import Dependency from './dependency'; import { RelativePath } from './dependency'; import { BitId, BitIds } from '../../../bit-id'; import Scope from '../../../scope/scope'; import { isValidPath } from '../../../utils'; import ValidationError from '../../../error/validation-error'; import validateType from '../../../utils/validate-type'; import { BitIdStr } from '../../../bit-id/bit-id'; import { ManipulateDirItem } from '../../component-ops/manipulate-dir'; import { PathLinux } from '../../../utils/path'; import { fetchRemoteVersions } from '../../../scope/scope-remotes'; export const DEPENDENCIES_TYPES = ['dependencies', 'devDependencies']; export const DEPENDENCIES_TYPES_UI_MAP = { dependencies: 'prod', devDependencies: 'dev' }; export default class Dependencies { constructor(readonly dependencies: Dependency[] = []) {} serialize(): Record<string, any>[] { return this.dependencies.map(dep => Object.assign({}, dep, { id: dep.id.toString() })); } get(): Dependency[] { return this.dependencies; } sort() { this.dependencies.sort((a, b) => { const idA = a.id.toString(); const idB = b.id.toString(); if (idA < idB) { return -1; } if (idA > idB) { return 1; } return 0; }); } getClone(): Dependency[] { // @ts-ignore AUTO-ADDED-AFTER-MIGRATION-PLEASE-FIX! return this.dependencies.map(dependency => Dependency.getClone(dependency)); } add(dependency: Dependency) { this.dependencies.push(dependency); } toStringOfIds(): string[] { return this.dependencies.map(dep => dep.id.toString()); } isEmpty(): boolean { return !this.dependencies.length; } asWritableObject() { return R.mergeAll(this.dependencies.map(dependency => dependency.id.toObject())); } cloneAsString(): Record<string, any>[] { return this.dependencies.map(dependency => { const dependencyClone = R.clone(dependency); dependencyClone.id = dependency.id.toString(); return dependencyClone; }); } cloneAsObject(): Record<string, any>[] { return this.dependencies.map(dependency => { const dependencyClone = R.clone(dependency); dependencyClone.id = dependency.id.serialize(); return dependencyClone; }); } stripOriginallySharedDir(manipulateDirData: ManipulateDirItem[], originallySharedDir: string): void { this.dependencies.forEach(dependency => { Dependency.stripOriginallySharedDir(dependency, manipulateDirData, originallySharedDir); }); } addWrapDir(manipulateDirData: ManipulateDirItem[], wrapDir: PathLinux): void { this.dependencies.forEach(dependency => { Dependency.addWrapDir(dependency, manipulateDirData, wrapDir); }); } /** * needed for calculating the originallySharedDir. when isCustomResolveUsed, don't take into * account the dependencies as they don't have relative paths */ getSourcesPaths(): string[] { return R.flatten( this.dependencies.map(dependency => dependency.relativePaths .map(relativePath => { return relativePath.isCustomResolveUsed ? null : relativePath.sourceRelativePath; }) .filter(x => x) ) ); } getById(id: BitId): Dependency | null | undefined { return this.dependencies.find(dep => dep.id.isEqual(id)); } getByIdStr(id: BitIdStr): Dependency | null | undefined { return this.dependencies.find(dep => dep.id.toString() === id); } getBySourcePath(sourcePath: string): Dependency | null | undefined { return this.dependencies.find(dependency => dependency.relativePaths.some(relativePath => { return relativePath.sourceRelativePath === sourcePath; }) ); } getAllIds(): BitIds { return BitIds.fromArray(this.dependencies.map(dependency => dependency.id)); } async addRemoteAndLocalVersions(scope: Scope, modelDependencies: Dependencies) { const dependenciesIds = this.dependencies.map(dependency => dependency.id); const localDependencies = await scope.latestVersions(dependenciesIds); const remoteVersionsDependencies = await fetchRemoteVersions(scope, dependenciesIds); this.dependencies.forEach(dependency => { const remoteVersionId = remoteVersionsDependencies.find(remoteId => remoteId.isEqualWithoutVersion(dependency.id) ); const localVersionId = localDependencies.find(localId => localId.isEqualWithoutVersion(dependency.id)); const modelVersionId = modelDependencies .get() .find(modelDependency => modelDependency.id.isEqualWithoutVersion(dependency.id)); // @ts-ignore AUTO-ADDED-AFTER-MIGRATION-PLEASE-FIX! dependency.remoteVersion = remoteVersionId ? remoteVersionId.version : null; // @ts-ignore AUTO-ADDED-AFTER-MIGRATION-PLEASE-FIX! dependency.localVersion = localVersionId ? localVersionId.version : null; // @ts-ignore AUTO-ADDED-AFTER-MIGRATION-PLEASE-FIX! dependency.currentVersion = modelVersionId ? modelVersionId.id.version : dependency.id.version; }); } getCustomResolvedData(): { [importSource: string]: BitId } { const importSourceMap = {}; this.dependencies.forEach((dependency: Dependency) => { dependency.relativePaths.forEach((relativePath: RelativePath) => { if (relativePath.isCustomResolveUsed) { if (!relativePath.importSource) { throw new Error( `${dependency.id.toString()} relativePath.importSource must be set when relativePath.isCustomResolveUsed` ); } importSourceMap[relativePath.importSource] = dependency.id; } }); }); return importSourceMap; } isCustomResolvedUsed(): boolean { return this.dependencies.some((dependency: Dependency) => { return dependency.relativePaths.some((relativePath: RelativePath) => relativePath.isCustomResolveUsed); }); } validate(): void { let message = 'failed validating the dependencies.'; validateType(message, this.dependencies, 'dependencies', 'array'); const allIds = this.getAllIds(); this.dependencies.forEach(dependency => { validateType(message, dependency, 'dependency', 'object'); if (!dependency.id) throw new ValidationError('one of the dependencies is missing ID'); if (!dependency.relativePaths) { throw new ValidationError(`a dependency ${dependency.id.toString()} is missing relativePaths`); } const sameIds = allIds.filterExact(dependency.id); if (sameIds.length > 1) { throw new ValidationError(`a dependency ${dependency.id.toString()} is duplicated`); } const permittedProperties = ['id', 'relativePaths']; const currentProperties = Object.keys(dependency); currentProperties.forEach(currentProp => { if (!permittedProperties.includes(currentProp)) { throw new ValidationError( `a dependency ${dependency.id.toString()} has an undetected property "${currentProp}"` ); } }); validateType(message, dependency.relativePaths, 'dependency.relativePaths', 'array'); dependency.relativePaths.forEach(relativePath => { message = `failed validating dependency ${dependency.id.toString()}.`; validateType(message, dependency, 'dependency', 'object'); const requiredProps = ['sourceRelativePath', 'destinationRelativePath']; const pathProps = ['sourceRelativePath', 'destinationRelativePath']; const optionalProps = ['importSpecifiers', 'isCustomResolveUsed', 'importSource']; const allProps = requiredProps.concat(optionalProps); requiredProps.forEach(prop => { if (!relativePath[prop]) { throw new ValidationError(`${message} relativePaths.${prop} is missing`); } }); pathProps.forEach(prop => { if (!isValidPath(relativePath[prop])) { throw new ValidationError(`${message} relativePaths.${prop} has an invalid path ${relativePath[prop]}`); } }); Object.keys(relativePath).forEach(prop => { if (!allProps.includes(prop)) { throw new ValidationError(`${message} undetected property of relativePaths "${prop}"`); } }); if (relativePath.isCustomResolveUsed) { if (!relativePath.importSource) { throw new ValidationError(`a dependency ${dependency.id.toString()} is missing relativePath.importSource`); } validateType(message, relativePath.importSource, 'relativePath.importSource', 'string'); } if (relativePath.importSpecifiers) { validateType(message, relativePath.importSpecifiers, 'relativePath.importSpecifiers', 'array'); // $FlowFixMe it's already confirmed that relativePath.importSpecifiers is set relativePath.importSpecifiers.forEach(importSpecifier => { validateType(message, importSpecifier, 'importSpecifier', 'object'); if (!importSpecifier.mainFile) { throw new ValidationError(`${message} mainFile property is missing from the importSpecifier`); } const specifierProps = ['isDefault', 'name'].sort().toString(); const mainFileProps = Object.keys(importSpecifier.mainFile) .sort() .toString(); if (mainFileProps !== specifierProps) { throw new ValidationError( `${message} expected properties of importSpecifier.mainFile "${specifierProps}", got "${mainFileProps}"` ); } if (importSpecifier.linkFile) { const linkFileProps = Object.keys(importSpecifier.linkFile) .sort() .toString(); if (linkFileProps !== specifierProps) { throw new ValidationError( `${message} expected properties of importSpecifier.linkFile "${specifierProps}", got "${linkFileProps}"` ); } } const specifierPermittedProps = ['mainFile', 'linkFile']; Object.keys(importSpecifier).forEach(prop => { if (!specifierPermittedProps.includes(prop)) { throw new ValidationError(`${message} undetected property of importSpecifier "${prop}"`); } }); }); } }); }); } }
the_stack
import { GlobalProps } from 'ojs/ojvcomponent'; import { ComponentChildren } from 'preact'; import CommonTypes = require('../ojcommontypes'); import { KeySet } from '../ojkeyset'; import { DataProvider, ItemMetadata, Item } from '../ojdataprovider'; import { baseComponent, baseComponentEventMap, baseComponentSettableProperties, JetElementCustomEvent, JetSetPropertyType } from '..'; export interface ojListView<K, D> extends baseComponent<ojListViewSettableProperties<K, D>> { as: string; currentItem: K; data: DataProvider<K, D>; display: 'list' | 'card'; dnd: { drag?: { items: { dataTypes?: string | string[]; drag?: ((param0: Event) => void); dragEnd?: ((param0: Event) => void); dragStart?: ((param0: Event, param1: { items: Element[]; }) => void); }; }; drop?: { items: { dataTypes?: string | string[]; dragEnter?: ((param0: Event, param1: { item: Element; }) => void); dragLeave?: ((param0: Event, param1: { item: Element; }) => void); dragOver?: ((param0: Event, param1: { item: Element; }) => void); drop?: ((param0: Event, param1: ojListView.ItemsDropContext) => void); }; }; reorder: { items: 'enabled' | 'disabled'; }; }; drillMode: 'collapsible' | 'none'; expanded: KeySet<K>; readonly firstSelectedItem: CommonTypes.ItemContext<K, D>; gridlines: { item: 'visible' | 'visibleExceptLast' | 'hidden'; }; groupHeaderPosition: 'static' | 'sticky'; item: { focusable?: ((param0: ojListView.ItemContext<K, D>) => boolean) | boolean; renderer?: ((param0: ojListView.ItemContext<K, D>) => { insert: Element | string; } | undefined) | null; selectable?: ((param0: ojListView.ItemContext<K, D>) => boolean) | boolean; }; scrollPolicy: 'auto' | 'loadAll' | 'loadMoreOnScroll'; scrollPolicyOptions: { fetchSize?: number; maxCount?: number; scroller?: Element | keyof HTMLElementTagNameMap | keyof SVGElementTagNameMap | string; }; scrollPosition: { index?: number; key?: K; offsetX?: number; offsetY?: number; parent?: K; x?: number; y?: number; }; scrollToKey: 'auto' | 'capability' | 'always' | 'never'; selected: KeySet<K>; selection: K[]; selectionMode: 'none' | 'single' | 'multiple'; selectionRequired: boolean; translations: { accessibleNavigateSkipItems?: string; accessibleReorderAfterItem?: string; accessibleReorderBeforeItem?: string; accessibleReorderInsideItem?: string; accessibleReorderTouchInstructionText?: string; indexerCharacters?: string; labelCopy?: string; labelCut?: string; labelPaste?: string; labelPasteAfter?: string; labelPasteBefore?: string; msgFetchingData?: string; msgItemsAppended?: string; msgNoData?: string; }; addEventListener<T extends keyof ojListViewEventMap<K, D>>(type: T, listener: (this: HTMLElement, ev: ojListViewEventMap<K, D>[T]) => any, options?: (boolean | AddEventListenerOptions)): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: (boolean | AddEventListenerOptions)): void; getProperty<T extends keyof ojListViewSettableProperties<K, D>>(property: T): ojListView<K, D>[T]; getProperty(property: string): any; setProperty<T extends keyof ojListViewSettableProperties<K, D>>(property: T, value: ojListViewSettableProperties<K, D>[T]): void; setProperty<T extends string>(property: T, value: JetSetPropertyType<T, ojListViewSettableProperties<K, D>>): void; setProperties(properties: ojListViewSettablePropertiesLenient<K, D>): void; getContextByNode(node: Element): ojListView.ContextByNode<K> | null; getDataForVisibleItem(context: { key?: K; index?: number; parent?: Element; }): D; refresh(): void; scrollToItem(item: { key: K; }): void; } export namespace ojListView { interface ojAnimateEnd extends CustomEvent<{ action: string; element: Element; [propName: string]: any; }> { } interface ojAnimateStart extends CustomEvent<{ action: string; element: Element; endCallback: (() => void); [propName: string]: any; }> { } interface ojBeforeCollapse<K> extends CustomEvent<{ item: Element; key: K; [propName: string]: any; }> { } interface ojBeforeCurrentItem<K> extends CustomEvent<{ item: Element; key: K; previousItem: Element; previousKey: K; [propName: string]: any; }> { } interface ojBeforeExpand<K> extends CustomEvent<{ item: Element; key: K; [propName: string]: any; }> { } interface ojCollapse<K> extends CustomEvent<{ item: Element; key: K; [propName: string]: any; }> { } interface ojCopy extends CustomEvent<{ items: Element[]; [propName: string]: any; }> { } interface ojCut extends CustomEvent<{ items: Element[]; [propName: string]: any; }> { } interface ojExpand<K> extends CustomEvent<{ item: Element; key: K; [propName: string]: any; }> { } interface ojItemAction<K, D> extends CustomEvent<{ context: CommonTypes.ItemContext<K, D>; originalEvent: Event; [propName: string]: any; }> { } interface ojPaste extends CustomEvent<{ item: Element; [propName: string]: any; }> { } interface ojReorder extends CustomEvent<{ items: Element[]; position: string; reference: Element; [propName: string]: any; }> { } // tslint:disable-next-line interface-over-type-literal type asChanged<K, D> = JetElementCustomEvent<ojListView<K, D>["as"]>; // tslint:disable-next-line interface-over-type-literal type currentItemChanged<K, D> = JetElementCustomEvent<ojListView<K, D>["currentItem"]>; // tslint:disable-next-line interface-over-type-literal type dataChanged<K, D> = JetElementCustomEvent<ojListView<K, D>["data"]>; // tslint:disable-next-line interface-over-type-literal type displayChanged<K, D> = JetElementCustomEvent<ojListView<K, D>["display"]>; // tslint:disable-next-line interface-over-type-literal type dndChanged<K, D> = JetElementCustomEvent<ojListView<K, D>["dnd"]>; // tslint:disable-next-line interface-over-type-literal type drillModeChanged<K, D> = JetElementCustomEvent<ojListView<K, D>["drillMode"]>; // tslint:disable-next-line interface-over-type-literal type expandedChanged<K, D> = JetElementCustomEvent<ojListView<K, D>["expanded"]>; // tslint:disable-next-line interface-over-type-literal type firstSelectedItemChanged<K, D> = JetElementCustomEvent<ojListView<K, D>["firstSelectedItem"]>; // tslint:disable-next-line interface-over-type-literal type gridlinesChanged<K, D> = JetElementCustomEvent<ojListView<K, D>["gridlines"]>; // tslint:disable-next-line interface-over-type-literal type groupHeaderPositionChanged<K, D> = JetElementCustomEvent<ojListView<K, D>["groupHeaderPosition"]>; // tslint:disable-next-line interface-over-type-literal type itemChanged<K, D> = JetElementCustomEvent<ojListView<K, D>["item"]>; // tslint:disable-next-line interface-over-type-literal type scrollPolicyChanged<K, D> = JetElementCustomEvent<ojListView<K, D>["scrollPolicy"]>; // tslint:disable-next-line interface-over-type-literal type scrollPolicyOptionsChanged<K, D> = JetElementCustomEvent<ojListView<K, D>["scrollPolicyOptions"]>; // tslint:disable-next-line interface-over-type-literal type scrollPositionChanged<K, D> = JetElementCustomEvent<ojListView<K, D>["scrollPosition"]>; // tslint:disable-next-line interface-over-type-literal type scrollToKeyChanged<K, D> = JetElementCustomEvent<ojListView<K, D>["scrollToKey"]>; // tslint:disable-next-line interface-over-type-literal type selectedChanged<K, D> = JetElementCustomEvent<ojListView<K, D>["selected"]>; // tslint:disable-next-line interface-over-type-literal type selectionChanged<K, D> = JetElementCustomEvent<ojListView<K, D>["selection"]>; // tslint:disable-next-line interface-over-type-literal type selectionModeChanged<K, D> = JetElementCustomEvent<ojListView<K, D>["selectionMode"]>; // tslint:disable-next-line interface-over-type-literal type selectionRequiredChanged<K, D> = JetElementCustomEvent<ojListView<K, D>["selectionRequired"]>; // tslint:disable-next-line interface-over-type-literal type ContextByNode<K> = { group?: boolean; index: number; key: K; parent?: Element; subId: string; }; // tslint:disable-next-line interface-over-type-literal type ItemContext<K, D> = { data: D; datasource: DataProvider<K, D>; depth?: number; index: number; key: K; leaf?: boolean; metadata: ItemMetadata<K>; parentElement: Element; parentKey?: K; }; // tslint:disable-next-line interface-over-type-literal type ItemsDropContext = { item: Element; position: 'before' | 'after' | 'inside'; reorder: boolean; }; // tslint:disable-next-line interface-over-type-literal type ItemTemplateContext<K = any, D = any> = { componentElement: Element; data: any; depth: number; index: number; item: Item<K, D>; key: any; leaf: boolean; parentkey: any; }; } export interface ojListViewEventMap<K, D> extends baseComponentEventMap<ojListViewSettableProperties<K, D>> { 'ojAnimateEnd': ojListView.ojAnimateEnd; 'ojAnimateStart': ojListView.ojAnimateStart; 'ojBeforeCollapse': ojListView.ojBeforeCollapse<K>; 'ojBeforeCurrentItem': ojListView.ojBeforeCurrentItem<K>; 'ojBeforeExpand': ojListView.ojBeforeExpand<K>; 'ojCollapse': ojListView.ojCollapse<K>; 'ojCopy': ojListView.ojCopy; 'ojCut': ojListView.ojCut; 'ojExpand': ojListView.ojExpand<K>; 'ojItemAction': ojListView.ojItemAction<K, D>; 'ojPaste': ojListView.ojPaste; 'ojReorder': ojListView.ojReorder; 'asChanged': JetElementCustomEvent<ojListView<K, D>["as"]>; 'currentItemChanged': JetElementCustomEvent<ojListView<K, D>["currentItem"]>; 'dataChanged': JetElementCustomEvent<ojListView<K, D>["data"]>; 'displayChanged': JetElementCustomEvent<ojListView<K, D>["display"]>; 'dndChanged': JetElementCustomEvent<ojListView<K, D>["dnd"]>; 'drillModeChanged': JetElementCustomEvent<ojListView<K, D>["drillMode"]>; 'expandedChanged': JetElementCustomEvent<ojListView<K, D>["expanded"]>; 'firstSelectedItemChanged': JetElementCustomEvent<ojListView<K, D>["firstSelectedItem"]>; 'gridlinesChanged': JetElementCustomEvent<ojListView<K, D>["gridlines"]>; 'groupHeaderPositionChanged': JetElementCustomEvent<ojListView<K, D>["groupHeaderPosition"]>; 'itemChanged': JetElementCustomEvent<ojListView<K, D>["item"]>; 'scrollPolicyChanged': JetElementCustomEvent<ojListView<K, D>["scrollPolicy"]>; 'scrollPolicyOptionsChanged': JetElementCustomEvent<ojListView<K, D>["scrollPolicyOptions"]>; 'scrollPositionChanged': JetElementCustomEvent<ojListView<K, D>["scrollPosition"]>; 'scrollToKeyChanged': JetElementCustomEvent<ojListView<K, D>["scrollToKey"]>; 'selectedChanged': JetElementCustomEvent<ojListView<K, D>["selected"]>; 'selectionChanged': JetElementCustomEvent<ojListView<K, D>["selection"]>; 'selectionModeChanged': JetElementCustomEvent<ojListView<K, D>["selectionMode"]>; 'selectionRequiredChanged': JetElementCustomEvent<ojListView<K, D>["selectionRequired"]>; } export interface ojListViewSettableProperties<K, D> extends baseComponentSettableProperties { as: string; currentItem: K; data: DataProvider<K, D>; display: 'list' | 'card'; dnd: { drag?: { items: { dataTypes?: string | string[]; drag?: ((param0: Event) => void); dragEnd?: ((param0: Event) => void); dragStart?: ((param0: Event, param1: { items: Element[]; }) => void); }; }; drop?: { items: { dataTypes?: string | string[]; dragEnter?: ((param0: Event, param1: { item: Element; }) => void); dragLeave?: ((param0: Event, param1: { item: Element; }) => void); dragOver?: ((param0: Event, param1: { item: Element; }) => void); drop?: ((param0: Event, param1: ojListView.ItemsDropContext) => void); }; }; reorder: { items: 'enabled' | 'disabled'; }; }; drillMode: 'collapsible' | 'none'; expanded: KeySet<K>; readonly firstSelectedItem: CommonTypes.ItemContext<K, D>; gridlines: { item: 'visible' | 'visibleExceptLast' | 'hidden'; }; groupHeaderPosition: 'static' | 'sticky'; item: { focusable?: ((param0: ojListView.ItemContext<K, D>) => boolean) | boolean; renderer?: ((param0: ojListView.ItemContext<K, D>) => { insert: Element | string; } | undefined) | null; selectable?: ((param0: ojListView.ItemContext<K, D>) => boolean) | boolean; }; scrollPolicy: 'auto' | 'loadAll' | 'loadMoreOnScroll'; scrollPolicyOptions: { fetchSize?: number; maxCount?: number; scroller?: Element | keyof HTMLElementTagNameMap | keyof SVGElementTagNameMap | string; }; scrollPosition: { index?: number; key?: K; offsetX?: number; offsetY?: number; parent?: K; x?: number; y?: number; }; scrollToKey: 'auto' | 'capability' | 'always' | 'never'; selected: KeySet<K>; selection: K[]; selectionMode: 'none' | 'single' | 'multiple'; selectionRequired: boolean; translations: { accessibleNavigateSkipItems?: string; accessibleReorderAfterItem?: string; accessibleReorderBeforeItem?: string; accessibleReorderInsideItem?: string; accessibleReorderTouchInstructionText?: string; indexerCharacters?: string; labelCopy?: string; labelCut?: string; labelPaste?: string; labelPasteAfter?: string; labelPasteBefore?: string; msgFetchingData?: string; msgItemsAppended?: string; msgNoData?: string; }; } export interface ojListViewSettablePropertiesLenient<K, D> extends Partial<ojListViewSettableProperties<K, D>> { [key: string]: any; } export type ListViewElement<K, D> = ojListView<K, D>; export namespace ListViewElement { interface ojAnimateEnd extends CustomEvent<{ action: string; element: Element; [propName: string]: any; }> { } interface ojAnimateStart extends CustomEvent<{ action: string; element: Element; endCallback: (() => void); [propName: string]: any; }> { } interface ojBeforeCollapse<K> extends CustomEvent<{ item: Element; key: K; [propName: string]: any; }> { } interface ojBeforeCurrentItem<K> extends CustomEvent<{ item: Element; key: K; previousItem: Element; previousKey: K; [propName: string]: any; }> { } interface ojBeforeExpand<K> extends CustomEvent<{ item: Element; key: K; [propName: string]: any; }> { } interface ojCollapse<K> extends CustomEvent<{ item: Element; key: K; [propName: string]: any; }> { } interface ojCopy extends CustomEvent<{ items: Element[]; [propName: string]: any; }> { } interface ojCut extends CustomEvent<{ items: Element[]; [propName: string]: any; }> { } interface ojExpand<K> extends CustomEvent<{ item: Element; key: K; [propName: string]: any; }> { } interface ojItemAction<K, D> extends CustomEvent<{ context: CommonTypes.ItemContext<K, D>; originalEvent: Event; [propName: string]: any; }> { } interface ojPaste extends CustomEvent<{ item: Element; [propName: string]: any; }> { } interface ojReorder extends CustomEvent<{ items: Element[]; position: string; reference: Element; [propName: string]: any; }> { } // tslint:disable-next-line interface-over-type-literal type asChanged<K, D> = JetElementCustomEvent<ojListView<K, D>["as"]>; // tslint:disable-next-line interface-over-type-literal type currentItemChanged<K, D> = JetElementCustomEvent<ojListView<K, D>["currentItem"]>; // tslint:disable-next-line interface-over-type-literal type dataChanged<K, D> = JetElementCustomEvent<ojListView<K, D>["data"]>; // tslint:disable-next-line interface-over-type-literal type displayChanged<K, D> = JetElementCustomEvent<ojListView<K, D>["display"]>; // tslint:disable-next-line interface-over-type-literal type dndChanged<K, D> = JetElementCustomEvent<ojListView<K, D>["dnd"]>; // tslint:disable-next-line interface-over-type-literal type drillModeChanged<K, D> = JetElementCustomEvent<ojListView<K, D>["drillMode"]>; // tslint:disable-next-line interface-over-type-literal type expandedChanged<K, D> = JetElementCustomEvent<ojListView<K, D>["expanded"]>; // tslint:disable-next-line interface-over-type-literal type firstSelectedItemChanged<K, D> = JetElementCustomEvent<ojListView<K, D>["firstSelectedItem"]>; // tslint:disable-next-line interface-over-type-literal type gridlinesChanged<K, D> = JetElementCustomEvent<ojListView<K, D>["gridlines"]>; // tslint:disable-next-line interface-over-type-literal type groupHeaderPositionChanged<K, D> = JetElementCustomEvent<ojListView<K, D>["groupHeaderPosition"]>; // tslint:disable-next-line interface-over-type-literal type itemChanged<K, D> = JetElementCustomEvent<ojListView<K, D>["item"]>; // tslint:disable-next-line interface-over-type-literal type scrollPolicyChanged<K, D> = JetElementCustomEvent<ojListView<K, D>["scrollPolicy"]>; // tslint:disable-next-line interface-over-type-literal type scrollPolicyOptionsChanged<K, D> = JetElementCustomEvent<ojListView<K, D>["scrollPolicyOptions"]>; // tslint:disable-next-line interface-over-type-literal type scrollPositionChanged<K, D> = JetElementCustomEvent<ojListView<K, D>["scrollPosition"]>; // tslint:disable-next-line interface-over-type-literal type scrollToKeyChanged<K, D> = JetElementCustomEvent<ojListView<K, D>["scrollToKey"]>; // tslint:disable-next-line interface-over-type-literal type selectedChanged<K, D> = JetElementCustomEvent<ojListView<K, D>["selected"]>; // tslint:disable-next-line interface-over-type-literal type selectionChanged<K, D> = JetElementCustomEvent<ojListView<K, D>["selection"]>; // tslint:disable-next-line interface-over-type-literal type selectionModeChanged<K, D> = JetElementCustomEvent<ojListView<K, D>["selectionMode"]>; // tslint:disable-next-line interface-over-type-literal type selectionRequiredChanged<K, D> = JetElementCustomEvent<ojListView<K, D>["selectionRequired"]>; // tslint:disable-next-line interface-over-type-literal type ContextByNode<K> = { group?: boolean; index: number; key: K; parent?: Element; subId: string; }; // tslint:disable-next-line interface-over-type-literal type ItemsDropContext = { item: Element; position: 'before' | 'after' | 'inside'; reorder: boolean; }; } export interface ListViewIntrinsicProps extends Partial<Readonly<ojListViewSettableProperties<any, any>>>, GlobalProps, Pick<preact.JSX.HTMLAttributes, 'ref' | 'key'> { onojAnimateEnd?: (value: ojListViewEventMap<any, any>['ojAnimateEnd']) => void; onojAnimateStart?: (value: ojListViewEventMap<any, any>['ojAnimateStart']) => void; onojBeforeCollapse?: (value: ojListViewEventMap<any, any>['ojBeforeCollapse']) => void; onojBeforeCurrentItem?: (value: ojListViewEventMap<any, any>['ojBeforeCurrentItem']) => void; onojBeforeExpand?: (value: ojListViewEventMap<any, any>['ojBeforeExpand']) => void; onojCollapse?: (value: ojListViewEventMap<any, any>['ojCollapse']) => void; onojCopy?: (value: ojListViewEventMap<any, any>['ojCopy']) => void; onojCut?: (value: ojListViewEventMap<any, any>['ojCut']) => void; onojExpand?: (value: ojListViewEventMap<any, any>['ojExpand']) => void; onojItemAction?: (value: ojListViewEventMap<any, any>['ojItemAction']) => void; onojPaste?: (value: ojListViewEventMap<any, any>['ojPaste']) => void; onojReorder?: (value: ojListViewEventMap<any, any>['ojReorder']) => void; onasChanged?: (value: ojListViewEventMap<any, any>['asChanged']) => void; oncurrentItemChanged?: (value: ojListViewEventMap<any, any>['currentItemChanged']) => void; ondataChanged?: (value: ojListViewEventMap<any, any>['dataChanged']) => void; ondisplayChanged?: (value: ojListViewEventMap<any, any>['displayChanged']) => void; ondndChanged?: (value: ojListViewEventMap<any, any>['dndChanged']) => void; ondrillModeChanged?: (value: ojListViewEventMap<any, any>['drillModeChanged']) => void; onexpandedChanged?: (value: ojListViewEventMap<any, any>['expandedChanged']) => void; onfirstSelectedItemChanged?: (value: ojListViewEventMap<any, any>['firstSelectedItemChanged']) => void; ongridlinesChanged?: (value: ojListViewEventMap<any, any>['gridlinesChanged']) => void; ongroupHeaderPositionChanged?: (value: ojListViewEventMap<any, any>['groupHeaderPositionChanged']) => void; onitemChanged?: (value: ojListViewEventMap<any, any>['itemChanged']) => void; onscrollPolicyChanged?: (value: ojListViewEventMap<any, any>['scrollPolicyChanged']) => void; onscrollPolicyOptionsChanged?: (value: ojListViewEventMap<any, any>['scrollPolicyOptionsChanged']) => void; onscrollPositionChanged?: (value: ojListViewEventMap<any, any>['scrollPositionChanged']) => void; onscrollToKeyChanged?: (value: ojListViewEventMap<any, any>['scrollToKeyChanged']) => void; onselectedChanged?: (value: ojListViewEventMap<any, any>['selectedChanged']) => void; onselectionChanged?: (value: ojListViewEventMap<any, any>['selectionChanged']) => void; onselectionModeChanged?: (value: ojListViewEventMap<any, any>['selectionModeChanged']) => void; onselectionRequiredChanged?: (value: ojListViewEventMap<any, any>['selectionRequiredChanged']) => void; children?: ComponentChildren; } declare global { namespace preact.JSX { interface IntrinsicElements { "oj-list-view": ListViewIntrinsicProps; } } }
the_stack
import { CommandUtils } from "./CommandUtils"; import { ObjectLiteral } from "../common/ObjectLiteral"; import * as path from "path"; import * as yargs from "yargs"; import chalk from "chalk"; import { exec } from "child_process"; import { TypeORMError } from "../error/TypeORMError"; /** * Generates a new project with TypeORM. */ export class InitCommand implements yargs.CommandModule { command = "init"; describe = "Generates initial TypeORM project structure. " + "If name specified then creates files inside directory called as name. " + "If its not specified then creates files inside current directory."; builder(args: yargs.Argv) { return args .option("c", { alias: "connection", default: "default", describe: "Name of the connection on which to run a query" }) .option("n", { alias: "name", describe: "Name of the project directory." }) .option("db", { alias: "database", describe: "Database type you'll use in your project." }) .option("express", { describe: "Indicates if express should be included in the project." }) .option("docker", { describe: "Set to true if docker-compose must be generated as well. False by default." }) .option("pm", { alias: "manager", choices: ["npm", "yarn"], default: "npm", describe: "Install packages, expected values are npm or yarn." }); } async handler(args: yargs.Arguments) { try { const database: string = args.database as any || "mysql"; const isExpress = args.express !== undefined ? true : false; const isDocker = args.docker !== undefined ? true : false; const basePath = process.cwd() + (args.name ? ("/" + args.name) : ""); const projectName = args.name ? path.basename(args.name as any) : undefined; const installNpm = args.pm === "yarn" ? false : true; await CommandUtils.createFile(basePath + "/package.json", InitCommand.getPackageJsonTemplate(projectName), false); if (isDocker) await CommandUtils.createFile(basePath + "/docker-compose.yml", InitCommand.getDockerComposeTemplate(database), false); await CommandUtils.createFile(basePath + "/.gitignore", InitCommand.getGitIgnoreFile()); await CommandUtils.createFile(basePath + "/README.md", InitCommand.getReadmeTemplate({ docker: isDocker }), false); await CommandUtils.createFile(basePath + "/tsconfig.json", InitCommand.getTsConfigTemplate()); await CommandUtils.createFile(basePath + "/ormconfig.json", InitCommand.getOrmConfigTemplate(database)); await CommandUtils.createFile(basePath + "/src/entity/User.ts", InitCommand.getUserEntityTemplate(database)); await CommandUtils.createFile(basePath + "/src/index.ts", InitCommand.getAppIndexTemplate(isExpress)); await CommandUtils.createDirectories(basePath + "/src/migration"); // generate extra files for express application if (isExpress) { await CommandUtils.createFile(basePath + "/src/routes.ts", InitCommand.getRoutesTemplate()); await CommandUtils.createFile(basePath + "/src/controller/UserController.ts", InitCommand.getControllerTemplate()); } const packageJsonContents = await CommandUtils.readFile(basePath + "/package.json"); await CommandUtils.createFile(basePath + "/package.json", InitCommand.appendPackageJson(packageJsonContents, database, isExpress)); if (args.name) { console.log(chalk.green(`Project created inside ${chalk.blue(basePath)} directory.`)); } else { console.log(chalk.green(`Project created inside current directory.`)); } if (args.pm && installNpm) { await InitCommand.executeCommand("npm install"); } else { await InitCommand.executeCommand("yarn install"); } } catch (err) { console.log(chalk.black.bgRed("Error during project initialization:")); console.error(err); process.exit(1); } } // ------------------------------------------------------------------------- // Protected Static Methods // ------------------------------------------------------------------------- protected static executeCommand(command: string) { return new Promise<string>((ok, fail) => { exec(command, (error: any, stdout: any, stderr: any) => { if (stdout) return ok(stdout); if (stderr) return fail(stderr); if (error) return fail(error); ok(""); }); }); } /** * Gets contents of the ormconfig file. */ protected static getOrmConfigTemplate(database: string): string { const options: ObjectLiteral = {}; switch (database) { case "mysql": Object.assign(options, { type: "mysql", host: "localhost", port: 3306, username: "test", password: "test", database: "test", }); break; case "mariadb": Object.assign(options, { type: "mariadb", host: "localhost", port: 3306, username: "test", password: "test", database: "test", }); break; case "sqlite": Object.assign(options, { type: "sqlite", "database": "database.sqlite", }); break; case "better-sqlite3": Object.assign(options, { type: "better-sqlite3", "database": "database.sqlite", }); break; case "postgres": Object.assign(options, { "type": "postgres", "host": "localhost", "port": 5432, "username": "test", "password": "test", "database": "test", }); break; case "cockroachdb": Object.assign(options, { "type": "cockroachdb", "host": "localhost", "port": 26257, "username": "root", "password": "", "database": "defaultdb", }); break; case "mssql": Object.assign(options, { "type": "mssql", "host": "localhost", "username": "sa", "password": "Admin12345", "database": "tempdb", }); break; case "oracle": Object.assign(options, { "type": "oracle", "host": "localhost", "username": "system", "password": "oracle", "port": 1521, "sid": "xe.oracle.docker", }); break; case "mongodb": Object.assign(options, { "type": "mongodb", "database": "test", }); break; } Object.assign(options, { synchronize: true, logging: false, entities: [ "src/entity/**/*.ts" ], migrations: [ "src/migration/**/*.ts" ], subscribers: [ "src/subscriber/**/*.ts" ], cli: { entitiesDir: "src/entity", migrationsDir: "src/migration", subscribersDir: "src/subscriber" } }); return JSON.stringify(options, undefined, 3); } /** * Gets contents of the ormconfig file. */ protected static getTsConfigTemplate(): string { return JSON.stringify({ compilerOptions: { lib: ["es5", "es6"], target: "es5", module: "commonjs", moduleResolution: "node", outDir: "./build", emitDecoratorMetadata: true, experimentalDecorators: true, sourceMap: true } } , undefined, 3); } /** * Gets contents of the .gitignore file. */ protected static getGitIgnoreFile(): string { return `.idea/ .vscode/ node_modules/ build/ tmp/ temp/`; } /** * Gets contents of the user entity. */ protected static getUserEntityTemplate(database: string): string { return `import {Entity, ${ database === "mongodb" ? "ObjectIdColumn, ObjectID" : "PrimaryGeneratedColumn" }, Column} from "typeorm"; @Entity() export class User { ${ database === "mongodb" ? "@ObjectIdColumn()" : "@PrimaryGeneratedColumn()" } id: ${ database === "mongodb" ? "ObjectID" : "number" }; @Column() firstName: string; @Column() lastName: string; @Column() age: number; } `; } /** * Gets contents of the route file (used when express is enabled). */ protected static getRoutesTemplate(): string { return `import {UserController} from "./controller/UserController"; export const Routes = [{ method: "get", route: "/users", controller: UserController, action: "all" }, { method: "get", route: "/users/:id", controller: UserController, action: "one" }, { method: "post", route: "/users", controller: UserController, action: "save" }, { method: "delete", route: "/users/:id", controller: UserController, action: "remove" }];`; } /** * Gets contents of the user controller file (used when express is enabled). */ protected static getControllerTemplate(): string { return `import {getRepository} from "typeorm"; import {NextFunction, Request, Response} from "express"; import {User} from "../entity/User"; export class UserController { private userRepository = getRepository(User); async all(request: Request, response: Response, next: NextFunction) { return this.userRepository.find(); } async one(request: Request, response: Response, next: NextFunction) { return this.userRepository.findOne(request.params.id); } async save(request: Request, response: Response, next: NextFunction) { return this.userRepository.save(request.body); } async remove(request: Request, response: Response, next: NextFunction) { let userToRemove = await this.userRepository.findOne(request.params.id); await this.userRepository.remove(userToRemove); } }`; } /** * Gets contents of the main (index) application file. */ protected static getAppIndexTemplate(express: boolean): string { if (express) { return `import "reflect-metadata"; import {createConnection} from "typeorm"; import * as express from "express"; import * as bodyParser from "body-parser"; import {Request, Response} from "express"; import {Routes} from "./routes"; import {User} from "./entity/User"; createConnection().then(async connection => { // create express app const app = express(); app.use(bodyParser.json()); // register express routes from defined application routes Routes.forEach(route => { (app as any)[route.method](route.route, (req: Request, res: Response, next: Function) => { const result = (new (route.controller as any))[route.action](req, res, next); if (result instanceof Promise) { result.then(result => result !== null && result !== undefined ? res.send(result) : undefined); } else if (result !== null && result !== undefined) { res.json(result); } }); }); // setup express app here // ... // start express server app.listen(3000); // insert new users for test await connection.manager.save(connection.manager.create(User, { firstName: "Timber", lastName: "Saw", age: 27 })); await connection.manager.save(connection.manager.create(User, { firstName: "Phantom", lastName: "Assassin", age: 24 })); console.log("Express server has started on port 3000. Open http://localhost:3000/users to see results"); }).catch(error => console.log(error)); `; } else { return `import "reflect-metadata"; import {createConnection} from "typeorm"; import {User} from "./entity/User"; createConnection().then(async connection => { console.log("Inserting a new user into the database..."); const user = new User(); user.firstName = "Timber"; user.lastName = "Saw"; user.age = 25; await connection.manager.save(user); console.log("Saved a new user with id: " + user.id); console.log("Loading users from the database..."); const users = await connection.manager.find(User); console.log("Loaded users: ", users); console.log("Here you can setup and run express/koa/any other framework."); }).catch(error => console.log(error)); `; } } /** * Gets contents of the new package.json file. */ protected static getPackageJsonTemplate(projectName?: string): string { return JSON.stringify({ name: projectName || "new-typeorm-project", version: "0.0.1", description: "Awesome project developed with TypeORM.", devDependencies: { }, dependencies: { }, scripts: { } }, undefined, 3); } /** * Gets contents of the new docker-compose.yml file. */ protected static getDockerComposeTemplate(database: string): string { switch (database) { case "mysql": return `version: '3' services: mysql: image: "mysql:5.7.10" ports: - "3306:3306" environment: MYSQL_ROOT_PASSWORD: "admin" MYSQL_USER: "test" MYSQL_PASSWORD: "test" MYSQL_DATABASE: "test" `; case "mariadb": return `version: '3' services: mariadb: image: "mariadb:10.1.16" ports: - "3306:3306" environment: MYSQL_ROOT_PASSWORD: "admin" MYSQL_USER: "test" MYSQL_PASSWORD: "test" MYSQL_DATABASE: "test" `; case "postgres": return `version: '3' services: postgres: image: "postgres:9.6.1" ports: - "5432:5432" environment: POSTGRES_USER: "test" POSTGRES_PASSWORD: "test" POSTGRES_DB: "test" `; case "cockroachdb": return `version: '3' services: cockroachdb: image: "cockroachdb/cockroach:v2.1.4" command: start --insecure ports: - "26257:26257" `; case "sqlite": case "better-sqlite3": return `version: '3' services: `; case "oracle": throw new TypeORMError(`You cannot initialize a project with docker for Oracle driver yet.`); // todo: implement for oracle as well case "mssql": return `version: '3' services: mssql: image: "microsoft/mssql-server-linux:rc2" ports: - "1433:1433" environment: SA_PASSWORD: "Admin12345" ACCEPT_EULA: "Y" `; case "mongodb": return `version: '3' services: mongodb: image: "mongo:4.0.6" container_name: "typeorm-mongodb" ports: - "27017:27017" `; } return ""; } /** * Gets contents of the new readme.md file. */ protected static getReadmeTemplate(options: { docker: boolean }): string { let template = `# Awesome Project Build with TypeORM Steps to run this project: 1. Run \`npm i\` command `; if (options.docker) { template += `2. Run \`docker-compose up\` command `; } else { template += `2. Setup database settings inside \`ormconfig.json\` file `; } template += `3. Run \`npm start\` command `; return template; } /** * Appends to a given package.json template everything needed. */ protected static appendPackageJson(packageJsonContents: string, database: string, express: boolean /*, docker: boolean*/): string { const packageJson = JSON.parse(packageJsonContents); if (!packageJson.devDependencies) packageJson.devDependencies = {}; Object.assign(packageJson.devDependencies, { "ts-node": "3.3.0", "@types/node": "^8.0.29", "typescript": "3.3.3333" }); if (!packageJson.dependencies) packageJson.dependencies = {}; Object.assign(packageJson.dependencies, { "typeorm": require("../package.json").version, "reflect-metadata": "^0.1.10" }); switch (database) { case "mysql": case "mariadb": packageJson.dependencies["mysql"] = "^2.14.1"; break; case "postgres": case "cockroachdb": packageJson.dependencies["pg"] = "^8.4.0"; break; case "sqlite": packageJson.dependencies["sqlite3"] = "^4.0.3"; break; case "better-sqlite3": packageJson.dependencies["better-sqlite3"] = "^7.0.0"; break; case "oracle": packageJson.dependencies["oracledb"] = "^1.13.1"; break; case "mssql": packageJson.dependencies["mssql"] = "^4.0.4"; break; case "mongodb": packageJson.dependencies["mongodb"] = "^3.0.8"; break; } if (express) { packageJson.dependencies["express"] = "^4.15.4"; packageJson.dependencies["body-parser"] = "^1.18.1"; } if (!packageJson.scripts) packageJson.scripts = {}; Object.assign(packageJson.scripts, { start: /*(docker ? "docker-compose up && " : "") + */"ts-node src/index.ts" }); return JSON.stringify(packageJson, undefined, 3); } }
the_stack
import {Equals} from "@swim/util"; import {Output, Debug, Format} from "@swim/codec"; import {AnyLength, Length, AnyAngle, Angle, AnyR2Point, R2Point, R2Box} from "@swim/math"; import type {GraphicsRenderer} from "../graphics/GraphicsRenderer"; import type {Graphics} from "../graphics/Graphics"; import type {DrawingContext} from "../drawing/DrawingContext"; import {PathContext} from "../path/PathContext"; import {PathRenderer} from "../path/PathRenderer"; /** @public */ export type AnyArc = Arc | ArcInit; /** @public */ export interface ArcInit { center?: R2Point; innerRadius?: AnyLength; outerRadius?: AnyLength; startAngle?: AnyAngle; sweepAngle?: AnyAngle; padAngle?: AnyAngle; padRadius?: AnyLength | null; cornerRadius?: AnyLength; } /** @public */ export class Arc implements Graphics, Equals, Debug { constructor(center: R2Point, innerRadius: Length, outerRadius: Length, startAngle: Angle, sweepAngle: Angle, padAngle: Angle, padRadius: Length | null, cornerRadius: Length) { this.center = center; this.innerRadius = innerRadius; this.outerRadius = outerRadius; this.startAngle = startAngle; this.sweepAngle = sweepAngle; this.padAngle = padAngle; this.padRadius = padRadius; this.cornerRadius = cornerRadius; } readonly center: R2Point; withCenter(center: AnyR2Point): Arc { center = R2Point.fromAny(center); if (this.center.equals(center)) { return this; } else { return this.copy(center as R2Point, this.innerRadius, this.outerRadius, this.startAngle, this.sweepAngle, this.padAngle, this.padRadius, this.cornerRadius); } } readonly innerRadius: Length; withInnerRadius(innerRadius: AnyLength): Arc { innerRadius = Length.fromAny(innerRadius); if (this.innerRadius.equals(innerRadius)) { return this; } else { return this.copy(this.center, innerRadius, this.outerRadius, this.startAngle, this.sweepAngle, this.padAngle, this.padRadius, this.cornerRadius); } } readonly outerRadius: Length; withOuterRadius(outerRadius: AnyLength): Arc { outerRadius = Length.fromAny(outerRadius); if (this.outerRadius.equals(outerRadius)) { return this; } else { return this.copy(this.center, this.innerRadius, outerRadius, this.startAngle, this.sweepAngle, this.padAngle, this.padRadius, this.cornerRadius); } } readonly startAngle: Angle; withStartAngle(startAngle: AnyAngle): Arc { startAngle = Angle.fromAny(startAngle); if (this.startAngle.equals(startAngle)) { return this; } else { return this.copy(this.center, this.innerRadius, this.outerRadius, startAngle, this.sweepAngle, this.padAngle, this.padRadius, this.cornerRadius); } } readonly sweepAngle: Angle; withSweepAngle(sweepAngle: AnyAngle): Arc { sweepAngle = Angle.fromAny(sweepAngle); if (this.sweepAngle.equals(sweepAngle)) { return this; } else { return this.copy(this.center, this.innerRadius, this.outerRadius, this.startAngle, sweepAngle, this.padAngle, this.padRadius, this.cornerRadius); } } readonly padAngle: Angle; withPadAngle(padAngle: AnyAngle): Arc { padAngle = Angle.fromAny(padAngle); if (this.padAngle.equals(padAngle)) { return this; } else { return this.copy(this.center, this.innerRadius, this.outerRadius, this.startAngle, this.sweepAngle, padAngle, this.padRadius, this.cornerRadius); } } readonly padRadius: Length | null; withPadRadius(padRadius: AnyLength | null): Arc { if (padRadius !== null) { padRadius = Length.fromAny(padRadius); } if (Equals(this.padRadius, padRadius)) { return this; } else { return this.copy(this.center, this.innerRadius, this.outerRadius, this.startAngle, this.sweepAngle, this.padAngle, padRadius, this.cornerRadius); } } readonly cornerRadius: Length; withCornerRadius(cornerRadius: AnyLength): Arc { cornerRadius = Length.fromAny(cornerRadius); if (this.cornerRadius.equals(cornerRadius)) { return this; } else { return this.copy(this.center, this.innerRadius, this.outerRadius, this.startAngle, this.sweepAngle, this.padAngle, this.padRadius, cornerRadius); } } render(): string; render(renderer: GraphicsRenderer, frame?: R2Box): void; render(renderer?: GraphicsRenderer, frame?: R2Box): string | void { if (renderer === void 0) { const context = new PathContext(); context.setPrecision(3); this.draw(context, frame); return context.toString(); } else if (renderer instanceof PathRenderer) { this.draw(renderer.context, frame); } } draw(context: DrawingContext, frame?: R2Box): void { this.renderArc(context, frame); } protected renderArc(context: DrawingContext, frame: R2Box | undefined): void { let size: number | undefined; if (frame !== void 0) { size = Math.min(frame.width, frame.height); } const center = this.center; const cx = center.x; const cy = center.y; let r0 = this.innerRadius.pxValue(size); let r1 = this.outerRadius.pxValue(size); const a0 = this.startAngle.radValue(); const da = this.sweepAngle.radValue(); const a1 = a0 + da; const cw = da >= 0; if (r1 < r0) { // swap inner and outer radii const r = r1; r1 = r0; r0 = r; } if (!(r1 > Arc.Epsilon)) { // degenerate point context.moveTo(cx, cy); } else if (da > 2 * Math.PI - Arc.Epsilon) { // full circle or annulus context.moveTo(cx + r1 * Math.cos(a0), cy + r1 * Math.sin(a0)); context.arc(cx, cy, r1, a0, a1, !cw); if (r0 > Arc.Epsilon) { context.moveTo(cx + r0 * Math.cos(a1), cy + r0 * Math.sin(a1)); context.arc(cx, cy, r0, a1, a0, cw); } } else { // circular or annular sector let a01 = a0; let a11 = a1; let a00 = a0; let a10 = a1; let da0 = da; let da1 = da; const ap = (this.padAngle.radValue()) / 2; const rp = +(ap > Arc.Epsilon) && (this.padRadius !== null ? this.padRadius.pxValue(size) : Math.sqrt(r0 * r0 + r1 * r1)); const rc = Math.min(Math.abs(r1 - r0) / 2, this.cornerRadius.pxValue(size)); let rc0 = rc; let rc1 = rc; if (rp > Arc.Epsilon) { // apply padding let p0 = Math.asin(rp / r0 * Math.sin(ap)); let p1 = Math.asin(rp / r1 * Math.sin(ap)); if ((da0 -= p0 * 2) > Arc.Epsilon) { p0 *= cw ? 1 : -1; a00 += p0; a10 -= p0; } else { da0 = 0; a00 = a10 = (a0 + a1) / 2; } if ((da1 -= p1 * 2) > Arc.Epsilon) { p1 *= cw ? 1 : -1; a01 += p1; a11 -= p1; } else { da1 = 0; a01 = a11 = (a0 + a1) / 2; } } let x00: number | undefined; let y00: number | undefined; const x01 = r1 * Math.cos(a01); const y01 = r1 * Math.sin(a01); const x10 = r0 * Math.cos(a10); const y10 = r0 * Math.sin(a10); let x11: number | undefined; let y11: number | undefined; if (rc > Arc.Epsilon) { // rounded corners x11 = r1 * Math.cos(a11); y11 = r1 * Math.sin(a11); x00 = r0 * Math.cos(a00); y00 = r0 * Math.sin(a00); if (da < Math.PI) { // limit corner radius to sector angle const oc = da0 > Arc.Epsilon ? Arc.intersect(x01, y01, x00, y00, x11, y11, x10, y10) : [x10, y10]; const ax = x01 - oc[0]!; const ay = y01 - oc[1]!; const bx = x11 - oc[0]!; const by = y11 - oc[1]!; const kc = 1 / Math.sin(0.5 * Math.acos((ax * bx + ay * by) / (Math.sqrt(ax * ax + ay * ay) * Math.sqrt(bx * bx + by * by)))); const lc = Math.sqrt(oc[0]! * oc[0]! + oc[1]! * oc[1]!); rc0 = Math.min(rc, (r0 - lc) / (kc - 1)); rc1 = Math.min(rc, (r1 - lc) / (kc + 1)); } } if (!(da1 > Arc.Epsilon)) { // collapsed sector context.moveTo(cx + x01, cy + y01); } else if (rc1 > Arc.Epsilon) { // rounded outer corners const t0 = Arc.cornerTangents(x00!, y00!, x01, y01, r1, rc1, cw); const t1 = Arc.cornerTangents(x11!, y11!, x10, y10, r1, rc1, cw); context.moveTo(cx + t0.cx + t0.x01, cy + t0.cy + t0.y01); if (rc1 < rc) { // draw merged outer corners context.arc(cx + t0.cx, cy + t0.cy, rc1, Math.atan2(t0.y01, t0.x01), Math.atan2(t1.y01, t1.x01), !cw); } else { // draw outer corners and arc context.arc(cx + t0.cx, cy + t0.cy, rc1, Math.atan2(t0.y01, t0.x01), Math.atan2(t0.y11, t0.x11), !cw); context.arc(cx, cy, r1, Math.atan2(t0.cy + t0.y11, t0.cx + t0.x11), Math.atan2(t1.cy + t1.y11, t1.cx + t1.x11), !cw); context.arc(cx + t1.cx, cy + t1.cy, rc1, Math.atan2(t1.y11, t1.x11), Math.atan2(t1.y01, t1.x01), !cw); } } else { // draw outer circular arc context.moveTo(cx + x01, cy + y01); context.arc(cx, cy, r1, a01, a11, !cw); } if (!(r0 > Arc.Epsilon) || !(da0 > Arc.Epsilon)) { // collapsed sector context.lineTo(cx + x10, cy + y10); } else if (rc0 > Arc.Epsilon) { // rounded inner corners const t0 = Arc.cornerTangents(x10, y10, x11!, y11!, r0, -rc0, cw); const t1 = Arc.cornerTangents(x01, y01, x00!, y00!, r0, -rc0, cw); context.lineTo(cx + t0.cx + t0.x01, cy + t0.cy + t0.y01); if (rc0 < rc) { // draw merged inner corners context.arc(cx + t0.cx, cy + t0.cy, rc0, Math.atan2(t0.y01, t0.x01), Math.atan2(t1.y01, t1.x01), !cw); } else { // draw inner corners and arc context.arc(cx + t0.cx, cy + t0.cy, rc0, Math.atan2(t0.y01, t0.x01), Math.atan2(t0.y11, t0.x11), !cw); context.arc(cx, cy, r0, Math.atan2(t0.cy + t0.y11, t0.cx + t0.x11), Math.atan2(t1.cy + t1.y11, t1.cx + t1.x11), cw); context.arc(cx + t1.cx, cy + t1.cy, rc0, Math.atan2(t1.y11, t1.x11), Math.atan2(t1.y01, t1.x01), !cw); } } else { // draw inner circular arc context.arc(cx, cy, r0, a10, a00, cw); } } context.closePath(); } protected copy(center: R2Point, innerRadius: Length, outerRadius: Length, startAngle: Angle, sweepAngle: Angle, padAngle: Angle, padRadius: Length | null, cornerRadius: Length): Arc { return new Arc(center, innerRadius, outerRadius, startAngle, sweepAngle, padAngle, padRadius, cornerRadius); } toAny(): ArcInit { return { center: this.center, innerRadius: this.innerRadius, outerRadius: this.outerRadius, startAngle: this.startAngle, sweepAngle: this.sweepAngle, padAngle: this.padAngle, padRadius: this.padRadius, cornerRadius: this.cornerRadius, }; } equals(that: unknown): boolean { if (this === that) { return true; } else if (that instanceof Arc) { return this.center.equals(that.center) && this.innerRadius.equals(that.innerRadius) && this.outerRadius.equals(that.outerRadius) && this.startAngle.equals(that.startAngle) && this.sweepAngle.equals(that.sweepAngle) && this.padAngle.equals(that.padAngle) && Equals(this.padRadius, that.padRadius) && this.cornerRadius.equals(that.cornerRadius); } return false; } debug<T>(output: Output<T>): Output<T> { output = output.write("Arc").write(46/*'.'*/).write("create").write(40/*'('*/).write(41/*')'*/); if (this.center.isDefined()) { output = output.write(46/*'.'*/).write("center").write(40/*'('*/).debug(this.center).write(41/*')'*/); } if (this.innerRadius.isDefined()) { output = output.write(46/*'.'*/).write("innerRadius").write(40/*'('*/).debug(this.innerRadius).write(41/*')'*/); } if (this.outerRadius.isDefined()) { output = output.write(46/*'.'*/).write("outerRadius").write(40/*'('*/).debug(this.outerRadius).write(41/*')'*/); } if (this.startAngle.isDefined()) { output = output.write(46/*'.'*/).write("startAngle").write(40/*'('*/).debug(this.startAngle).write(41/*')'*/); } if (this.sweepAngle.isDefined()) { output = output.write(46/*'.'*/).write("sweepAngle").write(40/*'('*/).debug(this.sweepAngle).write(41/*')'*/); } if (this.padAngle.isDefined()) { output = output.write(46/*'.'*/).write("padAngle").write(40/*'('*/).debug(this.padAngle).write(41/*')'*/); } if (this.padRadius !== null) { output = output.write(46/*'.'*/).write("padRadius").write(40/*'('*/).debug(this.padRadius).write(41/*')'*/); } if (this.cornerRadius.isDefined()) { output = output.write(46/*'.'*/).write("cornerRadius").write(40/*'('*/).debug(this.cornerRadius).write(41/*')'*/); } return output; } toString(): string { return Format.debug(this); } static create(center: AnyR2Point = R2Point.origin(), innerRadius: AnyLength = Length.zero(), outerRadius: AnyLength = Length.zero(), startAngle: AnyAngle = Angle.zero(), sweepAngle: AnyAngle = Angle.zero(), padAngle: AnyAngle = Angle.zero(), padRadius: AnyLength | null = null, cornerRadius: AnyLength = Length.zero()): Arc { center = R2Point.fromAny(center); innerRadius = Length.fromAny(innerRadius); outerRadius = Length.fromAny(outerRadius); startAngle = Angle.fromAny(startAngle); sweepAngle = Angle.fromAny(sweepAngle); padAngle = Angle.fromAny(padAngle); padRadius = padRadius !== null ? Length.fromAny(padRadius) : null; cornerRadius = Length.fromAny(cornerRadius); return new Arc(center as R2Point, innerRadius, outerRadius, startAngle, sweepAngle, padAngle, padRadius, cornerRadius); } static fromAny(value: AnyArc): Arc { if (value instanceof Arc) { return value; } else if (typeof value === "object" && value !== null) { return Arc.create(value.center, value.innerRadius, value.outerRadius, value.startAngle, value.sweepAngle, value.padAngle, value.padRadius, value.cornerRadius); } throw new TypeError("" + value); } private static intersect(x0: number, y0: number, x1: number, y1: number, x2: number, y2: number, x3: number, y3: number): [number, number] { const x10 = x1 - x0; const y10 = y1 - y0; const x32 = x3 - x2; const y32 = y3 - y2; const t = (x32 * (y0 - y2) - y32 * (x0 - x2)) / (y32 * x10 - x32 * y10); return [x0 + t * x10, y0 + t * y10]; } private static cornerTangents(x0: number, y0: number, x1: number, y1: number, r1: number, rc: number, cw: boolean) : {cx: number, cy: number, x01: number, y01: number, x11: number, y11: number} { // http://mathworld.wolfram.com/Circle-LineIntersection.html const x01 = x0 - x1; const y01 = y0 - y1; const lo = (cw ? rc : -rc) / Math.sqrt(x01 * x01 + y01 * y01); const ox = lo * y01; const oy = -lo * x01; const x11 = x0 + ox; const y11 = y0 + oy; const x10 = x1 + ox; const y10 = y1 + oy; const x00 = (x11 + x10) / 2; const y00 = (y11 + y10) / 2; const dx = x10 - x11; const dy = y10 - y11; const d2 = dx * dx + dy * dy; const r = r1 - rc; const D = x11 * y10 - x10 * y11; const d = (dy < 0 ? -1 : 1) * Math.sqrt(Math.max(0, r * r * d2 - D * D)); let cx0 = (D * dy - dx * d) / d2; let cy0 = (-D * dx - dy * d) / d2; const cx1 = (D * dy + dx * d) / d2; const cy1 = (-D * dx + dy * d) / d2; const dx0 = cx0 - x00; const dy0 = cy0 - y00; const dx1 = cx1 - x00; const dy1 = cy1 - y00; if (dx0 * dx0 + dy0 * dy0 > dx1 * dx1 + dy1 * dy1) { // pick closest intersection cx0 = cx1; cy0 = cy1; } return { cx: cx0, cy: cy0, x01: -ox, y01: -oy, x11: cx0 * (r1 / r - 1), y11: cy0 * (r1 / r - 1), }; } /** @internal */ static Epsilon: number = 1e-12; }
the_stack
import { Codicon } from 'vs/base/common/codicons'; import { KeyCode, KeyMod } from 'vs/base/common/keyCodes'; import { ILanguageService } from 'vs/editor/common/languages/language'; import { localize } from 'vs/nls'; import { IAction2Options, MenuId, MenuRegistry, registerAction2 } from 'vs/platform/actions/common/actions'; import { ContextKeyExpr } from 'vs/platform/contextkey/common/contextkey'; import { InputFocusedContext } from 'vs/platform/contextkey/common/contextkeys'; import { ServicesAccessor } from 'vs/platform/instantiation/common/instantiation'; import { KeybindingWeight } from 'vs/platform/keybinding/common/keybindingsRegistry'; import { insertCell } from 'vs/workbench/contrib/notebook/browser/controller/cellOperations'; import { INotebookActionContext, NotebookAction } from 'vs/workbench/contrib/notebook/browser/controller/coreActions'; import { NOTEBOOK_CELL_LIST_FOCUSED, NOTEBOOK_EDITOR_EDITABLE } from 'vs/workbench/contrib/notebook/common/notebookContextKeys'; import { CellViewModel } from 'vs/workbench/contrib/notebook/browser/viewModel/notebookViewModelImpl'; import { CellKind, NotebookSetting } from 'vs/workbench/contrib/notebook/common/notebookCommon'; const INSERT_CODE_CELL_ABOVE_COMMAND_ID = 'notebook.cell.insertCodeCellAbove'; const INSERT_CODE_CELL_BELOW_COMMAND_ID = 'notebook.cell.insertCodeCellBelow'; const INSERT_CODE_CELL_ABOVE_AND_FOCUS_CONTAINER_COMMAND_ID = 'notebook.cell.insertCodeCellAboveAndFocusContainer'; const INSERT_CODE_CELL_BELOW_AND_FOCUS_CONTAINER_COMMAND_ID = 'notebook.cell.insertCodeCellBelowAndFocusContainer'; const INSERT_CODE_CELL_AT_TOP_COMMAND_ID = 'notebook.cell.insertCodeCellAtTop'; const INSERT_MARKDOWN_CELL_ABOVE_COMMAND_ID = 'notebook.cell.insertMarkdownCellAbove'; const INSERT_MARKDOWN_CELL_BELOW_COMMAND_ID = 'notebook.cell.insertMarkdownCellBelow'; const INSERT_MARKDOWN_CELL_AT_TOP_COMMAND_ID = 'notebook.cell.insertMarkdownCellAtTop'; abstract class InsertCellCommand extends NotebookAction { constructor( desc: Readonly<IAction2Options>, private kind: CellKind, private direction: 'above' | 'below', private focusEditor: boolean ) { super(desc); } async runWithContext(accessor: ServicesAccessor, context: INotebookActionContext): Promise<void> { let newCell: CellViewModel | null = null; if (context.ui) { context.notebookEditor.focus(); } const languageService = accessor.get(ILanguageService); if (context.cell) { const idx = context.notebookEditor.getCellIndex(context.cell); newCell = insertCell(languageService, context.notebookEditor, idx, this.kind, this.direction, undefined, true); } else { const focusRange = context.notebookEditor.getFocus(); const next = Math.max(focusRange.end - 1, 0); newCell = insertCell(languageService, context.notebookEditor, next, this.kind, this.direction, undefined, true); } if (newCell) { context.notebookEditor.focusNotebookCell(newCell, this.focusEditor ? 'editor' : 'container'); } } } registerAction2(class InsertCodeCellAboveAction extends InsertCellCommand { constructor() { super( { id: INSERT_CODE_CELL_ABOVE_COMMAND_ID, title: localize('notebookActions.insertCodeCellAbove', "Insert Code Cell Above"), keybinding: { primary: KeyMod.CtrlCmd | KeyMod.Shift | KeyCode.Enter, when: ContextKeyExpr.and(NOTEBOOK_CELL_LIST_FOCUSED, InputFocusedContext.toNegated()), weight: KeybindingWeight.WorkbenchContrib }, menu: { id: MenuId.NotebookCellInsert, order: 0 } }, CellKind.Code, 'above', true); } }); registerAction2(class InsertCodeCellAboveAndFocusContainerAction extends InsertCellCommand { constructor() { super( { id: INSERT_CODE_CELL_ABOVE_AND_FOCUS_CONTAINER_COMMAND_ID, title: localize('notebookActions.insertCodeCellAboveAndFocusContainer', "Insert Code Cell Above and Focus Container") }, CellKind.Code, 'above', false); } }); registerAction2(class InsertCodeCellBelowAction extends InsertCellCommand { constructor() { super( { id: INSERT_CODE_CELL_BELOW_COMMAND_ID, title: localize('notebookActions.insertCodeCellBelow', "Insert Code Cell Below"), keybinding: { primary: KeyMod.CtrlCmd | KeyCode.Enter, when: ContextKeyExpr.and(NOTEBOOK_CELL_LIST_FOCUSED, InputFocusedContext.toNegated()), weight: KeybindingWeight.WorkbenchContrib }, menu: { id: MenuId.NotebookCellInsert, order: 1 } }, CellKind.Code, 'below', true); } }); registerAction2(class InsertCodeCellBelowAndFocusContainerAction extends InsertCellCommand { constructor() { super( { id: INSERT_CODE_CELL_BELOW_AND_FOCUS_CONTAINER_COMMAND_ID, title: localize('notebookActions.insertCodeCellBelowAndFocusContainer', "Insert Code Cell Below and Focus Container"), }, CellKind.Code, 'below', false); } }); registerAction2(class InsertMarkdownCellAboveAction extends InsertCellCommand { constructor() { super( { id: INSERT_MARKDOWN_CELL_ABOVE_COMMAND_ID, title: localize('notebookActions.insertMarkdownCellAbove', "Insert Markdown Cell Above"), menu: { id: MenuId.NotebookCellInsert, order: 2 } }, CellKind.Markup, 'above', true); } }); registerAction2(class InsertMarkdownCellBelowAction extends InsertCellCommand { constructor() { super( { id: INSERT_MARKDOWN_CELL_BELOW_COMMAND_ID, title: localize('notebookActions.insertMarkdownCellBelow', "Insert Markdown Cell Below"), menu: { id: MenuId.NotebookCellInsert, order: 3 } }, CellKind.Markup, 'below', true); } }); registerAction2(class InsertCodeCellAtTopAction extends NotebookAction { constructor() { super( { id: INSERT_CODE_CELL_AT_TOP_COMMAND_ID, title: localize('notebookActions.insertCodeCellAtTop', "Add Code Cell At Top"), f1: false }); } override async run(accessor: ServicesAccessor, context?: INotebookActionContext): Promise<void> { context = context ?? this.getEditorContextFromArgsOrActive(accessor); if (context) { this.runWithContext(accessor, context); } } async runWithContext(accessor: ServicesAccessor, context: INotebookActionContext): Promise<void> { const languageService = accessor.get(ILanguageService); const newCell = insertCell(languageService, context.notebookEditor, 0, CellKind.Code, 'above', undefined, true); if (newCell) { context.notebookEditor.focusNotebookCell(newCell, 'editor'); } } }); registerAction2(class InsertMarkdownCellAtTopAction extends NotebookAction { constructor() { super( { id: INSERT_MARKDOWN_CELL_AT_TOP_COMMAND_ID, title: localize('notebookActions.insertMarkdownCellAtTop', "Add Markdown Cell At Top"), f1: false }); } override async run(accessor: ServicesAccessor, context?: INotebookActionContext): Promise<void> { context = context ?? this.getEditorContextFromArgsOrActive(accessor); if (context) { this.runWithContext(accessor, context); } } async runWithContext(accessor: ServicesAccessor, context: INotebookActionContext): Promise<void> { const languageService = accessor.get(ILanguageService); const newCell = insertCell(languageService, context.notebookEditor, 0, CellKind.Markup, 'above', undefined, true); if (newCell) { context.notebookEditor.focusNotebookCell(newCell, 'editor'); } } }); MenuRegistry.appendMenuItem(MenuId.NotebookCellBetween, { command: { id: INSERT_CODE_CELL_BELOW_COMMAND_ID, title: localize('notebookActions.menu.insertCode', "$(add) Code"), tooltip: localize('notebookActions.menu.insertCode.tooltip', "Add Code Cell") }, order: 0, group: 'inline', when: ContextKeyExpr.and( NOTEBOOK_EDITOR_EDITABLE.isEqualTo(true), ContextKeyExpr.notEquals('config.notebook.experimental.insertToolbarAlignment', 'left') ) }); MenuRegistry.appendMenuItem(MenuId.NotebookCellBetween, { command: { id: INSERT_CODE_CELL_BELOW_COMMAND_ID, title: localize('notebookActions.menu.insertCode.minimalToolbar', "Add Code"), icon: Codicon.add, tooltip: localize('notebookActions.menu.insertCode.tooltip', "Add Code Cell") }, order: 0, group: 'inline', when: ContextKeyExpr.and( NOTEBOOK_EDITOR_EDITABLE.isEqualTo(true), ContextKeyExpr.equals('config.notebook.experimental.insertToolbarAlignment', 'left') ) }); MenuRegistry.appendMenuItem(MenuId.NotebookToolbar, { command: { id: INSERT_CODE_CELL_BELOW_COMMAND_ID, icon: Codicon.add, title: localize('notebookActions.menu.insertCode.ontoolbar', "Code"), tooltip: localize('notebookActions.menu.insertCode.tooltip', "Add Code Cell") }, order: -5, group: 'navigation/add', when: ContextKeyExpr.and( NOTEBOOK_EDITOR_EDITABLE.isEqualTo(true), ContextKeyExpr.notEquals('config.notebook.insertToolbarLocation', 'betweenCells'), ContextKeyExpr.notEquals('config.notebook.insertToolbarLocation', 'hidden') ) }); MenuRegistry.appendMenuItem(MenuId.NotebookCellListTop, { command: { id: INSERT_CODE_CELL_AT_TOP_COMMAND_ID, title: localize('notebookActions.menu.insertCode', "$(add) Code"), tooltip: localize('notebookActions.menu.insertCode.tooltip', "Add Code Cell") }, order: 0, group: 'inline', when: ContextKeyExpr.and( NOTEBOOK_EDITOR_EDITABLE.isEqualTo(true), ContextKeyExpr.notEquals('config.notebook.experimental.insertToolbarAlignment', 'left') ) }); MenuRegistry.appendMenuItem(MenuId.NotebookCellListTop, { command: { id: INSERT_CODE_CELL_AT_TOP_COMMAND_ID, title: localize('notebookActions.menu.insertCode.minimaltoolbar', "Add Code"), icon: Codicon.add, tooltip: localize('notebookActions.menu.insertCode.tooltip', "Add Code Cell") }, order: 0, group: 'inline', when: ContextKeyExpr.and( NOTEBOOK_EDITOR_EDITABLE.isEqualTo(true), ContextKeyExpr.equals('config.notebook.experimental.insertToolbarAlignment', 'left') ) }); MenuRegistry.appendMenuItem(MenuId.NotebookCellBetween, { command: { id: INSERT_MARKDOWN_CELL_BELOW_COMMAND_ID, title: localize('notebookActions.menu.insertMarkdown', "$(add) Markdown"), tooltip: localize('notebookActions.menu.insertMarkdown.tooltip', "Add Markdown Cell") }, order: 1, group: 'inline', when: ContextKeyExpr.and( NOTEBOOK_EDITOR_EDITABLE.isEqualTo(true), ContextKeyExpr.notEquals('config.notebook.experimental.insertToolbarAlignment', 'left') ) }); MenuRegistry.appendMenuItem(MenuId.NotebookToolbar, { command: { id: INSERT_MARKDOWN_CELL_BELOW_COMMAND_ID, icon: Codicon.add, title: localize('notebookActions.menu.insertMarkdown.ontoolbar', "Markdown"), tooltip: localize('notebookActions.menu.insertMarkdown.tooltip', "Add Markdown Cell") }, order: -5, group: 'navigation/add', when: ContextKeyExpr.and( NOTEBOOK_EDITOR_EDITABLE.isEqualTo(true), ContextKeyExpr.notEquals('config.notebook.insertToolbarLocation', 'betweenCells'), ContextKeyExpr.notEquals('config.notebook.insertToolbarLocation', 'hidden'), ContextKeyExpr.notEquals(`config.${NotebookSetting.globalToolbarShowLabel}`, false), ContextKeyExpr.notEquals(`config.${NotebookSetting.globalToolbarShowLabel}`, 'never') ) }); MenuRegistry.appendMenuItem(MenuId.NotebookCellListTop, { command: { id: INSERT_MARKDOWN_CELL_AT_TOP_COMMAND_ID, title: localize('notebookActions.menu.insertMarkdown', "$(add) Markdown"), tooltip: localize('notebookActions.menu.insertMarkdown.tooltip', "Add Markdown Cell") }, order: 1, group: 'inline', when: ContextKeyExpr.and( NOTEBOOK_EDITOR_EDITABLE.isEqualTo(true), ContextKeyExpr.notEquals('config.notebook.experimental.insertToolbarAlignment', 'left') ) });
the_stack
import * as chalk from "chalk"; import { assert } from "node-opcua-assert"; import { AttributeIds, QualifiedNameLike } from "node-opcua-data-model"; import { DiagnosticInfo, NodeClass } from "node-opcua-data-model"; import { DataValue, DataValueLike } from "node-opcua-data-value"; import { make_debugLog, make_errorLog, make_warningLog } from "node-opcua-debug"; import { NodeId } from "node-opcua-nodeid"; import { NumericRange } from "node-opcua-numeric-range"; import { Argument } from "node-opcua-service-call"; import { StatusCodes } from "node-opcua-status-code"; import { CallMethodResultOptions, PermissionType } from "node-opcua-types"; import { Variant } from "node-opcua-variant"; import { DataType, VariantLike } from "node-opcua-variant"; import { MethodFunctor, MethodFunctorCallback, UAMethod, UAObject, CloneExtraInfo, CloneFilter, CloneOptions, UAObjectType, ISessionContext, UAVariable } from "node-opcua-address-space-base"; import { SessionContext } from "../source"; import { _clone } from "./base_node_private"; import { _handle_hierarchy_parent } from "./namespace_impl"; import { BaseNodeImpl } from "./base_node_impl"; import { AddressSpacePrivate } from "./address_space_private"; const warningLog = make_warningLog(__filename); const debugLog = make_debugLog(__filename); const errorLog = make_errorLog(__filename); function default_check_valid_argument(arg: unknown): boolean { return (arg as any).constructor.name === "Argument"; } export class UAMethodImpl extends BaseNodeImpl implements UAMethod { public static checkValidArgument(args: unknown): boolean { return default_check_valid_argument(args); } public readonly nodeClass = NodeClass.Method; public get typeDefinitionObj(): UAObjectType { return super.typeDefinitionObj as UAObjectType; } public get parent(): UAObject | null { return super.parent as UAObject; } public value?: any; public methodDeclarationId: NodeId; public _getExecutableFlag?: (this: UAMethod, context: ISessionContext | null) => boolean; public _asyncExecutionFunction?: MethodFunctor; constructor(options: any) { super(options); this.value = options.value; this.methodDeclarationId = options.methodDeclarationId; } /** * * */ public getExecutableFlag(context: ISessionContext | null): boolean { if (!this.isBound()) { return false; } if (this._getExecutableFlag) { return this._getExecutableFlag(context); } return true; } /** * * @returns true if the method is bound */ public isBound(): boolean { return typeof this._asyncExecutionFunction === "function"; } public readAttribute( context: ISessionContext | null, attributeId: AttributeIds, indexRange?: NumericRange, dataEncoding?: QualifiedNameLike | null ): DataValue { const options: DataValueLike = {}; switch (attributeId) { case AttributeIds.Executable: options.value = { dataType: DataType.Boolean, value: this.getExecutableFlag(context) }; options.statusCode = StatusCodes.Good; break; case AttributeIds.UserExecutable: options.value = { dataType: DataType.Boolean, value: this.getExecutableFlag(context) }; options.statusCode = StatusCodes.Good; break; default: return BaseNodeImpl.prototype.readAttribute.call(this, context, attributeId, indexRange, dataEncoding); } return new DataValue(options); } public getInputArguments(): Argument[] { return this._getArguments("InputArguments"); } public getOutputArguments(): Argument[] { return this._getArguments("OutputArguments"); } public bindMethod(async_func: MethodFunctor): void { assert(typeof async_func === "function"); this._asyncExecutionFunction = async_func; } public execute( object: UAObject | UAObjectType | null, inputArguments: null | VariantLike[], context: SessionContext ): Promise<CallMethodResultOptions>; public execute( object: UAObject | UAObjectType | null, inputArguments: null | VariantLike[], context: ISessionContext, callback: MethodFunctorCallback ): void; public execute( object: UAObject | UAObjectType | null, inputArguments: VariantLike[] | null, context: ISessionContext, callback?: MethodFunctorCallback ): any { // istanbul ignore next if (!callback) { throw new Error("execute need to be promisified"); } assert(inputArguments === null || Array.isArray(inputArguments)); inputArguments = inputArguments || []; inputArguments = inputArguments.map(Variant.coerce); assert(inputArguments.length === 0 || inputArguments[0] instanceof Variant); assert(context !== null && typeof context === "object"); assert(typeof callback === "function"); object = object || (this.parent as UAObject); // istanbul ignore next if (!object) { errorLog("UAMethod#execute expects a valid object"); return callback(null, { statusCode: StatusCodes.BadInternalError }); } if (object.nodeClass !== NodeClass.Object && object.nodeClass !== NodeClass.ObjectType) { warningLog( "Method " + this.nodeId.toString() + " " + this.browseName.toString() + " called for a node that is not a Object/ObjectType but " + NodeClass[context.object!.nodeClass] ); return callback(null, { statusCode: StatusCodes.BadNodeIdInvalid }); } if (!this._asyncExecutionFunction) { warningLog("Method " + this.nodeId.toString() + " " + this.browseName.toString() + " has not been bound"); return callback(null, { statusCode: StatusCodes.BadInternalError }); } if (!this.getExecutableFlag(context)) { warningLog("Method " + this.nodeId.toString() + " " + this.browseName.toString() + " is not executable"); return callback(null, { statusCode: StatusCodes.BadNotExecutable }); } if (context.isAccessRestricted(this)) { return callback(null, { statusCode: StatusCodes.BadSecurityModeInsufficient }); } if (!context.checkPermission(this, PermissionType.Call)) { return callback(null, { statusCode: StatusCodes.BadUserAccessDenied }); } // verify that input arguments are correct // todo : const inputArgumentDiagnosticInfos: DiagnosticInfo[] = []; context.object = object; try { this._asyncExecutionFunction.call( this as UAMethodImpl, inputArguments as Variant[], context, (err: Error | null, callMethodResult: CallMethodResultOptions) => { if (err) { debugLog(err.message); debugLog(err); } callMethodResult = callMethodResult || {}; callMethodResult.statusCode = callMethodResult.statusCode || StatusCodes.Good; callMethodResult.outputArguments = callMethodResult.outputArguments || []; callMethodResult.inputArgumentResults = callMethodResult.inputArgumentResults?.length === inputArguments?.length ? callMethodResult.inputArgumentResults : inputArguments?.map(() => StatusCodes.Good); callMethodResult.inputArgumentDiagnosticInfos = callMethodResult.inputArgumentDiagnosticInfos || inputArgumentDiagnosticInfos; // verify that output arguments are correct according to schema // Todo : ... // const outputArgsDef = this.getOutputArguments(); // xx assert(outputArgsDef.length === callMethodResponse.outputArguments.length, // xx "_asyncExecutionFunction did not provide the expected number of output arguments"); // to be continued ... callback(err, callMethodResult); } ); } catch (err) { if (err instanceof Error) { warningLog(chalk.red("ERR in method handler"), err.message); warningLog(err.stack); } const callMethodResponse = { statusCode: StatusCodes.BadInternalError }; callback(err as Error, callMethodResponse); } } public clone(options: CloneOptions, optionalFilter?: CloneFilter, extraInfo?: CloneExtraInfo): UAMethod { assert(!options.componentOf || options.componentOf, "trying to create an orphan method ?"); const addressSpace = this.addressSpace as AddressSpacePrivate; options = { ...options, methodDeclarationId: this.nodeId }; options.references = options.references || []; _handle_hierarchy_parent(addressSpace, options.references, options); const clonedMethod = _clone.call(this, UAMethodImpl, options, optionalFilter, extraInfo) as UAMethodImpl; clonedMethod._asyncExecutionFunction = this._asyncExecutionFunction; clonedMethod._getExecutableFlag = this._getExecutableFlag; if (options.componentOf) { const m = options.componentOf.getMethodByName(clonedMethod.browseName.name!); assert(m); } return clonedMethod as UAMethod; } private _getArguments(name: string): Argument[] { assert(name === "InputArguments" || name === "OutputArguments"); const argsVariable = this.getPropertyByName(name); if (!argsVariable) { return []; } assert(argsVariable.nodeClass === NodeClass.Variable); const args = (argsVariable as UAVariable).readValue().value.value; if (!args) { return []; } // a list of extension object assert(Array.isArray(args)); assert(args.length === 0 || UAMethodImpl.checkValidArgument(args[0])); return args; } } // tslint:disable:no-var-requires // tslint:disable:max-line-length const thenify = require("thenify"); UAMethodImpl.prototype.execute = thenify.withCallback(UAMethodImpl.prototype.execute);
the_stack
import { Posts } from './collections/posts/collection'; import { forumTypeSetting, PublicInstanceSetting, hasEventsSetting, taggingNamePluralSetting, taggingNameIsSet, taggingNamePluralCapitalSetting, taggingNameCapitalSetting } from './instanceSettings'; import { legacyRouteAcronymSetting } from './publicSettings'; import { addRoute, PingbackDocument, RouterLocation, Route } from './vulcan-lib/routes'; import { onStartup } from './executionEnvironment'; import { REVIEW_NAME_IN_SITU, REVIEW_YEAR } from './reviewUtils'; import { forumSelect } from './forumTypeUtils'; export const communityPath = '/community'; const communitySubtitle = { subtitleLink: communityPath, subtitle: 'Community' }; const rationalitySubtitle = { subtitleLink: "/rationality", subtitle: "Rationality: A-Z" }; const hpmorSubtitle = { subtitleLink: "/hpmor", subtitle: "HPMoR" }; const codexSubtitle = { subtitleLink: "/codex", subtitle: "SlateStarCodex" }; const bestoflwSubtitle = { subtitleLink: "/bestoflesswrong", subtitle: "Best of LessWrong" }; const walledGardenPortalSubtitle = { subtitleLink: '/walledGarden', subtitle: "Walled Garden"}; const taggingDashboardSubtitle = { subtitleLink: '/tags/dashboard', subtitle: `${taggingNameIsSet.get() ? taggingNamePluralCapitalSetting.get() : 'Wiki-Tag'} Dashboard`} const reviewSubtitle = { subtitleLink: "/reviewVoting", subtitle: `${REVIEW_NAME_IN_SITU} Dashboard`} const aboutPostIdSetting = new PublicInstanceSetting<string>('aboutPostId', 'bJ2haLkcGeLtTWaD5', "warning") // Post ID for the /about route const faqPostIdSetting = new PublicInstanceSetting<string>('faqPostId', '2rWKkWuPrgTMpLRbp', "warning") // Post ID for the /faq route const contactPostIdSetting = new PublicInstanceSetting<string>('contactPostId', "ehcYkvyz7dh9L7Wt8", "warning") const introPostIdSetting = new PublicInstanceSetting<string | null>('introPostId', null, "optional") const eaHandbookPostIdSetting = new PublicInstanceSetting<string | null>('eaHandbookPostId', null, "optional") async function getPostPingbackById(parsedUrl: RouterLocation, postId: string|null): Promise<PingbackDocument|null> { if (!postId) return null; // If the URL contains a hash, it leads to either a comment, a landmark within // the post, or a builtin ID. // TODO: In the case of a comment, we should generate a comment-specific // pingback in addition to the pingback to the post the comment is on. // TODO: In the case of a landmark, we want to customize the hover preview to // reflect where in the post the link was to. return ({ collectionName: "Posts", documentId: postId }) } async function getPostPingbackByLegacyId(parsedUrl: RouterLocation, legacyId: string) { const parsedId = parseInt(legacyId, 36); const post = await Posts.findOne({"legacyId": parsedId.toString()}); if (!post) return null; return await getPostPingbackById(parsedUrl, post._id); } async function getPostPingbackBySlug(parsedUrl: RouterLocation, slug: string) { const post = await Posts.findOne({slug: slug}); if (!post) return null; return await getPostPingbackById(parsedUrl, post._id); } const postBackground = "white" const lw18ReviewPosts = [ ['sketch', 'yeADMcScw8EW9yxpH', 'a-sketch-of-good-communication'], ['babble', 'i42Dfoh4HtsCAfXxL', 'babble'], ['babble2', 'wQACBmK5bioNCgDoG', 'more-babble'], ['prune', 'rYJKvagRYeDM8E9Rf', 'prune'], ['validity', 'WQFioaudEH8R7fyhm', 'local-validity-as-a-key-to-sanity-and-civilization'], ['alarm', 'B2CfMNfay2P8f2yyc', 'the-loudest-alarm-is-probably-false'], ['argument', 'NLBbCQeNLFvBJJkrt', 'varieties-of-argumentative-experience'], ['toolbox', 'CPP2uLcaywEokFKQG', 'toolbox-thinking-and-law-thinking'], ['technical', 'tKwJQbo6SfWF2ifKh', 'toward-a-new-technical-explanation-of-technical-explanation'], ['nameless', '4ZwGqkMTyAvANYEDw', 'naming-the-nameless'], ['lotus', 'KwdcMts8P8hacqwrX', 'noticing-the-taste-of-lotus'], ['tails', 'asmZvCPHcB4SkSCMW', 'the-tails-coming-apart-as-metaphor-for-life'], ['honesty', 'xdwbX9pFEr7Pomaxv', 'meta-honesty-firming-up-honesty-around-its-edge-cases'], ['meditation', 'mELQFMi9egPn5EAjK', 'my-attempt-to-explain-looking-insight-meditation-and'], ['robust', '2jfiMgKkh7qw9z8Do', 'being-a-robust-agent'], ['punish', 'X5RyaEDHNq5qutSHK', 'anti-social-punishment'], ['common', '9QxnfMYccz9QRgZ5z', 'the-costly-coordination-mechanism-of-common-knowledge'], ['metacognition', 'K4eDzqS2rbcBDsCLZ', 'unrolling-social-metacognition-three-levels-of-meta-are-not'], ['web', 'AqbWna2S85pFTsHH4', 'the-intelligent-social-web'], ['market', 'a4jRN9nbD79PAhWTB', 'prediction-markets-when-do-they-work'], ['spaghetti', 'NQgWL7tvAPgN2LTLn', 'spaghetti-towers'], ['knowledge', 'nnNdz7XQrd5bWTgoP', 'on-the-loss-and-preservation-of-knowledge'], ['voting', 'D6trAzh6DApKPhbv4', 'a-voting-theory-primer-for-rationalists'], ['pavlov', '3rxMBRCYEmHCNDLhu', 'the-pavlov-strategy'], ['commons', '2G8j8D5auZKKAjSfY', 'inadequate-equilibria-vs-governance-of-the-commons'], ['science', 'v7c47vjta3mavY3QC', 'is-science-slowing-down'], ['rescue', 'BhXA6pvAbsFz3gvn4', 'research-rescuers-during-the-holocaust'], ['troll', 'CvKnhXTu9BPcdKE4W', 'an-untrollable-mathematician-illustrated'], ['long1', 'mFqG58s4NE3EE68Lq', 'why-did-everything-take-so-long'], ['long2', 'yxTP9FckrwoMjxPc4', 'why-everything-might-have-taken-so-long'], ['clickbait', 'YicoiQurNBxSp7a65', 'is-clickbait-destroying-our-general-intelligence'], ['active', 'XYYyzgyuRH5rFN64K', 'what-makes-people-intellectually-active'], ['daemon', 'nyCHnY7T5PHPLjxmN', 'open-question-are-minimal-circuits-daemon-free'], ['astro', 'Qz6w4GYZpgeDp6ATB', 'beyond-astronomical-waste'], ['birthorder1', 'tj8QP2EFdP8p54z6i', 'historical-mathematicians-exhibit-a-birth-order-effect-too'], ['birthorder2', 'QTLTic5nZ2DaBtoCv', 'birth-order-effect-found-in-nobel-laureates-in-physics'], ['gaming', 'AanbbjYr5zckMKde7', 'specification-gaming-examples-in-ai-1'], ['takeoff', 'AfGmsjGPXN97kNp57', 'arguments-about-fast-takeoff'], ['rocket', 'Gg9a4y8reWKtLe3Tn', 'the-rocket-alignment-problem'], ['agency', 'p7x32SEt43ZMC9r7r', 'embedded-agents'], ['faq', 'Djs38EWYZG8o7JMWY', 'paul-s-research-agenda-faq'], ['challenges', 'S7csET9CgBtpi7sCh', 'challenges-to-christiano-s-capability-amplification-proposal'], ['response', 'Djs38EWYZG8o7JMWY', 'paul-s-research-agenda-faq?commentId=79jM2ecef73zupPR4'], ['scale', 'bBdfbWfWxHN9Chjcq', 'robustness-to-scale'], ['coherence', 'NxF5G6CJiof6cemTw', 'coherence-arguments-do-not-imply-goal-directed-behavior'] ] lw18ReviewPosts.forEach( ([shortUrl, id, slug]) => addRoute({ name: `LessWrong 2018 Review ${id}/${slug}`, path: `/2018/${shortUrl}`, redirect: () => `/posts/${id}/${slug}` }) ) // User-profile routes addRoute( { name:'users.single', path:'/users/:slug', componentName: 'UsersSingle', //titleHoC: userPageTitleHoC, titleComponentName: 'UserPageTitle' }, { name:'users.single.user', path:'/user/:slug', componentName: 'UsersSingle' }, { name: "userOverview", path:'/user/:slug/overview', redirect: (location) => `/users/${location.params.slug}`, componentName: "UsersSingle", }, { name:'users.single.u', path:'/u/:slug', componentName: 'UsersSingle' }, { name:'users.account', path:'/account', componentName: 'UsersAccount', background: "white" }, { name:'users.manageSubscriptions', path:'/manageSubscriptions', componentName: 'ViewSubscriptionsPage', title: "Manage Subscriptions", background: "white" }, { name:'users.edit', path:'/users/:slug/edit', componentName: 'UsersAccount', background: "white" }, { name:'users.abTestGroups', path:'/abTestGroups', componentName: 'UsersViewABTests', }, { name: "users.banNotice", path: "/banNotice", componentName: "BannedNotice", }, // Miscellaneous LW2 routes { name: 'login', path: '/login', componentName: 'LoginPage', title: "Login", background: "white" }, { name: 'resendVerificationEmail', path: '/resendVerificationEmail', componentName: 'ResendVerificationEmailPage', background: "white" }, { name: 'inbox', path: '/inbox', componentName: 'InboxWrapper', title: "Inbox" }, { name: 'conversation', path: '/inbox/:_id', componentName: 'ConversationWrapper', title: "Private Conversation", background: "white", initialScroll: "bottom", }, { name: 'newPost', path: '/newPost', componentName: 'PostsNewForm', title: "New Post", background: "white" }, { name: 'editPost', path: '/editPost', componentName: 'PostsEditPage', background: "white" }, { name: 'postAnalytics', path: '/postAnalytics', componentName: 'PostsAnalyticsPage', background: "white" }, { name: 'collaboratePost', path: '/collaborateOnPost', componentName: 'PostCollaborationEditor', getPingback: async (parsedUrl) => await getPostPingbackById(parsedUrl, parsedUrl.query.postId), }, // disabled except during review voting phase { name:'reviewVoting', path: '/reviewVoting', redirect: () => `/reviewVoting/2020`, }, // { // name:'reviewVoting2019', // path: '/reviewVoting/2019', // title: "Voting 2019 Review", // componentName: "ReviewVotingPage2019" // }, { name:'reviewVoting2020', path: '/reviewVoting/2020', title: "Voting 2020 Review", componentName: "ReviewVotingPage", ...reviewSubtitle }, // Sequences { name: 'sequences.single.old', path: '/sequences/:_id', componentName: 'SequencesSingle', }, { name: 'sequences.single', path: '/s/:_id', componentName: 'SequencesSingle', titleComponentName: 'SequencesPageTitle', subtitleComponentName: 'SequencesPageTitle', }, { name: 'sequencesEdit', path: '/sequencesEdit/:_id', componentName: 'SequencesEditForm', background: "white" }, { name: 'sequencesNew', path: '/sequencesNew', componentName: 'SequencesNewForm', title: "New Sequence", background: "white" }, { name: 'sequencesPost', path: '/s/:sequenceId/p/:postId', componentName: 'SequencesPost', titleComponentName: 'PostsPageHeaderTitle', subtitleComponentName: 'PostsPageHeaderTitle', previewComponentName: 'PostLinkPreviewSequencePost', getPingback: async (parsedUrl) => await getPostPingbackById(parsedUrl, parsedUrl.params.postId), background: "white" }, { name: 'chaptersEdit', path: '/chaptersEdit/:_id', componentName: 'ChaptersEditForm', title: "Edit Chapter", background: "white" }, // Collections { name: 'collections', path: '/collections/:_id', componentName: 'CollectionsSingle' }, { name: 'bookmarks', path: '/bookmarks', componentName: 'BookmarksPage', title: 'Bookmarks', }, // Tags redirects { name: "TagsAll", path:'/tags', redirect: () => `/tags/all`, }, { name: "Concepts", path:'/concepts', redirect: () => `/tags/all`, }, { name: 'tagVoting', path: '/tagVoting', redirect: () => `/tagActivity`, }, { name: 'search', path: '/search', componentName: 'SearchPage', title: 'Search', background: "white" }, { name: 'votesByYear', path: '/votesByYear/:year', componentName: 'UserSuggestNominations', title: "Your Past Votes" }, ); if (taggingNameIsSet.get()) { addRoute( { name: 'tagsSingleCustomName', path: `/${taggingNamePluralSetting.get()}/:slug`, componentName: 'TagPage', titleComponentName: 'TagPageTitle', subtitleComponentName: 'TagPageTitle', previewComponentName: 'TagHoverPreview', }, { name: 'tagsSingleRedirectCustomName', path: '/tag/:slug', redirect: ({ params }) => `/${taggingNamePluralSetting.get()}/${params.slug}`, }, { name: 'tagsAllCustomName', path: `/${taggingNamePluralSetting.get()}/all`, componentName: 'AllTagsPage', title: `${taggingNamePluralCapitalSetting.get()} — Main Page`, }, { name: "tagsRedirectCustomName", path:'/tags/all', redirect: () => `/${taggingNamePluralSetting.get()}/all`, }, { name: 'tagDiscussionCustomName', path: `/${taggingNamePluralSetting.get()}/:slug/discussion`, componentName: 'TagDiscussionPage', titleComponentName: 'TagPageTitle', subtitleComponentName: 'TagPageTitle', previewComponentName: 'TagHoverPreview', background: "white" }, { name: 'tagDiscussionCustomNameRedirect', path: '/tag/:slug/discussion', redirect: ({params}) => `/${taggingNamePluralSetting.get()}/${params.slug}/discussion` }, { name: 'tagHistoryCustomName', path: `/${taggingNamePluralSetting.get()}/:slug/history`, componentName: 'TagHistoryPage', titleComponentName: 'TagHistoryPageTitle', subtitleComponentName: 'TagHistoryPageTitle', }, { name: 'tagHistoryCustomNameRedirect', path: '/tag/:slug/history', redirect: ({params}) => `/${taggingNamePluralSetting.get()}/${params.slug}/history` }, { name: 'tagEditCustomName', path: `/${taggingNamePluralSetting.get()}/:slug/edit`, componentName: 'EditTagPage', titleComponentName: 'TagPageTitle', subtitleComponentName: 'TagPageTitle', }, { name: 'tagEditCustomNameRedirect', path: '/tag/:slug/edit', redirect: ({params}) => `/${taggingNamePluralSetting.get()}/${params.slug}/edit` }, { name: 'tagCreateCustomName', path: `/${taggingNamePluralSetting.get()}/create`, title: `New ${taggingNameCapitalSetting.get()}`, componentName: 'NewTagPage', subtitleComponentName: 'TagPageTitle', background: "white" }, { name: 'tagCreateCustomNameRedirect', path: '/tag/create', redirect: () => `/${taggingNamePluralSetting.get()}/create` }, { name: 'randomTagCustomName', path: `/${taggingNamePluralSetting.get()}/random`, componentName: 'RandomTagPage', }, { name: 'randomTagCustomNameRedirect', path: '/tags/random', redirect: () => `/${taggingNamePluralSetting.get()}/random` }, { name: 'tagActivityCustomName', path: `/${taggingNamePluralSetting.get()}Activity`, componentName: 'TagVoteActivity', title: `${taggingNamePluralCapitalSetting.get()} Voting Activity` }, { name: 'tagActivityCustomNameRedirect', path: '/tagActivity', redirect: () => `/${taggingNamePluralSetting.get()}Activity` }, { name: 'tagFeedCustomName', path: `/${taggingNamePluralSetting.get()}Feed`, componentName: 'TagActivityFeed', title: `${taggingNamePluralCapitalSetting.get()} Activity` }, { name: 'tagFeedCustomNameRedirect', path: '/tagFeed', redirect: () => `/${taggingNamePluralSetting.get()}Feed` }, { name: 'taggingDashboardCustomName', path: `/${taggingNamePluralSetting.get()}/dashboard`, componentName: "TaggingDashboard", title: `${taggingNamePluralCapitalSetting.get()} Dashboard`, ...taggingDashboardSubtitle }, { name: 'taggingDashboardCustomNameRedirect', path: '/tags/dashboard', redirect: () => `/${taggingNamePluralSetting.get()}/dashboard` }, { name: 'taggingAllCustomNameRedirect', path: `/${taggingNamePluralSetting.get()}/`, redirect: () => `/${taggingNamePluralSetting.get()}/all` }, ) } else { addRoute( { name: 'allTags', path: '/tags/all', componentName: 'AllTagsPage', title: forumTypeSetting.get() === 'EAForum' ? "The EA Forum Wiki" : "Concepts Portal", }, { name: 'tags.single', path: '/tag/:slug', componentName: 'TagPage', titleComponentName: 'TagPageTitle', subtitleComponentName: 'TagPageTitle', previewComponentName: 'TagHoverPreview', }, { name: 'tagDiscussion', path: '/tag/:slug/discussion', componentName: 'TagDiscussionPage', titleComponentName: 'TagPageTitle', subtitleComponentName: 'TagPageTitle', previewComponentName: 'TagHoverPreview', background: "white" }, { name: 'tagHistory', path: '/tag/:slug/history', componentName: 'TagHistoryPage', titleComponentName: 'TagHistoryPageTitle', subtitleComponentName: 'TagHistoryPageTitle', }, { name: 'tagEdit', path: '/tag/:slug/edit', componentName: 'EditTagPage', titleComponentName: 'TagPageTitle', subtitleComponentName: 'TagPageTitle', }, { name: 'tagCreate', path: '/tag/create', componentName: 'NewTagPage', title: "New Tag", subtitleComponentName: 'TagPageTitle', background: "white" }, { name: 'randomTag', path: '/tags/random', componentName: 'RandomTagPage', }, { name: 'tagActivity', path: '/tagActivity', componentName: 'TagVoteActivity', title: 'Tag Voting Activity' }, { name: 'tagFeed', path: '/tagFeed', componentName: 'TagActivityFeed', title: 'Tag Activity' }, { name: 'taggingDashboard', path: '/tags/dashboard', componentName: "TaggingDashboard", title: "Tagging Dashboard", ...taggingDashboardSubtitle }, ) } onStartup(() => { const legacyRouteAcronym = legacyRouteAcronymSetting.get() addRoute( // Legacy (old-LW, also old-EAF) routes // Note that there are also server-side-only routes in server/legacy-redirects/routes.js. { name: 'post.legacy', path: `/:section(r)?/:subreddit(all|discussion|lesswrong)?/${legacyRouteAcronym}/:id/:slug?`, componentName: "LegacyPostRedirect", previewComponentName: "PostLinkPreviewLegacy", getPingback: (parsedUrl) => getPostPingbackByLegacyId(parsedUrl, parsedUrl.params.id), }, { name: 'comment.legacy', path: `/:section(r)?/:subreddit(all|discussion|lesswrong)?/${legacyRouteAcronym}/:id/:slug/:commentId`, componentName: "LegacyCommentRedirect", previewComponentName: "CommentLinkPreviewLegacy", noIndex: true, // TODO: Pingback comment } ); }); const forumSpecificRoutes = forumSelect<Route[]>({ EAForum: [ { name: 'home', path: '/', componentName: 'EAHome', sunshineSidebar: true }, { name:'about', path:'/about', componentName: 'PostsSingleRoute', _id: aboutPostIdSetting.get(), getPingback: async (parsedUrl) => await getPostPingbackById(parsedUrl, aboutPostIdSetting.get()), background: postBackground }, { name:'handbook', path:'/handbook', componentName: 'PostsSingleRoute', _id: eaHandbookPostIdSetting.get(), getPingback: async (parsedUrl) => await getPostPingbackById(parsedUrl, eaHandbookPostIdSetting.get()), background: postBackground }, { name: 'intro', path: '/intro', componentName: 'PostsSingleRoute', _id: introPostIdSetting.get(), getPingback: async (parsedUrl) => await getPostPingbackById(parsedUrl, introPostIdSetting.get()), background: postBackground }, { name: 'contact', path:'/contact', componentName: 'PostsSingleRoute', _id: contactPostIdSetting.get(), getPingback: async (parsedUrl) => await getPostPingbackById(parsedUrl, contactPostIdSetting.get()), background: postBackground }, { name: 'CommunityTag', path: '/meta', redirect: () => `/tag/community`, }, { name: 'eaSequencesRedirect', path: '/sequences', redirect: () => '/library' }, { name: 'eaLibrary', path: '/library', componentName: 'EASequencesHome' }, { name: 'EventsHome', path: '/events', componentName: 'EventsHome', title: 'Events', subtitle: 'Events', subtitleLink: '/events' }, { name: "communityRedirect", path:'/groupsAndEvents', redirect: () => communityPath }, { name: 'Community', path: communityPath, componentName: 'Community', title: 'Community', ...communitySubtitle }, { name: 'CommunityMembersFullMap', path: '/community/map', componentName: 'CommunityMembersFullMap', title: 'Community Members', ...communitySubtitle }, { name: 'EditMyProfile', path: '/profile/edit', componentName: 'EditProfileForm', title: 'Edit Profile', background: 'white', }, { name: 'EditProfile', path: '/profile/:slug/edit', componentName: 'EditProfileForm', title: 'Edit Profile', background: 'white', }, ], LessWrong: [ { name: 'home', path: '/', componentName: 'Home2', sunshineSidebar: true }, { name: 'about', path: '/about', componentName: 'PostsSingleRoute', _id: aboutPostIdSetting.get(), getPingback: async (parsedUrl) => await getPostPingbackById(parsedUrl, aboutPostIdSetting.get()), background: postBackground }, { name: 'contact', path:'/contact', componentName: 'PostsSingleRoute', _id: contactPostIdSetting.get(), getPingback: async (parsedUrl) => await getPostPingbackById(parsedUrl, contactPostIdSetting.get()), background: postBackground }, { name: 'faq', path: '/faq', componentName: 'PostsSingleRoute', _id: faqPostIdSetting.get(), getPingback: async (parsedUrl) => await getPostPingbackById(parsedUrl, faqPostIdSetting.get()), background: postBackground }, { name: 'donate', path: '/donate', componentName: 'PostsSingleRoute', _id:"LcpQQvcpWfPXvW7R9", getPingback: async (parsedUrl) => await getPostPingbackById(parsedUrl, "LcpQQvcpWfPXvW7R9"), background: postBackground }, { name: 'Meta', path: '/meta', redirect: () => `/tag/site-meta`, }, { name: 'bestoflesswrong', path: '/bestoflesswrong', componentName: 'BestOfLessWrong', title: "Best of LessWrong", ...bestoflwSubtitle, }, { name: 'HPMOR', path: '/hpmor', componentName: 'HPMOR', title: "Harry Potter and the Methods of Rationality", ...hpmorSubtitle, }, { name: 'Curated', path: '/curated', redirect: () => `/recommendations`, }, { name: 'Walled Garden', path: '/walledGarden', componentName: 'WalledGardenHome', title: "Walled Garden", }, { name: 'Walled Garden Portal', path: '/walledGardenPortal', redirect: () => `/walledGarden`, }, { name: 'HPMOR.posts.single', path: '/hpmor/:slug', componentName: 'PostsSingleSlug', previewComponentName: 'PostLinkPreviewSlug', ...hpmorSubtitle, getPingback: (parsedUrl) => getPostPingbackBySlug(parsedUrl, parsedUrl.params.slug), background: postBackground }, { name: 'Codex', path: '/codex', componentName: 'Codex', title: "The Codex", ...codexSubtitle, }, { name: 'Codex.posts.single', path: '/codex/:slug', componentName: 'PostsSingleSlug', previewComponentName: 'PostLinkPreviewSlug', ...codexSubtitle, getPingback: (parsedUrl) => getPostPingbackBySlug(parsedUrl, parsedUrl.params.slug), background: postBackground }, { name: 'bookLanding', path: '/books', redirect: () => `/books/2018`, }, { name: 'book2018Landing', path: '/books/2018', componentName: 'Book2018Landing', title: "Books: A Map that Reflects the Territory", background: "white" }, { name: 'book2019Landing', path: '/books/2019', componentName: 'Book2019Landing', title: "Books: Engines of Cognition", background: "white" }, { name: 'editPaymentInfo', path: '/payments/account', componentName: 'EditPaymentInfoPage' }, { name: 'paymentsAdmin', path: '/payments/admin', componentName: 'AdminPaymentsPage' }, { name: 'payments', path: '/payments', redirect: () => `/payments/admin`, // eventually, payments might be a userfacing feature, and we might do something else with this url }, { name:'coronavirus.link.db', path:'/coronavirus-link-database', componentName: 'SpreadsheetPage', title: "COVID-19 Link Database", }, { name: 'nominations2018-old', path: '/nominations2018', redirect: () => `/nominations/2018`, }, { name: 'nominations2018', path: '/nominations/2018', componentName: 'Nominations2018', title: "2018 Nominations", }, { name: 'nominations2019-old', path: '/nominations2019', redirect: () => `/nominations/2019`, }, { name: 'nominations2019', path: '/nominations/2019', componentName: 'Nominations2019', title: "2019 Nominations", }, { name: 'userReviews', path:'/users/:slug/reviews', redirect: (location) => `/users/${location.params.slug}/reviews/2019`, }, { name: 'reviews2018-old', path: '/reviews2018', redirect: () => `/reviews/2018`, }, { name: 'reviews2018', path: '/reviews/2018', componentName: 'Reviews2018', title: "2018 Reviews", }, { name: 'reviews2019-old', path: '/reviews2019', redirect: () => `/reviews/2019`, }, { name: 'reviews2019', path: '/reviews/2019', componentName: 'Reviews2019', title: "2019 Reviews", }, { name: 'sequencesHome', path: '/library', componentName: 'SequencesHome', title: "The Library" }, { name: 'Sequences', path: '/sequences', componentName: 'CoreSequences', title: "Rationality: A-Z" }, { name: 'Rationality', path: '/rationality', componentName: 'CoreSequences', title: "Rationality: A-Z", ...rationalitySubtitle }, { name: 'Rationality.posts.single', path: '/rationality/:slug', componentName: 'PostsSingleSlug', previewComponentName: 'PostLinkPreviewSlug', ...rationalitySubtitle, getPingback: (parsedUrl) => getPostPingbackBySlug(parsedUrl, parsedUrl.params.slug), background: postBackground }, ], AlignmentForum: [ { name:'alignment.home', path:'/', componentName: 'AlignmentForumHome', sunshineSidebar: true //TODO: remove this in production? }, { name:'about', path:'/about', componentName: 'PostsSingleRoute', _id: aboutPostIdSetting.get() }, { name: 'faq', path: '/faq', componentName: 'PostsSingleRoute', _id: faqPostIdSetting.get(), getPingback: async (parsedUrl) => await getPostPingbackById(parsedUrl, faqPostIdSetting.get()), background: postBackground }, { name: 'Meta', path: '/meta', redirect: () => `/tag/site-meta`, }, // Can remove these probably - no one is likely visiting on AF, but maybe not worth a 404 { name:'coronavirus.link.db', path:'/coronavirus-link-database', componentName: 'SpreadsheetPage', title: "COVID-19 Link Database", }, { name: 'nominations2018-old', path: '/nominations2018', redirect: () => `/nominations/2018`, }, { name: 'nominations2018', path: '/nominations/2018', componentName: 'Nominations2018', title: "2018 Nominations", }, { name: 'nominations2019-old', path: '/nominations2019', redirect: () => `/nominations/2019`, }, { name: 'nominations2019', path: '/nominations/2019', componentName: 'Nominations2019', title: "2019 Nominations", }, { name: 'userReviews', path:'/users/:slug/reviews', redirect: (location) => `/users/${location.params.slug}/reviews/2019`, }, { name: 'reviews2018-old', path: '/reviews2018', redirect: () => `/reviews/2018`, }, { name: 'reviews2018', path: '/reviews/2018', componentName: 'Reviews2018', title: "2018 Reviews", }, { name: 'reviews2019-old', path: '/reviews2019', redirect: () => `/reviews/2019`, }, { name: 'reviews2019', path: '/reviews/2019', componentName: 'Reviews2019', title: "2019 Reviews", }, { name: 'sequencesHome', path: '/library', componentName: 'SequencesHome', title: "The Library" }, { name: 'Sequences', path: '/sequences', componentName: 'CoreSequences', title: "Rationality: A-Z" }, { name: 'Rationality', path: '/rationality', componentName: 'CoreSequences', title: "Rationality: A-Z", ...rationalitySubtitle }, { name: 'Rationality.posts.single', path: '/rationality/:slug', componentName: 'PostsSingleSlug', previewComponentName: 'PostLinkPreviewSlug', ...rationalitySubtitle, getPingback: (parsedUrl) => getPostPingbackBySlug(parsedUrl, parsedUrl.params.slug), background: postBackground }, ], default: [ { name:'home', path:'/', componentName: 'Home2', sunshineSidebar: true //TODO: remove this in production? }, { name:'about', path:'/about', componentName: 'PostsSingleRoute', _id: aboutPostIdSetting.get() }, { name: 'faq', path: '/faq', componentName: 'PostsSingleRoute', _id: faqPostIdSetting.get(), getPingback: async (parsedUrl) => await getPostPingbackById(parsedUrl, faqPostIdSetting.get()), background: postBackground }, { name: 'contact', path:'/contact', componentName: 'PostsSingleRoute', _id: contactPostIdSetting.get(), getPingback: async (parsedUrl) => await getPostPingbackById(parsedUrl, contactPostIdSetting.get()), background: postBackground }, ], }) addRoute(...forumSpecificRoutes) addRoute( { name: 'AllComments', path: '/allComments', componentName: 'AllComments', title: "All Comments" }, { name: 'Shortform', path: '/shortform', componentName: 'ShortformPage', title: "Shortform" }, ); if (hasEventsSetting.get()) { addRoute( { name: 'EventsPast', path: '/pastEvents', componentName: 'EventsPast', title: "Past Events by Day" }, { name: 'EventsUpcoming', path: '/upcomingEvents', componentName: 'EventsUpcoming', title: "Upcoming Events by Day" }, { name: 'CommunityHome', path: forumTypeSetting.get() === 'EAForum' ? '/community-old' : communityPath, componentName: 'CommunityHome', title: 'Community', ...communitySubtitle }, { name: 'MeetupsHome', path: '/meetups', componentName: 'CommunityHome', title: 'Community', }, { name: 'AllLocalGroups', path: '/allgroups', componentName: 'AllGroupsPage', title: "All Local Groups" }, { name: 'GroupsMap', path: '/groups-map', componentName: 'GroupsMap', title: "Groups Map", standalone: true }, { name:'Localgroups.single', path: '/groups/:groupId', componentName: 'LocalGroupSingle', titleComponentName: 'LocalgroupPageTitle', ...communitySubtitle }, { name:'events.single', path: '/events/:_id/:slug?', componentName: 'PostsSingle', titleComponentName: 'PostsPageHeaderTitle', previewComponentName: 'PostLinkPreview', subtitle: forumTypeSetting.get() === 'EAForum' ? 'Events' : 'Community', subtitleLink: forumTypeSetting.get() === 'EAForum' ? '/events' : communityPath, getPingback: async (parsedUrl) => await getPostPingbackById(parsedUrl, parsedUrl.params._id), background: postBackground }, { name: 'groups.post', path: '/g/:groupId/p/:_id', componentName: 'PostsSingle', previewComponentName: 'PostLinkPreview', background: postBackground, ...communitySubtitle, getPingback: async (parsedUrl) => await getPostPingbackById(parsedUrl, parsedUrl.params._id), }, ); } addRoute( { name: 'searchTest', path: '/searchTest', componentName: 'SearchBar' }, { name: 'postsListEditorTest', path:'/postsListEditorTest', componentName: 'PostsListEditor' }, { name: 'imageUploadTest', path: '/imageUpload', componentName: 'ImageUpload' }, ); addRoute( { name:'posts.single', path:'/posts/:_id/:slug?', componentName: 'PostsSingle', titleComponentName: 'PostsPageHeaderTitle', subtitleComponentName: 'PostsPageHeaderTitle', previewComponentName: 'PostLinkPreview', getPingback: async (parsedUrl) => await getPostPingbackById(parsedUrl, parsedUrl.params._id), background: postBackground }, { name:'posts.slug.single', path:'/posts/slug/:slug?', componentName: 'PostsSingleSlugRedirect', titleComponentName: 'PostsPageHeaderTitle', subtitleComponentName: 'PostsPageHeaderTitle', previewComponentName: 'PostLinkPreviewSlug', getPingback: (parsedUrl) => getPostPingbackBySlug(parsedUrl, parsedUrl.params.slug), background: postBackground }, { name: 'posts.revisioncompare', path: '/compare/post/:_id/:slug', componentName: 'PostsCompareRevisions', titleComponentName: 'PostsPageHeaderTitle', }, { name: 'tags.revisioncompare', path: '/compare/tag/:slug', componentName: 'TagCompareRevisions', titleComponentName: 'PostsPageHeaderTitle', }, { name: 'post.revisionsselect', path: '/revisions/post/:_id/:slug', componentName: 'PostsRevisionSelect', titleComponentName: 'PostsPageHeaderTitle', }, { name: 'tag.revisionsselect', path: '/revisions/tag/:slug', componentName: 'TagPageRevisionSelect', titleComponentName: 'TagPageTitle', }, { name: 'admin', path: '/admin', componentName: 'AdminHome', title: "Admin" }, { name: 'migrations', path: '/admin/migrations', componentName: 'MigrationsDashboard', title: "Migrations" }, { name: 'moderation', path: '/moderation', componentName: 'ModerationLog', title: "Moderation Log", noIndex: true }, { name: 'moderatorComments', path: '/moderatorComments', componentName: 'ModeratorComments', }, { name: 'emailHistory', path: '/debug/emailHistory', componentName: 'EmailHistoryPage' }, { name: 'notificationEmailPreview', path: '/debug/notificationEmailPreview', componentName: 'NotificationEmailPreviewPage' }, ); addRoute( { path:'/posts/:_id/:slug/comment/:commentId?', name: 'comment.greaterwrong', componentName: "PostsSingle", titleComponentName: 'PostsPageHeaderTitle', subtitleComponentName: 'PostsPageHeaderTitle', previewComponentName: "PostCommentLinkPreviewGreaterWrong", noIndex: true, // TODO: Handle pingbacks leading to comments. } ); addRoute( { name: 'home2', path: '/home2', componentName: 'Home2', title: "Home2 Beta", }, { name: 'allPosts', path: '/allPosts', componentName: 'AllPostsPage', title: "All Posts", }, { name: 'questions', path: '/questions', componentName: 'QuestionsPage', title: "All Questions", }, { name: 'recommendations', path: '/recommendations', componentName: 'RecommendationsPage', title: "Recommendations", }, { name: 'emailToken', path: '/emailToken/:token', componentName: 'EmailTokenPage', }, { name: 'password-reset', path: '/resetPassword/:token', componentName: 'PasswordResetPage', }, { name: 'nominations', path: '/nominations', redirect: () => `/reviewVoting/${REVIEW_YEAR}`, }, { name: 'userReviewsByYear', path:'/users/:slug/reviews/:year', componentName: 'UserReviews', title: "User Reviews", }, { name: 'userReplies', path:'/users/:slug/replies', componentName: 'UserCommentsReplies', title: "User Comment Replies", }, { name: 'reviews', path: '/reviews', redirect: () => `/reviewVoting/${REVIEW_YEAR}`, }, { name: 'reviews-2020', path: '/reviews/2020', redirect: () => `/reviewVoting/2020`, }, { name: 'reviewAdmin', path: '/reviewAdmin', redirect: () => `/reviewAdmin/2020`, }, { name: 'reviewAdmin-year', path: '/reviewAdmin/:year', componentName: 'ReviewAdminDashboard', title: "Review Admin Dashboard", } );
the_stack
import { PagedAsyncIterableIterator } from "@azure/core-paging"; import { LoadBalancerBackendAddressPools } from "../operationsInterfaces"; import * as coreClient from "@azure/core-client"; import * as Mappers from "../models/mappers"; import * as Parameters from "../models/parameters"; import { NetworkManagementClient } from "../networkManagementClient"; import { PollerLike, PollOperationState, LroEngine } from "@azure/core-lro"; import { LroImpl } from "../lroImpl"; import { BackendAddressPool, LoadBalancerBackendAddressPoolsListNextOptionalParams, LoadBalancerBackendAddressPoolsListOptionalParams, LoadBalancerBackendAddressPoolsListResponse, LoadBalancerBackendAddressPoolsGetOptionalParams, LoadBalancerBackendAddressPoolsGetResponse, LoadBalancerBackendAddressPoolsCreateOrUpdateOptionalParams, LoadBalancerBackendAddressPoolsCreateOrUpdateResponse, LoadBalancerBackendAddressPoolsDeleteOptionalParams, LoadBalancerBackendAddressPoolsListNextResponse } from "../models"; /// <reference lib="esnext.asynciterable" /> /** Class containing LoadBalancerBackendAddressPools operations. */ export class LoadBalancerBackendAddressPoolsImpl implements LoadBalancerBackendAddressPools { private readonly client: NetworkManagementClient; /** * Initialize a new instance of the class LoadBalancerBackendAddressPools class. * @param client Reference to the service client */ constructor(client: NetworkManagementClient) { this.client = client; } /** * Gets all the load balancer backed address pools. * @param resourceGroupName The name of the resource group. * @param loadBalancerName The name of the load balancer. * @param options The options parameters. */ public list( resourceGroupName: string, loadBalancerName: string, options?: LoadBalancerBackendAddressPoolsListOptionalParams ): PagedAsyncIterableIterator<BackendAddressPool> { const iter = this.listPagingAll( resourceGroupName, loadBalancerName, options ); return { next() { return iter.next(); }, [Symbol.asyncIterator]() { return this; }, byPage: () => { return this.listPagingPage( resourceGroupName, loadBalancerName, options ); } }; } private async *listPagingPage( resourceGroupName: string, loadBalancerName: string, options?: LoadBalancerBackendAddressPoolsListOptionalParams ): AsyncIterableIterator<BackendAddressPool[]> { let result = await this._list(resourceGroupName, loadBalancerName, options); yield result.value || []; let continuationToken = result.nextLink; while (continuationToken) { result = await this._listNext( resourceGroupName, loadBalancerName, continuationToken, options ); continuationToken = result.nextLink; yield result.value || []; } } private async *listPagingAll( resourceGroupName: string, loadBalancerName: string, options?: LoadBalancerBackendAddressPoolsListOptionalParams ): AsyncIterableIterator<BackendAddressPool> { for await (const page of this.listPagingPage( resourceGroupName, loadBalancerName, options )) { yield* page; } } /** * Gets all the load balancer backed address pools. * @param resourceGroupName The name of the resource group. * @param loadBalancerName The name of the load balancer. * @param options The options parameters. */ private _list( resourceGroupName: string, loadBalancerName: string, options?: LoadBalancerBackendAddressPoolsListOptionalParams ): Promise<LoadBalancerBackendAddressPoolsListResponse> { return this.client.sendOperationRequest( { resourceGroupName, loadBalancerName, options }, listOperationSpec ); } /** * Gets load balancer backend address pool. * @param resourceGroupName The name of the resource group. * @param loadBalancerName The name of the load balancer. * @param backendAddressPoolName The name of the backend address pool. * @param options The options parameters. */ get( resourceGroupName: string, loadBalancerName: string, backendAddressPoolName: string, options?: LoadBalancerBackendAddressPoolsGetOptionalParams ): Promise<LoadBalancerBackendAddressPoolsGetResponse> { return this.client.sendOperationRequest( { resourceGroupName, loadBalancerName, backendAddressPoolName, options }, getOperationSpec ); } /** * Creates or updates a load balancer backend address pool. * @param resourceGroupName The name of the resource group. * @param loadBalancerName The name of the load balancer. * @param backendAddressPoolName The name of the backend address pool. * @param parameters Parameters supplied to the create or update load balancer backend address pool * operation. * @param options The options parameters. */ async beginCreateOrUpdate( resourceGroupName: string, loadBalancerName: string, backendAddressPoolName: string, parameters: BackendAddressPool, options?: LoadBalancerBackendAddressPoolsCreateOrUpdateOptionalParams ): Promise< PollerLike< PollOperationState<LoadBalancerBackendAddressPoolsCreateOrUpdateResponse>, LoadBalancerBackendAddressPoolsCreateOrUpdateResponse > > { const directSendOperation = async ( args: coreClient.OperationArguments, spec: coreClient.OperationSpec ): Promise<LoadBalancerBackendAddressPoolsCreateOrUpdateResponse> => { return this.client.sendOperationRequest(args, spec); }; const sendOperation = async ( args: coreClient.OperationArguments, spec: coreClient.OperationSpec ) => { let currentRawResponse: | coreClient.FullOperationResponse | undefined = undefined; const providedCallback = args.options?.onResponse; const callback: coreClient.RawResponseCallback = ( rawResponse: coreClient.FullOperationResponse, flatResponse: unknown ) => { currentRawResponse = rawResponse; providedCallback?.(rawResponse, flatResponse); }; const updatedArgs = { ...args, options: { ...args.options, onResponse: callback } }; const flatResponse = await directSendOperation(updatedArgs, spec); return { flatResponse, rawResponse: { statusCode: currentRawResponse!.status, body: currentRawResponse!.parsedBody, headers: currentRawResponse!.headers.toJSON() } }; }; const lro = new LroImpl( sendOperation, { resourceGroupName, loadBalancerName, backendAddressPoolName, parameters, options }, createOrUpdateOperationSpec ); return new LroEngine(lro, { resumeFrom: options?.resumeFrom, intervalInMs: options?.updateIntervalInMs, lroResourceLocationConfig: "azure-async-operation" }); } /** * Creates or updates a load balancer backend address pool. * @param resourceGroupName The name of the resource group. * @param loadBalancerName The name of the load balancer. * @param backendAddressPoolName The name of the backend address pool. * @param parameters Parameters supplied to the create or update load balancer backend address pool * operation. * @param options The options parameters. */ async beginCreateOrUpdateAndWait( resourceGroupName: string, loadBalancerName: string, backendAddressPoolName: string, parameters: BackendAddressPool, options?: LoadBalancerBackendAddressPoolsCreateOrUpdateOptionalParams ): Promise<LoadBalancerBackendAddressPoolsCreateOrUpdateResponse> { const poller = await this.beginCreateOrUpdate( resourceGroupName, loadBalancerName, backendAddressPoolName, parameters, options ); return poller.pollUntilDone(); } /** * Deletes the specified load balancer backend address pool. * @param resourceGroupName The name of the resource group. * @param loadBalancerName The name of the load balancer. * @param backendAddressPoolName The name of the backend address pool. * @param options The options parameters. */ async beginDelete( resourceGroupName: string, loadBalancerName: string, backendAddressPoolName: string, options?: LoadBalancerBackendAddressPoolsDeleteOptionalParams ): Promise<PollerLike<PollOperationState<void>, void>> { const directSendOperation = async ( args: coreClient.OperationArguments, spec: coreClient.OperationSpec ): Promise<void> => { return this.client.sendOperationRequest(args, spec); }; const sendOperation = async ( args: coreClient.OperationArguments, spec: coreClient.OperationSpec ) => { let currentRawResponse: | coreClient.FullOperationResponse | undefined = undefined; const providedCallback = args.options?.onResponse; const callback: coreClient.RawResponseCallback = ( rawResponse: coreClient.FullOperationResponse, flatResponse: unknown ) => { currentRawResponse = rawResponse; providedCallback?.(rawResponse, flatResponse); }; const updatedArgs = { ...args, options: { ...args.options, onResponse: callback } }; const flatResponse = await directSendOperation(updatedArgs, spec); return { flatResponse, rawResponse: { statusCode: currentRawResponse!.status, body: currentRawResponse!.parsedBody, headers: currentRawResponse!.headers.toJSON() } }; }; const lro = new LroImpl( sendOperation, { resourceGroupName, loadBalancerName, backendAddressPoolName, options }, deleteOperationSpec ); return new LroEngine(lro, { resumeFrom: options?.resumeFrom, intervalInMs: options?.updateIntervalInMs, lroResourceLocationConfig: "location" }); } /** * Deletes the specified load balancer backend address pool. * @param resourceGroupName The name of the resource group. * @param loadBalancerName The name of the load balancer. * @param backendAddressPoolName The name of the backend address pool. * @param options The options parameters. */ async beginDeleteAndWait( resourceGroupName: string, loadBalancerName: string, backendAddressPoolName: string, options?: LoadBalancerBackendAddressPoolsDeleteOptionalParams ): Promise<void> { const poller = await this.beginDelete( resourceGroupName, loadBalancerName, backendAddressPoolName, options ); return poller.pollUntilDone(); } /** * ListNext * @param resourceGroupName The name of the resource group. * @param loadBalancerName The name of the load balancer. * @param nextLink The nextLink from the previous successful call to the List method. * @param options The options parameters. */ private _listNext( resourceGroupName: string, loadBalancerName: string, nextLink: string, options?: LoadBalancerBackendAddressPoolsListNextOptionalParams ): Promise<LoadBalancerBackendAddressPoolsListNextResponse> { return this.client.sendOperationRequest( { resourceGroupName, loadBalancerName, nextLink, options }, listNextOperationSpec ); } } // Operation Specifications const serializer = coreClient.createSerializer(Mappers, /* isXml */ false); const listOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/loadBalancers/{loadBalancerName}/backendAddressPools", httpMethod: "GET", responses: { 200: { bodyMapper: Mappers.LoadBalancerBackendAddressPoolListResult }, default: { bodyMapper: Mappers.CloudError } }, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.$host, Parameters.resourceGroupName, Parameters.subscriptionId, Parameters.loadBalancerName ], headerParameters: [Parameters.accept], serializer }; const getOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/loadBalancers/{loadBalancerName}/backendAddressPools/{backendAddressPoolName}", httpMethod: "GET", responses: { 200: { bodyMapper: Mappers.BackendAddressPool }, default: { bodyMapper: Mappers.CloudError } }, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.$host, Parameters.resourceGroupName, Parameters.subscriptionId, Parameters.loadBalancerName, Parameters.backendAddressPoolName ], headerParameters: [Parameters.accept], serializer }; const createOrUpdateOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/loadBalancers/{loadBalancerName}/backendAddressPools/{backendAddressPoolName}", httpMethod: "PUT", responses: { 200: { bodyMapper: Mappers.BackendAddressPool }, 201: { bodyMapper: Mappers.BackendAddressPool }, 202: { bodyMapper: Mappers.BackendAddressPool }, 204: { bodyMapper: Mappers.BackendAddressPool }, default: { bodyMapper: Mappers.CloudError } }, requestBody: Parameters.parameters25, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.$host, Parameters.resourceGroupName, Parameters.subscriptionId, Parameters.loadBalancerName, Parameters.backendAddressPoolName ], headerParameters: [Parameters.accept, Parameters.contentType], mediaType: "json", serializer }; const deleteOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/loadBalancers/{loadBalancerName}/backendAddressPools/{backendAddressPoolName}", httpMethod: "DELETE", responses: { 200: {}, 201: {}, 202: {}, 204: {}, default: { bodyMapper: Mappers.CloudError } }, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.$host, Parameters.resourceGroupName, Parameters.subscriptionId, Parameters.loadBalancerName, Parameters.backendAddressPoolName ], headerParameters: [Parameters.accept], serializer }; const listNextOperationSpec: coreClient.OperationSpec = { path: "{nextLink}", httpMethod: "GET", responses: { 200: { bodyMapper: Mappers.LoadBalancerBackendAddressPoolListResult }, default: { bodyMapper: Mappers.CloudError } }, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.$host, Parameters.resourceGroupName, Parameters.subscriptionId, Parameters.nextLink, Parameters.loadBalancerName ], headerParameters: [Parameters.accept], serializer };
the_stack
* @module Tools */ import { DialogItem, DialogItemValue, DialogProperty, DialogPropertySyncItem } from "@itwin/appui-abstract"; import { assert } from "@itwin/core-bentley"; import { GeometryStreamProps, IModelError } from "@itwin/core-common"; import { Point2d, Point3d, PolygonOps, XAndY } from "@itwin/core-geometry"; import { LocateFilterStatus, LocateResponse } from "../ElementLocateManager"; import { FuzzySearch, FuzzySearchResults } from "../FuzzySearch"; import { HitDetail } from "../HitDetail"; import { IModelApp } from "../IModelApp"; import { DecorateContext, DynamicsContext } from "../ViewContext"; import { ScreenViewport } from "../Viewport"; /** * @public * @extensions */ export type ToolType = typeof Tool; /** * @public * @extensions */ export type ToolList = ToolType[]; /** * @public * @extensions */ export enum BeButton { Data = 0, Reset = 1, Middle = 2 } /** * @public * @extensions */ export enum CoordinateLockOverrides { None = 0, ACS = 1 << 1, Grid = 1 << 2, // also overrides unit lock All = 0xffff, } /** The *source* that generated an event. * @public * @extensions */ export enum InputSource { /** Source not defined */ Unknown = 0, /** From a mouse or other pointing device */ Mouse = 1, /** From a touch screen */ Touch = 2, } /** The *source* that generated a coordinate. * @public * @extensions */ export enum CoordSource { /** Event was created by an action from the user */ User = 0, /** Event was created by a program or by a precision keyin */ Precision = 1, /** Event was created by a tentative point */ TentativePoint = 2, /** Event was created by snapping to an element */ ElemSnap = 3, } /** Numeric mask for a set of modifier keys (control, shift, and alt). * @public * @extensions */ export enum BeModifierKeys { None = 0, Control = 1 << 0, Shift = 1 << 1, Alt = 1 << 2 } /** * @public * @extensions */ export class BeButtonState { private readonly _downUorPt: Point3d = new Point3d(); private readonly _downRawPt: Point3d = new Point3d(); public downTime: number = 0; public isDown: boolean = false; public isDoubleClick: boolean = false; public isDragging: boolean = false; public inputSource: InputSource = InputSource.Unknown; public get downRawPt() { return this._downRawPt; } public set downRawPt(pt: Point3d) { this._downRawPt.setFrom(pt); } public get downUorPt() { return this._downUorPt; } public set downUorPt(pt: Point3d) { this._downUorPt.setFrom(pt); } public init(downUorPt: Point3d, downRawPt: Point3d, downTime: number, isDown: boolean, isDoubleClick: boolean, isDragging: boolean, source: InputSource) { this.downUorPt = downUorPt; this.downRawPt = downRawPt; this.downTime = downTime; this.isDown = isDown; this.isDoubleClick = isDoubleClick; this.isDragging = isDragging; this.inputSource = source; } } /** Properties for constructing a BeButtonEvent * @public * @extensions */ export interface BeButtonEventProps { /** The point for this event, in world coordinates. * @note these coordinates may have been *adjusted* for some reason (e.g. snapping, locks, etc.) from the [[rawPoint]]. */ point?: Point3d; /** The *raw* (unadjusted) point for this event, in world coordinates. */ rawPoint?: Point3d; /** The point, in screen coordinates for this event. * @note generally the z value is not useful, but some 3d pointing devices do supply it. */ viewPoint?: Point3d; /** The [[ScreenViewport]] for the BeButtonEvent. If undefined, this event is invalid. */ viewport?: ScreenViewport; /** How the coordinate values were generated (either from an action by the user or from a program.) */ coordsFrom?: CoordSource; keyModifiers?: BeModifierKeys; /** The mouse button for this event. */ button?: BeButton; /** If true, this event was generated from a mouse-down transition, false from a button-up transition. */ isDown?: boolean; /** If true, this is the second down in a rapid double-click of the same button. */ isDoubleClick?: boolean; /** If true, this event was created by pressing, holding, and then moving a mouse button. */ isDragging?: boolean; /** Whether this event came from a pointing device (e.g. mouse) or a touch device. */ inputSource?: InputSource; } /** Object sent to Tools that holds information about button/touch/wheel events. * @public * @extensions */ export class BeButtonEvent implements BeButtonEventProps { private readonly _point: Point3d = new Point3d(); private readonly _rawPoint: Point3d = new Point3d(); private readonly _viewPoint: Point3d = new Point3d(); private _movement?: XAndY; /** The [[ScreenViewport]] from which this BeButtonEvent was generated. If undefined, this event is invalid. */ public viewport?: ScreenViewport; /** How the coordinate values were generated (either from an action by the user or from a program.) */ public coordsFrom = CoordSource.User; /** The keyboard modifiers that were pressed when the event was generated. */ public keyModifiers = BeModifierKeys.None; /** If true, this event was generated from a mouse-down transition, false from a button-up transition. */ public isDown = false; /** If true, this is the second down in a rapid double-click of the same button. */ public isDoubleClick = false; /** If true, this event was created by pressing, holding, and then moving a mouse button. */ public isDragging = false; /** The mouse button that created this event. */ public button = BeButton.Data; /** Whether this event came from a pointing device (e.g. mouse) or a touch device. */ public inputSource = InputSource.Unknown; public constructor(props?: BeButtonEventProps) { if (props) this.init(props); } /** Determine whether this BeButtonEvent has valid data. * @note BeButtonEvents may be constructed as "blank", and are not considered to hold valid data unless the [[viewport]] member is defined. */ public get isValid(): boolean { return this.viewport !== undefined; } /** The point for this event, in world coordinates. * @note these coordinates may have been *adjusted* for some reason (e.g. snapping, locks, etc.) from the [[rawPoint]]. */ public get point() { return this._point; } public set point(pt: Point3d) { this._point.setFrom(pt); } /** The *raw* (unadjusted) point for this event, in world coordinates. */ public get rawPoint() { return this._rawPoint; } public set rawPoint(pt: Point3d) { this._rawPoint.setFrom(pt); } /** The point, in screen coordinates for this event. * @note generally the z value is not useful, but some 3d pointing devices do supply it. */ public get viewPoint() { return this._viewPoint; } public set viewPoint(pt: Point3d) { this._viewPoint.setFrom(pt); } /** The difference in screen coordinates from previous motion event * @internal */ public get movement(): XAndY | undefined { return this._movement; } public set movement(mov: XAndY | undefined) { this._movement = mov; } /** Mark this BeButtonEvent as invalid. Can only become valid again by calling [[init]] */ public invalidate() { this.viewport = undefined; } /** Initialize the values of this BeButtonEvent. */ public init(props: BeButtonEventProps) { if (undefined !== props.point) this.point = props.point; if (undefined !== props.rawPoint) this.rawPoint = props.rawPoint; if (undefined !== props.viewPoint) this.viewPoint = props.viewPoint; if (undefined !== props.viewport) this.viewport = props.viewport; if (undefined !== props.coordsFrom) this.coordsFrom = props.coordsFrom; if (undefined !== props.keyModifiers) this.keyModifiers = props.keyModifiers; if (undefined !== props.isDown) this.isDown = props.isDown; if (undefined !== props.isDoubleClick) this.isDoubleClick = props.isDoubleClick; if (undefined !== props.isDragging) this.isDragging = props.isDragging; if (undefined !== props.button) this.button = props.button; if (undefined !== props.inputSource) this.inputSource = props.inputSource; } /** Determine whether the control key was pressed */ public get isControlKey() { return 0 !== (this.keyModifiers & BeModifierKeys.Control); } /** Determine whether the shift key was pressed */ public get isShiftKey() { return 0 !== (this.keyModifiers & BeModifierKeys.Shift); } /** Determine whether the alt key was pressed */ public get isAltKey() { return 0 !== (this.keyModifiers & BeModifierKeys.Alt); } /** Copy the values from another BeButtonEvent into this BeButtonEvent */ public setFrom(src: BeButtonEvent): this { this.point = src.point; this.rawPoint = src.rawPoint; this.viewPoint = src.viewPoint; this.viewport = src.viewport; this.coordsFrom = src.coordsFrom; this.keyModifiers = src.keyModifiers; this.isDown = src.isDown; this.isDoubleClick = src.isDoubleClick; this.isDragging = src.isDragging; this.button = src.button; this.inputSource = src.inputSource; return this; } /** Make a copy of this BeButtonEvent. */ public clone(): this { return new (this.constructor as typeof BeButtonEvent)(this) as this; } } /** Properties for initializing a BeTouchEvent * @public * @extensions */ export interface BeTouchEventProps extends BeButtonEventProps { touchEvent: TouchEvent; } /** A ButtonEvent generated by touch input. * @public * @extensions */ export class BeTouchEvent extends BeButtonEvent implements BeTouchEventProps { public tapCount: number = 0; public touchEvent: TouchEvent; public get touchCount(): number { return this.touchEvent.targetTouches.length; } public get isSingleTouch(): boolean { return 1 === this.touchCount; } public get isTwoFingerTouch(): boolean { return 2 === this.touchCount; } public get isSingleTap(): boolean { return 1 === this.tapCount && 1 === this.touchCount; } public get isDoubleTap(): boolean { return 2 === this.tapCount && 1 === this.touchCount; } public get isTwoFingerTap(): boolean { return 1 === this.tapCount && 2 === this.touchCount; } public constructor(props: BeTouchEventProps) { super(props); this.touchEvent = props.touchEvent; } public override setFrom(src: BeTouchEvent): this { super.setFrom(src); this.touchEvent = src.touchEvent; this.tapCount = src.tapCount; return this; } public static getTouchPosition(touch: Touch, vp: ScreenViewport): Point2d { const rect = vp.getClientRect(); return Point2d.createFrom({ x: touch.clientX - rect.left, y: touch.clientY - rect.top }); } public static getTouchListCentroid(list: TouchList, vp: ScreenViewport): Point2d | undefined { switch (list.length) { case 0: { return undefined; } case 1: { return this.getTouchPosition(list[0], vp); } case 2: { return this.getTouchPosition(list[0], vp).interpolate(0.5, this.getTouchPosition(list[1], vp)); } default: { const points: Point2d[] = []; // eslint-disable-next-line @typescript-eslint/prefer-for-of for (let i = 0; i < list.length; i++) { points.push(this.getTouchPosition(list[i], vp)); } const centroid = Point2d.createZero(); PolygonOps.centroidAndAreaXY(points, centroid); return centroid; } } } public static findTouchById(list: TouchList, id: number): Touch | undefined { // eslint-disable-next-line @typescript-eslint/prefer-for-of for (let i = 0; i < list.length; i++) { if (id === list[i].identifier) return list[i]; } return undefined; } } /** Properties for constructing a BeWheelEvent * @public * @extensions */ export interface BeWheelEventProps extends BeButtonEventProps { wheelDelta?: number; time?: number; } /** A BeButtonEvent generated by movement of a mouse wheel. * @note wheel events include mouse location. * @public * @extensions */ export class BeWheelEvent extends BeButtonEvent implements BeWheelEventProps { public wheelDelta: number; public time: number; public constructor(props?: BeWheelEventProps) { super(props); this.wheelDelta = (props && props.wheelDelta !== undefined) ? props.wheelDelta : 0; this.time = (props && props.time) ? props.time : Date.now(); } public override setFrom(src: BeWheelEvent): this { super.setFrom(src); this.wheelDelta = src.wheelDelta; this.time = src.time; return this; } } /** A Tool that performs an action. It has a *toolId* that uniquely identifies it, so it can be found via a lookup in the [[ToolRegistry]]. * Every time a tools run, a new instance of (a subclass of) this class is created and its [[run]] method is invoked. * @see [[InteractiveTool]] for a base Tool class to handle user input events from a Viewport. * @see [Tools]($docs/learning/frontend/tools.md) * @public * @extensions */ export class Tool { /** If true, this Tool will not appear in the list from [[ToolRegistry.getToolList]]. This should be overridden in subclasses to hide them. */ public static hidden = false; /** The unique string that identifies this tool. This must be overridden in every subclass. */ public static toolId = ""; /** The icon for this Tool. This may be overridden in subclasses to provide a tool icon. * The value is the name of an icon WebFont entry, or if specifying an SVG symbol, use `svg:` prefix. */ public static iconSpec = ""; /** The namespace that provides localized strings for this Tool. Subclasses should override this. */ public static namespace: string; /** @internal */ public get ctor() { return this.constructor as ToolType; } public constructor(..._args: any[]) { } /** The minimum number of arguments allowed by [[parseAndRun]]. If subclasses override [[parseAndRun]], they should also * override this method to indicate the minimum number of arguments their implementation expects. UI controls can use * this information to ensure the tool has enough information to execute. */ public static get minArgs(): number { return 0; } /** The maximum number of arguments allowed by [[parseAndRun]], or undefined if there is no maximum. * If subclasses override [[parseAndRun]], they should also override this method to indicate the maximum * number of arguments their implementation expects. */ public static get maxArgs(): number | undefined { return 0; } /** * Register this Tool class with the [[ToolRegistry]]. * @param namespace optional namespace to supply to [[ToolRegistry.register]]. If undefined, use namespace from superclass. */ public static register(namespace?: string) { IModelApp.tools.register(this, namespace); } private static getLocalizedKey(name: string): string | undefined { const key = `tools.${this.toolId}.${name}`; const val = IModelApp.localization.getLocalizedStringWithNamespace(this.namespace, key); return key === val ? undefined : val; // if translation for key doesn't exist, `translate` returns the key as the result } /** * Get the localized keyin string for this Tool class. This returns the value of "tools." + this.toolId + ".keyin" from * its registered Namespace (e.g. "en/MyApp.json"). */ public static get keyin(): string { const keyin = this.getLocalizedKey("keyin"); return (undefined !== keyin) ? keyin : ""; // default to empty string } /** * Get the English keyin string for this Tool class. This returns the value of "tools." + this.toolId + ".keyin" from * its registered Namespace (e.g. "en/MyApp.json"). */ public static get englishKeyin(): string { const key = `tools.${this.toolId}.keyin`; const val = IModelApp.localization.getEnglishString(this.namespace, key); return val !== key ? val : ""; // default to empty string } /** * Get the localized flyover for this Tool class. This returns the value of "tools." + this.toolId + ".flyover" from * its registered Namespace (e.g. "en/MyApp.json"). If that key is not in the localization namespace, * [[keyin]] is returned. */ public static get flyover(): string { const flyover = this.getLocalizedKey("flyover"); return (undefined !== flyover) ? flyover : this.keyin; // default to keyin } /** * Get the localized description for this Tool class. This returns the value of "tools." + this.toolId + ".description" from * its registered Namespace (e.g. "en/MyApp.json"). If that key is not in the localization namespace, * [[flyover]] is returned. */ public static get description(): string { const description = this.getLocalizedKey("description"); return (undefined !== description) ? description : this.flyover; // default to flyover } /** * Get the toolId string for this Tool class. This string is used to identify the Tool in the ToolRegistry and is used to localize * the keyin, description, etc. from the current locale. */ public get toolId(): string { return this.ctor.toolId; } /** Get the localized keyin string from this Tool's class * @see `static get keyin()` */ public get keyin(): string { return this.ctor.keyin; } /** Get the localized flyover string from this Tool's class * @see `static get flyover()` */ public get flyover(): string { return this.ctor.flyover; } /** Get the localized description string from this Tool's class * @see `static get description()` */ public get description(): string { return this.ctor.description; } /** Get the iconSpec from this Tool's class. * @see `static iconSpec` */ public get iconSpec(): string { return this.ctor.iconSpec; } /** * Run this instance of a Tool. Subclasses should override to perform some action. * @returns `true` if the tool executed successfully. */ public async run(..._args: any[]): Promise<boolean> { return true; } /** Run this instance of a tool using a series of string arguments. Override this method to parse the arguments, and if they're * acceptable, execute your [[run]] method. If the arguments aren't valid, return `false`. * @note if you override this method, you must also override the static [[minArgs]] and [[maxArgs]] getters. * @note Generally, implementers of this method are **not** expected to call `super.parseAndRun(...)`. Instead, call your * [[run]] method with the appropriate (parsed) arguments directly. */ public async parseAndRun(..._args: string[]): Promise<boolean> { return this.run(); } } /** * @public * @extensions */ export enum EventHandled { No = 0, Yes = 1 } /** A Tool that may be installed, via [[ToolAdmin]], to handle user input. The ToolAdmin manages the currently installed ViewingTool, PrimitiveTool, * InputCollector, and IdleTool. Each must derive from this class and there may only be one of each type installed at a time. * @public * @extensions */ export abstract class InteractiveTool extends Tool { /** Used to avoid sending tools up events for which they did not receive the down event. */ public receivedDownEvent = false; /** Override to execute additional logic when tool is installed. Return false to prevent this tool from becoming active */ public async onInstall(): Promise<boolean> { return true; } /** Override to execute additional logic after tool becomes active */ public async onPostInstall(): Promise<void> { } public abstract exitTool(): Promise<void>; /** Override Call to reset tool to initial state */ public async onReinitialize(): Promise<void> { } /** Invoked when the tool becomes no longer active, to perform additional cleanup logic */ public async onCleanup(): Promise<void> { } /** Notification of a ViewTool or InputCollector starting and this tool is being suspended. * @note Applies only to PrimitiveTool and InputCollector, a ViewTool can't be suspended. */ public async onSuspend(): Promise<void> { } /** Notification of a ViewTool or InputCollector exiting and this tool is being unsuspended. * @note Applies only to PrimitiveTool and InputCollector, a ViewTool can't be suspended. */ public async onUnsuspend(): Promise<void> { } /** Called to support operations on pickable decorations, like snapping. */ public testDecorationHit(_id: string): boolean { return false; } /** Called to allow snapping to pickable decoration geometry. * @note Snap geometry can be different from decoration geometry (ex. center point of a + symbol). Valid decoration geometry for snapping should be "stable" and not change based on the current cursor location. */ public getDecorationGeometry(_hit: HitDetail): GeometryStreamProps | undefined { return undefined; } /** * Called to allow an active tool to display non-element decorations in overlay mode. * This method is NOT called while the tool is suspended by a viewing tool or input collector. */ public decorate(_context: DecorateContext): void { } /** * Called to allow a suspended tool to display non-element decorations in overlay mode. * This method is ONLY called when the tool is suspended by a viewing tool or input collector. * @note Applies only to PrimitiveTool and InputCollector, a ViewTool can't be suspended. */ public decorateSuspended(_context: DecorateContext): void { } /** Invoked when the reset button is pressed. * @return No by default. Sub-classes may ascribe special meaning to this status. * @note To support right-press menus, a tool should put its reset event processing in onResetButtonUp instead of onResetButtonDown. */ public async onResetButtonDown(_ev: BeButtonEvent): Promise<EventHandled> { return EventHandled.No; } /** Invoked when the reset button is released. * @return No by default. Sub-classes may ascribe special meaning to this status. */ public async onResetButtonUp(_ev: BeButtonEvent): Promise<EventHandled> { return EventHandled.No; } /** Invoked when the data button is pressed. * @return No by default. Sub-classes may ascribe special meaning to this status. */ public async onDataButtonDown(_ev: BeButtonEvent): Promise<EventHandled> { return EventHandled.No; } /** Invoked when the data button is released. * @return No by default. Sub-classes may ascribe special meaning to this status. */ public async onDataButtonUp(_ev: BeButtonEvent): Promise<EventHandled> { return EventHandled.No; } /** Invoked when the middle mouse button is pressed. * @return Yes if event completely handled by tool and event should not be passed on to the IdleTool. */ public async onMiddleButtonDown(_ev: BeButtonEvent): Promise<EventHandled> { return EventHandled.No; } /** Invoked when the middle mouse button is released. * @return Yes if event completely handled by tool and event should not be passed on to the IdleTool. */ public async onMiddleButtonUp(_ev: BeButtonEvent): Promise<EventHandled> { return EventHandled.No; } /** Invoked when the cursor is moving */ public async onMouseMotion(_ev: BeButtonEvent): Promise<void> { } /** Invoked when the cursor begins moving while a button is depressed. * @return Yes if event completely handled by tool and event should not be passed on to the IdleTool. */ public async onMouseStartDrag(_ev: BeButtonEvent): Promise<EventHandled> { return EventHandled.No; } /** Invoked when the button is released after onMouseStartDrag. * @note default placement tool behavior is to treat press, drag, and release of data button the same as click, click by calling onDataButtonDown. * @return Yes if event completely handled by tool and event should not be passed on to the IdleTool. */ public async onMouseEndDrag(ev: BeButtonEvent): Promise<EventHandled> { if (BeButton.Data !== ev.button) return EventHandled.No; if (ev.isDown) return this.onDataButtonDown(ev); const downEv = ev.clone(); downEv.isDown = true; return this.onDataButtonDown(downEv); } /** Invoked when the mouse wheel moves. * @return Yes if event completely handled by tool and event should not be passed on to the IdleTool. */ public async onMouseWheel(_ev: BeWheelEvent): Promise<EventHandled> { return EventHandled.No; } /** Called when Control, Shift, or Alt modifier keys are pressed or released. * @param _wentDown up or down key event * @param _modifier The modifier key mask * @param _event The event that caused this call * @return Yes to refresh view decorations or update dynamics. */ public async onModifierKeyTransition(_wentDown: boolean, _modifier: BeModifierKeys, _event: KeyboardEvent): Promise<EventHandled> { return EventHandled.No; } /** Called when any key is pressed or released. * @param _wentDown up or down key event * @param _keyEvent The KeyboardEvent * @return Yes to prevent further processing of this event * @see [[onModifierKeyTransition]] */ public async onKeyTransition(_wentDown: boolean, _keyEvent: KeyboardEvent): Promise<EventHandled> { return EventHandled.No; } /** Called when user adds a touch point by placing a finger or stylus on the surface. */ public async onTouchStart(_ev: BeTouchEvent): Promise<void> { } /** Called when user removes a touch point by lifting a finger or stylus from the surface. */ public async onTouchEnd(_ev: BeTouchEvent): Promise<void> { } /** Called when the last touch point is removed from the surface completing the current gesture. This is a convenience event sent following onTouchEnd when no target touch points remain on the surface. */ public async onTouchComplete(_ev: BeTouchEvent): Promise<void> { } /** Called when a touch point is interrupted in some way and needs to be dropped from the list of target touches. */ public async onTouchCancel(_ev: BeTouchEvent): Promise<void> { } /** Called when a touch point moves along the surface. */ public async onTouchMove(_ev: BeTouchEvent): Promise<void> { } /** Called after at least one touch point has moved for an appreciable time and distance along the surface to not be considered a tap. * @param _ev The event that caused this call * @param _startEv The event from the last call to onTouchStart * @return Yes if event completely handled by tool and event should not be passed on to the IdleTool. */ public async onTouchMoveStart(_ev: BeTouchEvent, _startEv: BeTouchEvent): Promise<EventHandled> { return EventHandled.No; } /** Called when touch point(s) are added and removed from a surface within a small time window without any touch point moving. * @param _ev The event that caused this call * @return Yes if event completely handled by tool and event should not be passed on to the IdleTool. * @note A double or triple tap event will not be preceded by a single tap event. */ public async onTouchTap(_ev: BeTouchEvent): Promise<EventHandled> { return EventHandled.No; } public isCompatibleViewport(_vp: ScreenViewport, _isSelectedViewChange: boolean): boolean { return true; } public isValidLocation(_ev: BeButtonEvent, _isButtonEvent: boolean): boolean { return true; } /** * Called when active view changes. Tool may choose to restart or exit based on current view type. * @param previous The previously active view. * @param current The new active view. */ public onSelectedViewportChanged(_previous: ScreenViewport | undefined, _current: ScreenViewport | undefined): void { } /** * Invoked before the locate tooltip is displayed to retrieve the information about the located element. Allows the tool to override the toolTip. * @param hit The HitDetail whose info is needed. * @return A Promise for the HTMLElement or string to describe the hit. * @note If you override this method, you may decide whether to call your superclass' implementation or not (it is not required). */ public async getToolTip(_hit: HitDetail): Promise<HTMLElement | string> { return _hit.getToolTip(); } /** Convenience method to check whether control key is currently down without needing a button event. */ public get isControlDown(): boolean { return IModelApp.toolAdmin.currentInputState.isControlDown; } /** Fill the supplied button event from the current cursor location. */ public getCurrentButtonEvent(ev: BeButtonEvent): void { IModelApp.toolAdmin.fillEventFromCursorLocation(ev); } /** Call to find out if dynamics are currently active. */ public get isDynamicsStarted(): boolean { return IModelApp.viewManager.inDynamicsMode; } /** Call to initialize dynamics mode. While dynamics are active onDynamicFrame will be called. Dynamics are typically only used by a PrimitiveTool that creates or modifies geometric elements. */ public beginDynamics(): void { IModelApp.toolAdmin.beginDynamics(); } /** Call to terminate dynamics mode. */ public endDynamics(): void { IModelApp.toolAdmin.endDynamics(); } /** Called to allow Tool to display dynamic elements. */ public onDynamicFrame(_ev: BeButtonEvent, _context: DynamicsContext): void { } /** Invoked to allow tools to filter which elements can be located. * @return Reject if hit is unacceptable for this tool (fill out response with explanation, if it is defined) */ public async filterHit(_hit: HitDetail, _out?: LocateResponse): Promise<LocateFilterStatus> { return LocateFilterStatus.Accept; } /** Helper method to keep the view cursor, display of locate circle, and coordinate lock overrides consistent with [[AccuSnap.isLocateEnabled]] and [[AccuSnap.isSnapEnabled]]. * @param enableLocate Value to pass to [[AccuSnap.enableLocate]]. Tools that locate elements should always pass true to give the user feedback regarding the element at the current cursor location. * @param enableSnap Optional value to pass to [[AccuSnap.enableSnap]]. Tools that don't care about the element pick location should not pass true. Default is false. * @note User must also have snapping enabled [[AccuSnap.isSnapEnabledByUser]], otherwise [[TentativePoint]] is used to snap. * @param cursor Optional tool specific cursor override. Default is either cross or dynamics cursor depending on whether dynamics are currently active. * @param coordLockOvr Optional tool specific coordinate lock overrides. A tool that only identifies elements and does not use [[BeButtonEvent.point]] can set ToolState.coordLockOvr to CoordinateLockOverrides.ACS * or CoordinateLockOverrides.All, otherwise locate is affected by the input point being first projected to the ACS plane. A tool that will use [[BeButtonEvent.point]], especially those that call [[AccuSnap.enableSnap]] * should honor all locks and leave ToolState.coordLockOvr set to CoordinateLockOverrides.None, the default for ViewTool and PrimitiveTool. */ public changeLocateState(enableLocate: boolean, enableSnap?: boolean, cursor?: string, coordLockOvr?: CoordinateLockOverrides): void { const { toolAdmin, viewManager, accuSnap } = IModelApp; if (undefined !== cursor) { toolAdmin.setCursor(cursor); toolAdmin.setLocateCircleOn(enableLocate); viewManager.invalidateDecorationsAllViews(); } else { toolAdmin.setLocateCursor(enableLocate); } // Always set the one that is true first, otherwise AccuSnap will clear the TouchCursor. if (enableLocate) { accuSnap.enableLocate(true); accuSnap.enableSnap(true === enableSnap); } else { accuSnap.enableSnap(true === enableSnap); accuSnap.enableLocate(false); } if (undefined !== coordLockOvr) { toolAdmin.toolState.coordLockOvr = coordLockOvr; } else { if (enableLocate && !accuSnap.isSnapEnabled) toolAdmin.toolState.coordLockOvr |= CoordinateLockOverrides.ACS; else toolAdmin.toolState.coordLockOvr &= ~CoordinateLockOverrides.ACS; } } /** Helper method for tools that need to locate existing elements. * Initializes [[ElementLocateManager]], changes the view cursor to locate, enables display of the locate circle, and sets the appropriate coordinate lock overrides. * @see [[changeLocateState]] */ public initLocateElements(enableLocate: boolean = true, enableSnap?: boolean, cursor?: string, coordLockOvr?: CoordinateLockOverrides): void { IModelApp.locateManager.initToolLocate(); this.changeLocateState(enableLocate, enableSnap, cursor, coordLockOvr); } /** @internal */ protected toolSettingProperties?: Map<string, DialogProperty<any>>; /** @internal */ protected restoreToolSettingPropertyValue(property: DialogProperty<any>): boolean { const itemValue = IModelApp.toolAdmin.toolSettingsState.getInitialToolSettingValue(this.toolId, property.name); if (undefined === itemValue?.value) return false; property.dialogItemValue = itemValue; return true; } /** @internal */ protected saveToolSettingPropertyValue(property: DialogProperty<any>, itemValue: DialogItemValue): boolean { if (undefined === itemValue.value) return false; property.value = itemValue.value; IModelApp.toolAdmin.toolSettingsState.saveToolSettingProperty(this.toolId, property.item); return true; } /** @internal */ protected syncToolSettingPropertyValue(property: DialogProperty<any>, isDisabled?: boolean): void { if (undefined !== isDisabled) property.isDisabled = isDisabled; this.syncToolSettingsProperties([property.syncItem]); } /** @internal */ protected getToolSettingPropertyByName(propertyName: string): DialogProperty<any> { const foundProperty = this.toolSettingProperties?.get(propertyName); if (foundProperty) return foundProperty; throw new Error(`property not found: ${propertyName}`); } /** Override to return the property that is disabled/enabled if the supplied property is a lock property. * @see [[changeToolSettingPropertyValue]] * @beta */ protected getToolSettingPropertyLocked(_property: DialogProperty<any>): DialogProperty<any> | undefined { return undefined; } /** Helper method for responding to a tool setting property value change by updating saved settings. * @see [[applyToolSettingPropertyChange]] * @see [[getToolSettingPropertyLocked]] to return the corresponding locked property, if any. * @beta */ protected changeToolSettingPropertyValue(syncItem: DialogPropertySyncItem): boolean { const property = this.getToolSettingPropertyByName(syncItem.propertyName); if (!this.saveToolSettingPropertyValue(property, syncItem.value)) return false; const lockedProperty = this.getToolSettingPropertyLocked(property); if (undefined !== lockedProperty) this.syncToolSettingPropertyValue(lockedProperty, !property.value); return true; } /** Helper method to establish initial values for tool setting properties from saved settings. * @see [[supplyToolSettingsProperties]] * @beta */ protected initializeToolSettingPropertyValues(properties: DialogProperty<any>[]): void { if (undefined !== this.toolSettingProperties) return; this.toolSettingProperties = new Map<string, DialogProperty<any>>(); for (const property of properties) { this.toolSettingProperties.set(property.name, property); this.restoreToolSettingPropertyValue(property); } } /** Used to supply list of properties that can be used to generate ToolSettings. If undefined is returned then no ToolSettings will be displayed. * @see [[initializeToolSettingPropertyValues]] * @beta */ public supplyToolSettingsProperties(): DialogItem[] | undefined { return undefined; } /** Used to receive property changes from UI. Return false if there was an error applying updatedValue. * @see [[changeToolSettingPropertyValue]] * @beta */ public async applyToolSettingPropertyChange(_updatedValue: DialogPropertySyncItem): Promise<boolean> { return true; } /** Called by tool to synchronize the UI with property changes made by tool. This is typically used to provide user feedback during tool dynamics. * If the syncData contains a quantity value and if the displayValue is not defined, the displayValue will be generated in the UI layer before displaying the value. * @beta */ public syncToolSettingsProperties(syncData: DialogPropertySyncItem[]) { IModelApp.toolAdmin.syncToolSettingsProperties(this.toolId, syncData); } /** Called by tool to inform UI to reload ToolSettings with new set of properties. This allows properties to be added or removed from ToolSetting * component as tool processing progresses. * @beta */ public reloadToolSettingsProperties() { IModelApp.toolAdmin.reloadToolSettingsProperties(); } /** Used to "bump" the value of a tool setting. To "bump" a setting means to toggle a boolean value or cycle through enum values. * If no `settingIndex` param is specified, the first setting is bumped. * Return true if the setting was successfully bumped. * @beta */ public async bumpToolSetting(_settingIndex?: number): Promise<boolean> { return false; } } /** The InputCollector class can be used to implement a command for gathering input * (ex. get a distance by snapping to 2 points) without affecting the state of the active primitive tool. * An InputCollector will suspend the active PrimitiveTool and can be suspended by a ViewTool. * @public * @extensions */ export abstract class InputCollector extends InteractiveTool { public override async run(..._args: any[]): Promise<boolean> { const toolAdmin = IModelApp.toolAdmin; // An input collector can only suspend a primitive tool, don't install if a viewing tool is active... if (undefined !== toolAdmin.viewTool || !await toolAdmin.onInstallTool(this)) return false; await toolAdmin.startInputCollector(this); await toolAdmin.onPostInstallTool(this); return true; } public async exitTool() { return IModelApp.toolAdmin.exitInputCollector(); } public override async onResetButtonUp(_ev: BeButtonEvent): Promise<EventHandled> { await this.exitTool(); return EventHandled.Yes; } } /** The result type of [[ToolRegistry.parseAndRun]]. * @public * @extensions */ export enum ParseAndRunResult { /** The tool's `parseAndRun` method was invoked and returned `true`. */ Success, /** No tool matching the toolId in the keyin is registered. */ ToolNotFound, /** The number of arguments supplied does not meet the constraints of the Tool. @see [[Tool.minArgs]] and [[Tool.maxArgs]]. */ BadArgumentCount, /** The tool's `parseAndRun` method returned `false`. */ FailedToRun, /** An opening double-quote character was not paired with a closing double-quote character. */ MismatchedQuotes, } /** Possible errors resulting from [[ToolRegistry.parseKeyin]]. * @public * @extensions */ export enum KeyinParseError { /** No registered tool matching the keyin was found. */ ToolNotFound = ParseAndRunResult.ToolNotFound, /** The opening double-quote of an argument was not terminated with a closing double-quote. */ MismatchedQuotes = ParseAndRunResult.MismatchedQuotes, } /** Possible errors form [[ToolRegistry.parseKeyin]]. * @public * @extensions */ export interface ParseKeyinError { /** Union discriminator for [[ParseKeyinResult]]. */ ok: false; /** The specific error that occurred during parsing. */ error: KeyinParseError; } /** Successful result from [[ToolRegistry.parseKeyin]]. * @public * @extensions */ export interface ParsedKeyin { /** Union discriminator for [[ParseKeyinResult]]. */ ok: true; /** The constructor for the Tool that handles the keyin. */ tool: ToolType; /** The parsed arguments to be passed to [[Tool.parseAndRun]]. */ args: string[]; } /** The result type of [[ToolRegistry.parseKeyin]]. * @public * @extensions */ export type ParseKeyinResult = ParsedKeyin | ParseKeyinError; /** The ToolRegistry holds a mapping between toolIds and their corresponding [[Tool]] class. This provides the mechanism to * find Tools by their toolId, and also a way to iterate over the set of Tools available. * @public */ export class ToolRegistry { public readonly tools = new Map<string, ToolType>(); private _keyinList?: ToolList; public shutdown() { this.tools.clear(); this._keyinList = undefined; } /** * Un-register a previously registered Tool class. * @param toolId the toolId of a previously registered tool to unRegister. */ public unRegister(toolId: string) { this.tools.delete(toolId); this._keyinList = undefined; } /** * Register a Tool class. This establishes a connection between the toolId of the class and the class itself. * @param toolClass the subclass of Tool to register. * @param namespace the namespace for the localized strings for this tool. If undefined, use namespace from superclass. */ public register(toolClass: ToolType, namespace?: string) { if (namespace) // namespace is optional because it can come from superclass toolClass.namespace = namespace; if (toolClass.toolId.length === 0) return; // must be an abstract class, ignore it if (!toolClass.namespace) throw new IModelError(-1, "Tools must have a namespace"); this.tools.set(toolClass.toolId, toolClass); this._keyinList = undefined; // throw away the current keyinList so we'll produce a new one next time we're asked. } /** * Register all the Tool classes found in a module. * @param modelObj the module to search for subclasses of Tool. */ public registerModule(moduleObj: any, namespace?: string) { for (const thisMember in moduleObj) { // eslint-disable-line guard-for-in const thisTool = moduleObj[thisMember]; if (thisTool.prototype instanceof Tool) { this.register(thisTool, namespace); } } } /** Look up a tool by toolId */ public find(toolId: string): ToolType | undefined { return this.tools.get(toolId); } /** * Look up a tool by toolId and, if found, create an instance with the supplied arguments. * @param toolId the toolId of the tool * @param args arguments to pass to the constructor. * @returns an instance of the registered Tool class, or undefined if toolId is not registered. */ public create(toolId: string, ...args: any[]): Tool | undefined { const toolClass = this.find(toolId); return toolClass ? new toolClass(...args) : undefined; } /** * Look up a tool by toolId and, if found, create an instance with the supplied arguments and run it. * @param toolId toolId of the immediate tool * @param args arguments to pass to the constructor, and to run. * @return true if the tool was found and successfully run. */ public async run(toolId: string, ...args: any[]): Promise<boolean> { const tool = this.create(toolId, ...args); return tool !== undefined && tool.run(...args); } /** * Split key-in into and array of string arguments. Handles embedded quoted strings. * @param keyin keyin string to process * #return an Array of string argument */ private tokenize(keyin: string): { tokens: string[], firstQuotedIndex?: number, mismatchedQuotes?: boolean } { const isWhitespace = (char: string) => "" === char.trim(); const tokens: string[] = []; let index = 0; let firstQuotedIndex; while (index < keyin.length) { // Looking for beginning of next token. const ch = keyin[index]; if (isWhitespace(ch)) { ++index; continue; } if ('"' !== ch) { // Unquoted token. let endIndex = keyin.length; for (let i = index + 1; i < keyin.length; i++) { if (isWhitespace(keyin[i])) { endIndex = i; break; } } tokens.push(keyin.substring(index, endIndex)); index = endIndex; continue; } // Quoted argument. if (undefined === firstQuotedIndex) firstQuotedIndex = tokens.length; let endQuoteIndex; let searchIndex = index + 1; let anyEmbeddedQuotes = false; while (searchIndex < keyin.length) { searchIndex = keyin.indexOf('"', searchIndex); if (-1 === searchIndex) break; // A literal " is embedded as "" if (searchIndex + 1 > keyin.length || keyin[searchIndex + 1] !== '"') { endQuoteIndex = searchIndex; break; } anyEmbeddedQuotes = true; searchIndex = searchIndex + 2; } if (undefined === endQuoteIndex) { return { tokens, mismatchedQuotes: true }; } else { let token = keyin.substring(index + 1, endQuoteIndex); if (anyEmbeddedQuotes) { const regex = /""/g; token = token.replace(regex, '"'); } tokens.push(token); index = endQuoteIndex + 1; } } return { tokens, firstQuotedIndex }; } /** Given a string consisting of a toolId followed by any number of arguments, locate the corresponding Tool and parse the arguments. * Tokens are delimited by whitespace. * The Tool is determined by finding the longest string of unquoted tokens starting at the beginning of the key-in string that matches a registered Tool's * `keyin` or `englishKeyin`. * Tokens following the Tool's keyin are parsed as arguments. * Arguments may be quoted using "double quotes". The opening quote must be preceded by whitespace. Examples, assuming the tool Id is `my keyin`: * - `my keyin "abc" "def"` => two arguments: `abc` and `def` * - `my keyin abc"def"` => one argument: `abc"def"` * A literal double-quote character can be embedded in a quoted argument as follows: * - `my keyin "abc""def"` => one argument: `abc"def`. * @param keyin A string consisting of a toolId followed by any number of arguments. The arguments are separated by whitespace. * @returns The tool, if found, along with an array of parsed arguments. * @public */ public parseKeyin(keyin: string): ParseKeyinResult { const tools = this.getToolList(); let tool; const args: string[] = []; const findTool = (lowerKeyin: string) => tools.find((x) => x.keyin.toLowerCase() === lowerKeyin || x.englishKeyin.toLowerCase() === lowerKeyin); // try the trivial, common case first tool = findTool(keyin.toLowerCase()); if (undefined !== tool) return { ok: true, tool, args }; // Tokenize to separate keyin from arguments // ###TODO there's actually nothing that prevents a Tool from including leading/trailing spaces in its keyin, or sequences of more than one space...we will fail to find such tools if they exist... const split = this.tokenize(keyin); const tokens = split.tokens; if (split.mismatchedQuotes) return { ok: false, error: KeyinParseError.MismatchedQuotes }; else if (tokens.length <= 1) return { ok: false, error: KeyinParseError.ToolNotFound }; // Find the longest starting substring that matches a tool's keyin. const maxIndex = undefined !== split.firstQuotedIndex ? split.firstQuotedIndex - 1 : tokens.length - 2; for (let i = maxIndex; i >= 0; i--) { let substr = tokens[0]; for (let j = 1; j <= i; j++) { substr += " "; substr += tokens[j]; } tool = findTool(substr.toLowerCase()); if (undefined !== tool) { // Any subsequent tokens are arguments. for (let k = i + 1; k < tokens.length; k++) args.push(tokens[k]); break; } } return tool ? { ok: true, tool, args } : { ok: false, error: KeyinParseError.ToolNotFound }; } /** Get a list of Tools currently registered, excluding hidden tools */ public getToolList(): ToolList { if (this._keyinList === undefined) { this._keyinList = []; this.tools.forEach((thisTool) => { if (!thisTool.hidden) this._keyinList!.push(thisTool); }); } return this._keyinList; } /** Given a string consisting of a toolId followed by any number of arguments, parse the keyin string and invoke the corresponding tool's `parseAndRun` method. * @param keyin A string consisting of a toolId followed by any number of arguments. * @returns A status indicating whether the keyin was successfully parsed and executed. * @see [[parseKeyin]] to parse the keyin string and for a detailed description of the syntax. * @throws any Error thrown by the tool's `parseAndRun` method. * @public */ public async parseAndRun(keyin: string): Promise<ParseAndRunResult> { const parsed = this.parseKeyin(keyin); if (!parsed.ok) { switch (parsed.error) { case KeyinParseError.MismatchedQuotes: return ParseAndRunResult.MismatchedQuotes; case KeyinParseError.ToolNotFound: return ParseAndRunResult.ToolNotFound; } } assert(parsed.ok); // exhaustive switch above... const maxArgs = parsed.tool.maxArgs; if (parsed.args.length < parsed.tool.minArgs || (undefined !== maxArgs && parsed.args.length > maxArgs)) return ParseAndRunResult.BadArgumentCount; const tool = new parsed.tool(); return await tool.parseAndRun(...parsed.args) ? ParseAndRunResult.Success : ParseAndRunResult.FailedToRun; } /** * Find a tool by its localized keyin using a FuzzySearch * @param keyin the localized keyin string of the Tool. * @note Make sure the i18n resources are all loaded (e.g. `await IModelApp.i81n.waitForAllRead()`) before calling this method. * @public */ public findPartialMatches(keyin: string): FuzzySearchResults<ToolType> { return new FuzzySearch<ToolType>().search(this.getToolList(), ["keyin"], keyin.toLowerCase()); } /** * Find a tool by its localized keyin. * @param keyin the localized keyin string of the Tool. * @returns the Tool class, if an exact match is found, otherwise returns undefined. * @note Make sure the i18n resources are all loaded (e.g. `await IModelApp.i81n.waitForAllRead()`) before calling this method. * @public */ public findExactMatch(keyin: string): ToolType | undefined { keyin = keyin.toLowerCase(); return this.getToolList().find((thisTool) => thisTool.keyin.toLowerCase() === keyin); } } /** @internal */ export class CoreTools { public static namespace = "CoreTools"; public static tools = "CoreTools:tools."; public static translate(prompt: string) { return IModelApp.localization.getLocalizedString(this.tools + prompt); } public static outputPromptByKey(key: string) { return IModelApp.notifications.outputPromptByKey(this.tools + key); } }
the_stack
import * as aws from "@pulumi/aws"; import * as pulumi from "@pulumi/pulumi"; export type EsDomain = aws.elasticsearch.Domain | pulumi.Output<aws.elasticsearch.GetDomainResult>; class Policies { private readonly awsRegion: string; private readonly callerIdentityOutput: pulumi.Output<aws.GetCallerIdentityResult>; constructor() { const current = aws.getCallerIdentity({}); this.callerIdentityOutput = pulumi.output(current); this.awsRegion = aws.config.requireRegion(); } getDynamoDbToElasticLambdaPolicy(domain: EsDomain): aws.iam.Policy { return new aws.iam.Policy("DynamoDbToElasticLambdaPolicy-updated", { description: "This policy enables access to ES and Dynamodb streams", policy: { Version: "2012-10-17", Statement: [ { Sid: "PermissionForES", Effect: "Allow", Action: [ "es:ESHttpDelete", "es:ESHttpPatch", "es:ESHttpPost", "es:ESHttpPut" ], Resource: [ pulumi.interpolate`${domain.arn}`, pulumi.interpolate`${domain.arn}/*` ] } ] } }); } getFileManagerLambdaPolicy(bucket: aws.s3.Bucket): aws.iam.Policy { return new aws.iam.Policy("FileManagerLambdaPolicy", { description: "This policy enables access to Lambda and S3", policy: { Version: "2012-10-17", Statement: [ { Sid: "PermissionForLambda", Effect: "Allow", Action: "lambda:InvokeFunction", Resource: "*" }, { Sid: "PermissionForS3", Effect: "Allow", Action: "s3:*", Resource: pulumi.interpolate`arn:aws:s3:::${bucket.id}/*` } ] } }); } getPreRenderingServiceLambdaPolicy( primaryDynamodbTable: aws.dynamodb.Table, elasticsearchDynamodbTable: aws.dynamodb.Table, bucket: aws.s3.Bucket ): aws.iam.Policy { return new aws.iam.Policy("PreRenderingServicePolicy", { description: "This policy enables access to Lambda, S3, Cloudfront and Dynamodb", policy: { Version: "2012-10-17", Statement: [ { Sid: "PermissionForDynamodb", Effect: "Allow", Action: [ "dynamodb:BatchGetItem", "dynamodb:BatchWriteItem", "dynamodb:DeleteItem", "dynamodb:GetItem", "dynamodb:PutItem", "dynamodb:Query", "dynamodb:Scan", "dynamodb:UpdateItem" ], Resource: [ pulumi.interpolate`${primaryDynamodbTable.arn}`, pulumi.interpolate`${primaryDynamodbTable.arn}/*`, pulumi.interpolate`${elasticsearchDynamodbTable.arn}`, pulumi.interpolate`${elasticsearchDynamodbTable.arn}/*` ] }, { Sid: "PermissionForLambda", Effect: "Allow", Action: "lambda:InvokeFunction", Resource: pulumi.interpolate`arn:aws:lambda:${this.awsRegion}:${this.callerIdentityOutput.accountId}:function:*` }, { Sid: "PermissionForS3", Effect: "Allow", Action: [ "s3:DeleteObject", "s3:GetObject", "s3:GetObjectAcl", "s3:PutObject", "s3:PutObjectAcl" ], Resource: [ pulumi.interpolate`arn:aws:s3:::${bucket.id}/*`, /** * We're using the hard-coded value for "delivery" S3 bucket because; * It is created during deployment of the `apps/website` stack which is after the api stack, * so, we don't know its ARN. */ "arn:aws:s3:::delivery-*/*" ] }, { Sid: "PermissionForCloudfront", Effect: "Allow", Action: "cloudfront:CreateInvalidation", Resource: pulumi.interpolate`arn:aws:cloudfront::${this.callerIdentityOutput.accountId}:distribution/*` } ] } }); } getPbExportPagesLambdaPolicy( primaryDynamodbTable: aws.dynamodb.Table, bucket: aws.s3.Bucket ): aws.iam.Policy { return new aws.iam.Policy("PbExportPageTaskLambdaPolicy", { description: "This policy enables access to Dynamodb", policy: { Version: "2012-10-17", Statement: [ { Sid: "AllowDynamoDBAccess", Effect: "Allow", Action: [ "dynamodb:BatchGetItem", "dynamodb:BatchWriteItem", "dynamodb:PutItem", "dynamodb:DeleteItem", "dynamodb:GetItem", "dynamodb:Query", "dynamodb:UpdateItem" ], Resource: [ pulumi.interpolate`${primaryDynamodbTable.arn}`, pulumi.interpolate`${primaryDynamodbTable.arn}/*` ] }, { Sid: "PermissionForS3", Effect: "Allow", Action: [ "s3:GetObjectAcl", "s3:DeleteObject", "s3:PutObjectAcl", "s3:PutObject", "s3:GetObject", "s3:ListBucket" ], Resource: [ pulumi.interpolate`arn:aws:s3:::${bucket.id}/*`, // We need to explicitly add bucket ARN to "Resource" list for "s3:ListBucket" action. pulumi.interpolate`arn:aws:s3:::${bucket.id}` ] }, { Sid: "PermissionForLambda", Effect: "Allow", Action: ["lambda:InvokeFunction"], Resource: pulumi.interpolate`arn:aws:lambda:${this.awsRegion}:${this.callerIdentityOutput.accountId}:function:*` } ] } }); } getImportPagesLambdaPolicy({ primaryDynamodbTable, elasticsearchDynamodbTable, bucket, elasticsearchDomain, cognitoUserPool }: { primaryDynamodbTable: aws.dynamodb.Table; elasticsearchDynamodbTable: aws.dynamodb.Table; bucket: aws.s3.Bucket; elasticsearchDomain: EsDomain; cognitoUserPool: aws.cognito.UserPool; }): aws.iam.Policy { return new aws.iam.Policy("ImportPageLambdaPolicy", { description: "This policy enables access to ES, Dynamodb, S3, Lambda and Cognito IDP", policy: { Version: "2012-10-17", Statement: [ { Sid: "PermissionForDynamodb", Effect: "Allow", Action: [ "dynamodb:BatchGetItem", "dynamodb:BatchWriteItem", "dynamodb:PutItem", "dynamodb:DeleteItem", "dynamodb:GetItem", "dynamodb:Query", "dynamodb:UpdateItem" ], Resource: [ pulumi.interpolate`${primaryDynamodbTable.arn}`, pulumi.interpolate`${primaryDynamodbTable.arn}/*`, pulumi.interpolate`${elasticsearchDynamodbTable.arn}`, pulumi.interpolate`${elasticsearchDynamodbTable.arn}/*` ] }, { Sid: "PermissionForS3", Effect: "Allow", Action: [ "s3:GetObjectAcl", "s3:DeleteObject", "s3:PutObjectAcl", "s3:PutObject", "s3:GetObject", "s3:ListBucket" ], Resource: [ pulumi.interpolate`arn:aws:s3:::${bucket.id}/*`, // We need to explicitly add bucket ARN to "Resource" list for "s3:ListBucket" action. pulumi.interpolate`arn:aws:s3:::${bucket.id}` ] }, { Sid: "PermissionForLambda", Effect: "Allow", Action: ["lambda:InvokeFunction"], Resource: pulumi.interpolate`arn:aws:lambda:${this.awsRegion}:${this.callerIdentityOutput.accountId}:function:*` }, { Sid: "PermissionForCognitoIdp", Effect: "Allow", Action: "cognito-idp:*", Resource: pulumi.interpolate`${cognitoUserPool.arn}` }, { Sid: "PermissionForES", Effect: "Allow", Action: "es:*", Resource: [ pulumi.interpolate`${elasticsearchDomain.arn}`, pulumi.interpolate`${elasticsearchDomain.arn}/*` ] } ] } }); } getPbUpdateSettingsLambdaPolicy(primaryDynamodbTable: aws.dynamodb.Table): aws.iam.Policy { return new aws.iam.Policy("PbUpdateSettingsLambdaPolicy", { description: "This policy enables access to Dynamodb", policy: { Version: "2012-10-17", Statement: [ { Sid: "AllowDynamoDBAccess", Effect: "Allow", Action: [ "dynamodb:BatchGetItem", "dynamodb:BatchWriteItem", "dynamodb:PutItem", "dynamodb:DeleteItem", "dynamodb:GetItem", "dynamodb:Query", "dynamodb:UpdateItem" ], Resource: [ pulumi.interpolate`${primaryDynamodbTable.arn}`, pulumi.interpolate`${primaryDynamodbTable.arn}/*` ] } ] } }); } getApiGraphqlLambdaPolicy({ primaryDynamodbTable, elasticsearchDynamodbTable, bucket, elasticsearchDomain, cognitoUserPool }: { primaryDynamodbTable: aws.dynamodb.Table; elasticsearchDynamodbTable: aws.dynamodb.Table; bucket: aws.s3.Bucket; elasticsearchDomain: EsDomain; cognitoUserPool: aws.cognito.UserPool; }): aws.iam.Policy { return new aws.iam.Policy("ApiGraphqlLambdaPolicy", { description: "This policy enables access to ES, Dynamodb, S3, Lambda and Cognito IDP", policy: { Version: "2012-10-17", Statement: [ { Sid: "PermissionForDynamodb", Effect: "Allow", Action: [ "dynamodb:BatchGetItem", "dynamodb:BatchWriteItem", "dynamodb:ConditionCheckItem", "dynamodb:CreateBackup", "dynamodb:CreateTable", "dynamodb:CreateTableReplica", "dynamodb:DeleteBackup", "dynamodb:DeleteItem", "dynamodb:DeleteTable", "dynamodb:DeleteTableReplica", "dynamodb:DescribeBackup", "dynamodb:DescribeContinuousBackups", "dynamodb:DescribeContributorInsights", "dynamodb:DescribeExport", "dynamodb:DescribeKinesisStreamingDestination", "dynamodb:DescribeLimits", "dynamodb:DescribeReservedCapacity", "dynamodb:DescribeReservedCapacityOfferings", "dynamodb:DescribeStream", "dynamodb:DescribeTable", "dynamodb:DescribeTableReplicaAutoScaling", "dynamodb:DescribeTimeToLive", "dynamodb:DisableKinesisStreamingDestination", "dynamodb:EnableKinesisStreamingDestination", "dynamodb:ExportTableToPointInTime", "dynamodb:GetItem", "dynamodb:GetRecords", "dynamodb:GetShardIterator", "dynamodb:ListBackups", "dynamodb:ListContributorInsights", "dynamodb:ListExports", "dynamodb:ListStreams", "dynamodb:ListTables", "dynamodb:ListTagsOfResource", "dynamodb:PartiQLDelete", "dynamodb:PartiQLInsert", "dynamodb:PartiQLSelect", "dynamodb:PartiQLUpdate", "dynamodb:PurchaseReservedCapacityOfferings", "dynamodb:PutItem", "dynamodb:Query", "dynamodb:RestoreTableFromBackup", "dynamodb:RestoreTableToPointInTime", "dynamodb:Scan", "dynamodb:UpdateContinuousBackups", "dynamodb:UpdateContributorInsights", "dynamodb:UpdateItem", "dynamodb:UpdateTable", "dynamodb:UpdateTableReplicaAutoScaling", "dynamodb:UpdateTimeToLive" ], Resource: [ pulumi.interpolate`${primaryDynamodbTable.arn}`, pulumi.interpolate`${primaryDynamodbTable.arn}/*`, pulumi.interpolate`${elasticsearchDynamodbTable.arn}`, pulumi.interpolate`${elasticsearchDynamodbTable.arn}/*` ] }, { Sid: "PermissionForS3", Effect: "Allow", Action: [ "s3:GetObjectAcl", "s3:DeleteObject", "s3:PutObjectAcl", "s3:PutObject", "s3:GetObject" ], Resource: pulumi.interpolate`arn:aws:s3:::${bucket.id}/*` }, { Sid: "PermissionForLambda", Effect: "Allow", Action: ["lambda:InvokeFunction"], Resource: pulumi.interpolate`arn:aws:lambda:${this.awsRegion}:${this.callerIdentityOutput.accountId}:function:*` }, { Sid: "PermissionForCognitoIdp", Effect: "Allow", Action: "cognito-idp:*", Resource: pulumi.interpolate`${cognitoUserPool.arn}` }, { Sid: "PermissionForES", Effect: "Allow", Action: "es:*", Resource: [ pulumi.interpolate`${elasticsearchDomain.arn}`, pulumi.interpolate`${elasticsearchDomain.arn}/*` ] } ] } }); } getHeadlessCmsLambdaPolicy({ primaryDynamodbTable, elasticsearchDynamodbTable, elasticsearchDomain }: { primaryDynamodbTable: aws.dynamodb.Table; elasticsearchDynamodbTable: aws.dynamodb.Table; elasticsearchDomain: EsDomain; }): aws.iam.Policy { return new aws.iam.Policy("HeadlessCmsLambdaPolicy", { description: "This policy enables access to ES and Dynamodb streams", policy: { Version: "2012-10-17", Statement: [ { Sid: "PermissionDynamodb", Effect: "Allow", Action: [ "dynamodb:BatchGetItem", "dynamodb:BatchWriteItem", "dynamodb:ConditionCheckItem", "dynamodb:CreateBackup", "dynamodb:CreateTable", "dynamodb:CreateTableReplica", "dynamodb:DeleteBackup", "dynamodb:DeleteItem", "dynamodb:DeleteTable", "dynamodb:DeleteTableReplica", "dynamodb:DescribeBackup", "dynamodb:DescribeContinuousBackups", "dynamodb:DescribeContributorInsights", "dynamodb:DescribeExport", "dynamodb:DescribeKinesisStreamingDestination", "dynamodb:DescribeLimits", "dynamodb:DescribeReservedCapacity", "dynamodb:DescribeReservedCapacityOfferings", "dynamodb:DescribeStream", "dynamodb:DescribeTable", "dynamodb:DescribeTableReplicaAutoScaling", "dynamodb:DescribeTimeToLive", "dynamodb:DisableKinesisStreamingDestination", "dynamodb:EnableKinesisStreamingDestination", "dynamodb:ExportTableToPointInTime", "dynamodb:GetItem", "dynamodb:GetRecords", "dynamodb:GetShardIterator", "dynamodb:ListBackups", "dynamodb:ListContributorInsights", "dynamodb:ListExports", "dynamodb:ListStreams", "dynamodb:ListTables", "dynamodb:ListTagsOfResource", "dynamodb:PartiQLDelete", "dynamodb:PartiQLInsert", "dynamodb:PartiQLSelect", "dynamodb:PartiQLUpdate", "dynamodb:PurchaseReservedCapacityOfferings", "dynamodb:PutItem", "dynamodb:Query", "dynamodb:RestoreTableFromBackup", "dynamodb:RestoreTableToPointInTime", "dynamodb:Scan", "dynamodb:UpdateContinuousBackups", "dynamodb:UpdateContributorInsights", "dynamodb:UpdateItem", "dynamodb:UpdateTable", "dynamodb:UpdateTableReplicaAutoScaling", "dynamodb:UpdateTimeToLive" ], Resource: [ pulumi.interpolate`${primaryDynamodbTable.arn}`, pulumi.interpolate`${primaryDynamodbTable.arn}/*`, pulumi.interpolate`${elasticsearchDynamodbTable.arn}`, pulumi.interpolate`${elasticsearchDynamodbTable.arn}/*` ] }, { Sid: "PermissionForES", Effect: "Allow", Action: "es:*", Resource: [ pulumi.interpolate`${elasticsearchDomain.arn}`, pulumi.interpolate`${elasticsearchDomain.arn}/*` ] } ] } }); } } const policies = new Policies(); export default policies;
the_stack
import { BaseHandler, clearArray, Disposable, EditString, IDisposable, ImmediateDisposable, MoveArrayValue, NoUpdate, ObjectStateHandler, OptionalStateView, setValue, StateHandler, StateView, UpdatePartial, UpdateResult, } from "."; import {ClientResult, CompileErrors, Output, PosRange, ResultValue, RuntimeError,} from "../data/result"; import * as messages from "../data/messages"; import { CompletionCandidate, HandleData, KernelStatusString, ModifyStream, NotebookUpdate, Signatures, TaskInfo, TaskStatus } from "../data/messages"; import {CellComment, CellMetadata, NotebookCell, NotebookConfig} from "../data/data"; import {ContentEdit, diffEdits} from "../data/content_edit"; import {EditBuffer} from "../data/edit_buffer"; import {deepEquals, Deferred} from "../util/helpers"; import {notReceiver} from "../messaging/receiver"; import {ConstView, ProxyStateView} from "./state_handler"; import {ServerStateHandler} from "./server_state"; export type CellPresenceState = {id: number, name: string, color: string, range: PosRange, avatar?: string}; export interface CellState { id: number, language: string, content: string, metadata: CellMetadata, comments: Record<string, CellComment>, output: Output[], results: (ResultValue | ClientResult)[], compileErrors: CompileErrors[], runtimeError: RuntimeError | undefined, // ephemeral states presence: Record<number, CellPresenceState>; editing: boolean, error: boolean, running: boolean queued: boolean, currentSelection: PosRange | undefined, currentHighlight: { range: PosRange, className: string} | undefined } export type CompletionHint = { cell: number, offset: number; completions: CompletionCandidate[] } export type SignatureHint = { cell: number, offset: number, signatures?: Signatures }; export type NBConfig = {open: boolean, config: NotebookConfig} export type KernelSymbols = Record<string, Record<string, ResultValue>>; export type KernelInfo = Record<string, string>; export type KernelTasks = Record<string, TaskInfo>; // taskId -> TaskInfo export interface KernelState { symbols: KernelSymbols, status: KernelStatusString, info: KernelInfo, tasks: KernelTasks } export type PresenceState = { id: number, name: string, color: string, avatar?: string, selection?: { cellId: number, range: PosRange}}; export interface NotebookState { // basic states path: string, cells: Record<number, CellState>, // cellId -> state cellOrder: number[], // this is the canonical ordering of the cells. config: NBConfig, kernel: KernelState, // ephemeral states activeCellId: number | undefined, activeCompletion: { cellId: number, offset: number, resolve: (completion: CompletionHint) => void, reject: () => void } | undefined, activeSignature: { cellId: number, offset: number, resolve: (signature: SignatureHint) => void, reject: () => void } | undefined, activePresence: Record<number, PresenceState>, // map of handle ID to message received. activeStreams: Record<number, (HandleData | ModifyStream)[]>, } export class NotebookStateHandler extends BaseHandler<NotebookState> { readonly loaded: Promise<void>; private lazyActiveCellView?: StateView<CellState | undefined>; constructor( parent: StateHandler<NotebookState>, readonly cellsHandler: StateHandler<Record<number, CellState>>, readonly updateHandler: NotebookUpdateHandler, readonly _loaded?: Promise<void> ) { super(parent); if (_loaded === undefined) { if (this.isLoading) { const tasksView = this.view('kernel').view('tasks'); this.loaded = new Promise<void>(resolve => { const obs = tasksView.addObserver((current, prev) => { if (!current[this.state.path] || current[this.state.path].status === TaskStatus.Complete) { obs.dispose(); resolve() } }); }) } else { this.loaded = Promise.resolve() } } else { this.loaded = _loaded; } this.loaded.then(_ => this.updateHandler.localVersion = 0) } /** * A (lazily-created) view which gives update on whatever the focused cell is (if a cell is focused) */ get activeCellView(): OptionalStateView<CellState> { if (!this.lazyActiveCellView) { const noActiveState: StateView<CellState | undefined> = new ConstView(undefined); let currentState = this.state.activeCellId !== undefined ? this.cellsHandler.view(this.state.activeCellId) : noActiveState; const view = new ProxyStateView(currentState); this.lazyActiveCellView = view; this.observeKey("activeCellId", activeCellId => { if (activeCellId !== undefined && (!view.state || view.state.id !== activeCellId)) { if (currentState !== noActiveState) { currentState.dispose(); } currentState = this.cellsHandler.view(activeCellId); view.setParent(currentState); } else if (activeCellId === undefined && view.state) { if (currentState !== noActiveState) { currentState.dispose(); } currentState = noActiveState; view.setParent(noActiveState); } }); } return this.lazyActiveCellView; } static forPath(path: string) { const baseHandler = new ObjectStateHandler<NotebookState>({ path, cells: {}, cellOrder: [], config: {open: false, config: NotebookConfig.default}, kernel: { symbols: {}, status: 'disconnected', info: {}, tasks: {}, }, activePresence: {}, activeCellId: undefined, activeCompletion: undefined, activeSignature: undefined, activeStreams: {}, }); const cellsHandler = baseHandler.lens("cells"); const updateHandler = new NotebookUpdateHandler(baseHandler, cellsHandler, 0, 0, new EditBuffer()) const handler = new NotebookStateHandler(baseHandler, cellsHandler, updateHandler); cellsHandler.disposeWith(handler); updateHandler.disposeWith(handler); return handler; } protected compare(s1: any, s2: any): boolean { return deepEquals(s1, s2) } availableValuesAt(id: number): Record<string, ResultValue> { return availableResultValues(this.state.kernel.symbols, this.state.cellOrder, id); } getCellIndex(cellId: number, cellOrder: number[] = this.state.cellOrder): number | undefined { return cellOrder.indexOf(cellId) } getCellIdAtIndex(cellIdx: number): number | undefined { return this.state.cellOrder[cellIdx] } getPreviousCellId(anchorId: number, cellOrder: number[] = this.state.cellOrder): number | undefined { const anchorIdx = this.getCellIndex(anchorId, cellOrder) return anchorIdx !== undefined ? cellOrder[anchorIdx - 1] : undefined } getNextCellId(anchorId: number, cellOrder: number[] = this.state.cellOrder): number | undefined { const anchorIdx = this.getCellIndex(anchorId, cellOrder) return anchorIdx !== undefined ? cellOrder[anchorIdx + 1] : undefined } /** * Change the currently selected cell. * * @param selected The ID of the cell to select OR the ID of the anchor cell for `relative`. If `undefined`, deselects cells. * @param options Options, consisting of: * relative If set, select the cell either above or below the one with ID specified by `selected` * skipHiddenCode If set alongside a relative cell selection, cells with hidden code blocks should be skipped. * editing If set, indicate that the cell is editing in addition to being selected. * @return The ID of the cell that was selected, possibly undefined if nothing was selected. */ selectCell(selected: number | undefined, options?: { relative?: "above" | "below", skipHiddenCode?: boolean, editing?: boolean}): number | undefined { let id = selected; this.update(state => { if (id !== undefined) { const anchorIdx = state.cellOrder.indexOf(id) if (options?.relative === "above") { let prevIdx = anchorIdx - 1; id = state.cellOrder[prevIdx]; if (options?.skipHiddenCode) { while (prevIdx > -1 && state.cells[id]?.metadata.hideSource) { --prevIdx; id = state.cellOrder[prevIdx]; } } } else if (options?.relative === "below") { let nextIdx = anchorIdx + 1 id = state.cellOrder[nextIdx]; if (options?.skipHiddenCode) { while (nextIdx < state.cellOrder.length && state.cells[id]?.metadata.hideSource) { ++nextIdx; id = state.cellOrder[nextIdx]; } } } } id = id ?? (selected === -1 ? 0 : selected); // if "above" or "below" don't exist, just select `selected`. const prev = state.activeCellId; const update: UpdatePartial<NotebookState> = { activeCellId: id, cells: id === undefined ? {} : { [id]: { editing: options?.editing ?? false }, ...((prev === undefined && prev !== id) ? {} : {[prev]: {editing: false}}) } }; return update; }) return id } /** * Helper for inserting a cell. * * @param direction Whether to insert below of above the anchor * @param anchor The anchor. If it is undefined, the anchor is based on the currently selected cell. If none is * selected, the anchor is either the first or last cell (depending on the direction supplied). * The anchor is used to determine the location, language, and metadata to supply to the new cell. * @return A Promise that resolves with the inserted cell's id. */ insertCell(direction: 'above' | 'below', anchor?: {id: number, language: string, metadata: CellMetadata, content?: string}): Promise<number> { const state = this.state; let currentCellId = state.activeCellId; if (anchor === undefined) { if (currentCellId === undefined) { if (direction === 'above') { currentCellId = state.cellOrder[0]; } else { currentCellId = state.cellOrder[state.cellOrder.length - 1]; } } const currentCell = state.cells[currentCellId]; anchor = {id: currentCellId, language: (currentCell?.language === undefined || currentCell?.language === 'viz') ? 'scala' : currentCell.language, metadata: currentCell?.metadata ?? new CellMetadata()}; } const anchorIdx = this.getCellIndex(anchor.id)!; const prevIdx = direction === 'above' ? anchorIdx - 1 : anchorIdx; const maybePrevId = state.cellOrder[prevIdx] ?? -1; // generate the max ID here. Note that there is a possible race condition if another client is inserting a cell at the same time. const maxId = state.cellOrder.reduce((acc, cellId) => acc > cellId ? acc : cellId, -1) const cellTemplate = {id: maxId + 1, language: anchor.language, content: anchor.content ?? '', metadata: anchor.metadata, prev: maybePrevId} // trigger the insert return this.updateHandler.insertCell(maxId + 1, anchor.language, anchor.content ?? '', anchor.metadata, maybePrevId).then( insert => insert.cell.id ) } /** * Helper for inserting an inspection cell * @param result * @param viewType */ insertInspectionCell(result: ResultValue, viewType?: string) { this.insertCell("below", { id: result.sourceCell, language: 'viz', metadata: new CellMetadata(false, false, false), content: JSON.stringify({type: viewType, value: result.name}) }).then(id => this.selectCell(id)) } deleteCell(id?: number, selectPrevCell: boolean = true): Promise<number | undefined> { if (id === undefined) { id = this.state.activeCellId; } if (id !== undefined) { const waitForDelete = new Promise<number>(resolve => { const cellOrder = this.view("cellOrder") const obs = cellOrder.addObserver(order => { if (! order.includes(id!)) { resolve(id!); obs.dispose(); } }).disposeWith(this) }) if (selectPrevCell) { const nextId = this.getNextCellId(id) ?? this.getPreviousCellId(id) waitForDelete.then(deletedId => { if (deletedId !== undefined && nextId !== undefined) { this.selectCell(nextId) } }) } this.updateHandler.deleteCell(id); return waitForDelete } else return Promise.resolve(undefined) } setCellLanguage(id: number, language: string, source?: any) { const cell = this.cellsHandler.state[id]; this.cellsHandler.updateField(id, () => ({ language, // clear a bunch of stuff if we're changing to text... hm, maybe we need to do something else when it's a a text cell... output: language === "text" ? clearArray() : NoUpdate, results: language === "text" ? clearArray() : NoUpdate, error: language === "text" ? false : NoUpdate, compileErrors: language === "text" ? clearArray() : NoUpdate, runtimeError: language === "text" ? setValue(undefined) : NoUpdate, }), source) } // wait for cell to transition to a specific state waitForCellChange(id: number, targetState: "queued" | "running" | "error"): Promise<void> { return new Promise<void>(resolve => { const obs = this.addObserver(state => { const maybeChanged = state.cells[id]; if (maybeChanged && maybeChanged[targetState]) { obs.dispose(); resolve(); } }).disposeWith(this) }) } get isLoading(): boolean { const nbLoaded = ServerStateHandler.getNotebook(this.state.path)?.loaded return nbLoaded === undefined || !nbLoaded || !!(this.state.kernel.tasks[this.state.path] ?? false) } fork(disposeContext?: IDisposable): NotebookStateHandler { const fork = new NotebookStateHandler( this.parent.fork(disposeContext).disposeWith(this), this.cellsHandler.fork(disposeContext).disposeWith(this), this.updateHandler, this.loaded ).disposeWith(this); return disposeContext ? fork.disposeWith(disposeContext) : fork; } } /** * Handles Notebook Updates. * * Keeps track of `globalVersion`, `localVersion` and the Edit Buffer, making sure they are updated when necessary. * * Watches the state of this notebook's cells, translating their state changes into NotebookUpdates which are then * observed by the dispatcher and sent to the server. * * TODO: can this be refactored so it's not a "broadcaster"? The dependencies seem backwards; shouldn't this just * talk directly to the server message dispatcher rather than the dispatcher listening to this? */ export class NotebookUpdateHandler extends Disposable { // extends ObjectStateHandler<NotebookUpdate[]>{ cellWatchers: Record<number, StateView<CellState>> = {}; private observers: ((update: NotebookUpdate, rep?: Deferred<NotebookUpdate>) => void)[] = []; constructor( state: StateView<NotebookState>, cellsHandler: StateView<Record<number, CellState>>, public globalVersion: number, public localVersion: number, public edits: EditBuffer ) { super() state.view("config").view("config", notReceiver) .addObserver(config => this.updateConfig(config)) state.view("cellOrder", notReceiver).addObserver((order, updateResult) => { if (updateResult.update instanceof MoveArrayValue) { const movedCell = updateResult.update.movedValue; const myIndex = updateResult.update.toIndex; const prev = order[myIndex - 1] ?? -1; this.moveCell(movedCell, prev); } }) state.view("cellOrder").addObserver((newOrder, update) => { for (const id of Object.values(update.addedValues ?? {})) { this.watchCell( id!, cellsHandler.view(id!).filterSource(notReceiver).disposeWith(this) ); } for (const id of Object.values(update.removedValues ?? {})) { if (id !== undefined && this.cellWatchers[id]) { this.cellWatchers[id].tryDispose(); delete this.cellWatchers[id]; } } }) this.onDispose.then(() => this.observers.splice(0, this.observers.length)) } addUpdate(update: NotebookUpdate, rep?: Deferred<NotebookUpdate>) { if (update.localVersion !== this.localVersion) { throw new Error(`Update Version mismatch! Update had ${update.localVersion}, but I had ${this.localVersion}`) } this.edits = this.edits.push(update.localVersion, update); this.observers.forEach(obs => obs(update, rep)); } requestUpdate<T extends NotebookUpdate>(update: T): Promise<T> { const rep = new Deferred<T>() this.addUpdate(update, rep); return rep; } insertCell(cellId: number, language: string, content: string, metadata: CellMetadata, prevId: number) { this.localVersion++; const cell = new NotebookCell(cellId, language, content, [], metadata); const update = new messages.InsertCell(this.globalVersion, this.localVersion, cell, prevId); return this.requestUpdate(update) } deleteCell(id: number) { this.localVersion++; const update = new messages.DeleteCell(this.globalVersion, this.localVersion, id) return this.requestUpdate(update) } moveCell(id: number, after: number) { this.localVersion++; const update = new messages.MoveCell(this.globalVersion, this.localVersion, id, after); this.addUpdate(update); } updateCell(id: number, changed: {edits?: ContentEdit[], metadata?: CellMetadata}) { this.localVersion++; const update = new messages.UpdateCell(this.globalVersion, this.localVersion, id, changed.edits ?? [], changed.metadata) this.addUpdate(update) } createComment(cellId: number, comment: CellComment): void { this.addUpdate(new messages.CreateComment(this.globalVersion, this.localVersion, cellId, comment)); } deleteComment(cellId: number, commentId: string): void { this.addUpdate(new messages.DeleteComment(this.globalVersion, this.localVersion, cellId, commentId)); } updateComment(cellId: number, commentId: string, range: PosRange, content: string): void { this.addUpdate(new messages.UpdateComment(this.globalVersion, this.localVersion, cellId, commentId, range, content)); } setCellOutput(cellId: number, output: Output) { this.addUpdate(new messages.SetCellOutput(this.globalVersion, this.localVersion, cellId, output)) } updateConfig(config: NotebookConfig) { this.localVersion++; const update = new messages.UpdateConfig(this.globalVersion, this.localVersion, config); this.addUpdate(update); } rebaseUpdate(update: NotebookUpdate) { this.globalVersion = update.globalVersion if (update.localVersion < this.localVersion) { update = this.edits.rebaseThrough(update, this.localVersion); // discard edits before the local version from server – it will handle rebasing at least until that point this.edits = this.edits.discard(update.localVersion) } return update } private watchCell(id: number, handler: StateView<CellState>) { this.cellWatchers[id] = handler handler.view("output").addObserver((newOutput, updateResult) => { Object.values(updateResult.addedValues ?? {}).forEach(o => { this.setCellOutput(id, o) }) }).disposeWith(this) handler.view("results", notReceiver).addObserver((newResults) => { if (newResults[0] && newResults[0] instanceof ClientResult) { newResults[0].toOutput().then( o => this.addUpdate(new messages.SetCellOutput(this.globalVersion, this.localVersion, id, o)) ) } }).disposeWith(this) handler.view("language").addObserver(lang => { this.addUpdate(new messages.SetCellLanguage(this.globalVersion, this.localVersion, id, lang)) }).disposeWith(this) handler.view("content").addObserver((content, updateResult) => { if (updateResult.update instanceof EditString) { this.updateCell(id, {edits: updateResult.update.edits}) } else if (updateResult.oldValue !== undefined) { this.updateCell(id, {edits: diffEdits(updateResult.oldValue, content)}) } else { // the only updates possible should be EditString or SetValue, so this is a defect console.error("Unexpected update to cell content", updateResult) throw new Error("Unexpected update to cell content") } }).disposeWith(this) handler.view("metadata").addObserver(metadata => { this.updateCell(id, {metadata}) }).disposeWith(this) const existingComments: Set<string> = new Set(Object.keys(handler.state.comments)) handler.view("comments").addObserver((current, updateResult) => { UpdateResult.addedOrChangedKeys(updateResult).forEach(commentId => { if (existingComments.has(commentId)) { const currentComment = current[commentId]; this.updateComment(id, commentId, currentComment.range, currentComment.content) } else { existingComments.add(commentId); this.createComment(id, current[commentId]); } }) Object.keys(updateResult.removedValues ?? {}).forEach(commentId => this.deleteComment(id, commentId)) }).disposeWith(this) } addObserver(fn: (update: NotebookUpdate, rep?: Deferred<NotebookUpdate>) => void): IDisposable { this.observers.push(fn); return new ImmediateDisposable(() => { const idx = this.observers.indexOf(fn); if (idx >= 0) { this.observers.splice(idx, 1); } }) } protected compare(s1: any, s2: any): boolean { return deepEquals(s1, s2); } } /** * Helper function for extracting the result values available to a particular cell from the symbols available in the * kernel */ export function availableResultValues(symbols: KernelSymbols, cellOrder: number[], id?: number): Record<string, ResultValue> { const availableCells = Object.keys(symbols); // first, make sure to add any predef cells (they don't appear in cellOrder) const cellsInScope = availableCells.filter(id => id.startsWith('-')); const cellIdx = id !== undefined ? cellOrder.indexOf(id) : cellOrder.length - 1; if (cellIdx >= 0) { cellsInScope.push(...cellOrder.slice(0, cellIdx).map(id => id.toString())); } return cellsInScope.reduce<Record<string, ResultValue>>((acc, next) => { Object.values(symbols[next] || {}) .forEach((result: ResultValue) => acc[result.name] = result); return acc; }, {}); }
the_stack
import app, { Component } from '../src/apprun'; app.on('hi', _ => { }) app.on('debug', _ => { }); class TestComponent extends Component { state = 'x'; view = (state) => state update = { 'hi': (state, value) => value, '#hi': (state, value) => value, 'hiNull': (state, value) => null, 'hiAsync': async (state, value) => { return new Promise(resolve => { resolve(value); }) }, 'hiAsyncNull': async (state, value) => { }, 'hi-global': [(state, value) => value, { global: true}] } rendered = () => { } } describe('Component', () => { let component; beforeEach(() => { component = new TestComponent(); }); it('should allow element to be undefined', () => { spyOn(component, 'view'); expect(component.element).toBeUndefined() expect(component.view).not.toHaveBeenCalled(); }) it('should trigger view when mounted with render option', () => { spyOn(component, 'view'); component.mount(document.body, { render: true }); expect(component.element).toBe(document.body); expect(component.view).toHaveBeenCalled(); }) it('should not trigger view when mounted', () => { spyOn(component, 'view'); component.mount(document.body); expect(component.element).toBe(document.body); expect(component.view).not.toHaveBeenCalled(); }) it('should trigger view when started', () => { spyOn(component, 'view'); component.start(document.body); expect(component.element).toBe(document.body); expect(component.view).toHaveBeenCalled(); }) it('should not trigger when update returns null or undefined', () => { component.mount(document.body); spyOn(component, 'view'); component.run('hi', null); expect(component.view).not.toHaveBeenCalled(); component.run('hiNull'); expect(component.view).not.toHaveBeenCalled(); }) it('should not trigger view when update returns null or undefined with async', () => { component.mount(document.body); spyOn(component, 'view'); component.run('hiAsync', null); expect(component.view).not.toHaveBeenCalledWith(); //Promise expect(component.state).not.toBeNull(); component.run('hiAsyncNull'); expect(component.view).not.toHaveBeenCalledWith(); //Promise expect(component.state).not.toBeNull(); }) it('should handle local events', () => { component.mount(document.body); spyOn(component, 'view'); component.run('hi', ''); expect(component.view).toHaveBeenCalled(); }) it('should not handle unknown global events', () => { component.mount(document.body); spyOn(component, 'view'); app.run('hi'); expect(component.view).not.toHaveBeenCalled(); }) it('should handle global events', () => { component.mount(document.body); spyOn(component, 'view'); app.run('#hi', ''); expect(component.view).toHaveBeenCalled(); }) it('should handle individual global event', () => { component.mount(document.body); spyOn(component, 'view'); app.run('hi-global', ''); expect(component.view).toHaveBeenCalled(); }) it('should track history', () => { component.start(document.body, { history: true }); expect(component.state).toBe('x'); component.run('hi', 'xx'); expect(component.state).toBe('xx'); component.run('hi', 'xxx'); expect(component.state).toBe('xxx'); component.run('history-prev'); expect(component.state).toBe('xx'); component.run('history-next'); expect(component.state).toBe('xxx'); }); it('should track history with custom event name', () => { component.start(document.body, { history: { prev: 'prev', next: 'next' } }); expect(component.state).toBe('x'); component.run('hi', 'xx'); expect(component.state).toBe('xx'); component.run('hi', 'xxx'); expect(component.state).toBe('xxx'); component.run('prev'); expect(component.state).toBe('xx'); component.run('next'); expect(component.state).toBe('xxx'); }); it('should track history with global custom event name', () => { spyOn(component, 'view'); component.mount(document.body, { render: true, history: { prev: 'prev', next: 'next' }, global_event: true }); expect(component.state).toBe('x'); app.run('hi', 'xx'); expect(component.state).toBe('xx'); app.run('hi', 'xxx'); expect(component.state).toBe('xxx'); app.run('prev'); expect(component.state).toBe('xx'); app.run('next'); expect(component.state).toBe('xxx'); }); it('should call rendered function', () => { const spy = jasmine.createSpy('spy'); component.rendered = state => spy(state); component.start(document.body); expect(spy).toHaveBeenCalledWith('x'); component.run('hi', 'abc'); expect(spy).toHaveBeenCalledWith('abc'); }); it('should handle async update', (done) => { const fn = async () => new Promise((resolve, reject) => { window.setTimeout(() => { resolve('xx'); }, 10); }); const spy = jasmine.createSpy('spy'); class Test extends Component { state = -1; view = state => spy(state); update = { method1: async (...args) => { const v = await fn(); return v; } } } const t = new Test().start(); t.run('method1') window.setTimeout(() => { const callArgs = spy.calls.allArgs(); expect(callArgs[0][0]).toBe(-1); expect(callArgs[1][0]).toBe('xx'); done() }, 20); }); it('should support tuple in update', () => { let i = 0; class Test extends Component { state = -1; update = { 'method1': [_ => i++, { once: true }], } } const t = new Test().start(); t.run('method1'); // t.run('method1'); // t.run('method1'); expect(i).toEqual(1); }); it('should support async tuple in update', (done) => { let i = 0; const fn = async () => new Promise<string>((resolve) => { window.setTimeout(() => { resolve('xx'); }, 10); }); class Test extends Component { state = -1; update = { 'method1': [async _ => { const t = await fn(); i++ }, { once: true }], } } const t = new Test().start(); t.run('method1'); // t.run('method1'); // t.run('method1'); window.setTimeout(() => { expect(i).toBe(1); done(); }, 20) }); it('should support update alias', () => { let i = 0; class Test extends Component { state = -1; update = { 'method1, m1, m2, #m3': [_ => ++i, {}] } } const t = new Test().start(); t.run('method1'); t.run('m1'); t.run('m2'); app.run('#m3'); expect(i).toBe(4); }); it('should support call back', () => { let i = 0; class Test extends Component { state = -1; update = { 'method1': [_ => ++i, { callback: _ => ++i }] } } const t = new Test().start(); t.run('method1'); expect(i).toBe(2); }); it('should support options', () => { class Test extends Component { view = (state) => state update = { 'method1': [(state, val) => val, { render: false }] } } const t = new Test(); t.start(document.body); spyOn(t, 'view'); t.run('method1', 'x'); expect(t.view).not.toHaveBeenCalled(); }) it('should support call back, alias and options', () => { let i = 0; class Test extends Component { state = -1; update = { 'method1, m1, m2, #m3': [_ => ++i, { callback: _ => ++i }] } } const t = new Test().start(); t.run('method1'); t.run('m1'); t.run('m2'); app.run('#m3'); expect(i).toBe(8); }); it('should save/attach component to element', () => { component.start(document.body); expect(document.body['_component']).toBe(component); }) it('should clean up the element children', () => { class Test extends Component { view = () => <img src="a"/> } const div = document.createElement('div'); const img1 = document.createElement('img'); const img2 = document.createElement('img'); div.appendChild(img1); div.appendChild(img2); const t = new Test().start(div); expect(div.children.length).toBe(1); }); // it('should call destroy when component is replaced', () => { //// Jest does not support MutationObserver, run the following in browser console in V2 branch (ES6) // class Test extends Component { // view = () => { } // unload = () => console.log('destroy'); // } // const div = document.createElement('div'); // const t = new Test().start(div); // div.setAttribute('_c', null); // const e = document.querySelector('#my-app'); // e.parentNode.removeChild(e) // }); it('should add the . event by default', () => { class Test extends Component { state = 'a' view = state => <div>{state}</div> } const div = document.createElement('div'); const t = new Test().mount(div); t.run('.'); expect(div.innerHTML).toBe('<div>a</div>'); }) it('should route in mount option', () => { class Test extends Component { state = 'ab' view = state => <div>{state}</div> } const div = document.createElement('div'); const t = new Test().mount(div, {route: '#test'}); app.run('#test'); expect(div.innerHTML).toBe('<div>ab</div>'); }) it('should allow initial state as a function', () => { class Test extends Component { state = () => 'abc' view = state => <div>{state}</div> } const div = document.createElement('div'); const t = new Test().start(div); expect(div.innerHTML).toBe('<div>abc</div>'); }) it('should allow initial state as an async function', (done) => { class Test extends Component { state = async () => new Promise(resolve => setTimeout(() => resolve(100))); view = state => <div>{state}</div> } const div = document.createElement('div'); const t = new Test().start(div); setTimeout(() => { expect(div.innerHTML).toBe('<div>100</div>'); done(); }); }) it('should wait existing promise state to be resolve', (done) => { class Test extends Component { state = async () => new Promise(resolve => setTimeout(() => resolve('old'), 150)); view = state => <div>{state}</div> } const div = document.createElement('div'); const t = new Test().start(div); t.setState(new Promise(resolve => setTimeout(() => resolve('new'), 50))); setTimeout(() => { expect(div.innerHTML).toBe('<div>new</div>'); done(); }, 200); }) });
the_stack
import * as coreClient from "@azure/core-client"; import * as coreAuth from "@azure/core-auth"; import { PollerLike, PollOperationState, LroEngine } from "@azure/core-lro"; import { LroImpl } from "./lroImpl"; import { ServersImpl, ReplicasImpl, FirewallRulesImpl, VirtualNetworkRulesImpl, DatabasesImpl, ConfigurationsImpl, ServerParametersImpl, LogFilesImpl, ServerAdministratorsImpl, RecoverableServersImpl, ServerBasedPerformanceTierImpl, LocationBasedPerformanceTierImpl, CheckNameAvailabilityImpl, OperationsImpl, ServerSecurityAlertPoliciesImpl, QueryTextsImpl, TopQueryStatisticsImpl, WaitStatisticsImpl, AdvisorsImpl, RecommendedActionsImpl, LocationBasedRecommendedActionSessionsOperationStatusImpl, LocationBasedRecommendedActionSessionsResultImpl, PrivateEndpointConnectionsImpl, PrivateLinkResourcesImpl, ServerKeysImpl } from "./operations"; import { Servers, Replicas, FirewallRules, VirtualNetworkRules, Databases, Configurations, ServerParameters, LogFiles, ServerAdministrators, RecoverableServers, ServerBasedPerformanceTier, LocationBasedPerformanceTier, CheckNameAvailability, Operations, ServerSecurityAlertPolicies, QueryTexts, TopQueryStatistics, WaitStatistics, Advisors, RecommendedActions, LocationBasedRecommendedActionSessionsOperationStatus, LocationBasedRecommendedActionSessionsResult, PrivateEndpointConnections, PrivateLinkResources, ServerKeys } from "./operationsInterfaces"; import * as Parameters from "./models/parameters"; import * as Mappers from "./models/mappers"; import { MySQLManagementClientOptionalParams, ResetQueryPerformanceInsightDataOptionalParams, ResetQueryPerformanceInsightDataResponse, CreateRecommendedActionSessionOptionalParams } from "./models"; export class MySQLManagementClient extends coreClient.ServiceClient { $host: string; subscriptionId: string; /** * Initializes a new instance of the MySQLManagementClient class. * @param credentials Subscription credentials which uniquely identify client subscription. * @param subscriptionId The ID of the target subscription. * @param options The parameter options */ constructor( credentials: coreAuth.TokenCredential, subscriptionId: string, options?: MySQLManagementClientOptionalParams ) { if (credentials === undefined) { throw new Error("'credentials' cannot be null"); } if (subscriptionId === undefined) { throw new Error("'subscriptionId' cannot be null"); } // Initializing default values for options if (!options) { options = {}; } const defaults: MySQLManagementClientOptionalParams = { requestContentType: "application/json; charset=utf-8", credential: credentials }; const packageDetails = `azsdk-js-arm-mysql/5.0.0`; const userAgentPrefix = options.userAgentOptions && options.userAgentOptions.userAgentPrefix ? `${options.userAgentOptions.userAgentPrefix} ${packageDetails}` : `${packageDetails}`; if (!options.credentialScopes) { options.credentialScopes = ["https://management.azure.com/.default"]; } const optionsWithDefaults = { ...defaults, ...options, userAgentOptions: { userAgentPrefix }, baseUri: options.endpoint || "https://management.azure.com" }; super(optionsWithDefaults); // Parameter assignments this.subscriptionId = subscriptionId; // Assigning values to Constant parameters this.$host = options.$host || "https://management.azure.com"; this.servers = new ServersImpl(this); this.replicas = new ReplicasImpl(this); this.firewallRules = new FirewallRulesImpl(this); this.virtualNetworkRules = new VirtualNetworkRulesImpl(this); this.databases = new DatabasesImpl(this); this.configurations = new ConfigurationsImpl(this); this.serverParameters = new ServerParametersImpl(this); this.logFiles = new LogFilesImpl(this); this.serverAdministrators = new ServerAdministratorsImpl(this); this.recoverableServers = new RecoverableServersImpl(this); this.serverBasedPerformanceTier = new ServerBasedPerformanceTierImpl(this); this.locationBasedPerformanceTier = new LocationBasedPerformanceTierImpl( this ); this.checkNameAvailability = new CheckNameAvailabilityImpl(this); this.operations = new OperationsImpl(this); this.serverSecurityAlertPolicies = new ServerSecurityAlertPoliciesImpl( this ); this.queryTexts = new QueryTextsImpl(this); this.topQueryStatistics = new TopQueryStatisticsImpl(this); this.waitStatistics = new WaitStatisticsImpl(this); this.advisors = new AdvisorsImpl(this); this.recommendedActions = new RecommendedActionsImpl(this); this.locationBasedRecommendedActionSessionsOperationStatus = new LocationBasedRecommendedActionSessionsOperationStatusImpl( this ); this.locationBasedRecommendedActionSessionsResult = new LocationBasedRecommendedActionSessionsResultImpl( this ); this.privateEndpointConnections = new PrivateEndpointConnectionsImpl(this); this.privateLinkResources = new PrivateLinkResourcesImpl(this); this.serverKeys = new ServerKeysImpl(this); } /** * Reset data for Query Performance Insight. * @param resourceGroupName The name of the resource group. The name is case insensitive. * @param serverName The name of the server. * @param options The options parameters. */ resetQueryPerformanceInsightData( resourceGroupName: string, serverName: string, options?: ResetQueryPerformanceInsightDataOptionalParams ): Promise<ResetQueryPerformanceInsightDataResponse> { return this.sendOperationRequest( { resourceGroupName, serverName, options }, resetQueryPerformanceInsightDataOperationSpec ); } /** * Create recommendation action session for the advisor. * @param resourceGroupName The name of the resource group. The name is case insensitive. * @param serverName The name of the server. * @param advisorName The advisor name for recommendation action. * @param databaseName The name of the database. * @param options The options parameters. */ async beginCreateRecommendedActionSession( resourceGroupName: string, serverName: string, advisorName: string, databaseName: string, options?: CreateRecommendedActionSessionOptionalParams ): Promise<PollerLike<PollOperationState<void>, void>> { const directSendOperation = async ( args: coreClient.OperationArguments, spec: coreClient.OperationSpec ): Promise<void> => { return this.sendOperationRequest(args, spec); }; const sendOperation = async ( args: coreClient.OperationArguments, spec: coreClient.OperationSpec ) => { let currentRawResponse: | coreClient.FullOperationResponse | undefined = undefined; const providedCallback = args.options?.onResponse; const callback: coreClient.RawResponseCallback = ( rawResponse: coreClient.FullOperationResponse, flatResponse: unknown ) => { currentRawResponse = rawResponse; providedCallback?.(rawResponse, flatResponse); }; const updatedArgs = { ...args, options: { ...args.options, onResponse: callback } }; const flatResponse = await directSendOperation(updatedArgs, spec); return { flatResponse, rawResponse: { statusCode: currentRawResponse!.status, body: currentRawResponse!.parsedBody, headers: currentRawResponse!.headers.toJSON() } }; }; const lro = new LroImpl( sendOperation, { resourceGroupName, serverName, advisorName, databaseName, options }, createRecommendedActionSessionOperationSpec ); return new LroEngine(lro, { resumeFrom: options?.resumeFrom, intervalInMs: options?.updateIntervalInMs }); } /** * Create recommendation action session for the advisor. * @param resourceGroupName The name of the resource group. The name is case insensitive. * @param serverName The name of the server. * @param advisorName The advisor name for recommendation action. * @param databaseName The name of the database. * @param options The options parameters. */ async beginCreateRecommendedActionSessionAndWait( resourceGroupName: string, serverName: string, advisorName: string, databaseName: string, options?: CreateRecommendedActionSessionOptionalParams ): Promise<void> { const poller = await this.beginCreateRecommendedActionSession( resourceGroupName, serverName, advisorName, databaseName, options ); return poller.pollUntilDone(); } servers: Servers; replicas: Replicas; firewallRules: FirewallRules; virtualNetworkRules: VirtualNetworkRules; databases: Databases; configurations: Configurations; serverParameters: ServerParameters; logFiles: LogFiles; serverAdministrators: ServerAdministrators; recoverableServers: RecoverableServers; serverBasedPerformanceTier: ServerBasedPerformanceTier; locationBasedPerformanceTier: LocationBasedPerformanceTier; checkNameAvailability: CheckNameAvailability; operations: Operations; serverSecurityAlertPolicies: ServerSecurityAlertPolicies; queryTexts: QueryTexts; topQueryStatistics: TopQueryStatistics; waitStatistics: WaitStatistics; advisors: Advisors; recommendedActions: RecommendedActions; locationBasedRecommendedActionSessionsOperationStatus: LocationBasedRecommendedActionSessionsOperationStatus; locationBasedRecommendedActionSessionsResult: LocationBasedRecommendedActionSessionsResult; privateEndpointConnections: PrivateEndpointConnections; privateLinkResources: PrivateLinkResources; serverKeys: ServerKeys; } // Operation Specifications const serializer = coreClient.createSerializer(Mappers, /* isXml */ false); const resetQueryPerformanceInsightDataOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/resetQueryPerformanceInsightData", httpMethod: "POST", responses: { 200: { bodyMapper: Mappers.QueryPerformanceInsightResetDataResult }, default: { bodyMapper: Mappers.CloudError } }, queryParameters: [Parameters.apiVersion2], urlParameters: [ Parameters.$host, Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.serverName ], headerParameters: [Parameters.accept], serializer }; const createRecommendedActionSessionOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/advisors/{advisorName}/createRecommendedActionSession", httpMethod: "POST", responses: { 200: {}, 201: {}, 202: {}, 204: {} }, queryParameters: [Parameters.apiVersion2, Parameters.databaseName1], urlParameters: [ Parameters.$host, Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.serverName, Parameters.advisorName ], serializer };
the_stack