prefix
stringlengths 82
32.6k
| middle
stringlengths 5
470
| suffix
stringlengths 0
81.2k
| file_path
stringlengths 6
168
| repo_name
stringlengths 16
77
| context
listlengths 5
5
| lang
stringclasses 4
values | ground_truth
stringlengths 5
470
|
---|---|---|---|---|---|---|---|
import BookModel from "../models/BookModel";
import Bucket from "../models/Bucket";
import Token from "../lib/GenerateToken";
import { ERROR, MAX_EPUB_SIZE_MB } from "../common/const";
import { TokStatus, Book } from "../common/types";
import {
sendJsonResponse,
parseSimplePostData,
md5,
uuid,
} from "../common/utils";
import filetype from "file-type-cjs";
import fs from "node:fs";
import EPub from "epub";
import os from "node:os";
import path from "node:path";
import crypto from "node:crypto";
import { exec } from "node:child_process";
import http from "node:http";
async function getEpubCoverFromEpubFile_UNIX(
epubFilepath: string
): Promise<[Buffer, string] | null> {
let randomString = crypto.randomBytes(16).toString("hex");
let tempDir = path.join(os.tmpdir(), `tmp-${randomString}`);
fs.mkdirSync(tempDir);
let unzipCMD = `unzip -q ${epubFilepath} -d ${tempDir}`;
let unzipCMDExec = new Promise((resolve, reject) => {
exec(unzipCMD, (err: any, stdout: any, stderr: any) => {
if (err) reject(err);
resolve(stdout);
});
});
try {
await unzipCMDExec;
} catch (err) {
console.error(err);
fs.rmSync(tempDir, { recursive: true }); // we r good boys!
return null;
}
let findCMD = `find ${tempDir} -type f \\( -iname \\*.jpeg -o -iname \\*.jpg -o -iname \\*.png \\) | grep -Ei 'cover\\.|index-1_1'`;
let findCMDExec: Promise<string> = new Promise((resolve, reject) => {
exec(findCMD, (err: any, stdout: any, stderr: any) => {
if (err) reject(err);
resolve(stdout);
});
});
let selectedFilePath: string;
try {
selectedFilePath = await findCMDExec;
selectedFilePath = selectedFilePath.trim();
} catch (err) {
console.error(err);
fs.rmSync(tempDir, { recursive: true }); // we r good boys!
return null;
}
let ret: [Buffer, string] = [
Buffer.from(fs.readFileSync(selectedFilePath)),
selectedFilePath,
];
fs.rmSync(tempDir, { recursive: true }); // we r good boys!
return ret;
}
export default async function (
req: http.IncomingMessage,
res: http.ServerResponse
) {
const BOOK_DB = new BookModel();
const BUCKET = new Bucket();
await BOOK_DB.init();
await BUCKET.init();
try {
if (req.method === "GET") {
try {
let userBooks = await BOOK_DB.getBooks();
userBooks = userBooks.map((e) => {
delete e.path;
return e;
});
sendJsonResponse(res, userBooks, 200);
} catch (error) {
console.error(error);
sendJsonResponse(res, ERROR.internalErr);
}
} else if (req.method === "POST") {
const authorization = req.headers?.authorization;
const authToken = authorization?.split(" ")?.pop();
if (!authorization || !authToken) {
sendJsonResponse(res, ERROR.unauthorized, 401);
return;
}
const token = new Token();
const tokenStatus: TokStatus = token.verify(authToken);
if (
tokenStatus === TokStatus.INVALID ||
tokenStatus === TokStatus.INVALID_SIG
) {
sendJsonResponse(res, ERROR.unauthorized, 401);
return;
}
const parsedAuthToken: any = token.UNSAFE_parse(authToken);
let epubBuffer: Buffer;
epubBuffer = await parseSimplePostData(req);
let epubSizeInMB = Math.ceil(epubBuffer.length / 1e6);
let bufferMime = await filetype.fromBuffer(epubBuffer);
if (bufferMime.mime != "application/epub+zip") {
sendJsonResponse(res, ERROR.invalidMimeForResource, 415);
return;
}
if (epubSizeInMB > MAX_EPUB_SIZE_MB) {
sendJsonResponse(res, ERROR.fileTooLarge, 400);
return;
}
let randomString = crypto.randomBytes(16).toString("hex");
const tempEpubFilePath = path.join(os.tmpdir(), `tmp-${randomString}.epub`);
fs.writeFileSync(tempEpubFilePath, epubBuffer);
const epub: any = await new Promise((resolve, reject) => {
const epub = new EPub(tempEpubFilePath);
epub.on("end", () => resolve(epub));
epub.on("error", reject);
epub.parse();
});
let epubCoverBuffer = await getEpubCoverFromEpubFile_UNIX(tempEpubFilePath);
console.log(epubCoverBuffer);
let epubSignature = md5(epubBuffer.toString("hex"));
| let foundBook = await BOOK_DB.getBook("", epubSignature); |
if (foundBook) {
sendJsonResponse(
res,
{
...ERROR.resourceExists,
data: {
id: foundBook.id,
},
},
409
);
return;
}
let epubFilePermalink = await BUCKET.pushBufferWithName(
epubBuffer,
`${epubSignature}.epub`
);
let epubCoverPermalink = null;
if (epubCoverBuffer) {
epubCoverPermalink = await BUCKET.pushBufferWithName(
epubCoverBuffer[0],
`${epubSignature}.${epubCoverBuffer[1].split(".").pop()}`
);
}
let epubID = uuid();
let epubEntry: Book = {
id: epubID,
userid: parsedAuthToken.id,
title: epub.metadata?.title ?? epubID.split("-").pop(),
author: epub.metadata?.creator ?? parsedAuthToken.email,
path: epubFilePermalink,
signature: epubSignature,
cover: epubCoverPermalink,
};
const pushed = await BOOK_DB.pushBook(epubEntry);
if (!pushed) {
sendJsonResponse(res, ERROR.internalErr, 500);
return;
}
sendJsonResponse(
res,
{
error: null,
message: `successfully published a book of id ${epubEntry.id}`,
data: {
id: epubEntry.id,
},
},
201
);
} else if (req.method === "DELETE") {
const authorization = req.headers?.authorization;
const authToken = authorization?.split(" ")?.pop();
if (!authorization || !authToken) {
sendJsonResponse(res, ERROR.unauthorized, 401);
return;
}
const token = new Token();
const tokenStatus: TokStatus = token.verify(authToken);
if (
tokenStatus === TokStatus.INVALID ||
tokenStatus === TokStatus.INVALID_SIG
) {
sendJsonResponse(res, ERROR.unauthorized, 401);
return;
}
const parsedAuthToken: any = token.UNSAFE_parse(authToken);
let body: Buffer;
body = await parseSimplePostData(req);
let data: any;
try {
data = JSON.parse(body.toString());
} catch {
sendJsonResponse(res, ERROR.invalidJSONData, 400);
return;
}
if (!data.bookid) {
sendJsonResponse(res, ERROR.badRequest, 400);
return;
}
let bookDeleted = await BOOK_DB.deleteBook(data.bookid, parsedAuthToken.id);
if (!bookDeleted) {
sendJsonResponse(res, {
error: "unable-to-delete-book",
message: `was unable to delete book ${data.bookid}, perhaps the id was invalid?`,
status: 404
}, 404)
return;
}
sendJsonResponse(res, {
error: null,
message: `successfully deleted book of id ${data.bookid}`,
status: 204,
data: {
id: data.bookid,
}
}, 204)
}
} finally {
await BOOK_DB.close();
}
}
| src/routes/Books.ts | Aadv1k-quillia-52c5b34 | [
{
"filename": "src/common/utils.ts",
"retrieved_chunk": " res.writeHead(code ?? 200, {\n \"Content-type\": \"application/epub+zip\"\n });\n res.write(epubBuffer);\n}\nexport function uuid(): string {\n const nid = nanoid.customAlphabet(\"1234567890abcdef\", 10);\n let id = nid();\n return id;\n}",
"score": 33.52333495264028
},
{
"filename": "src/routes/Issue.ts",
"retrieved_chunk": " res.on(\"end\", () => resolve(data));\n res.on(\"error\", (error) => reject(error));\n });\n });\n let epubBuffer = Buffer.concat(response);\n sendEpubResponse(res, epubBuffer);\n return;\n } else {\n let userIssues = await ISSUE_DB.getIssues(parsedAuthToken.id);\n if (!userIssues) {",
"score": 30.270399661720013
},
{
"filename": "src/common/utils.ts",
"retrieved_chunk": "export async function getBufferFromRawURL(resourceUrl: string): Promise<Buffer | null> {\n let url = new URL(resourceUrl);\n try {\n let buffArr: Buffer[] = await new Promise((resolve, reject) => {\n let func = url.protocol === \"https:\" ? https : http;\n func.get(url, (res) => {\n let data: Buffer[] = [];\n res.on(\"data\", (d: Buffer) => data.push(d))\n res.on(\"error\", reject)\n res.on(\"end\", () => resolve(data))",
"score": 29.55535499922505
},
{
"filename": "src/common/utils.ts",
"retrieved_chunk": " resolve([fields, files]);\n })\n })\n}\nexport function parseSimplePostData(req: http.IncomingMessage): Promise<Buffer> {\n return new Promise((resolve, reject) => {\n let data: Buffer[] = [];\n req.on(\"data\", (chunk: Buffer) => data.push(chunk))\n req.on(\"end\", () => { \n const buf = Buffer.concat(data);",
"score": 27.265655109213963
},
{
"filename": "src/routes/Issue.ts",
"retrieved_chunk": " let targetBook = await BOOK_DB.getBook(requestedBook);\n if (!targetBook) {\n sendJsonResponse(res, ERROR.resourceNotExists, 404);\n return;\n }\n let epubResourcePath = targetBook.path;\n const response: Array<Buffer> = await new Promise((resolve, reject) => {\n https.get(epubResourcePath, (res) => {\n let data: Array<Buffer> = [];\n res.on(\"data\", (d: Buffer) => data.push(d));",
"score": 27.207242893361506
}
] | typescript | let foundBook = await BOOK_DB.getBook("", epubSignature); |
import { ObjectDiscovery } from "./object-discovery";
import { Condition, Constraint, Rule } from "../types/rule";
export class Evaluator {
private _objectDiscovery: ObjectDiscovery = new ObjectDiscovery();
/**
* Evaluates a rule against a set of criteria and returns the result.
* If the criteria is an array (indicating multiple criteria to test),
* the rule will be evaluated against each item in the array and
* an array of results will be returned.
*
* @param rule The rule to evaluate.
* @param criteria The criteria to evaluate the rule against.
*/
evaluate(rule: Rule, criteria: object | object[]): boolean | any {
// Cater for the case where the conditions property is not an array.
const conditions =
rule.conditions instanceof Array ? rule.conditions : [rule.conditions];
if (criteria instanceof Array) {
const result = [];
for (const c of criteria) {
result.push(this.evaluateRule(conditions, c, rule?.default));
}
return result;
}
return this.evaluateRule(conditions, criteria, rule?.default);
}
/**
* Evaluates a rule against a set of criteria and returns the result.
* @param conditions The conditions to evaluate.
* @param criteria The criteria to evaluate the conditions against.
* @param defaultResult The default result to return if no conditions pass.
*/
private evaluateRule(
| conditions: Condition[],
criteria: object,
defaultResult?: any
): boolean | any { |
// We should evaluate all conditions and return the result
// of the first condition that passes.
for (const condition of conditions) {
const result = this.evaluateCondition(condition, criteria);
if (result) {
return condition?.result ?? true;
}
}
// If no conditions pass, we should return the default result of
// the rule or false if no default result is provided.
return defaultResult ?? false;
}
/**
* Evaluates a condition against a set of criteria and returns the result.
* Uses recursion to evaluate nested conditions.
* @param condition The condition to evaluate.
* @param criteria The criteria to evaluate the condition against.
*/
private evaluateCondition(condition: Condition, criteria: object): boolean {
// The condition must have an 'any' or 'all' property.
const type = this._objectDiscovery.conditionType(condition);
if (!type) {
return false;
}
// If the type is 'all' or 'none', we should set the initial
// result to true, otherwise we should set it to false.
let result = ["all", "none"].includes(type);
// Check each node in the condition.
for (const node of condition[type]) {
let fn;
if (this._objectDiscovery.isCondition(node)) {
fn = "evaluateCondition";
}
if (this._objectDiscovery.isConstraint(node)) {
fn = "checkConstraint";
}
// Process the node
switch (type) {
case "any":
result = result || this[fn](node, criteria);
break;
case "all":
result = result && this[fn](node, criteria);
break;
case "none":
result = result && !this[fn](node, criteria);
}
}
return result;
}
/**
* Checks a constraint against a set of criteria and returns true whenever the constraint passes.
* @param constraint The constraint to evaluate.
* @param criteria The criteria to evaluate the constraint with.
*/
private checkConstraint(constraint: Constraint, criteria: object): boolean {
// If the value contains '.' we should assume it is a nested property
const criterion = constraint.field.includes(".")
? this._objectDiscovery.resolveNestedProperty(constraint.field, criteria)
: criteria[constraint.field];
// If the criteria object does not have the field
// we are looking for, we should return false.
if (!criterion) {
return false;
}
switch (constraint.operator) {
case "==":
return criterion == constraint.value;
case "!=":
return criterion != constraint.value;
case ">":
return criterion > constraint.value;
case ">=":
return criterion >= constraint.value;
case "<":
return criterion < constraint.value;
case "<=":
return criterion <= constraint.value;
case "in":
return (
Array.isArray(constraint.value) &&
constraint.value.includes(criterion as never)
);
case "not in":
return (
!Array.isArray(constraint.value) ||
!constraint.value.includes(criterion as never)
);
default:
return false;
}
}
}
| src/services/evaluator.ts | andrewbrg-rulepilot-517f473 | [
{
"filename": "src/services/rule-pilot.ts",
"retrieved_chunk": " }\n /**\n * Evaluates a rule against a set of criteria and returns the result.\n * If the criteria is an array (indicating multiple criteria to test),\n * the rule will be evaluated against each item in the array and\n * an array of results will be returned.\n *\n * @param rule The rule to evaluate.\n * @param criteria The criteria to evaluate the rule against.\n * @param trustRule Set true to avoid validating the rule before evaluating it (faster).",
"score": 36.30727755465793
},
{
"filename": "src/services/rule-pilot.ts",
"retrieved_chunk": " */\n static builder(): Builder {\n return this._rulePilot.builder();\n }\n /**\n * Evaluates a rule against a set of criteria and returns the result.\n * If the criteria is an array (indicating multiple criteria to test),\n * the rule will be evaluated against each item in the array and\n * an array of results will be returned.\n *",
"score": 29.96538917102565
},
{
"filename": "src/services/rule-pilot.ts",
"retrieved_chunk": " * @param rule The rule to evaluate.\n * @param criteria The criteria to evaluate the rule against.\n * @param trustRule Set true to avoid validating the rule before evaluating it (faster).\n * @throws Error if the rule is invalid.\n */\n static async evaluate<T>(\n rule: Rule,\n criteria: object | object[],\n trustRule = false\n ): Promise<T> {",
"score": 27.464899712462675
},
{
"filename": "src/services/validator.ts",
"retrieved_chunk": " rule.conditions instanceof Array ? rule.conditions : [rule.conditions];\n // Validate the 'conditions' property.\n if (\n conditions.length === 0 ||\n (this.objectDiscovery.isObject(conditions[0]) &&\n !Object.keys(conditions[0]).length)\n ) {\n return {\n isValid: false,\n error: {",
"score": 26.57352236116642
},
{
"filename": "src/types/rule.ts",
"retrieved_chunk": " | (string | number | boolean | object)[];\n}\nexport interface Condition<R = any> {\n any?: (Constraint | Condition<R>)[];\n all?: (Constraint | Condition<R>)[];\n none?: (Constraint | Condition<R>)[];\n result?: R;\n}\nexport interface Rule<R = any> {\n conditions: Condition<R> | Condition<R>[];",
"score": 25.611379535509435
}
] | typescript | conditions: Condition[],
criteria: object,
defaultResult?: any
): boolean | any { |
import IssueModel from "../models/IssueModel";
import BookModel from "../models/BookModel";
import UserModel from "../models/UserModel";
import Token from "../lib/GenerateToken";
import { ERROR } from "../common/const";
import { TokStatus, Issue } from "../common/types";
import {
sendJsonResponse,
sendEpubResponse,
parseSimplePostData,
uuid,
getBufferFromRawURL,
} from "../common/utils";
import http from "node:http";
import https from "node:https";
export default async function (
req: http.IncomingMessage,
res: http.ServerResponse
) {
const ISSUE_DB = new IssueModel();
const BOOK_DB = new BookModel();
const USER_DB = new UserModel();
const authorization = req.headers?.authorization;
const authToken = authorization?.split(" ")?.pop()?.trim();
try {
if (req.method === "OPTIONS") {
sendJsonResponse(res, {}, 200);
return;
}
if (!authorization || !authToken) {
sendJsonResponse(res, ERROR.unauthorized, 401);
return;
}
const token = new Token();
const tokenStatus: TokStatus = token.verify(authToken);
if (
tokenStatus === TokStatus.INVALID ||
tokenStatus === TokStatus.INVALID_SIG
) {
sendJsonResponse(res, ERROR.unauthorized, 401);
return;
}
| await ISSUE_DB.init(); |
await BOOK_DB.init();
await USER_DB.init();
const parsedAuthToken: any = token.UNSAFE_parse(authToken);
if (req.method === "GET") {
let URLParams = req.url.split("/").slice(3);
let requestedBook = URLParams?.[0];
if (requestedBook) {
let targetBook = await BOOK_DB.getBook(requestedBook);
if (!targetBook) {
sendJsonResponse(res, ERROR.resourceNotExists, 404);
return;
}
let epubResourcePath = targetBook.path;
const response: Array<Buffer> = await new Promise((resolve, reject) => {
https.get(epubResourcePath, (res) => {
let data: Array<Buffer> = [];
res.on("data", (d: Buffer) => data.push(d));
res.on("end", () => resolve(data));
res.on("error", (error) => reject(error));
});
});
let epubBuffer = Buffer.concat(response);
sendEpubResponse(res, epubBuffer);
return;
} else {
let userIssues = await ISSUE_DB.getIssues(parsedAuthToken.id);
if (!userIssues) {
sendJsonResponse(res, ERROR.resourceNotExists, 404);
} else {
sendJsonResponse(res, userIssues, 200);
}
}
} else if (req.method === "POST") {
if (req.headers?.["content-type"] != "application/json") {
sendJsonResponse(res, ERROR.invalidMimeForResource, 415);
return;
}
let issueData: Issue;
try {
let issuePostData = await parseSimplePostData(req);
issueData = JSON.parse(issuePostData.toString());
} catch (error) {
console.error(error);
sendJsonResponse(res, ERROR.badRequest, 400);
return;
}
if (!issueData.lenderid || !issueData.bookid) {
sendJsonResponse(res, ERROR.badRequest, 400);
return;
}
let foundLender = await USER_DB.getUserByID(issueData.lenderid);
let foundBook = await BOOK_DB.getBook(issueData.bookid);
if (!foundLender || !foundBook) {
sendJsonResponse(res, ERROR.resourceNotExists, 404);
return;
}
let foundIssue = await ISSUE_DB.getIssue(
foundLender.id,
foundBook.id,
parsedAuthToken.id
);
if (foundIssue) {
sendJsonResponse(
res,
{
...ERROR.resourceExists,
data: {
id: foundIssue.id,
bookid: foundIssue.bookid,
},
},
409
);
return;
}
let issueid = uuid();
let issueEntry: Issue = {
id: issueid,
borrowerid: parsedAuthToken.id,
lenderid: foundLender.id,
bookid: foundBook.id,
};
const pushed = await ISSUE_DB.pushIssue(issueEntry);
if (!pushed) {
sendJsonResponse(res, ERROR.internalErr, 500);
return;
}
sendJsonResponse(
res,
{
error: null,
message: `successfully created a new issue of id ${issueEntry.id}`,
data: {
id: pushed.id,
borrower: pushed.borrowerid,
lender: pushed.lenderid,
book: foundBook.title,
},
},
201
);
}
} finally {
await ISSUE_DB.close();
await BOOK_DB.close();
await USER_DB.close();
}
}
| src/routes/Issue.ts | Aadv1k-quillia-52c5b34 | [
{
"filename": "src/routes/Books.ts",
"retrieved_chunk": " return;\n }\n const token = new Token();\n const tokenStatus: TokStatus = token.verify(authToken);\n if (\n tokenStatus === TokStatus.INVALID ||\n tokenStatus === TokStatus.INVALID_SIG\n ) {\n sendJsonResponse(res, ERROR.unauthorized, 401);\n return;",
"score": 69.92177871904867
},
{
"filename": "src/routes/Books.ts",
"retrieved_chunk": " const token = new Token();\n const tokenStatus: TokStatus = token.verify(authToken);\n if (\n tokenStatus === TokStatus.INVALID ||\n tokenStatus === TokStatus.INVALID_SIG\n ) {\n sendJsonResponse(res, ERROR.unauthorized, 401);\n return;\n }\n const parsedAuthToken: any = token.UNSAFE_parse(authToken);",
"score": 68.3952825250439
},
{
"filename": "src/routes/Login.ts",
"retrieved_chunk": " }\n if (md5(parsedData.password) !== foundUser.password) {\n sendJsonResponse(res, ERROR.unauthorized, 401);\n return;\n }\n const token = new Token();\n const { password, ...tokenBody} = foundUser;\n let accessToken = token.generate(tokenBody);\n sendJsonResponse(res, {\n messaged: \"found the given user\",",
"score": 21.385952327554953
},
{
"filename": "src/common/types.ts",
"retrieved_chunk": "export enum TokStatus {\n EXPIRED,\n INVALID,\n INVALID_SIG,\n VALID\n}",
"score": 21.29965538302991
},
{
"filename": "src/lib/GenerateToken.ts",
"retrieved_chunk": " }\n let b64Head = Buffer.from(JSON.stringify(head)).toString(\"base64\").replace(/=/g, \"\");\n let b64Body = Buffer.from(JSON.stringify(body)).toString(\"base64\").replace(/=/g, \"\");\n let signature = this.sign(`${b64Head}.${b64Body}`);\n return `${b64Head}.${b64Body}.${signature}`\n }\n verify(token: string): TokStatus {\n let [head, body, signature] = token.split('.');\n if (!head || !body || !signature) {\n return TokStatus.INVALID;",
"score": 20.084490568854633
}
] | typescript | await ISSUE_DB.init(); |
import IssueModel from "../models/IssueModel";
import BookModel from "../models/BookModel";
import UserModel from "../models/UserModel";
import Token from "../lib/GenerateToken";
import { ERROR } from "../common/const";
import { TokStatus, Issue } from "../common/types";
import {
sendJsonResponse,
sendEpubResponse,
parseSimplePostData,
uuid,
getBufferFromRawURL,
} from "../common/utils";
import http from "node:http";
import https from "node:https";
export default async function (
req: http.IncomingMessage,
res: http.ServerResponse
) {
const ISSUE_DB = new IssueModel();
const BOOK_DB = new BookModel();
const USER_DB = new UserModel();
const authorization = req.headers?.authorization;
const authToken = authorization?.split(" ")?.pop()?.trim();
try {
if (req.method === "OPTIONS") {
sendJsonResponse(res, {}, 200);
return;
}
if (!authorization || !authToken) {
sendJsonResponse(res, ERROR.unauthorized, 401);
return;
}
const token = new Token();
const tokenStatus: TokStatus = token.verify(authToken);
if (
tokenStatus === TokStatus.INVALID ||
tokenStatus === TokStatus.INVALID_SIG
) {
sendJsonResponse(res, ERROR.unauthorized, 401);
return;
}
await ISSUE_DB.init();
await BOOK_DB.init();
await USER_DB.init();
const parsedAuthToken: any = token.UNSAFE_parse(authToken);
if (req.method === "GET") {
let URLParams = req.url.split("/").slice(3);
let requestedBook = URLParams?.[0];
if (requestedBook) {
let targetBook = await BOOK_DB.getBook(requestedBook);
if (!targetBook) {
sendJsonResponse(res, ERROR.resourceNotExists, 404);
return;
}
let epubResourcePath = targetBook.path;
const response: Array<Buffer> = await new Promise((resolve, reject) => {
https.get(epubResourcePath, (res) => {
let data: Array<Buffer> = [];
res.on("data", (d: Buffer) => data.push(d));
res.on("end", () => resolve(data));
res.on("error", (error) => reject(error));
});
});
let epubBuffer = Buffer.concat(response);
sendEpubResponse(res, epubBuffer);
return;
} else {
let userIssues = await ISSUE_DB.getIssues(parsedAuthToken.id);
if (!userIssues) {
sendJsonResponse(res, ERROR.resourceNotExists, 404);
} else {
sendJsonResponse(res, userIssues, 200);
}
}
} else if (req.method === "POST") {
if (req.headers?.["content-type"] != "application/json") {
sendJsonResponse(res, ERROR.invalidMimeForResource, 415);
return;
}
let issueData: Issue;
try {
let issuePostData = await parseSimplePostData(req);
issueData = JSON.parse(issuePostData.toString());
} catch (error) {
console.error(error);
sendJsonResponse(res, ERROR.badRequest, 400);
return;
}
if (!issueData.lenderid || !issueData.bookid) {
sendJsonResponse(res, ERROR.badRequest, 400);
return;
}
let foundLender = await USER_DB | .getUserByID(issueData.lenderid); |
let foundBook = await BOOK_DB.getBook(issueData.bookid);
if (!foundLender || !foundBook) {
sendJsonResponse(res, ERROR.resourceNotExists, 404);
return;
}
let foundIssue = await ISSUE_DB.getIssue(
foundLender.id,
foundBook.id,
parsedAuthToken.id
);
if (foundIssue) {
sendJsonResponse(
res,
{
...ERROR.resourceExists,
data: {
id: foundIssue.id,
bookid: foundIssue.bookid,
},
},
409
);
return;
}
let issueid = uuid();
let issueEntry: Issue = {
id: issueid,
borrowerid: parsedAuthToken.id,
lenderid: foundLender.id,
bookid: foundBook.id,
};
const pushed = await ISSUE_DB.pushIssue(issueEntry);
if (!pushed) {
sendJsonResponse(res, ERROR.internalErr, 500);
return;
}
sendJsonResponse(
res,
{
error: null,
message: `successfully created a new issue of id ${issueEntry.id}`,
data: {
id: pushed.id,
borrower: pushed.borrowerid,
lender: pushed.lenderid,
book: foundBook.title,
},
},
201
);
}
} finally {
await ISSUE_DB.close();
await BOOK_DB.close();
await USER_DB.close();
}
}
| src/routes/Issue.ts | Aadv1k-quillia-52c5b34 | [
{
"filename": "src/routes/Signup.ts",
"retrieved_chunk": " parsedData = JSON.parse(data === \"\" ? '{}' : data);\n } catch {\n sendJsonResponse(res, ERROR.invalidJSONData, 400)\n return;\n }\n if (!parsedData.email || !parsedData.password) {\n sendJsonResponse(res, ERROR.badRequest, 400);\n return;\n }\n if (!isEmailValid(parsedData.email)) {",
"score": 25.179277691299156
},
{
"filename": "src/routes/Signup.ts",
"retrieved_chunk": " sendJsonResponse(res, ERROR.badRequest, 400);\n return;\n }\n await DB.init();\n let foundUser = await DB.getUser(parsedData.email);\n if (foundUser) {\n sendJsonResponse(res, ERROR.userAlreadyExists, 409)\n return;\n }\n let user: User = {",
"score": 24.470425410906216
},
{
"filename": "src/routes/Books.ts",
"retrieved_chunk": " }\n if (!data.bookid) {\n sendJsonResponse(res, ERROR.badRequest, 400);\n return;\n }\n let bookDeleted = await BOOK_DB.deleteBook(data.bookid, parsedAuthToken.id);\n if (!bookDeleted) {\n sendJsonResponse(res, {\n error: \"unable-to-delete-book\",\n message: `was unable to delete book ${data.bookid}, perhaps the id was invalid?`,",
"score": 23.466534891100757
},
{
"filename": "src/routes/Login.ts",
"retrieved_chunk": " } catch(error) {\n sendJsonResponse(res, ERROR.invalidJSONData, 400)\n return;\n }\n await DB.init();\n const foundUser: User = await DB.getUser(parsedData.email);\n await DB.close();\n if (!foundUser) {\n sendJsonResponse(res, ERROR.userNotFound, 404);\n return;",
"score": 16.952596838168976
},
{
"filename": "src/routes/Books.ts",
"retrieved_chunk": " let epubBuffer: Buffer;\n epubBuffer = await parseSimplePostData(req);\n let epubSizeInMB = Math.ceil(epubBuffer.length / 1e6);\n let bufferMime = await filetype.fromBuffer(epubBuffer);\n if (bufferMime.mime != \"application/epub+zip\") {\n sendJsonResponse(res, ERROR.invalidMimeForResource, 415);\n return;\n }\n if (epubSizeInMB > MAX_EPUB_SIZE_MB) {\n sendJsonResponse(res, ERROR.fileTooLarge, 400);",
"score": 15.902750561079774
}
] | typescript | .getUserByID(issueData.lenderid); |
import IssueModel from "../models/IssueModel";
import BookModel from "../models/BookModel";
import UserModel from "../models/UserModel";
import Token from "../lib/GenerateToken";
import { ERROR } from "../common/const";
import { TokStatus, Issue } from "../common/types";
import {
sendJsonResponse,
sendEpubResponse,
parseSimplePostData,
uuid,
getBufferFromRawURL,
} from "../common/utils";
import http from "node:http";
import https from "node:https";
export default async function (
req: http.IncomingMessage,
res: http.ServerResponse
) {
const ISSUE_DB = new IssueModel();
const BOOK_DB = new BookModel();
const USER_DB = new UserModel();
const authorization = req.headers?.authorization;
const authToken = authorization?.split(" ")?.pop()?.trim();
try {
if (req.method === "OPTIONS") {
sendJsonResponse(res, {}, 200);
return;
}
if (!authorization || !authToken) {
sendJsonResponse(res, ERROR.unauthorized, 401);
return;
}
const token = new Token();
const tokenStatus: TokStatus = token.verify(authToken);
if (
tokenStatus === TokStatus.INVALID ||
tokenStatus === TokStatus.INVALID_SIG
) {
sendJsonResponse(res, ERROR.unauthorized, 401);
return;
}
await ISSUE_DB.init();
await BOOK_DB.init();
await USER_DB.init();
const parsedAuthToken: any = token.UNSAFE_parse(authToken);
if (req.method === "GET") {
let URLParams = req.url.split("/").slice(3);
let requestedBook = URLParams?.[0];
if (requestedBook) {
let targetBook = await BOOK_DB.getBook(requestedBook);
if (!targetBook) {
sendJsonResponse(res, ERROR.resourceNotExists, 404);
return;
}
let epubResourcePath = targetBook.path;
const response: Array<Buffer> = await new Promise((resolve, reject) => {
https.get(epubResourcePath, (res) => {
let data: Array<Buffer> = [];
res.on("data", (d: Buffer) => data.push(d));
res.on("end", () => resolve(data));
res.on("error", (error) => reject(error));
});
});
let epubBuffer = Buffer.concat(response);
sendEpubResponse(res, epubBuffer);
return;
} else {
let userIssues = await ISSUE_DB.getIssues(parsedAuthToken.id);
if (!userIssues) {
sendJsonResponse(res, ERROR.resourceNotExists, 404);
} else {
sendJsonResponse(res, userIssues, 200);
}
}
} else if (req.method === "POST") {
if (req.headers?.["content-type"] != "application/json") {
sendJsonResponse(res, ERROR.invalidMimeForResource, 415);
return;
}
let issueData: Issue;
try {
let issuePostData = await parseSimplePostData(req);
issueData = JSON.parse(issuePostData.toString());
} catch (error) {
console.error(error);
sendJsonResponse(res, ERROR.badRequest, 400);
return;
}
if (!issueData.lenderid || !issueData.bookid) {
sendJsonResponse(res, ERROR.badRequest, 400);
return;
}
let foundLender = await USER_DB.getUserByID(issueData.lenderid);
let foundBook = await BOOK_DB.getBook(issueData.bookid);
if (!foundLender || !foundBook) {
sendJsonResponse(res, ERROR.resourceNotExists, 404);
return;
}
let foundIssue = await ISSUE_DB.getIssue(
foundLender.id,
foundBook.id,
parsedAuthToken.id
);
if (foundIssue) {
sendJsonResponse(
res,
{
...ERROR.resourceExists,
data: {
id: foundIssue.id,
bookid: foundIssue.bookid,
},
},
409
);
return;
}
let issueid = uuid();
let issueEntry: Issue = {
id: issueid,
borrowerid: parsedAuthToken.id,
lenderid: foundLender.id,
bookid: foundBook.id,
};
const pushed | = await ISSUE_DB.pushIssue(issueEntry); |
if (!pushed) {
sendJsonResponse(res, ERROR.internalErr, 500);
return;
}
sendJsonResponse(
res,
{
error: null,
message: `successfully created a new issue of id ${issueEntry.id}`,
data: {
id: pushed.id,
borrower: pushed.borrowerid,
lender: pushed.lenderid,
book: foundBook.title,
},
},
201
);
}
} finally {
await ISSUE_DB.close();
await BOOK_DB.close();
await USER_DB.close();
}
}
| src/routes/Issue.ts | Aadv1k-quillia-52c5b34 | [
{
"filename": "src/models/IssueModel.ts",
"retrieved_chunk": " const result = await this.client.query(\"SELECT EXISTS (SELECT 1 FROM issues WHERE id = $1)\", [issueid])\n return result.rows[0].exists\n } \n async pushIssue(data: Issue): Promise<Issue | null> {\n try {\n await this.client.query(\n \"INSERT INTO issues (id, lenderid, borrowerid, bookid) VALUES ($1, $2, $3, $4)\",\n [data.id, data.lenderid, data.borrowerid, data.bookid]\n );\n return data;",
"score": 25.703131246778256
},
{
"filename": "src/common/types.ts",
"retrieved_chunk": "export interface User {\n id?: string,\n email: string;\n password: string;\n}\nexport interface Issue {\n id: string,\n lenderid: string,\n borrowerid: string,\n bookid: string",
"score": 18.58499353766196
},
{
"filename": "src/models/IssueModel.ts",
"retrieved_chunk": " try {\n await this.client.query(\n \"DELETE FROM issues WHERE issueid = $1 OR borrowerid = $2 OR lenderid = $3\",\n [issueid ?? \"\", borrowerid ?? \"\", lenderid ?? \"\"]\n );\n } catch (error) {\n console.error(error);\n return null;\n }\n }",
"score": 17.27440563661295
},
{
"filename": "src/routes/Books.ts",
"retrieved_chunk": " let epubEntry: Book = {\n id: epubID,\n userid: parsedAuthToken.id,\n title: epub.metadata?.title ?? epubID.split(\"-\").pop(),\n author: epub.metadata?.creator ?? parsedAuthToken.email,\n path: epubFilePermalink,\n signature: epubSignature,\n cover: epubCoverPermalink,\n };\n const pushed = await BOOK_DB.pushBook(epubEntry);",
"score": 15.598317789211366
},
{
"filename": "src/routes/Books.ts",
"retrieved_chunk": " data: {\n id: foundBook.id,\n },\n },\n 409\n );\n return;\n }\n let epubFilePermalink = await BUCKET.pushBufferWithName(\n epubBuffer,",
"score": 14.968849980783645
}
] | typescript | = await ISSUE_DB.pushIssue(issueEntry); |
import IssueModel from "../models/IssueModel";
import BookModel from "../models/BookModel";
import UserModel from "../models/UserModel";
import Token from "../lib/GenerateToken";
import { ERROR } from "../common/const";
import { TokStatus, Issue } from "../common/types";
import {
sendJsonResponse,
sendEpubResponse,
parseSimplePostData,
uuid,
getBufferFromRawURL,
} from "../common/utils";
import http from "node:http";
import https from "node:https";
export default async function (
req: http.IncomingMessage,
res: http.ServerResponse
) {
const ISSUE_DB = new IssueModel();
const BOOK_DB = new BookModel();
const USER_DB = new UserModel();
const authorization = req.headers?.authorization;
const authToken = authorization?.split(" ")?.pop()?.trim();
try {
if (req.method === "OPTIONS") {
sendJsonResponse(res, {}, 200);
return;
}
if (!authorization || !authToken) {
sendJsonResponse(res, ERROR.unauthorized, 401);
return;
}
const token = new Token();
const tokenStatus: TokStatus = token.verify(authToken);
if (
tokenStatus === TokStatus.INVALID ||
tokenStatus === TokStatus.INVALID_SIG
) {
sendJsonResponse(res, ERROR.unauthorized, 401);
return;
}
await ISSUE_DB.init();
await BOOK_DB.init();
await USER_DB.init();
const parsedAuthToken: any = token.UNSAFE_parse(authToken);
if (req.method === "GET") {
let URLParams = req.url.split("/").slice(3);
let requestedBook = URLParams?.[0];
if (requestedBook) {
let targetBook = await BOOK_DB.getBook(requestedBook);
if (!targetBook) {
sendJsonResponse(res, ERROR.resourceNotExists, 404);
return;
}
let epubResourcePath = targetBook.path;
const response: Array<Buffer> = await new Promise((resolve, reject) => {
https.get(epubResourcePath, (res) => {
let data: Array<Buffer> = [];
res.on("data", (d: Buffer) => data.push(d));
res.on("end", () => resolve(data));
res.on("error", (error) => reject(error));
});
});
let epubBuffer = Buffer.concat(response);
sendEpubResponse(res, epubBuffer);
return;
} else {
let userIssues = await ISSUE_DB.getIssues(parsedAuthToken.id);
if (!userIssues) {
sendJsonResponse(res, ERROR.resourceNotExists, 404);
} else {
sendJsonResponse(res, userIssues, 200);
}
}
} else if (req.method === "POST") {
if (req.headers?.["content-type"] != "application/json") {
sendJsonResponse(res, ERROR.invalidMimeForResource, 415);
return;
}
let issueData: Issue;
try {
let issuePostData = await parseSimplePostData(req);
issueData = JSON.parse(issuePostData.toString());
} catch (error) {
console.error(error);
sendJsonResponse(res, ERROR.badRequest, 400);
return;
}
if (!issueData.lenderid || !issueData.bookid) {
sendJsonResponse(res, ERROR.badRequest, 400);
return;
}
let foundLender = await USER_DB.getUserByID(issueData.lenderid);
let foundBook = await BOOK_DB.getBook(issueData.bookid);
if (!foundLender || !foundBook) {
sendJsonResponse(res, ERROR.resourceNotExists, 404);
return;
}
| let foundIssue = await ISSUE_DB.getIssue(
foundLender.id,
foundBook.id,
parsedAuthToken.id
); |
if (foundIssue) {
sendJsonResponse(
res,
{
...ERROR.resourceExists,
data: {
id: foundIssue.id,
bookid: foundIssue.bookid,
},
},
409
);
return;
}
let issueid = uuid();
let issueEntry: Issue = {
id: issueid,
borrowerid: parsedAuthToken.id,
lenderid: foundLender.id,
bookid: foundBook.id,
};
const pushed = await ISSUE_DB.pushIssue(issueEntry);
if (!pushed) {
sendJsonResponse(res, ERROR.internalErr, 500);
return;
}
sendJsonResponse(
res,
{
error: null,
message: `successfully created a new issue of id ${issueEntry.id}`,
data: {
id: pushed.id,
borrower: pushed.borrowerid,
lender: pushed.lenderid,
book: foundBook.title,
},
},
201
);
}
} finally {
await ISSUE_DB.close();
await BOOK_DB.close();
await USER_DB.close();
}
}
| src/routes/Issue.ts | Aadv1k-quillia-52c5b34 | [
{
"filename": "src/routes/Books.ts",
"retrieved_chunk": " });\n let epubCoverBuffer = await getEpubCoverFromEpubFile_UNIX(tempEpubFilePath);\n console.log(epubCoverBuffer);\n let epubSignature = md5(epubBuffer.toString(\"hex\"));\n let foundBook = await BOOK_DB.getBook(\"\", epubSignature);\n if (foundBook) {\n sendJsonResponse(\n res,\n {\n ...ERROR.resourceExists,",
"score": 31.879115359924207
},
{
"filename": "src/routes/Books.ts",
"retrieved_chunk": " data: {\n id: foundBook.id,\n },\n },\n 409\n );\n return;\n }\n let epubFilePermalink = await BUCKET.pushBufferWithName(\n epubBuffer,",
"score": 23.989155341247894
},
{
"filename": "src/routes/Books.ts",
"retrieved_chunk": " }\n if (!data.bookid) {\n sendJsonResponse(res, ERROR.badRequest, 400);\n return;\n }\n let bookDeleted = await BOOK_DB.deleteBook(data.bookid, parsedAuthToken.id);\n if (!bookDeleted) {\n sendJsonResponse(res, {\n error: \"unable-to-delete-book\",\n message: `was unable to delete book ${data.bookid}, perhaps the id was invalid?`,",
"score": 19.567208209114252
},
{
"filename": "src/routes/Books.ts",
"retrieved_chunk": " status: 404\n }, 404)\n return;\n }\n sendJsonResponse(res, {\n error: null,\n message: `successfully deleted book of id ${data.bookid}`,\n status: 204,\n data: {\n id: data.bookid,",
"score": 15.309241097044623
},
{
"filename": "src/routes/Books.ts",
"retrieved_chunk": " let epubEntry: Book = {\n id: epubID,\n userid: parsedAuthToken.id,\n title: epub.metadata?.title ?? epubID.split(\"-\").pop(),\n author: epub.metadata?.creator ?? parsedAuthToken.email,\n path: epubFilePermalink,\n signature: epubSignature,\n cover: epubCoverPermalink,\n };\n const pushed = await BOOK_DB.pushBook(epubEntry);",
"score": 13.411517298047956
}
] | typescript | let foundIssue = await ISSUE_DB.getIssue(
foundLender.id,
foundBook.id,
parsedAuthToken.id
); |
import { ObjectDiscovery } from "./object-discovery";
import { Condition, Constraint, Operator, Rule } from "../types/rule";
export interface ValidationResult {
isValid: boolean;
error?: {
message: string;
element: object;
};
}
export class Validator {
private objectDiscovery: ObjectDiscovery = new ObjectDiscovery();
/**
* Takes in a rule as a parameter and returns a boolean indicating whether the rule is valid or not.
* @param rule The rule to validate.
*/
validate(rule: Rule): ValidationResult {
// Assume the rule is valid.
let result: ValidationResult = { isValid: true };
// Check the rule is a valid JSON
if (!this.objectDiscovery.isObject(rule)) {
return {
isValid: false,
error: {
message: "The rule must be a valid JSON object.",
element: rule,
},
};
}
// Cater for the case where the conditions property is not an array.
const conditions =
rule.conditions instanceof Array ? rule.conditions : [rule.conditions];
// Validate the 'conditions' property.
if (
conditions.length === 0 ||
(this.objectDiscovery.isObject(conditions[0]) &&
!Object.keys(conditions[0]).length)
) {
return {
isValid: false,
error: {
message:
"The conditions property must contain at least one condition.",
element: rule,
},
};
}
// Validate each condition in the rule.
for (const condition of conditions) {
const subResult = this.validateCondition(condition);
result.isValid = result.isValid && subResult.isValid;
result.error = result?.error ?? subResult?.error;
}
return result;
}
/** ml/l.k,
* Evaluates a condition to ensure it is syntactically correct.
* @param condition The condition to validate.
* @param depth The current recursion depth
*/
private validateCondition(
condition: | Condition,
depth: number = 0
): ValidationResult { |
// Check to see if the condition is valid.
let result = this.isValidCondition(condition);
if (!result.isValid) {
return result;
}
// Set the type of condition.
const type = this.objectDiscovery.conditionType(condition);
// Check if the condition is iterable
if(!Array.isArray(condition[type])) {
return {
isValid: false,
error: {
message: `The condition '${type}' should be iterable.`,
element: condition,
},
};
}
// Validate each item in the condition.
for (const node of condition[type]) {
const isCondition = this.objectDiscovery.isCondition(node);
if (isCondition) {
const subResult = this.validateCondition(node as Condition, depth + 1);
result.isValid = result.isValid && subResult.isValid;
result.error = result?.error ?? subResult?.error;
}
const isConstraint = this.objectDiscovery.isConstraint(node);
if (isConstraint) {
const subResult = this.validateConstraint(node as Constraint);
result.isValid = result.isValid && subResult.isValid;
result.error = result?.error ?? subResult?.error;
}
if (!isConstraint && !isCondition) {
return {
isValid: false,
error: {
message: "Each node should be a condition or constraint.",
element: node,
},
};
}
// Result is only valid on the root condition.
if (depth > 0 && "result" in condition) {
return {
isValid: false,
error: {
message: 'Nested conditions cannot have a property "result".',
element: node,
},
};
}
// If any part fails validation there is no point to continue.
if (!result.isValid) {
break;
}
}
return result;
}
/**
* Checks a constraint to ensure it is syntactically correct.
* @param constraint The constraint to validate.
*/
private validateConstraint(constraint: Constraint): ValidationResult {
if ("string" !== typeof constraint.field) {
return {
isValid: false,
error: {
message: 'Constraint "field" must be of type string.',
element: constraint,
},
};
}
const operators = ["==", "!=", ">", "<", ">=", "<=", "in", "not in"];
if (!operators.includes(constraint.operator as Operator)) {
return {
isValid: false,
error: {
message: 'Constraint "operator" has invalid type.',
element: constraint,
},
};
}
// We must check that the value is an array if the operator is 'in' or 'not in'.
if (
["in", "not in"].includes(constraint.operator) &&
!Array.isArray(constraint.value)
) {
return {
isValid: false,
error: {
message:
'Constraint "value" must be an array if the "operator" is "in" or "not in"',
element: constraint,
},
};
}
return { isValid: true };
}
/**
* Checks an object to see if it is a valid condition.
* @param obj The object to check.
*/
private isValidCondition(obj: any): ValidationResult {
if (!this.objectDiscovery.isCondition(obj)) {
return {
isValid: false,
error: {
message: "Invalid condition structure.",
element: obj,
},
};
}
const isAny = "any" in obj;
const isAll = "all" in obj;
const isNone = "none" in obj;
// A valid condition must have an 'any', 'all', or 'none' property,
// but cannot have more than one.
if ((isAny && isAll) || (isAny && isNone) || (isAll && isNone)) {
return {
isValid: false,
error: {
message:
'A condition cannot have more than one "any", "all", or "none" property.',
element: obj,
},
};
}
return { isValid: true };
}
}
| src/services/validator.ts | andrewbrg-rulepilot-517f473 | [
{
"filename": "src/services/evaluator.ts",
"retrieved_chunk": " * Evaluates a condition against a set of criteria and returns the result.\n * Uses recursion to evaluate nested conditions.\n * @param condition The condition to evaluate.\n * @param criteria The criteria to evaluate the condition against.\n */\n private evaluateCondition(condition: Condition, criteria: object): boolean {\n // The condition must have an 'any' or 'all' property.\n const type = this._objectDiscovery.conditionType(condition);\n if (!type) {\n return false;",
"score": 26.62295429546278
},
{
"filename": "src/services/object-discovery.ts",
"retrieved_chunk": "import { Condition, ConditionType, Constraint } from \"../types/rule\";\nexport class ObjectDiscovery {\n /**\n * Returns the type of condition passed to the function.\n * @param condition The condition to check.\n */\n conditionType(condition: Condition): ConditionType | null {\n if (\"any\" in condition) return \"any\";\n if (\"all\" in condition) return \"all\";\n if (\"none\" in condition) return \"none\";",
"score": 20.938435643284517
},
{
"filename": "src/services/builder.ts",
"retrieved_chunk": " * @param type The type of condition\n * @param nodes Any child nodes of the condition\n * @param result The result of the condition node (for granular rules)\n */\n condition(\n type: ConditionType,\n nodes: Condition[ConditionType],\n result?: Condition[\"result\"]\n ): Condition {\n return {",
"score": 19.68631514042048
},
{
"filename": "src/services/evaluator.ts",
"retrieved_chunk": " * @param defaultResult The default result to return if no conditions pass.\n */\n private evaluateRule(\n conditions: Condition[],\n criteria: object,\n defaultResult?: any\n ): boolean | any {\n // We should evaluate all conditions and return the result\n // of the first condition that passes.\n for (const condition of conditions) {",
"score": 16.855438213225547
},
{
"filename": "src/services/object-discovery.ts",
"retrieved_chunk": " return null;\n }\n /**\n * Checks an object to see if it is a valid condition.\n * @param obj The object to check.\n */\n isCondition(obj: unknown): obj is Condition {\n return !this.isObject(obj)\n ? false\n : \"any\" in obj || \"all\" in obj || \"none\" in obj;",
"score": 15.526293107254347
}
] | typescript | Condition,
depth: number = 0
): ValidationResult { |
import { Builder } from "./builder";
import { Mutator } from "./mutator";
import { Evaluator } from "./evaluator";
import { ValidationResult, Validator } from "./validator";
import { Rule } from "../types/rule";
import { RuleError } from "../types/error";
export class RulePilot {
private static _rulePilot = new RulePilot();
private _mutator: Mutator = new Mutator();
private _validator: Validator = new Validator();
private _evaluator: Evaluator = new Evaluator();
/**
* Returns a rule builder class instance.
* Allows for the construction of rules using a fluent interface.
*/
builder(): Builder {
return new Builder(this._validator);
}
/**
* Adds a mutation to the rule pilot instance.
* Mutations allow for the modification of the criteria before
* it is evaluated against a rule.
*
* @param name The name of the mutation.
* @param mutation The mutation function.
*/
addMutation(name: string, mutation: Function): RulePilot {
this._mutator.add(name, mutation);
return this;
}
/**
* Removes a mutation to the rule pilot instance.
* Any cached mutation values for this mutation will be purged.
*
* @param name The name of the mutation.
*/
removeMutation(name: string): RulePilot {
this._mutator.remove(name);
return this;
}
/**
* Clears the mutator cache.
* The entire cache, or cache for a specific mutator, can be cleared
* by passing or omitting the mutator name as an argument.
*
* @param name The mutator name to clear the cache for.
*/
clearMutationCache(name?: string): RulePilot {
this._mutator.clearCache(name);
return this;
}
/**
* Evaluates a rule against a set of criteria and returns the result.
* If the criteria is an array (indicating multiple criteria to test),
* the rule will be evaluated against each item in the array and
* an array of results will be returned.
*
* @param rule The rule to evaluate.
* @param criteria The criteria to evaluate the rule against.
* @param trustRule Set true to avoid validating the rule before evaluating it (faster).
* @throws Error if the rule is invalid.
*/
async evaluate<T>(
rule: Rule,
criteria: object | object[],
trustRule = false
): Promise<T> {
// Before we evaluate the rule, we should validate it.
// If `trustRuleset` is set to true, we will skip validation.
const validationResult = !trustRule && this.validate(rule);
if (!trustRule && !validationResult.isValid) {
| throw new RuleError(validationResult); |
}
return this._evaluator.evaluate(rule, await this._mutator.mutate(criteria));
}
/**
* Takes in a rule as a parameter and returns a ValidationResult
* indicating whether the rule is valid or not.
*
* Invalid rules will contain an error property which contains a message and the element
* that caused the validation to fail.
*
* @param rule The rule to validate.
*/
validate(rule: Rule): ValidationResult {
return this._validator.validate(rule);
}
/**
* Returns a rule builder class instance.
* Allows for the construction of rules using a fluent interface.
*/
static builder(): Builder {
return this._rulePilot.builder();
}
/**
* Evaluates a rule against a set of criteria and returns the result.
* If the criteria is an array (indicating multiple criteria to test),
* the rule will be evaluated against each item in the array and
* an array of results will be returned.
*
* @param rule The rule to evaluate.
* @param criteria The criteria to evaluate the rule against.
* @param trustRule Set true to avoid validating the rule before evaluating it (faster).
* @throws Error if the rule is invalid.
*/
static async evaluate<T>(
rule: Rule,
criteria: object | object[],
trustRule = false
): Promise<T> {
return RulePilot._rulePilot.evaluate<T>(rule, criteria, trustRule);
}
/**
* Takes in a rule as a parameter and returns a ValidationResult
* indicating whether the rule is valid or not.
*
* Invalid rules will contain an error property which contains a message and the element
* that caused the validation to fail.
*
* @param rule The rule to validate.
*/
static validate(rule: Rule): ValidationResult {
return RulePilot._rulePilot.validate(rule);
}
/**
* Adds a mutation.
*
* Mutations allow for the modification of the criteria before
* it is evaluated against a rule.
*
* @param name The name of the mutation.
* @param mutation The mutation function.
*/
static addMutation(name: string, mutation: Function): RulePilot {
return RulePilot._rulePilot.addMutation(name, mutation);
}
/**
* Removes a mutation to the rule pilot instance.
* Any cached mutation values for this mutation will be purged.
*
* @param name The name of the mutation.
*/
static removeMutation(name: string): RulePilot {
return RulePilot._rulePilot.removeMutation(name);
}
/**
* Clears the mutator cache.
* The entire cache, or cache for a specific mutator, can be cleared
* by passing or omitting the mutator name as an argument.
*
* @param name The mutator name to clear the cache for.
*/
static clearMutationCache(name?: string): RulePilot {
return RulePilot._rulePilot.clearMutationCache(name);
}
}
| src/services/rule-pilot.ts | andrewbrg-rulepilot-517f473 | [
{
"filename": "src/services/builder.ts",
"retrieved_chunk": " return this.rule;\n }\n const validationResult = this.validator.validate(this.rule);\n if (validationResult.isValid) {\n return this.rule;\n }\n throw new RuleError(validationResult);\n }\n /**\n * Creates a new condition node",
"score": 43.99957662294109
},
{
"filename": "src/services/evaluator.ts",
"retrieved_chunk": " * @param criteria The criteria to evaluate the constraint with.\n */\n private checkConstraint(constraint: Constraint, criteria: object): boolean {\n // If the value contains '.' we should assume it is a nested property\n const criterion = constraint.field.includes(\".\")\n ? this._objectDiscovery.resolveNestedProperty(constraint.field, criteria)\n : criteria[constraint.field];\n // If the criteria object does not have the field\n // we are looking for, we should return false.\n if (!criterion) {",
"score": 26.53025625946966
},
{
"filename": "src/services/builder.ts",
"retrieved_chunk": " this.rule.default = value;\n return this;\n }\n /**\n * Builds the rule being and returns it\n * @param validate Whether to validate the rule before returning it\n * @throws Error if validation is enabled and the rule is invalid\n */\n build(validate?: boolean): Rule {\n if (!validate) {",
"score": 26.055199586034558
},
{
"filename": "src/services/evaluator.ts",
"retrieved_chunk": " }\n // If the type is 'all' or 'none', we should set the initial\n // result to true, otherwise we should set it to false.\n let result = [\"all\", \"none\"].includes(type);\n // Check each node in the condition.\n for (const node of condition[type]) {\n let fn;\n if (this._objectDiscovery.isCondition(node)) {\n fn = \"evaluateCondition\";\n }",
"score": 23.244293748562356
},
{
"filename": "src/types/error.ts",
"retrieved_chunk": "import { ValidationResult } from \"../services/validator\";\nexport class RuleError extends Error {\n constructor(validationResult: ValidationResult) {\n super(validationResult.error.message);\n this.element = validationResult.error.element;\n }\n /** The name/type of the error. */\n type: string = RuleError.name;\n /** The element that caused the error. */\n element: object;",
"score": 22.679417032246537
}
] | typescript | throw new RuleError(validationResult); |
import { Builder } from "./builder";
import { Mutator } from "./mutator";
import { Evaluator } from "./evaluator";
import { ValidationResult, Validator } from "./validator";
import { Rule } from "../types/rule";
import { RuleError } from "../types/error";
export class RulePilot {
private static _rulePilot = new RulePilot();
private _mutator: Mutator = new Mutator();
private _validator: Validator = new Validator();
private _evaluator: Evaluator = new Evaluator();
/**
* Returns a rule builder class instance.
* Allows for the construction of rules using a fluent interface.
*/
builder(): Builder {
return new Builder(this._validator);
}
/**
* Adds a mutation to the rule pilot instance.
* Mutations allow for the modification of the criteria before
* it is evaluated against a rule.
*
* @param name The name of the mutation.
* @param mutation The mutation function.
*/
addMutation(name: string, mutation: Function): RulePilot {
this._mutator.add(name, mutation);
return this;
}
/**
* Removes a mutation to the rule pilot instance.
* Any cached mutation values for this mutation will be purged.
*
* @param name The name of the mutation.
*/
removeMutation(name: string): RulePilot {
this._mutator.remove(name);
return this;
}
/**
* Clears the mutator cache.
* The entire cache, or cache for a specific mutator, can be cleared
* by passing or omitting the mutator name as an argument.
*
* @param name The mutator name to clear the cache for.
*/
clearMutationCache(name?: string): RulePilot {
this._mutator.clearCache(name);
return this;
}
/**
* Evaluates a rule against a set of criteria and returns the result.
* If the criteria is an array (indicating multiple criteria to test),
* the rule will be evaluated against each item in the array and
* an array of results will be returned.
*
* @param rule The rule to evaluate.
* @param criteria The criteria to evaluate the rule against.
* @param trustRule Set true to avoid validating the rule before evaluating it (faster).
* @throws Error if the rule is invalid.
*/
async evaluate<T>(
rule: Rule,
criteria: object | object[],
trustRule = false
): Promise<T> {
// Before we evaluate the rule, we should validate it.
// If `trustRuleset` is set to true, we will skip validation.
const validationResult = !trustRule && this.validate(rule);
if (!trustRule && !validationResult.isValid) {
throw new RuleError(validationResult);
}
return this._evaluator.evaluate(rule, await this._mutator.mutate(criteria));
}
/**
* Takes in a rule as a parameter and returns a ValidationResult
* indicating whether the rule is valid or not.
*
* Invalid rules will contain an error property which contains a message and the element
* that caused the validation to fail.
*
* @param rule The rule to validate.
*/
validate(rule: Rule): ValidationResult {
return this._validator.validate(rule);
}
/**
* Returns a rule builder class instance.
* Allows for the construction of rules using a fluent interface.
*/
| static builder(): Builder { |
return this._rulePilot.builder();
}
/**
* Evaluates a rule against a set of criteria and returns the result.
* If the criteria is an array (indicating multiple criteria to test),
* the rule will be evaluated against each item in the array and
* an array of results will be returned.
*
* @param rule The rule to evaluate.
* @param criteria The criteria to evaluate the rule against.
* @param trustRule Set true to avoid validating the rule before evaluating it (faster).
* @throws Error if the rule is invalid.
*/
static async evaluate<T>(
rule: Rule,
criteria: object | object[],
trustRule = false
): Promise<T> {
return RulePilot._rulePilot.evaluate<T>(rule, criteria, trustRule);
}
/**
* Takes in a rule as a parameter and returns a ValidationResult
* indicating whether the rule is valid or not.
*
* Invalid rules will contain an error property which contains a message and the element
* that caused the validation to fail.
*
* @param rule The rule to validate.
*/
static validate(rule: Rule): ValidationResult {
return RulePilot._rulePilot.validate(rule);
}
/**
* Adds a mutation.
*
* Mutations allow for the modification of the criteria before
* it is evaluated against a rule.
*
* @param name The name of the mutation.
* @param mutation The mutation function.
*/
static addMutation(name: string, mutation: Function): RulePilot {
return RulePilot._rulePilot.addMutation(name, mutation);
}
/**
* Removes a mutation to the rule pilot instance.
* Any cached mutation values for this mutation will be purged.
*
* @param name The name of the mutation.
*/
static removeMutation(name: string): RulePilot {
return RulePilot._rulePilot.removeMutation(name);
}
/**
* Clears the mutator cache.
* The entire cache, or cache for a specific mutator, can be cleared
* by passing or omitting the mutator name as an argument.
*
* @param name The mutator name to clear the cache for.
*/
static clearMutationCache(name?: string): RulePilot {
return RulePilot._rulePilot.clearMutationCache(name);
}
}
| src/services/rule-pilot.ts | andrewbrg-rulepilot-517f473 | [
{
"filename": "src/services/validator.ts",
"retrieved_chunk": " private objectDiscovery: ObjectDiscovery = new ObjectDiscovery();\n /**\n * Takes in a rule as a parameter and returns a boolean indicating whether the rule is valid or not.\n * @param rule The rule to validate.\n */\n validate(rule: Rule): ValidationResult {\n // Assume the rule is valid.\n let result: ValidationResult = { isValid: true };\n // Check the rule is a valid JSON\n if (!this.objectDiscovery.isObject(rule)) {",
"score": 28.53618181312906
},
{
"filename": "src/services/builder.ts",
"retrieved_chunk": " this.rule.default = value;\n return this;\n }\n /**\n * Builds the rule being and returns it\n * @param validate Whether to validate the rule before returning it\n * @throws Error if validation is enabled and the rule is invalid\n */\n build(validate?: boolean): Rule {\n if (!validate) {",
"score": 28.244392814514903
},
{
"filename": "src/services/builder.ts",
"retrieved_chunk": " return this.rule;\n }\n const validationResult = this.validator.validate(this.rule);\n if (validationResult.isValid) {\n return this.rule;\n }\n throw new RuleError(validationResult);\n }\n /**\n * Creates a new condition node",
"score": 21.68680659675862
},
{
"filename": "src/services/builder.ts",
"retrieved_chunk": " */\n add(node: Condition): Builder {\n (this.rule.conditions as Condition[]).push(node);\n return this;\n }\n /**\n * Sets the default value of the rule being constructed\n * @param value The default value of the rule\n */\n default(value: Rule[\"default\"]): Builder {",
"score": 19.943663948878527
},
{
"filename": "src/services/builder.ts",
"retrieved_chunk": " constructor(validator: Validator) {\n this.validator = validator;\n }\n /** Stores to rule being constructed */\n private rule: Rule = { conditions: [] };\n /** Holds a reference to the Validator class */\n private validator: Validator;\n /**\n * Adds a node (in the root) to the rule being constructed\n * @param node The node to add to the rule",
"score": 18.22880488999009
}
] | typescript | static builder(): Builder { |
import IssueModel from "../models/IssueModel";
import BookModel from "../models/BookModel";
import UserModel from "../models/UserModel";
import Token from "../lib/GenerateToken";
import { ERROR } from "../common/const";
import { TokStatus, Issue } from "../common/types";
import {
sendJsonResponse,
sendEpubResponse,
parseSimplePostData,
uuid,
getBufferFromRawURL,
} from "../common/utils";
import http from "node:http";
import https from "node:https";
export default async function (
req: http.IncomingMessage,
res: http.ServerResponse
) {
const ISSUE_DB = new IssueModel();
const BOOK_DB = new BookModel();
const USER_DB = new UserModel();
const authorization = req.headers?.authorization;
const authToken = authorization?.split(" ")?.pop()?.trim();
try {
if (req.method === "OPTIONS") {
sendJsonResponse(res, {}, 200);
return;
}
if (!authorization || !authToken) {
sendJsonResponse(res, ERROR.unauthorized, 401);
return;
}
const token = new Token();
const tokenStatus: TokStatus = token.verify(authToken);
if (
tokenStatus === TokStatus.INVALID ||
tokenStatus === TokStatus.INVALID_SIG
) {
sendJsonResponse(res, ERROR.unauthorized, 401);
return;
}
await ISSUE_DB.init();
await BOOK_DB.init();
await USER_DB.init();
const parsedAuthToken: any = token.UNSAFE_parse(authToken);
if (req.method === "GET") {
let URLParams = req.url.split("/").slice(3);
let requestedBook = URLParams?.[0];
if (requestedBook) {
let targetBook = await BOOK_DB.getBook(requestedBook);
if (!targetBook) {
sendJsonResponse( | res, ERROR.resourceNotExists, 404); |
return;
}
let epubResourcePath = targetBook.path;
const response: Array<Buffer> = await new Promise((resolve, reject) => {
https.get(epubResourcePath, (res) => {
let data: Array<Buffer> = [];
res.on("data", (d: Buffer) => data.push(d));
res.on("end", () => resolve(data));
res.on("error", (error) => reject(error));
});
});
let epubBuffer = Buffer.concat(response);
sendEpubResponse(res, epubBuffer);
return;
} else {
let userIssues = await ISSUE_DB.getIssues(parsedAuthToken.id);
if (!userIssues) {
sendJsonResponse(res, ERROR.resourceNotExists, 404);
} else {
sendJsonResponse(res, userIssues, 200);
}
}
} else if (req.method === "POST") {
if (req.headers?.["content-type"] != "application/json") {
sendJsonResponse(res, ERROR.invalidMimeForResource, 415);
return;
}
let issueData: Issue;
try {
let issuePostData = await parseSimplePostData(req);
issueData = JSON.parse(issuePostData.toString());
} catch (error) {
console.error(error);
sendJsonResponse(res, ERROR.badRequest, 400);
return;
}
if (!issueData.lenderid || !issueData.bookid) {
sendJsonResponse(res, ERROR.badRequest, 400);
return;
}
let foundLender = await USER_DB.getUserByID(issueData.lenderid);
let foundBook = await BOOK_DB.getBook(issueData.bookid);
if (!foundLender || !foundBook) {
sendJsonResponse(res, ERROR.resourceNotExists, 404);
return;
}
let foundIssue = await ISSUE_DB.getIssue(
foundLender.id,
foundBook.id,
parsedAuthToken.id
);
if (foundIssue) {
sendJsonResponse(
res,
{
...ERROR.resourceExists,
data: {
id: foundIssue.id,
bookid: foundIssue.bookid,
},
},
409
);
return;
}
let issueid = uuid();
let issueEntry: Issue = {
id: issueid,
borrowerid: parsedAuthToken.id,
lenderid: foundLender.id,
bookid: foundBook.id,
};
const pushed = await ISSUE_DB.pushIssue(issueEntry);
if (!pushed) {
sendJsonResponse(res, ERROR.internalErr, 500);
return;
}
sendJsonResponse(
res,
{
error: null,
message: `successfully created a new issue of id ${issueEntry.id}`,
data: {
id: pushed.id,
borrower: pushed.borrowerid,
lender: pushed.lenderid,
book: foundBook.title,
},
},
201
);
}
} finally {
await ISSUE_DB.close();
await BOOK_DB.close();
await USER_DB.close();
}
}
| src/routes/Issue.ts | Aadv1k-quillia-52c5b34 | [
{
"filename": "src/routes/Books.ts",
"retrieved_chunk": " }\n const parsedAuthToken: any = token.UNSAFE_parse(authToken);\n let body: Buffer;\n body = await parseSimplePostData(req);\n let data: any;\n try {\n data = JSON.parse(body.toString());\n } catch {\n sendJsonResponse(res, ERROR.invalidJSONData, 400);\n return;",
"score": 26.655959688488984
},
{
"filename": "src/routes/Books.ts",
"retrieved_chunk": " const token = new Token();\n const tokenStatus: TokStatus = token.verify(authToken);\n if (\n tokenStatus === TokStatus.INVALID ||\n tokenStatus === TokStatus.INVALID_SIG\n ) {\n sendJsonResponse(res, ERROR.unauthorized, 401);\n return;\n }\n const parsedAuthToken: any = token.UNSAFE_parse(authToken);",
"score": 23.743382360057137
},
{
"filename": "src/routes/Books.ts",
"retrieved_chunk": " console.error(error);\n sendJsonResponse(res, ERROR.internalErr);\n }\n } else if (req.method === \"POST\") {\n const authorization = req.headers?.authorization;\n const authToken = authorization?.split(\" \")?.pop();\n if (!authorization || !authToken) {\n sendJsonResponse(res, ERROR.unauthorized, 401);\n return;\n }",
"score": 23.33548024904719
},
{
"filename": "src/routes/Books.ts",
"retrieved_chunk": " id: epubEntry.id,\n },\n },\n 201\n );\n } else if (req.method === \"DELETE\") {\n const authorization = req.headers?.authorization;\n const authToken = authorization?.split(\" \")?.pop();\n if (!authorization || !authToken) {\n sendJsonResponse(res, ERROR.unauthorized, 401);",
"score": 22.961266859515042
},
{
"filename": "src/routes/Books.ts",
"retrieved_chunk": " try {\n if (req.method === \"GET\") {\n try {\n let userBooks = await BOOK_DB.getBooks();\n userBooks = userBooks.map((e) => {\n delete e.path;\n return e;\n });\n sendJsonResponse(res, userBooks, 200);\n } catch (error) {",
"score": 21.459949974086413
}
] | typescript | res, ERROR.resourceNotExists, 404); |
import { Builder } from "./builder";
import { Mutator } from "./mutator";
import { Evaluator } from "./evaluator";
import { ValidationResult, Validator } from "./validator";
import { Rule } from "../types/rule";
import { RuleError } from "../types/error";
export class RulePilot {
private static _rulePilot = new RulePilot();
private _mutator: Mutator = new Mutator();
private _validator: Validator = new Validator();
private _evaluator: Evaluator = new Evaluator();
/**
* Returns a rule builder class instance.
* Allows for the construction of rules using a fluent interface.
*/
builder(): Builder {
return new Builder(this._validator);
}
/**
* Adds a mutation to the rule pilot instance.
* Mutations allow for the modification of the criteria before
* it is evaluated against a rule.
*
* @param name The name of the mutation.
* @param mutation The mutation function.
*/
addMutation(name: string, mutation: Function): RulePilot {
this._mutator.add(name, mutation);
return this;
}
/**
* Removes a mutation to the rule pilot instance.
* Any cached mutation values for this mutation will be purged.
*
* @param name The name of the mutation.
*/
removeMutation(name: string): RulePilot {
this._mutator.remove(name);
return this;
}
/**
* Clears the mutator cache.
* The entire cache, or cache for a specific mutator, can be cleared
* by passing or omitting the mutator name as an argument.
*
* @param name The mutator name to clear the cache for.
*/
clearMutationCache(name?: string): RulePilot {
this._mutator.clearCache(name);
return this;
}
/**
* Evaluates a rule against a set of criteria and returns the result.
* If the criteria is an array (indicating multiple criteria to test),
* the rule will be evaluated against each item in the array and
* an array of results will be returned.
*
* @param rule The rule to evaluate.
* @param criteria The criteria to evaluate the rule against.
* @param trustRule Set true to avoid validating the rule before evaluating it (faster).
* @throws Error if the rule is invalid.
*/
async evaluate<T>(
rule: | Rule,
criteria: object | object[],
trustRule = false
): Promise<T> { |
// Before we evaluate the rule, we should validate it.
// If `trustRuleset` is set to true, we will skip validation.
const validationResult = !trustRule && this.validate(rule);
if (!trustRule && !validationResult.isValid) {
throw new RuleError(validationResult);
}
return this._evaluator.evaluate(rule, await this._mutator.mutate(criteria));
}
/**
* Takes in a rule as a parameter and returns a ValidationResult
* indicating whether the rule is valid or not.
*
* Invalid rules will contain an error property which contains a message and the element
* that caused the validation to fail.
*
* @param rule The rule to validate.
*/
validate(rule: Rule): ValidationResult {
return this._validator.validate(rule);
}
/**
* Returns a rule builder class instance.
* Allows for the construction of rules using a fluent interface.
*/
static builder(): Builder {
return this._rulePilot.builder();
}
/**
* Evaluates a rule against a set of criteria and returns the result.
* If the criteria is an array (indicating multiple criteria to test),
* the rule will be evaluated against each item in the array and
* an array of results will be returned.
*
* @param rule The rule to evaluate.
* @param criteria The criteria to evaluate the rule against.
* @param trustRule Set true to avoid validating the rule before evaluating it (faster).
* @throws Error if the rule is invalid.
*/
static async evaluate<T>(
rule: Rule,
criteria: object | object[],
trustRule = false
): Promise<T> {
return RulePilot._rulePilot.evaluate<T>(rule, criteria, trustRule);
}
/**
* Takes in a rule as a parameter and returns a ValidationResult
* indicating whether the rule is valid or not.
*
* Invalid rules will contain an error property which contains a message and the element
* that caused the validation to fail.
*
* @param rule The rule to validate.
*/
static validate(rule: Rule): ValidationResult {
return RulePilot._rulePilot.validate(rule);
}
/**
* Adds a mutation.
*
* Mutations allow for the modification of the criteria before
* it is evaluated against a rule.
*
* @param name The name of the mutation.
* @param mutation The mutation function.
*/
static addMutation(name: string, mutation: Function): RulePilot {
return RulePilot._rulePilot.addMutation(name, mutation);
}
/**
* Removes a mutation to the rule pilot instance.
* Any cached mutation values for this mutation will be purged.
*
* @param name The name of the mutation.
*/
static removeMutation(name: string): RulePilot {
return RulePilot._rulePilot.removeMutation(name);
}
/**
* Clears the mutator cache.
* The entire cache, or cache for a specific mutator, can be cleared
* by passing or omitting the mutator name as an argument.
*
* @param name The mutator name to clear the cache for.
*/
static clearMutationCache(name?: string): RulePilot {
return RulePilot._rulePilot.clearMutationCache(name);
}
}
| src/services/rule-pilot.ts | andrewbrg-rulepilot-517f473 | [
{
"filename": "src/services/builder.ts",
"retrieved_chunk": " this.rule.default = value;\n return this;\n }\n /**\n * Builds the rule being and returns it\n * @param validate Whether to validate the rule before returning it\n * @throws Error if validation is enabled and the rule is invalid\n */\n build(validate?: boolean): Rule {\n if (!validate) {",
"score": 33.38060336845669
},
{
"filename": "src/services/evaluator.ts",
"retrieved_chunk": " * @param rule The rule to evaluate.\n * @param criteria The criteria to evaluate the rule against.\n */\n evaluate(rule: Rule, criteria: object | object[]): boolean | any {\n // Cater for the case where the conditions property is not an array.\n const conditions =\n rule.conditions instanceof Array ? rule.conditions : [rule.conditions];\n if (criteria instanceof Array) {\n const result = [];\n for (const c of criteria) {",
"score": 32.64642532351573
},
{
"filename": "src/services/evaluator.ts",
"retrieved_chunk": " result.push(this.evaluateRule(conditions, c, rule?.default));\n }\n return result;\n }\n return this.evaluateRule(conditions, criteria, rule?.default);\n }\n /**\n * Evaluates a rule against a set of criteria and returns the result.\n * @param conditions The conditions to evaluate.\n * @param criteria The criteria to evaluate the conditions against.",
"score": 27.128227953684185
},
{
"filename": "src/services/evaluator.ts",
"retrieved_chunk": " * Evaluates a condition against a set of criteria and returns the result.\n * Uses recursion to evaluate nested conditions.\n * @param condition The condition to evaluate.\n * @param criteria The criteria to evaluate the condition against.\n */\n private evaluateCondition(condition: Condition, criteria: object): boolean {\n // The condition must have an 'any' or 'all' property.\n const type = this._objectDiscovery.conditionType(condition);\n if (!type) {\n return false;",
"score": 21.790123299616273
},
{
"filename": "src/services/evaluator.ts",
"retrieved_chunk": "import { ObjectDiscovery } from \"./object-discovery\";\nimport { Condition, Constraint, Rule } from \"../types/rule\";\nexport class Evaluator {\n private _objectDiscovery: ObjectDiscovery = new ObjectDiscovery();\n /**\n * Evaluates a rule against a set of criteria and returns the result.\n * If the criteria is an array (indicating multiple criteria to test),\n * the rule will be evaluated against each item in the array and\n * an array of results will be returned.\n *",
"score": 20.711408491790483
}
] | typescript | Rule,
criteria: object | object[],
trustRule = false
): Promise<T> { |
import { ObjectDiscovery } from "./object-discovery";
import { Condition, Constraint, Operator, Rule } from "../types/rule";
export interface ValidationResult {
isValid: boolean;
error?: {
message: string;
element: object;
};
}
export class Validator {
private objectDiscovery: ObjectDiscovery = new ObjectDiscovery();
/**
* Takes in a rule as a parameter and returns a boolean indicating whether the rule is valid or not.
* @param rule The rule to validate.
*/
validate(rule: Rule): ValidationResult {
// Assume the rule is valid.
let result: ValidationResult = { isValid: true };
// Check the rule is a valid JSON
if (!this.objectDiscovery.isObject(rule)) {
return {
isValid: false,
error: {
message: "The rule must be a valid JSON object.",
element: rule,
},
};
}
// Cater for the case where the conditions property is not an array.
const conditions =
rule.conditions instanceof Array ? rule.conditions : [rule.conditions];
// Validate the 'conditions' property.
if (
conditions.length === 0 ||
(this.objectDiscovery.isObject(conditions[0]) &&
!Object.keys(conditions[0]).length)
) {
return {
isValid: false,
error: {
message:
"The conditions property must contain at least one condition.",
element: rule,
},
};
}
// Validate each condition in the rule.
for (const condition of conditions) {
const subResult = this.validateCondition(condition);
result.isValid = result.isValid && subResult.isValid;
result.error = result?.error ?? subResult?.error;
}
return result;
}
/** ml/l.k,
* Evaluates a condition to ensure it is syntactically correct.
* @param condition The condition to validate.
* @param depth The current recursion depth
*/
private validateCondition(
condition: Condition,
depth: number = 0
): ValidationResult {
// Check to see if the condition is valid.
let result = this.isValidCondition(condition);
if (!result.isValid) {
return result;
}
// Set the type of condition.
const type = this.objectDiscovery.conditionType(condition);
// Check if the condition is iterable
if(!Array.isArray(condition[type])) {
return {
isValid: false,
error: {
message: `The condition '${type}' should be iterable.`,
element: condition,
},
};
}
// Validate each item in the condition.
for (const node of condition[type]) {
const isCondition = this.objectDiscovery.isCondition(node);
if (isCondition) {
const subResult = this.validateCondition(node as Condition, depth + 1);
result.isValid = result.isValid && subResult.isValid;
result.error = result?.error ?? subResult?.error;
}
const isConstraint = this.objectDiscovery.isConstraint(node);
if (isConstraint) {
| const subResult = this.validateConstraint(node as Constraint); |
result.isValid = result.isValid && subResult.isValid;
result.error = result?.error ?? subResult?.error;
}
if (!isConstraint && !isCondition) {
return {
isValid: false,
error: {
message: "Each node should be a condition or constraint.",
element: node,
},
};
}
// Result is only valid on the root condition.
if (depth > 0 && "result" in condition) {
return {
isValid: false,
error: {
message: 'Nested conditions cannot have a property "result".',
element: node,
},
};
}
// If any part fails validation there is no point to continue.
if (!result.isValid) {
break;
}
}
return result;
}
/**
* Checks a constraint to ensure it is syntactically correct.
* @param constraint The constraint to validate.
*/
private validateConstraint(constraint: Constraint): ValidationResult {
if ("string" !== typeof constraint.field) {
return {
isValid: false,
error: {
message: 'Constraint "field" must be of type string.',
element: constraint,
},
};
}
const operators = ["==", "!=", ">", "<", ">=", "<=", "in", "not in"];
if (!operators.includes(constraint.operator as Operator)) {
return {
isValid: false,
error: {
message: 'Constraint "operator" has invalid type.',
element: constraint,
},
};
}
// We must check that the value is an array if the operator is 'in' or 'not in'.
if (
["in", "not in"].includes(constraint.operator) &&
!Array.isArray(constraint.value)
) {
return {
isValid: false,
error: {
message:
'Constraint "value" must be an array if the "operator" is "in" or "not in"',
element: constraint,
},
};
}
return { isValid: true };
}
/**
* Checks an object to see if it is a valid condition.
* @param obj The object to check.
*/
private isValidCondition(obj: any): ValidationResult {
if (!this.objectDiscovery.isCondition(obj)) {
return {
isValid: false,
error: {
message: "Invalid condition structure.",
element: obj,
},
};
}
const isAny = "any" in obj;
const isAll = "all" in obj;
const isNone = "none" in obj;
// A valid condition must have an 'any', 'all', or 'none' property,
// but cannot have more than one.
if ((isAny && isAll) || (isAny && isNone) || (isAll && isNone)) {
return {
isValid: false,
error: {
message:
'A condition cannot have more than one "any", "all", or "none" property.',
element: obj,
},
};
}
return { isValid: true };
}
}
| src/services/validator.ts | andrewbrg-rulepilot-517f473 | [
{
"filename": "src/services/evaluator.ts",
"retrieved_chunk": " if (this._objectDiscovery.isConstraint(node)) {\n fn = \"checkConstraint\";\n }\n // Process the node\n switch (type) {\n case \"any\":\n result = result || this[fn](node, criteria);\n break;\n case \"all\":\n result = result && this[fn](node, criteria);",
"score": 43.52157394585594
},
{
"filename": "src/services/evaluator.ts",
"retrieved_chunk": " }\n // If the type is 'all' or 'none', we should set the initial\n // result to true, otherwise we should set it to false.\n let result = [\"all\", \"none\"].includes(type);\n // Check each node in the condition.\n for (const node of condition[type]) {\n let fn;\n if (this._objectDiscovery.isCondition(node)) {\n fn = \"evaluateCondition\";\n }",
"score": 43.08643190654824
},
{
"filename": "src/services/builder.ts",
"retrieved_chunk": " return this.rule;\n }\n const validationResult = this.validator.validate(this.rule);\n if (validationResult.isValid) {\n return this.rule;\n }\n throw new RuleError(validationResult);\n }\n /**\n * Creates a new condition node",
"score": 39.2067431893494
},
{
"filename": "src/services/builder.ts",
"retrieved_chunk": " * @param type The type of condition\n * @param nodes Any child nodes of the condition\n * @param result The result of the condition node (for granular rules)\n */\n condition(\n type: ConditionType,\n nodes: Condition[ConditionType],\n result?: Condition[\"result\"]\n ): Condition {\n return {",
"score": 26.75806394249811
},
{
"filename": "src/services/builder.ts",
"retrieved_chunk": " */\n add(node: Condition): Builder {\n (this.rule.conditions as Condition[]).push(node);\n return this;\n }\n /**\n * Sets the default value of the rule being constructed\n * @param value The default value of the rule\n */\n default(value: Rule[\"default\"]): Builder {",
"score": 24.90894865796377
}
] | typescript | const subResult = this.validateConstraint(node as Constraint); |
import http from "node:http";
import { sendJsonResponse, md5, uuid, parseSimplePostData } from "../common/utils";
import { ERROR } from "../common/const";
import { User } from "../common/types";
import UserModel from "../models/UserModel";
import Token from "../lib/GenerateToken";
import isEmailValid from "../lib/isEmailValid";
export default async function (
req: http.IncomingMessage,
res: http.ServerResponse
) {
const DB = new UserModel();
if (req.method !== "POST") {
sendJsonResponse(res, ERROR.methodNotAllowed, 405);
return;
}
let data: any = await parseSimplePostData(req);
data = data.toString();
let parsedData: User;
try {
parsedData = JSON.parse(data === "" ? '{}' : data);
} catch {
sendJsonResponse(res, ERROR.invalidJSONData, 400)
return;
}
if (!parsedData.email || !parsedData.password) {
sendJsonResponse(res, ERROR.badRequest, 400);
return;
}
if (!isEmailValid(parsedData.email)) {
sendJsonResponse(res, ERROR.badRequest, 400);
return;
}
await DB.init();
let foundUser = await DB.getUser(parsedData.email);
if (foundUser) {
sendJsonResponse(res, ERROR.userAlreadyExists, 409)
return;
}
let user: User = {
id: uuid(),
email: parsedData.email,
password: md5(parsedData.password),
}
const token = new Token();
let pushed = await DB.pushUser(user)
const { password, ...tokenBody} = user;
let accessToken = token.generate(tokenBody);
if (pushed !== null) {
sendJsonResponse(res, {
status: 201,
message: "successfully created new user",
error: null,
token: accessToken,
data: {
email: user.email,
| id: user.id
} |
}, 201)
} else {
sendJsonResponse(res, ERROR.internalErr, 500);
}
await DB.close();
}
| src/routes/Signup.ts | Aadv1k-quillia-52c5b34 | [
{
"filename": "src/routes/Issue.ts",
"retrieved_chunk": " sendJsonResponse(\n res,\n {\n error: null,\n message: `successfully created a new issue of id ${issueEntry.id}`,\n data: {\n id: pushed.id,\n borrower: pushed.borrowerid,\n lender: pushed.lenderid,\n book: foundBook.title,",
"score": 26.856812598959547
},
{
"filename": "src/routes/Login.ts",
"retrieved_chunk": " status: 200,\n error: null,\n token: accessToken,\n data: {\n email: foundUser.email,\n id: foundUser.id,\n }\n }, 200)\n}",
"score": 26.378143800630045
},
{
"filename": "src/models/UserModel.ts",
"retrieved_chunk": " await this.client.query(`DELETE FROM users WHERE id = $1 OR email = $2`, [user.id, user.email]);\n return user;\n } catch (error) {\n throw error;\n }\n }\n async pushUser(user: User): Promise<User | void> {\n try {\n await this.client.query(\"INSERT INTO users (id, email, password) VALUES ($1, $2, $3)\", [user.id, user.email, user.password]);\n return user;",
"score": 23.651754980488324
},
{
"filename": "src/routes/Books.ts",
"retrieved_chunk": " if (!pushed) {\n sendJsonResponse(res, ERROR.internalErr, 500);\n return;\n }\n sendJsonResponse(\n res,\n {\n error: null,\n message: `successfully published a book of id ${epubEntry.id}`,\n data: {",
"score": 21.080566017598635
},
{
"filename": "src/routes/Books.ts",
"retrieved_chunk": " status: 404\n }, 404)\n return;\n }\n sendJsonResponse(res, {\n error: null,\n message: `successfully deleted book of id ${data.bookid}`,\n status: 204,\n data: {\n id: data.bookid,",
"score": 19.93666015545607
}
] | typescript | id: user.id
} |
import {
Rule,
Operator,
Condition,
Constraint,
ConditionType,
} from "../types/rule";
import { Validator } from "./validator";
import { RuleError } from "../types/error";
export class Builder {
constructor(validator: Validator) {
this.validator = validator;
}
/** Stores to rule being constructed */
private rule: Rule = { conditions: [] };
/** Holds a reference to the Validator class */
private validator: Validator;
/**
* Adds a node (in the root) to the rule being constructed
* @param node The node to add to the rule
*/
add(node: Condition): Builder {
(this.rule.conditions as Condition[]).push(node);
return this;
}
/**
* Sets the default value of the rule being constructed
* @param value The default value of the rule
*/
default(value: Rule["default"]): Builder {
this.rule.default = value;
return this;
}
/**
* Builds the rule being and returns it
* @param validate Whether to validate the rule before returning it
* @throws Error if validation is enabled and the rule is invalid
*/
build(validate?: boolean): Rule {
if (!validate) {
return this.rule;
}
| const validationResult = this.validator.validate(this.rule); |
if (validationResult.isValid) {
return this.rule;
}
throw new RuleError(validationResult);
}
/**
* Creates a new condition node
* @param type The type of condition
* @param nodes Any child nodes of the condition
* @param result The result of the condition node (for granular rules)
*/
condition(
type: ConditionType,
nodes: Condition[ConditionType],
result?: Condition["result"]
): Condition {
return {
[type]: nodes,
...(result ? { result } : {}),
};
}
/**
* Creates a new constraint node
* @param field The field to apply the constraint to
* @param operator The operator to apply to the field
* @param value The value to compare the field to
*/
constraint(
field: string,
operator: Operator,
value: Constraint["value"]
): Constraint {
return {
field,
operator,
value,
};
}
}
| src/services/builder.ts | andrewbrg-rulepilot-517f473 | [
{
"filename": "src/services/rule-pilot.ts",
"retrieved_chunk": " * @throws Error if the rule is invalid.\n */\n async evaluate<T>(\n rule: Rule,\n criteria: object | object[],\n trustRule = false\n ): Promise<T> {\n // Before we evaluate the rule, we should validate it.\n // If `trustRuleset` is set to true, we will skip validation.\n const validationResult = !trustRule && this.validate(rule);",
"score": 48.60631660794263
},
{
"filename": "src/services/rule-pilot.ts",
"retrieved_chunk": " * that caused the validation to fail.\n *\n * @param rule The rule to validate.\n */\n validate(rule: Rule): ValidationResult {\n return this._validator.validate(rule);\n }\n /**\n * Returns a rule builder class instance.\n * Allows for the construction of rules using a fluent interface.",
"score": 38.43166379182097
},
{
"filename": "src/services/rule-pilot.ts",
"retrieved_chunk": " */\n static validate(rule: Rule): ValidationResult {\n return RulePilot._rulePilot.validate(rule);\n }\n /**\n * Adds a mutation.\n *\n * Mutations allow for the modification of the criteria before\n * it is evaluated against a rule.\n *",
"score": 38.092588665136645
},
{
"filename": "src/services/validator.ts",
"retrieved_chunk": " private objectDiscovery: ObjectDiscovery = new ObjectDiscovery();\n /**\n * Takes in a rule as a parameter and returns a boolean indicating whether the rule is valid or not.\n * @param rule The rule to validate.\n */\n validate(rule: Rule): ValidationResult {\n // Assume the rule is valid.\n let result: ValidationResult = { isValid: true };\n // Check the rule is a valid JSON\n if (!this.objectDiscovery.isObject(rule)) {",
"score": 35.8089393576707
},
{
"filename": "src/services/rule-pilot.ts",
"retrieved_chunk": " return RulePilot._rulePilot.evaluate<T>(rule, criteria, trustRule);\n }\n /**\n * Takes in a rule as a parameter and returns a ValidationResult\n * indicating whether the rule is valid or not.\n *\n * Invalid rules will contain an error property which contains a message and the element\n * that caused the validation to fail.\n *\n * @param rule The rule to validate.",
"score": 30.054437459012696
}
] | typescript | const validationResult = this.validator.validate(this.rule); |
import { Builder } from "./builder";
import { Mutator } from "./mutator";
import { Evaluator } from "./evaluator";
import { ValidationResult, Validator } from "./validator";
import { Rule } from "../types/rule";
import { RuleError } from "../types/error";
export class RulePilot {
private static _rulePilot = new RulePilot();
private _mutator: Mutator = new Mutator();
private _validator: Validator = new Validator();
private _evaluator: Evaluator = new Evaluator();
/**
* Returns a rule builder class instance.
* Allows for the construction of rules using a fluent interface.
*/
builder(): Builder {
return new Builder(this._validator);
}
/**
* Adds a mutation to the rule pilot instance.
* Mutations allow for the modification of the criteria before
* it is evaluated against a rule.
*
* @param name The name of the mutation.
* @param mutation The mutation function.
*/
addMutation(name: string, mutation: Function): RulePilot {
this._mutator.add(name, mutation);
return this;
}
/**
* Removes a mutation to the rule pilot instance.
* Any cached mutation values for this mutation will be purged.
*
* @param name The name of the mutation.
*/
removeMutation(name: string): RulePilot {
this._mutator.remove(name);
return this;
}
/**
* Clears the mutator cache.
* The entire cache, or cache for a specific mutator, can be cleared
* by passing or omitting the mutator name as an argument.
*
* @param name The mutator name to clear the cache for.
*/
clearMutationCache(name?: string): RulePilot {
this._mutator.clearCache(name);
return this;
}
/**
* Evaluates a rule against a set of criteria and returns the result.
* If the criteria is an array (indicating multiple criteria to test),
* the rule will be evaluated against each item in the array and
* an array of results will be returned.
*
* @param rule The rule to evaluate.
* @param criteria The criteria to evaluate the rule against.
* @param trustRule Set true to avoid validating the rule before evaluating it (faster).
* @throws Error if the rule is invalid.
*/
async evaluate<T>(
rule: Rule,
criteria: object | object[],
trustRule = false
): Promise<T> {
// Before we evaluate the rule, we should validate it.
// If `trustRuleset` is set to true, we will skip validation.
const validationResult = !trustRule && this.validate(rule);
if (!trustRule && !validationResult.isValid) {
throw new RuleError(validationResult);
}
return this._evaluator.evaluate(rule, await this._mutator.mutate(criteria));
}
/**
* Takes in a rule as a parameter and returns a ValidationResult
* indicating whether the rule is valid or not.
*
* Invalid rules will contain an error property which contains a message and the element
* that caused the validation to fail.
*
* @param rule The rule to validate.
*/
validate(rule: Rule): ValidationResult {
return this._validator.validate(rule);
}
/**
* Returns a rule builder class instance.
* Allows for the construction of rules using a fluent interface.
*/
static builder(): Builder {
return this._rulePilot.builder();
}
/**
* Evaluates a rule against a set of criteria and returns the result.
* If the criteria is an array (indicating multiple criteria to test),
* the rule will be evaluated against each item in the array and
* an array of results will be returned.
*
* @param rule The rule to evaluate.
* @param criteria The criteria to evaluate the rule against.
* @param trustRule Set true to avoid validating the rule before evaluating it (faster).
* @throws Error if the rule is invalid.
*/
static async evaluate<T>(
rule: Rule,
criteria: object | object[],
trustRule = false
): Promise<T> {
return RulePilot._rulePilot.evaluate<T>(rule, criteria, trustRule);
}
/**
* Takes in a rule as a parameter and returns a ValidationResult
* indicating whether the rule is valid or not.
*
* Invalid rules will contain an error property which contains a message and the element
* that caused the validation to fail.
*
* @param rule The rule to validate.
*/
| static validate(rule: Rule): ValidationResult { |
return RulePilot._rulePilot.validate(rule);
}
/**
* Adds a mutation.
*
* Mutations allow for the modification of the criteria before
* it is evaluated against a rule.
*
* @param name The name of the mutation.
* @param mutation The mutation function.
*/
static addMutation(name: string, mutation: Function): RulePilot {
return RulePilot._rulePilot.addMutation(name, mutation);
}
/**
* Removes a mutation to the rule pilot instance.
* Any cached mutation values for this mutation will be purged.
*
* @param name The name of the mutation.
*/
static removeMutation(name: string): RulePilot {
return RulePilot._rulePilot.removeMutation(name);
}
/**
* Clears the mutator cache.
* The entire cache, or cache for a specific mutator, can be cleared
* by passing or omitting the mutator name as an argument.
*
* @param name The mutator name to clear the cache for.
*/
static clearMutationCache(name?: string): RulePilot {
return RulePilot._rulePilot.clearMutationCache(name);
}
}
| src/services/rule-pilot.ts | andrewbrg-rulepilot-517f473 | [
{
"filename": "src/services/validator.ts",
"retrieved_chunk": " private objectDiscovery: ObjectDiscovery = new ObjectDiscovery();\n /**\n * Takes in a rule as a parameter and returns a boolean indicating whether the rule is valid or not.\n * @param rule The rule to validate.\n */\n validate(rule: Rule): ValidationResult {\n // Assume the rule is valid.\n let result: ValidationResult = { isValid: true };\n // Check the rule is a valid JSON\n if (!this.objectDiscovery.isObject(rule)) {",
"score": 56.683059562418066
},
{
"filename": "src/services/builder.ts",
"retrieved_chunk": " this.rule.default = value;\n return this;\n }\n /**\n * Builds the rule being and returns it\n * @param validate Whether to validate the rule before returning it\n * @throws Error if validation is enabled and the rule is invalid\n */\n build(validate?: boolean): Rule {\n if (!validate) {",
"score": 36.947566891805614
},
{
"filename": "src/services/evaluator.ts",
"retrieved_chunk": "import { ObjectDiscovery } from \"./object-discovery\";\nimport { Condition, Constraint, Rule } from \"../types/rule\";\nexport class Evaluator {\n private _objectDiscovery: ObjectDiscovery = new ObjectDiscovery();\n /**\n * Evaluates a rule against a set of criteria and returns the result.\n * If the criteria is an array (indicating multiple criteria to test),\n * the rule will be evaluated against each item in the array and\n * an array of results will be returned.\n *",
"score": 30.980101813780507
},
{
"filename": "src/services/validator.ts",
"retrieved_chunk": " return {\n isValid: false,\n error: {\n message: \"The rule must be a valid JSON object.\",\n element: rule,\n },\n };\n }\n // Cater for the case where the conditions property is not an array.\n const conditions =",
"score": 26.703669315290092
},
{
"filename": "src/services/evaluator.ts",
"retrieved_chunk": " result.push(this.evaluateRule(conditions, c, rule?.default));\n }\n return result;\n }\n return this.evaluateRule(conditions, criteria, rule?.default);\n }\n /**\n * Evaluates a rule against a set of criteria and returns the result.\n * @param conditions The conditions to evaluate.\n * @param criteria The criteria to evaluate the conditions against.",
"score": 22.97677276638769
}
] | typescript | static validate(rule: Rule): ValidationResult { |
import { ObjectDiscovery } from "./object-discovery";
import { Condition, Constraint, Rule } from "../types/rule";
export class Evaluator {
private _objectDiscovery: ObjectDiscovery = new ObjectDiscovery();
/**
* Evaluates a rule against a set of criteria and returns the result.
* If the criteria is an array (indicating multiple criteria to test),
* the rule will be evaluated against each item in the array and
* an array of results will be returned.
*
* @param rule The rule to evaluate.
* @param criteria The criteria to evaluate the rule against.
*/
evaluate(rule: Rule, criteria: object | object[]): boolean | any {
// Cater for the case where the conditions property is not an array.
const conditions =
rule.conditions instanceof Array ? rule.conditions : [rule.conditions];
if (criteria instanceof Array) {
const result = [];
for (const c of criteria) {
result.push(this.evaluateRule(conditions, c, rule?.default));
}
return result;
}
return this.evaluateRule(conditions, criteria, rule?.default);
}
/**
* Evaluates a rule against a set of criteria and returns the result.
* @param conditions The conditions to evaluate.
* @param criteria The criteria to evaluate the conditions against.
* @param defaultResult The default result to return if no conditions pass.
*/
private evaluateRule(
conditions: Condition[],
criteria: object,
defaultResult?: any
): boolean | any {
// We should evaluate all conditions and return the result
// of the first condition that passes.
for (const condition of conditions) {
const result = this.evaluateCondition(condition, criteria);
if (result) {
return condition?.result ?? true;
}
}
// If no conditions pass, we should return the default result of
// the rule or false if no default result is provided.
return defaultResult ?? false;
}
/**
* Evaluates a condition against a set of criteria and returns the result.
* Uses recursion to evaluate nested conditions.
* @param condition The condition to evaluate.
* @param criteria The criteria to evaluate the condition against.
*/
private evaluateCondition(condition: Condition, criteria: object): boolean {
// The condition must have an 'any' or 'all' property.
const type = this._objectDiscovery.conditionType(condition);
if (!type) {
return false;
}
// If the type is 'all' or 'none', we should set the initial
// result to true, otherwise we should set it to false.
let result = ["all", "none"].includes(type);
// Check each node in the condition.
for (const node of condition[type]) {
let fn;
if (this._objectDiscovery.isCondition(node)) {
fn = "evaluateCondition";
}
if (this._objectDiscovery.isConstraint(node)) {
fn = "checkConstraint";
}
// Process the node
switch (type) {
case "any":
result = result || this[fn](node, criteria);
break;
case "all":
result = result && this[fn](node, criteria);
break;
case "none":
result = result && !this[fn](node, criteria);
}
}
return result;
}
/**
* Checks a constraint against a set of criteria and returns true whenever the constraint passes.
* @param constraint The constraint to evaluate.
* @param criteria The criteria to evaluate the constraint with.
*/
private checkConstraint(constraint: Constraint, criteria: object): boolean {
// If the value contains '.' we should assume it is a nested property
const criterion = constraint.field.includes(".")
| ? this._objectDiscovery.resolveNestedProperty(constraint.field, criteria)
: criteria[constraint.field]; |
// If the criteria object does not have the field
// we are looking for, we should return false.
if (!criterion) {
return false;
}
switch (constraint.operator) {
case "==":
return criterion == constraint.value;
case "!=":
return criterion != constraint.value;
case ">":
return criterion > constraint.value;
case ">=":
return criterion >= constraint.value;
case "<":
return criterion < constraint.value;
case "<=":
return criterion <= constraint.value;
case "in":
return (
Array.isArray(constraint.value) &&
constraint.value.includes(criterion as never)
);
case "not in":
return (
!Array.isArray(constraint.value) ||
!constraint.value.includes(criterion as never)
);
default:
return false;
}
}
}
| src/services/evaluator.ts | andrewbrg-rulepilot-517f473 | [
{
"filename": "src/services/validator.ts",
"retrieved_chunk": " /**\n * Checks a constraint to ensure it is syntactically correct.\n * @param constraint The constraint to validate.\n */\n private validateConstraint(constraint: Constraint): ValidationResult {\n if (\"string\" !== typeof constraint.field) {\n return {\n isValid: false,\n error: {\n message: 'Constraint \"field\" must be of type string.',",
"score": 57.96582849110094
},
{
"filename": "src/services/builder.ts",
"retrieved_chunk": " [type]: nodes,\n ...(result ? { result } : {}),\n };\n }\n /**\n * Creates a new constraint node\n * @param field The field to apply the constraint to\n * @param operator The operator to apply to the field\n * @param value The value to compare the field to\n */",
"score": 50.06215721428386
},
{
"filename": "src/services/builder.ts",
"retrieved_chunk": " constraint(\n field: string,\n operator: Operator,\n value: Constraint[\"value\"]\n ): Constraint {\n return {\n field,\n operator,\n value,\n };",
"score": 45.202607682741856
},
{
"filename": "src/services/validator.ts",
"retrieved_chunk": " element: constraint,\n },\n };\n }\n // We must check that the value is an array if the operator is 'in' or 'not in'.\n if (\n [\"in\", \"not in\"].includes(constraint.operator) &&\n !Array.isArray(constraint.value)\n ) {\n return {",
"score": 41.38764338933536
},
{
"filename": "src/services/object-discovery.ts",
"retrieved_chunk": " }\n /**\n * Checks an object to see if it is a valid constraint.\n * @param obj The object to check.\n */\n isConstraint(obj: unknown): obj is Constraint {\n return !this.isObject(obj)\n ? false\n : \"field\" in obj && \"operator\" in obj && \"value\" in obj;\n }",
"score": 38.078354529030356
}
] | typescript | ? this._objectDiscovery.resolveNestedProperty(constraint.field, criteria)
: criteria[constraint.field]; |
import { ObjectDiscovery } from "./object-discovery";
import { Condition, Constraint, Rule } from "../types/rule";
export class Evaluator {
private _objectDiscovery: ObjectDiscovery = new ObjectDiscovery();
/**
* Evaluates a rule against a set of criteria and returns the result.
* If the criteria is an array (indicating multiple criteria to test),
* the rule will be evaluated against each item in the array and
* an array of results will be returned.
*
* @param rule The rule to evaluate.
* @param criteria The criteria to evaluate the rule against.
*/
evaluate(rule: Rule, criteria: object | object[]): boolean | any {
// Cater for the case where the conditions property is not an array.
const conditions =
rule.conditions instanceof Array ? rule.conditions : [rule.conditions];
if (criteria instanceof Array) {
const result = [];
for (const c of criteria) {
result.push(this.evaluateRule(conditions, c, rule?.default));
}
return result;
}
return this.evaluateRule(conditions, criteria, rule?.default);
}
/**
* Evaluates a rule against a set of criteria and returns the result.
* @param conditions The conditions to evaluate.
* @param criteria The criteria to evaluate the conditions against.
* @param defaultResult The default result to return if no conditions pass.
*/
private evaluateRule(
conditions: Condition[],
criteria: object,
defaultResult?: any
): boolean | any {
// We should evaluate all conditions and return the result
// of the first condition that passes.
for (const condition of conditions) {
const result = this.evaluateCondition(condition, criteria);
if (result) {
return condition?.result ?? true;
}
}
// If no conditions pass, we should return the default result of
// the rule or false if no default result is provided.
return defaultResult ?? false;
}
/**
* Evaluates a condition against a set of criteria and returns the result.
* Uses recursion to evaluate nested conditions.
* @param condition The condition to evaluate.
* @param criteria The criteria to evaluate the condition against.
*/
private evaluateCondition(condition: Condition, criteria: object): boolean {
// The condition must have an 'any' or 'all' property.
const type = this._objectDiscovery.conditionType(condition);
if (!type) {
return false;
}
// If the type is 'all' or 'none', we should set the initial
// result to true, otherwise we should set it to false.
let result = ["all", "none"].includes(type);
// Check each node in the condition.
for (const node of condition[type]) {
let fn;
| if (this._objectDiscovery.isCondition(node)) { |
fn = "evaluateCondition";
}
if (this._objectDiscovery.isConstraint(node)) {
fn = "checkConstraint";
}
// Process the node
switch (type) {
case "any":
result = result || this[fn](node, criteria);
break;
case "all":
result = result && this[fn](node, criteria);
break;
case "none":
result = result && !this[fn](node, criteria);
}
}
return result;
}
/**
* Checks a constraint against a set of criteria and returns true whenever the constraint passes.
* @param constraint The constraint to evaluate.
* @param criteria The criteria to evaluate the constraint with.
*/
private checkConstraint(constraint: Constraint, criteria: object): boolean {
// If the value contains '.' we should assume it is a nested property
const criterion = constraint.field.includes(".")
? this._objectDiscovery.resolveNestedProperty(constraint.field, criteria)
: criteria[constraint.field];
// If the criteria object does not have the field
// we are looking for, we should return false.
if (!criterion) {
return false;
}
switch (constraint.operator) {
case "==":
return criterion == constraint.value;
case "!=":
return criterion != constraint.value;
case ">":
return criterion > constraint.value;
case ">=":
return criterion >= constraint.value;
case "<":
return criterion < constraint.value;
case "<=":
return criterion <= constraint.value;
case "in":
return (
Array.isArray(constraint.value) &&
constraint.value.includes(criterion as never)
);
case "not in":
return (
!Array.isArray(constraint.value) ||
!constraint.value.includes(criterion as never)
);
default:
return false;
}
}
}
| src/services/evaluator.ts | andrewbrg-rulepilot-517f473 | [
{
"filename": "src/services/validator.ts",
"retrieved_chunk": " condition: Condition,\n depth: number = 0\n ): ValidationResult {\n // Check to see if the condition is valid.\n let result = this.isValidCondition(condition);\n if (!result.isValid) {\n return result;\n }\n // Set the type of condition.\n const type = this.objectDiscovery.conditionType(condition);",
"score": 37.18074898212566
},
{
"filename": "src/services/validator.ts",
"retrieved_chunk": " // Validate each item in the condition.\n for (const node of condition[type]) {\n const isCondition = this.objectDiscovery.isCondition(node);\n if (isCondition) {\n const subResult = this.validateCondition(node as Condition, depth + 1);\n result.isValid = result.isValid && subResult.isValid;\n result.error = result?.error ?? subResult?.error;\n }\n const isConstraint = this.objectDiscovery.isConstraint(node);\n if (isConstraint) {",
"score": 36.585478632383875
},
{
"filename": "src/services/validator.ts",
"retrieved_chunk": " // Check if the condition is iterable\n if(!Array.isArray(condition[type])) {\n return {\n isValid: false,\n error: {\n message: `The condition '${type}' should be iterable.`,\n element: condition,\n },\n };\n }",
"score": 34.508060892216825
},
{
"filename": "src/services/builder.ts",
"retrieved_chunk": " * @param type The type of condition\n * @param nodes Any child nodes of the condition\n * @param result The result of the condition node (for granular rules)\n */\n condition(\n type: ConditionType,\n nodes: Condition[ConditionType],\n result?: Condition[\"result\"]\n ): Condition {\n return {",
"score": 32.68143970505211
},
{
"filename": "src/services/object-discovery.ts",
"retrieved_chunk": "import { Condition, ConditionType, Constraint } from \"../types/rule\";\nexport class ObjectDiscovery {\n /**\n * Returns the type of condition passed to the function.\n * @param condition The condition to check.\n */\n conditionType(condition: Condition): ConditionType | null {\n if (\"any\" in condition) return \"any\";\n if (\"all\" in condition) return \"all\";\n if (\"none\" in condition) return \"none\";",
"score": 31.647475394255284
}
] | typescript | if (this._objectDiscovery.isCondition(node)) { |
import { ObjectDiscovery } from "./object-discovery";
import { Condition, Constraint, Operator, Rule } from "../types/rule";
export interface ValidationResult {
isValid: boolean;
error?: {
message: string;
element: object;
};
}
export class Validator {
private objectDiscovery: ObjectDiscovery = new ObjectDiscovery();
/**
* Takes in a rule as a parameter and returns a boolean indicating whether the rule is valid or not.
* @param rule The rule to validate.
*/
validate(rule: Rule): ValidationResult {
// Assume the rule is valid.
let result: ValidationResult = { isValid: true };
// Check the rule is a valid JSON
if (!this.objectDiscovery.isObject(rule)) {
return {
isValid: false,
error: {
message: "The rule must be a valid JSON object.",
element: rule,
},
};
}
// Cater for the case where the conditions property is not an array.
const conditions =
rule.conditions instanceof Array ? rule.conditions : [rule.conditions];
// Validate the 'conditions' property.
if (
conditions.length === 0 ||
(this.objectDiscovery.isObject(conditions[0]) &&
!Object.keys(conditions[0]).length)
) {
return {
isValid: false,
error: {
message:
"The conditions property must contain at least one condition.",
element: rule,
},
};
}
// Validate each condition in the rule.
for (const condition of conditions) {
const subResult = this.validateCondition(condition);
result.isValid = result.isValid && subResult.isValid;
result.error = result?.error ?? subResult?.error;
}
return result;
}
/** ml/l.k,
* Evaluates a condition to ensure it is syntactically correct.
* @param condition The condition to validate.
* @param depth The current recursion depth
*/
private validateCondition(
condition: Condition,
depth: number = 0
): ValidationResult {
// Check to see if the condition is valid.
let result = this.isValidCondition(condition);
if (!result.isValid) {
return result;
}
// Set the type of condition.
const type = this.objectDiscovery.conditionType(condition);
// Check if the condition is iterable
if(!Array.isArray(condition[type])) {
return {
isValid: false,
error: {
message: `The condition '${type}' should be iterable.`,
element: condition,
},
};
}
// Validate each item in the condition.
for (const node of condition[type]) {
const isCondition = this.objectDiscovery.isCondition(node);
if (isCondition) {
const subResult = this.validateCondition(node as Condition, depth + 1);
result.isValid = result.isValid && subResult.isValid;
result.error = result?.error ?? subResult?.error;
}
const isConstraint = this.objectDiscovery.isConstraint(node);
if (isConstraint) {
const subResult = this.validateConstraint(node as Constraint);
result.isValid = result.isValid && subResult.isValid;
result.error = result?.error ?? subResult?.error;
}
if (!isConstraint && !isCondition) {
return {
isValid: false,
error: {
message: "Each node should be a condition or constraint.",
element: node,
},
};
}
// Result is only valid on the root condition.
if (depth > 0 && "result" in condition) {
return {
isValid: false,
error: {
message: 'Nested conditions cannot have a property "result".',
element: node,
},
};
}
// If any part fails validation there is no point to continue.
if (!result.isValid) {
break;
}
}
return result;
}
/**
* Checks a constraint to ensure it is syntactically correct.
* @param constraint The constraint to validate.
*/
private validateConstraint(constraint: Constraint): ValidationResult {
if ("string" !== typeof constraint.field) {
return {
isValid: false,
error: {
message: 'Constraint "field" must be of type string.',
element: constraint,
},
};
}
const operators = ["==", "!=", ">", "<", ">=", "<=", "in", "not in"];
| if (!operators.includes(constraint.operator as Operator)) { |
return {
isValid: false,
error: {
message: 'Constraint "operator" has invalid type.',
element: constraint,
},
};
}
// We must check that the value is an array if the operator is 'in' or 'not in'.
if (
["in", "not in"].includes(constraint.operator) &&
!Array.isArray(constraint.value)
) {
return {
isValid: false,
error: {
message:
'Constraint "value" must be an array if the "operator" is "in" or "not in"',
element: constraint,
},
};
}
return { isValid: true };
}
/**
* Checks an object to see if it is a valid condition.
* @param obj The object to check.
*/
private isValidCondition(obj: any): ValidationResult {
if (!this.objectDiscovery.isCondition(obj)) {
return {
isValid: false,
error: {
message: "Invalid condition structure.",
element: obj,
},
};
}
const isAny = "any" in obj;
const isAll = "all" in obj;
const isNone = "none" in obj;
// A valid condition must have an 'any', 'all', or 'none' property,
// but cannot have more than one.
if ((isAny && isAll) || (isAny && isNone) || (isAll && isNone)) {
return {
isValid: false,
error: {
message:
'A condition cannot have more than one "any", "all", or "none" property.',
element: obj,
},
};
}
return { isValid: true };
}
}
| src/services/validator.ts | andrewbrg-rulepilot-517f473 | [
{
"filename": "src/services/builder.ts",
"retrieved_chunk": " constraint(\n field: string,\n operator: Operator,\n value: Constraint[\"value\"]\n ): Constraint {\n return {\n field,\n operator,\n value,\n };",
"score": 24.287561851480056
},
{
"filename": "src/types/rule.ts",
"retrieved_chunk": "export type ConditionType = \"any\" | \"all\" | \"none\";\nexport type Operator = \"==\" | \"!=\" | \">\" | \"<\" | \">=\" | \"<=\" | \"in\" | \"not in\";\nexport interface Constraint {\n field: string;\n operator: Operator;\n value:\n | string\n | number\n | boolean\n | object",
"score": 23.6994167233681
},
{
"filename": "src/services/evaluator.ts",
"retrieved_chunk": " case \"not in\":\n return (\n !Array.isArray(constraint.value) ||\n !constraint.value.includes(criterion as never)\n );\n default:\n return false;\n }\n }\n}",
"score": 21.451673127889578
},
{
"filename": "src/services/evaluator.ts",
"retrieved_chunk": " * @param criteria The criteria to evaluate the constraint with.\n */\n private checkConstraint(constraint: Constraint, criteria: object): boolean {\n // If the value contains '.' we should assume it is a nested property\n const criterion = constraint.field.includes(\".\")\n ? this._objectDiscovery.resolveNestedProperty(constraint.field, criteria)\n : criteria[constraint.field];\n // If the criteria object does not have the field\n // we are looking for, we should return false.\n if (!criterion) {",
"score": 18.996753894073628
},
{
"filename": "src/services/object-discovery.ts",
"retrieved_chunk": " }\n /**\n * Checks an object to see if it is a valid constraint.\n * @param obj The object to check.\n */\n isConstraint(obj: unknown): obj is Constraint {\n return !this.isObject(obj)\n ? false\n : \"field\" in obj && \"operator\" in obj && \"value\" in obj;\n }",
"score": 17.308947677071465
}
] | typescript | if (!operators.includes(constraint.operator as Operator)) { |
import { ObjectDiscovery } from "./object-discovery";
import { Condition, Constraint, Rule } from "../types/rule";
export class Evaluator {
private _objectDiscovery: ObjectDiscovery = new ObjectDiscovery();
/**
* Evaluates a rule against a set of criteria and returns the result.
* If the criteria is an array (indicating multiple criteria to test),
* the rule will be evaluated against each item in the array and
* an array of results will be returned.
*
* @param rule The rule to evaluate.
* @param criteria The criteria to evaluate the rule against.
*/
evaluate(rule: Rule, criteria: object | object[]): boolean | any {
// Cater for the case where the conditions property is not an array.
const conditions =
rule.conditions instanceof Array ? rule.conditions : [rule.conditions];
if (criteria instanceof Array) {
const result = [];
for (const c of criteria) {
result.push(this.evaluateRule(conditions, c, rule?.default));
}
return result;
}
return this.evaluateRule(conditions, criteria, rule?.default);
}
/**
* Evaluates a rule against a set of criteria and returns the result.
* @param conditions The conditions to evaluate.
* @param criteria The criteria to evaluate the conditions against.
* @param defaultResult The default result to return if no conditions pass.
*/
private evaluateRule(
conditions: Condition[],
criteria: object,
defaultResult?: any
): boolean | any {
// We should evaluate all conditions and return the result
// of the first condition that passes.
for (const condition of conditions) {
const result = this.evaluateCondition(condition, criteria);
if (result) {
return condition?.result ?? true;
}
}
// If no conditions pass, we should return the default result of
// the rule or false if no default result is provided.
return defaultResult ?? false;
}
/**
* Evaluates a condition against a set of criteria and returns the result.
* Uses recursion to evaluate nested conditions.
* @param condition The condition to evaluate.
* @param criteria The criteria to evaluate the condition against.
*/
private evaluateCondition(condition: Condition, criteria: object): boolean {
// The condition must have an 'any' or 'all' property.
| const type = this._objectDiscovery.conditionType(condition); |
if (!type) {
return false;
}
// If the type is 'all' or 'none', we should set the initial
// result to true, otherwise we should set it to false.
let result = ["all", "none"].includes(type);
// Check each node in the condition.
for (const node of condition[type]) {
let fn;
if (this._objectDiscovery.isCondition(node)) {
fn = "evaluateCondition";
}
if (this._objectDiscovery.isConstraint(node)) {
fn = "checkConstraint";
}
// Process the node
switch (type) {
case "any":
result = result || this[fn](node, criteria);
break;
case "all":
result = result && this[fn](node, criteria);
break;
case "none":
result = result && !this[fn](node, criteria);
}
}
return result;
}
/**
* Checks a constraint against a set of criteria and returns true whenever the constraint passes.
* @param constraint The constraint to evaluate.
* @param criteria The criteria to evaluate the constraint with.
*/
private checkConstraint(constraint: Constraint, criteria: object): boolean {
// If the value contains '.' we should assume it is a nested property
const criterion = constraint.field.includes(".")
? this._objectDiscovery.resolveNestedProperty(constraint.field, criteria)
: criteria[constraint.field];
// If the criteria object does not have the field
// we are looking for, we should return false.
if (!criterion) {
return false;
}
switch (constraint.operator) {
case "==":
return criterion == constraint.value;
case "!=":
return criterion != constraint.value;
case ">":
return criterion > constraint.value;
case ">=":
return criterion >= constraint.value;
case "<":
return criterion < constraint.value;
case "<=":
return criterion <= constraint.value;
case "in":
return (
Array.isArray(constraint.value) &&
constraint.value.includes(criterion as never)
);
case "not in":
return (
!Array.isArray(constraint.value) ||
!constraint.value.includes(criterion as never)
);
default:
return false;
}
}
}
| src/services/evaluator.ts | andrewbrg-rulepilot-517f473 | [
{
"filename": "src/services/rule-pilot.ts",
"retrieved_chunk": " }\n /**\n * Evaluates a rule against a set of criteria and returns the result.\n * If the criteria is an array (indicating multiple criteria to test),\n * the rule will be evaluated against each item in the array and\n * an array of results will be returned.\n *\n * @param rule The rule to evaluate.\n * @param criteria The criteria to evaluate the rule against.\n * @param trustRule Set true to avoid validating the rule before evaluating it (faster).",
"score": 38.35820629165303
},
{
"filename": "src/services/object-discovery.ts",
"retrieved_chunk": "import { Condition, ConditionType, Constraint } from \"../types/rule\";\nexport class ObjectDiscovery {\n /**\n * Returns the type of condition passed to the function.\n * @param condition The condition to check.\n */\n conditionType(condition: Condition): ConditionType | null {\n if (\"any\" in condition) return \"any\";\n if (\"all\" in condition) return \"all\";\n if (\"none\" in condition) return \"none\";",
"score": 36.60639493398283
},
{
"filename": "src/services/validator.ts",
"retrieved_chunk": " condition: Condition,\n depth: number = 0\n ): ValidationResult {\n // Check to see if the condition is valid.\n let result = this.isValidCondition(condition);\n if (!result.isValid) {\n return result;\n }\n // Set the type of condition.\n const type = this.objectDiscovery.conditionType(condition);",
"score": 34.68831295323084
},
{
"filename": "src/services/validator.ts",
"retrieved_chunk": " result.error = result?.error ?? subResult?.error;\n }\n return result;\n }\n /** ml/l.k,\n * Evaluates a condition to ensure it is syntactically correct.\n * @param condition The condition to validate.\n * @param depth The current recursion depth\n */\n private validateCondition(",
"score": 31.438410086188124
},
{
"filename": "src/services/validator.ts",
"retrieved_chunk": " message:\n \"The conditions property must contain at least one condition.\",\n element: rule,\n },\n };\n }\n // Validate each condition in the rule.\n for (const condition of conditions) {\n const subResult = this.validateCondition(condition);\n result.isValid = result.isValid && subResult.isValid;",
"score": 30.6866102112522
}
] | typescript | const type = this._objectDiscovery.conditionType(condition); |
import { createHash } from "crypto";
import { EventEmitter } from "events";
import { Logger } from "./logger";
import { ObjectDiscovery } from "./object-discovery";
export class Mutator {
private _cache: Map<string, any> = new Map();
private _buffer: Map<string, boolean> = new Map();
private _mutations: Map<string, Function> = new Map();
private _objectDiscovery = new ObjectDiscovery();
private _eventEmitter = new EventEmitter();
/**
* Adds a mutation to the mutator instance.
* @param name The name of the mutation.
* @param mutation The mutation function.
*/
add(name: string, mutation: Function): void {
this._mutations.set(name, mutation);
}
/**
* Removes a mutation to the mutator instance.
* Any cached mutation values for this mutation will be purged.
* @param name The name of the mutation.
*/
remove(name: string): void {
this.clearCache(name);
this._mutations.delete(name);
}
/**
* Clears the mutator cache.
* The entire cache, or cache for a specific mutator, can be cleared
* by passing or omitting the mutator name as an argument.
* @param name The mutator name to clear the cache for.
*/
clearCache(name?: string): void {
if (!name) {
this._cache.clear();
return;
}
for (const key of this._cache.keys()) {
if (key.startsWith(name)) {
this._cache.delete(key);
}
}
}
/**
* Mutates and returns a criteria object.
* @param criteria The criteria to mutate.
*/
async mutate(criteria: object | object[]): Promise<object | object[]> {
// Handles checking the mutability of a criteria object
// If it is mutable it will be cloned, mutated and returned
const exec = async (criteria) => {
// If there are no mutations or the criteria does not contain
// any of the mutation keys, return the criteria as is.
if (!this._mutations.size || !this.hasMutations(criteria)) {
return criteria;
}
// Make a copy of the criteria.
const copy = { ...criteria };
// Apply the mutations to the copy and return it.
await this.applyMutations(copy);
return copy;
};
// If the criteria is an array, we want to apply the mutations
// to each item in the array in parallel.
if (criteria instanceof Array) {
return await Promise.all(
criteria.map(
(c) =>
new Promise(async (resolve) => {
resolve(await exec(c));
})
)
);
} else {
return await exec(criteria);
}
}
/**
* Checks if the criteria contains any mutate-able properties.
* @param criteria The criteria to check.
* @param result Whether a mutate-able property has been found.
* @param parentPath The parent path to the current property.
*/
private hasMutations(
criteria: object,
result: boolean = false,
parentPath: string = ""
): boolean {
// If we have already found a mutation, we can stop.
if (result) return true;
for (const key of Object.keys(criteria)) {
if (result) return true;
// Prepare dotted path to the current property.
const path = parentPath ? `${parentPath}.${key}` : key;
// If the value is an object, we should recurse.
result = this._objectDiscovery.isObject(criteria[key])
? result || this.hasMutations(criteria[key], result, path)
: result || this._mutations.has(path);
}
return result;
}
/**
* Recursively applies mutations to the criteria.
* @param criteria The criteria to mutate.
* @param parentPath The parent path to the current property.
*/
private async applyMutations(
criteria: object,
parentPath: string = ""
): Promise<void> {
const promises = Object.keys(criteria).map(
async (key) =>
new Promise(async (resolve) => {
// Prepare dotted path to the current property.
const path = parentPath ? `${parentPath}.${key}` : key;
if (this._objectDiscovery.isObject(criteria[key])) {
await this.applyMutations(criteria[key], path);
}
if (this._mutations.has(path)) {
criteria[key] = await this.execMutation(key, criteria, path);
}
resolve(criteria[key]);
})
);
await Promise.all(promises);
}
/**
* Executes a mutation.
* Defers duplicate executions to the same object from a memory cache.
* @param criteriaProp The criteria property to execute the mutation on.
* @param criteria The criteria to execute the mutation with.
* @param mutationKey The key of the mutation to execute.
*/
private async execMutation(
criteriaProp: string,
criteria: unknown,
mutationKey: string
): Promise<any> {
const value = criteria[criteriaProp];
// Create a cache key
const cacheKey = `${mutationKey}${createHash("md5")
.update(value.toString())
.digest("hex")}`;
// If the mutation has already been executed, return the cached result.
if (this._cache.has(cacheKey)) {
| Logger.debug(`Cache hit on "${mutationKey}" with param "${value}"`); |
return this._cache.get(cacheKey);
}
// If the mutation is already in progress, wait for it to finish.
if (this._buffer.get(cacheKey)) {
return await new Promise((resolve) => {
Logger.debug(
`Waiting on mutation "${mutationKey}" with param "${value}"`
);
this._eventEmitter.once(`mutation:${cacheKey}`, (result) => {
Logger.debug(
`Resolved mutation "${mutationKey}" with param "${value}"`
);
resolve(result);
});
});
}
// Set the buffer to true to indicate that the mutation is in progress.
// This prevents duplicate executions of the same mutation.
this._buffer.set(cacheKey, true);
// Execute the mutation
Logger.debug(`Running mutation "${mutationKey}" with param "${value}"`);
const mutation = this._mutations.get(mutationKey);
const result = await mutation(value, criteria);
// Cache the result and release the buffer to false.
this._cache.set(cacheKey, result);
this._buffer.set(cacheKey, false);
// Emit an event to indicate that the mutation has been executed.
this._eventEmitter.emit(`mutation:${cacheKey}`, result);
return result;
}
}
| src/services/mutator.ts | andrewbrg-rulepilot-517f473 | [
{
"filename": "src/services/evaluator.ts",
"retrieved_chunk": " * @param criteria The criteria to evaluate the constraint with.\n */\n private checkConstraint(constraint: Constraint, criteria: object): boolean {\n // If the value contains '.' we should assume it is a nested property\n const criterion = constraint.field.includes(\".\")\n ? this._objectDiscovery.resolveNestedProperty(constraint.field, criteria)\n : criteria[constraint.field];\n // If the criteria object does not have the field\n // we are looking for, we should return false.\n if (!criterion) {",
"score": 15.683010407664414
},
{
"filename": "src/services/logger.ts",
"retrieved_chunk": "export class Logger {\n static debug(message: string): void {\n if (!process.env.DEBUG) return;\n console.debug(message);\n }\n}",
"score": 14.637629315602135
},
{
"filename": "src/services/validator.ts",
"retrieved_chunk": " element: constraint,\n },\n };\n }\n const operators = [\"==\", \"!=\", \">\", \"<\", \">=\", \"<=\", \"in\", \"not in\"];\n if (!operators.includes(constraint.operator as Operator)) {\n return {\n isValid: false,\n error: {\n message: 'Constraint \"operator\" has invalid type.',",
"score": 12.788646653977061
},
{
"filename": "src/services/rule-pilot.ts",
"retrieved_chunk": " /**\n * Removes a mutation to the rule pilot instance.\n * Any cached mutation values for this mutation will be purged.\n *\n * @param name The name of the mutation.\n */\n removeMutation(name: string): RulePilot {\n this._mutator.remove(name);\n return this;\n }",
"score": 12.306630659592962
},
{
"filename": "src/services/rule-pilot.ts",
"retrieved_chunk": " * @param name The name of the mutation.\n * @param mutation The mutation function.\n */\n static addMutation(name: string, mutation: Function): RulePilot {\n return RulePilot._rulePilot.addMutation(name, mutation);\n }\n /**\n * Removes a mutation to the rule pilot instance.\n * Any cached mutation values for this mutation will be purged.\n *",
"score": 12.080966229431993
}
] | typescript | Logger.debug(`Cache hit on "${mutationKey}" with param "${value}"`); |
import { Builder } from "./builder";
import { Mutator } from "./mutator";
import { Evaluator } from "./evaluator";
import { ValidationResult, Validator } from "./validator";
import { Rule } from "../types/rule";
import { RuleError } from "../types/error";
export class RulePilot {
private static _rulePilot = new RulePilot();
private _mutator: Mutator = new Mutator();
private _validator: Validator = new Validator();
private _evaluator: Evaluator = new Evaluator();
/**
* Returns a rule builder class instance.
* Allows for the construction of rules using a fluent interface.
*/
builder(): Builder {
return new Builder(this._validator);
}
/**
* Adds a mutation to the rule pilot instance.
* Mutations allow for the modification of the criteria before
* it is evaluated against a rule.
*
* @param name The name of the mutation.
* @param mutation The mutation function.
*/
addMutation(name: string, mutation: Function): RulePilot {
this._mutator.add(name, mutation);
return this;
}
/**
* Removes a mutation to the rule pilot instance.
* Any cached mutation values for this mutation will be purged.
*
* @param name The name of the mutation.
*/
removeMutation(name: string): RulePilot {
this._mutator.remove(name);
return this;
}
/**
* Clears the mutator cache.
* The entire cache, or cache for a specific mutator, can be cleared
* by passing or omitting the mutator name as an argument.
*
* @param name The mutator name to clear the cache for.
*/
clearMutationCache(name?: string): RulePilot {
this._mutator.clearCache(name);
return this;
}
/**
* Evaluates a rule against a set of criteria and returns the result.
* If the criteria is an array (indicating multiple criteria to test),
* the rule will be evaluated against each item in the array and
* an array of results will be returned.
*
* @param rule The rule to evaluate.
* @param criteria The criteria to evaluate the rule against.
* @param trustRule Set true to avoid validating the rule before evaluating it (faster).
* @throws Error if the rule is invalid.
*/
async evaluate<T>(
rule: Rule,
criteria: object | object[],
trustRule = false
): Promise<T> {
// Before we evaluate the rule, we should validate it.
// If `trustRuleset` is set to true, we will skip validation.
const validationResult = !trustRule && this.validate(rule);
| if (!trustRule && !validationResult.isValid) { |
throw new RuleError(validationResult);
}
return this._evaluator.evaluate(rule, await this._mutator.mutate(criteria));
}
/**
* Takes in a rule as a parameter and returns a ValidationResult
* indicating whether the rule is valid or not.
*
* Invalid rules will contain an error property which contains a message and the element
* that caused the validation to fail.
*
* @param rule The rule to validate.
*/
validate(rule: Rule): ValidationResult {
return this._validator.validate(rule);
}
/**
* Returns a rule builder class instance.
* Allows for the construction of rules using a fluent interface.
*/
static builder(): Builder {
return this._rulePilot.builder();
}
/**
* Evaluates a rule against a set of criteria and returns the result.
* If the criteria is an array (indicating multiple criteria to test),
* the rule will be evaluated against each item in the array and
* an array of results will be returned.
*
* @param rule The rule to evaluate.
* @param criteria The criteria to evaluate the rule against.
* @param trustRule Set true to avoid validating the rule before evaluating it (faster).
* @throws Error if the rule is invalid.
*/
static async evaluate<T>(
rule: Rule,
criteria: object | object[],
trustRule = false
): Promise<T> {
return RulePilot._rulePilot.evaluate<T>(rule, criteria, trustRule);
}
/**
* Takes in a rule as a parameter and returns a ValidationResult
* indicating whether the rule is valid or not.
*
* Invalid rules will contain an error property which contains a message and the element
* that caused the validation to fail.
*
* @param rule The rule to validate.
*/
static validate(rule: Rule): ValidationResult {
return RulePilot._rulePilot.validate(rule);
}
/**
* Adds a mutation.
*
* Mutations allow for the modification of the criteria before
* it is evaluated against a rule.
*
* @param name The name of the mutation.
* @param mutation The mutation function.
*/
static addMutation(name: string, mutation: Function): RulePilot {
return RulePilot._rulePilot.addMutation(name, mutation);
}
/**
* Removes a mutation to the rule pilot instance.
* Any cached mutation values for this mutation will be purged.
*
* @param name The name of the mutation.
*/
static removeMutation(name: string): RulePilot {
return RulePilot._rulePilot.removeMutation(name);
}
/**
* Clears the mutator cache.
* The entire cache, or cache for a specific mutator, can be cleared
* by passing or omitting the mutator name as an argument.
*
* @param name The mutator name to clear the cache for.
*/
static clearMutationCache(name?: string): RulePilot {
return RulePilot._rulePilot.clearMutationCache(name);
}
}
| src/services/rule-pilot.ts | andrewbrg-rulepilot-517f473 | [
{
"filename": "src/services/builder.ts",
"retrieved_chunk": " return this.rule;\n }\n const validationResult = this.validator.validate(this.rule);\n if (validationResult.isValid) {\n return this.rule;\n }\n throw new RuleError(validationResult);\n }\n /**\n * Creates a new condition node",
"score": 27.088071099655927
},
{
"filename": "src/services/evaluator.ts",
"retrieved_chunk": " * @param criteria The criteria to evaluate the constraint with.\n */\n private checkConstraint(constraint: Constraint, criteria: object): boolean {\n // If the value contains '.' we should assume it is a nested property\n const criterion = constraint.field.includes(\".\")\n ? this._objectDiscovery.resolveNestedProperty(constraint.field, criteria)\n : criteria[constraint.field];\n // If the criteria object does not have the field\n // we are looking for, we should return false.\n if (!criterion) {",
"score": 26.53025625946966
},
{
"filename": "src/services/builder.ts",
"retrieved_chunk": " this.rule.default = value;\n return this;\n }\n /**\n * Builds the rule being and returns it\n * @param validate Whether to validate the rule before returning it\n * @throws Error if validation is enabled and the rule is invalid\n */\n build(validate?: boolean): Rule {\n if (!validate) {",
"score": 26.055199586034558
},
{
"filename": "src/services/evaluator.ts",
"retrieved_chunk": " }\n // If the type is 'all' or 'none', we should set the initial\n // result to true, otherwise we should set it to false.\n let result = [\"all\", \"none\"].includes(type);\n // Check each node in the condition.\n for (const node of condition[type]) {\n let fn;\n if (this._objectDiscovery.isCondition(node)) {\n fn = \"evaluateCondition\";\n }",
"score": 23.244293748562356
},
{
"filename": "src/services/evaluator.ts",
"retrieved_chunk": " * @param rule The rule to evaluate.\n * @param criteria The criteria to evaluate the rule against.\n */\n evaluate(rule: Rule, criteria: object | object[]): boolean | any {\n // Cater for the case where the conditions property is not an array.\n const conditions =\n rule.conditions instanceof Array ? rule.conditions : [rule.conditions];\n if (criteria instanceof Array) {\n const result = [];\n for (const c of criteria) {",
"score": 22.645241817999423
}
] | typescript | if (!trustRule && !validationResult.isValid) { |
import { ObjectDiscovery } from "./object-discovery";
import { Condition, Constraint, Operator, Rule } from "../types/rule";
export interface ValidationResult {
isValid: boolean;
error?: {
message: string;
element: object;
};
}
export class Validator {
private objectDiscovery: ObjectDiscovery = new ObjectDiscovery();
/**
* Takes in a rule as a parameter and returns a boolean indicating whether the rule is valid or not.
* @param rule The rule to validate.
*/
validate(rule: Rule): ValidationResult {
// Assume the rule is valid.
let result: ValidationResult = { isValid: true };
// Check the rule is a valid JSON
if (!this.objectDiscovery.isObject(rule)) {
return {
isValid: false,
error: {
message: "The rule must be a valid JSON object.",
element: rule,
},
};
}
// Cater for the case where the conditions property is not an array.
const conditions =
rule.conditions instanceof Array ? rule.conditions : [rule.conditions];
// Validate the 'conditions' property.
if (
conditions.length === 0 ||
(this.objectDiscovery.isObject(conditions[0]) &&
!Object.keys(conditions[0]).length)
) {
return {
isValid: false,
error: {
message:
"The conditions property must contain at least one condition.",
element: rule,
},
};
}
// Validate each condition in the rule.
for (const condition of conditions) {
const subResult = this.validateCondition(condition);
result.isValid = result.isValid && subResult.isValid;
result.error = result?.error ?? subResult?.error;
}
return result;
}
/** ml/l.k,
* Evaluates a condition to ensure it is syntactically correct.
* @param condition The condition to validate.
* @param depth The current recursion depth
*/
private validateCondition(
condition: Condition,
depth: number = 0
): ValidationResult {
// Check to see if the condition is valid.
let result = this.isValidCondition(condition);
if (!result.isValid) {
return result;
}
// Set the type of condition.
const type = this.objectDiscovery.conditionType(condition);
// Check if the condition is iterable
if(!Array.isArray(condition[type])) {
return {
isValid: false,
error: {
message: `The condition '${type}' should be iterable.`,
element: condition,
},
};
}
// Validate each item in the condition.
for (const node of condition[type]) {
| const isCondition = this.objectDiscovery.isCondition(node); |
if (isCondition) {
const subResult = this.validateCondition(node as Condition, depth + 1);
result.isValid = result.isValid && subResult.isValid;
result.error = result?.error ?? subResult?.error;
}
const isConstraint = this.objectDiscovery.isConstraint(node);
if (isConstraint) {
const subResult = this.validateConstraint(node as Constraint);
result.isValid = result.isValid && subResult.isValid;
result.error = result?.error ?? subResult?.error;
}
if (!isConstraint && !isCondition) {
return {
isValid: false,
error: {
message: "Each node should be a condition or constraint.",
element: node,
},
};
}
// Result is only valid on the root condition.
if (depth > 0 && "result" in condition) {
return {
isValid: false,
error: {
message: 'Nested conditions cannot have a property "result".',
element: node,
},
};
}
// If any part fails validation there is no point to continue.
if (!result.isValid) {
break;
}
}
return result;
}
/**
* Checks a constraint to ensure it is syntactically correct.
* @param constraint The constraint to validate.
*/
private validateConstraint(constraint: Constraint): ValidationResult {
if ("string" !== typeof constraint.field) {
return {
isValid: false,
error: {
message: 'Constraint "field" must be of type string.',
element: constraint,
},
};
}
const operators = ["==", "!=", ">", "<", ">=", "<=", "in", "not in"];
if (!operators.includes(constraint.operator as Operator)) {
return {
isValid: false,
error: {
message: 'Constraint "operator" has invalid type.',
element: constraint,
},
};
}
// We must check that the value is an array if the operator is 'in' or 'not in'.
if (
["in", "not in"].includes(constraint.operator) &&
!Array.isArray(constraint.value)
) {
return {
isValid: false,
error: {
message:
'Constraint "value" must be an array if the "operator" is "in" or "not in"',
element: constraint,
},
};
}
return { isValid: true };
}
/**
* Checks an object to see if it is a valid condition.
* @param obj The object to check.
*/
private isValidCondition(obj: any): ValidationResult {
if (!this.objectDiscovery.isCondition(obj)) {
return {
isValid: false,
error: {
message: "Invalid condition structure.",
element: obj,
},
};
}
const isAny = "any" in obj;
const isAll = "all" in obj;
const isNone = "none" in obj;
// A valid condition must have an 'any', 'all', or 'none' property,
// but cannot have more than one.
if ((isAny && isAll) || (isAny && isNone) || (isAll && isNone)) {
return {
isValid: false,
error: {
message:
'A condition cannot have more than one "any", "all", or "none" property.',
element: obj,
},
};
}
return { isValid: true };
}
}
| src/services/validator.ts | andrewbrg-rulepilot-517f473 | [
{
"filename": "src/services/evaluator.ts",
"retrieved_chunk": " }\n // If the type is 'all' or 'none', we should set the initial\n // result to true, otherwise we should set it to false.\n let result = [\"all\", \"none\"].includes(type);\n // Check each node in the condition.\n for (const node of condition[type]) {\n let fn;\n if (this._objectDiscovery.isCondition(node)) {\n fn = \"evaluateCondition\";\n }",
"score": 40.35315001790184
},
{
"filename": "src/services/builder.ts",
"retrieved_chunk": " * @param type The type of condition\n * @param nodes Any child nodes of the condition\n * @param result The result of the condition node (for granular rules)\n */\n condition(\n type: ConditionType,\n nodes: Condition[ConditionType],\n result?: Condition[\"result\"]\n ): Condition {\n return {",
"score": 27.184441390723716
},
{
"filename": "src/services/evaluator.ts",
"retrieved_chunk": " * Evaluates a condition against a set of criteria and returns the result.\n * Uses recursion to evaluate nested conditions.\n * @param condition The condition to evaluate.\n * @param criteria The criteria to evaluate the condition against.\n */\n private evaluateCondition(condition: Condition, criteria: object): boolean {\n // The condition must have an 'any' or 'all' property.\n const type = this._objectDiscovery.conditionType(condition);\n if (!type) {\n return false;",
"score": 24.32610614086437
},
{
"filename": "src/services/builder.ts",
"retrieved_chunk": " return this.rule;\n }\n const validationResult = this.validator.validate(this.rule);\n if (validationResult.isValid) {\n return this.rule;\n }\n throw new RuleError(validationResult);\n }\n /**\n * Creates a new condition node",
"score": 21.866439519935494
},
{
"filename": "src/services/object-discovery.ts",
"retrieved_chunk": "import { Condition, ConditionType, Constraint } from \"../types/rule\";\nexport class ObjectDiscovery {\n /**\n * Returns the type of condition passed to the function.\n * @param condition The condition to check.\n */\n conditionType(condition: Condition): ConditionType | null {\n if (\"any\" in condition) return \"any\";\n if (\"all\" in condition) return \"all\";\n if (\"none\" in condition) return \"none\";",
"score": 21.783512805032927
}
] | typescript | const isCondition = this.objectDiscovery.isCondition(node); |
import { ObjectDiscovery } from "./object-discovery";
import { Condition, Constraint, Operator, Rule } from "../types/rule";
export interface ValidationResult {
isValid: boolean;
error?: {
message: string;
element: object;
};
}
export class Validator {
private objectDiscovery: ObjectDiscovery = new ObjectDiscovery();
/**
* Takes in a rule as a parameter and returns a boolean indicating whether the rule is valid or not.
* @param rule The rule to validate.
*/
validate(rule: Rule): ValidationResult {
// Assume the rule is valid.
let result: ValidationResult = { isValid: true };
// Check the rule is a valid JSON
if (!this.objectDiscovery.isObject(rule)) {
return {
isValid: false,
error: {
message: "The rule must be a valid JSON object.",
element: rule,
},
};
}
// Cater for the case where the conditions property is not an array.
const conditions =
rule.conditions instanceof Array ? rule.conditions : [rule.conditions];
// Validate the 'conditions' property.
if (
conditions.length === 0 ||
(this.objectDiscovery.isObject(conditions[0]) &&
!Object.keys(conditions[0]).length)
) {
return {
isValid: false,
error: {
message:
"The conditions property must contain at least one condition.",
element: rule,
},
};
}
// Validate each condition in the rule.
for (const condition of conditions) {
const subResult = this.validateCondition(condition);
result.isValid = result.isValid && subResult.isValid;
result.error = result?.error ?? subResult?.error;
}
return result;
}
/** ml/l.k,
* Evaluates a condition to ensure it is syntactically correct.
* @param condition The condition to validate.
* @param depth The current recursion depth
*/
private validateCondition(
condition: Condition,
depth: number = 0
): ValidationResult {
// Check to see if the condition is valid.
let result = this.isValidCondition(condition);
if (!result.isValid) {
return result;
}
// Set the type of condition.
| const type = this.objectDiscovery.conditionType(condition); |
// Check if the condition is iterable
if(!Array.isArray(condition[type])) {
return {
isValid: false,
error: {
message: `The condition '${type}' should be iterable.`,
element: condition,
},
};
}
// Validate each item in the condition.
for (const node of condition[type]) {
const isCondition = this.objectDiscovery.isCondition(node);
if (isCondition) {
const subResult = this.validateCondition(node as Condition, depth + 1);
result.isValid = result.isValid && subResult.isValid;
result.error = result?.error ?? subResult?.error;
}
const isConstraint = this.objectDiscovery.isConstraint(node);
if (isConstraint) {
const subResult = this.validateConstraint(node as Constraint);
result.isValid = result.isValid && subResult.isValid;
result.error = result?.error ?? subResult?.error;
}
if (!isConstraint && !isCondition) {
return {
isValid: false,
error: {
message: "Each node should be a condition or constraint.",
element: node,
},
};
}
// Result is only valid on the root condition.
if (depth > 0 && "result" in condition) {
return {
isValid: false,
error: {
message: 'Nested conditions cannot have a property "result".',
element: node,
},
};
}
// If any part fails validation there is no point to continue.
if (!result.isValid) {
break;
}
}
return result;
}
/**
* Checks a constraint to ensure it is syntactically correct.
* @param constraint The constraint to validate.
*/
private validateConstraint(constraint: Constraint): ValidationResult {
if ("string" !== typeof constraint.field) {
return {
isValid: false,
error: {
message: 'Constraint "field" must be of type string.',
element: constraint,
},
};
}
const operators = ["==", "!=", ">", "<", ">=", "<=", "in", "not in"];
if (!operators.includes(constraint.operator as Operator)) {
return {
isValid: false,
error: {
message: 'Constraint "operator" has invalid type.',
element: constraint,
},
};
}
// We must check that the value is an array if the operator is 'in' or 'not in'.
if (
["in", "not in"].includes(constraint.operator) &&
!Array.isArray(constraint.value)
) {
return {
isValid: false,
error: {
message:
'Constraint "value" must be an array if the "operator" is "in" or "not in"',
element: constraint,
},
};
}
return { isValid: true };
}
/**
* Checks an object to see if it is a valid condition.
* @param obj The object to check.
*/
private isValidCondition(obj: any): ValidationResult {
if (!this.objectDiscovery.isCondition(obj)) {
return {
isValid: false,
error: {
message: "Invalid condition structure.",
element: obj,
},
};
}
const isAny = "any" in obj;
const isAll = "all" in obj;
const isNone = "none" in obj;
// A valid condition must have an 'any', 'all', or 'none' property,
// but cannot have more than one.
if ((isAny && isAll) || (isAny && isNone) || (isAll && isNone)) {
return {
isValid: false,
error: {
message:
'A condition cannot have more than one "any", "all", or "none" property.',
element: obj,
},
};
}
return { isValid: true };
}
}
| src/services/validator.ts | andrewbrg-rulepilot-517f473 | [
{
"filename": "src/services/evaluator.ts",
"retrieved_chunk": " }\n // If the type is 'all' or 'none', we should set the initial\n // result to true, otherwise we should set it to false.\n let result = [\"all\", \"none\"].includes(type);\n // Check each node in the condition.\n for (const node of condition[type]) {\n let fn;\n if (this._objectDiscovery.isCondition(node)) {\n fn = \"evaluateCondition\";\n }",
"score": 37.18105446607456
},
{
"filename": "src/services/evaluator.ts",
"retrieved_chunk": " * Evaluates a condition against a set of criteria and returns the result.\n * Uses recursion to evaluate nested conditions.\n * @param condition The condition to evaluate.\n * @param criteria The criteria to evaluate the condition against.\n */\n private evaluateCondition(condition: Condition, criteria: object): boolean {\n // The condition must have an 'any' or 'all' property.\n const type = this._objectDiscovery.conditionType(condition);\n if (!type) {\n return false;",
"score": 35.624240242372
},
{
"filename": "src/services/builder.ts",
"retrieved_chunk": " * @param type The type of condition\n * @param nodes Any child nodes of the condition\n * @param result The result of the condition node (for granular rules)\n */\n condition(\n type: ConditionType,\n nodes: Condition[ConditionType],\n result?: Condition[\"result\"]\n ): Condition {\n return {",
"score": 34.73582132942402
},
{
"filename": "src/services/object-discovery.ts",
"retrieved_chunk": "import { Condition, ConditionType, Constraint } from \"../types/rule\";\nexport class ObjectDiscovery {\n /**\n * Returns the type of condition passed to the function.\n * @param condition The condition to check.\n */\n conditionType(condition: Condition): ConditionType | null {\n if (\"any\" in condition) return \"any\";\n if (\"all\" in condition) return \"all\";\n if (\"none\" in condition) return \"none\";",
"score": 33.71727711668085
},
{
"filename": "src/services/evaluator.ts",
"retrieved_chunk": " const result = this.evaluateCondition(condition, criteria);\n if (result) {\n return condition?.result ?? true;\n }\n }\n // If no conditions pass, we should return the default result of\n // the rule or false if no default result is provided.\n return defaultResult ?? false;\n }\n /**",
"score": 26.81605057433419
}
] | typescript | const type = this.objectDiscovery.conditionType(condition); |
import { ObjectDiscovery } from "./object-discovery";
import { Condition, Constraint, Operator, Rule } from "../types/rule";
export interface ValidationResult {
isValid: boolean;
error?: {
message: string;
element: object;
};
}
export class Validator {
private objectDiscovery: ObjectDiscovery = new ObjectDiscovery();
/**
* Takes in a rule as a parameter and returns a boolean indicating whether the rule is valid or not.
* @param rule The rule to validate.
*/
validate(rule: Rule): ValidationResult {
// Assume the rule is valid.
let result: ValidationResult = { isValid: true };
// Check the rule is a valid JSON
if (!this.objectDiscovery.isObject(rule)) {
return {
isValid: false,
error: {
message: "The rule must be a valid JSON object.",
element: rule,
},
};
}
// Cater for the case where the conditions property is not an array.
const conditions =
rule.conditions instanceof Array ? rule.conditions : [rule.conditions];
// Validate the 'conditions' property.
if (
conditions.length === 0 ||
(this.objectDiscovery.isObject(conditions[0]) &&
!Object.keys(conditions[0]).length)
) {
return {
isValid: false,
error: {
message:
"The conditions property must contain at least one condition.",
element: rule,
},
};
}
// Validate each condition in the rule.
for (const condition of conditions) {
const subResult = this.validateCondition(condition);
result.isValid = result.isValid && subResult.isValid;
result.error = result?.error ?? subResult?.error;
}
return result;
}
/** ml/l.k,
* Evaluates a condition to ensure it is syntactically correct.
* @param condition The condition to validate.
* @param depth The current recursion depth
*/
private validateCondition(
condition: Condition,
depth: number = 0
): ValidationResult {
// Check to see if the condition is valid.
let result = this.isValidCondition(condition);
if (!result.isValid) {
return result;
}
// Set the type of condition.
const type = this.objectDiscovery.conditionType(condition);
// Check if the condition is iterable
if(!Array.isArray(condition[type])) {
return {
isValid: false,
error: {
message: `The condition '${type}' should be iterable.`,
element: condition,
},
};
}
// Validate each item in the condition.
for (const node of condition[type]) {
const isCondition = this.objectDiscovery.isCondition(node);
if (isCondition) {
const subResult = this.validateCondition(node as Condition, depth + 1);
result.isValid = result.isValid && subResult.isValid;
result.error = result?.error ?? subResult?.error;
}
const isConstraint = this.objectDiscovery.isConstraint(node);
if (isConstraint) {
const subResult = this | .validateConstraint(node as Constraint); |
result.isValid = result.isValid && subResult.isValid;
result.error = result?.error ?? subResult?.error;
}
if (!isConstraint && !isCondition) {
return {
isValid: false,
error: {
message: "Each node should be a condition or constraint.",
element: node,
},
};
}
// Result is only valid on the root condition.
if (depth > 0 && "result" in condition) {
return {
isValid: false,
error: {
message: 'Nested conditions cannot have a property "result".',
element: node,
},
};
}
// If any part fails validation there is no point to continue.
if (!result.isValid) {
break;
}
}
return result;
}
/**
* Checks a constraint to ensure it is syntactically correct.
* @param constraint The constraint to validate.
*/
private validateConstraint(constraint: Constraint): ValidationResult {
if ("string" !== typeof constraint.field) {
return {
isValid: false,
error: {
message: 'Constraint "field" must be of type string.',
element: constraint,
},
};
}
const operators = ["==", "!=", ">", "<", ">=", "<=", "in", "not in"];
if (!operators.includes(constraint.operator as Operator)) {
return {
isValid: false,
error: {
message: 'Constraint "operator" has invalid type.',
element: constraint,
},
};
}
// We must check that the value is an array if the operator is 'in' or 'not in'.
if (
["in", "not in"].includes(constraint.operator) &&
!Array.isArray(constraint.value)
) {
return {
isValid: false,
error: {
message:
'Constraint "value" must be an array if the "operator" is "in" or "not in"',
element: constraint,
},
};
}
return { isValid: true };
}
/**
* Checks an object to see if it is a valid condition.
* @param obj The object to check.
*/
private isValidCondition(obj: any): ValidationResult {
if (!this.objectDiscovery.isCondition(obj)) {
return {
isValid: false,
error: {
message: "Invalid condition structure.",
element: obj,
},
};
}
const isAny = "any" in obj;
const isAll = "all" in obj;
const isNone = "none" in obj;
// A valid condition must have an 'any', 'all', or 'none' property,
// but cannot have more than one.
if ((isAny && isAll) || (isAny && isNone) || (isAll && isNone)) {
return {
isValid: false,
error: {
message:
'A condition cannot have more than one "any", "all", or "none" property.',
element: obj,
},
};
}
return { isValid: true };
}
}
| src/services/validator.ts | andrewbrg-rulepilot-517f473 | [
{
"filename": "src/services/evaluator.ts",
"retrieved_chunk": " if (this._objectDiscovery.isConstraint(node)) {\n fn = \"checkConstraint\";\n }\n // Process the node\n switch (type) {\n case \"any\":\n result = result || this[fn](node, criteria);\n break;\n case \"all\":\n result = result && this[fn](node, criteria);",
"score": 37.65356084243909
},
{
"filename": "src/services/builder.ts",
"retrieved_chunk": " return this.rule;\n }\n const validationResult = this.validator.validate(this.rule);\n if (validationResult.isValid) {\n return this.rule;\n }\n throw new RuleError(validationResult);\n }\n /**\n * Creates a new condition node",
"score": 33.19376461751742
},
{
"filename": "src/services/evaluator.ts",
"retrieved_chunk": " }\n // If the type is 'all' or 'none', we should set the initial\n // result to true, otherwise we should set it to false.\n let result = [\"all\", \"none\"].includes(type);\n // Check each node in the condition.\n for (const node of condition[type]) {\n let fn;\n if (this._objectDiscovery.isCondition(node)) {\n fn = \"evaluateCondition\";\n }",
"score": 32.37971200064647
},
{
"filename": "src/services/rule-pilot.ts",
"retrieved_chunk": " if (!trustRule && !validationResult.isValid) {\n throw new RuleError(validationResult);\n }\n return this._evaluator.evaluate(rule, await this._mutator.mutate(criteria));\n }\n /**\n * Takes in a rule as a parameter and returns a ValidationResult\n * indicating whether the rule is valid or not.\n *\n * Invalid rules will contain an error property which contains a message and the element",
"score": 21.841635443068665
},
{
"filename": "src/services/builder.ts",
"retrieved_chunk": " */\n add(node: Condition): Builder {\n (this.rule.conditions as Condition[]).push(node);\n return this;\n }\n /**\n * Sets the default value of the rule being constructed\n * @param value The default value of the rule\n */\n default(value: Rule[\"default\"]): Builder {",
"score": 21.714221738278376
}
] | typescript | .validateConstraint(node as Constraint); |
import { Inject, Injectable, Logger } from '@nestjs/common'
import { ExchangeRateRepository } from './exchange-rate.repository'
import { FreeCurrencyConversionExchangeRateRepository } from './free-currency-conversion-exchange-rate.repository'
import { HostExchangeRateRepository } from './host-exchange-rate.repository'
@Injectable()
export class RedundantExchangeRateRepository implements ExchangeRateRepository {
private logger = new Logger(RedundantExchangeRateRepository.name)
constructor(
@Inject(FreeCurrencyConversionExchangeRateRepository)
private freeCurrencyConversionExchangeRateRepository: FreeCurrencyConversionExchangeRateRepository,
@Inject(HostExchangeRateRepository)
private hostExchangeRateRepository: HostExchangeRateRepository
) {}
async getSpotPrice(fromCurrency: string, toCurrency: string): Promise<number> {
this.logger.log({
message: 'Get spot price',
fromCurrency,
toCurrency
})
try {
const spotPrice =
await this.freeCurrencyConversionExchangeRateRepository.getSpotPrice(
fromCurrency,
toCurrency
)
this.logger.log({
message: 'Successfully got spot price',
fromCurrency,
toCurrency,
spotPrice
})
return spotPrice
} catch (error) {
this.logger.log({
message: 'Failed to get spot price. Falling back to another exchange rate',
fromCurrency,
toCurrency,
error
})
| return this.hostExchangeRateRepository.getSpotPrice(fromCurrency, toCurrency)
} |
}
}
| src/repository/redundant-exchange-rate.repository.ts | tech-leads-club-nestjs-dependency-inversion-5d4fefe | [
{
"filename": "src/controller/exchange-rate.controller.ts",
"retrieved_chunk": " const spotPrice = await this.service.getSpotPrice(fromCurrency, toCurrency)\n return { spotPrice }\n }\n}",
"score": 11.857723826386925
},
{
"filename": "src/controller/exchange-rate.controller.ts",
"retrieved_chunk": "import { Controller, Get, Inject, Query } from '@nestjs/common'\nimport { ExchangeRateService } from 'src/service/exchange-rate.service'\n@Controller('exchange-rate')\nexport class ExchangeRateController {\n constructor(@Inject(ExchangeRateService) private service: ExchangeRateService) {}\n @Get('/spot-price')\n async getSpotPrice(\n @Query('fromCurrency') fromCurrency: string,\n @Query('toCurrency') toCurrency: string\n ): Promise<{ spotPrice: number }> {",
"score": 11.785687034765605
},
{
"filename": "src/service/exchange-rate.service.ts",
"retrieved_chunk": " getSpotPrice(fromCurrency: string, toCurrency: string): Promise<number> {\n return this.repository.getSpotPrice(fromCurrency, toCurrency)\n }\n}",
"score": 9.070357771941582
},
{
"filename": "src/repository/host-exchange-rate.repository.ts",
"retrieved_chunk": "import { Inject, Injectable } from '@nestjs/common'\nimport { ExchangeHostClient } from 'src/client/exchange-host.client'\nimport { ExchangeRateRepository } from './exchange-rate.repository'\n@Injectable()\nexport class HostExchangeRateRepository implements ExchangeRateRepository {\n constructor(@Inject(ExchangeHostClient) private client: ExchangeHostClient) {}\n async getSpotPrice(fromCurrency: string, toCurrency: string): Promise<number> {\n const rates = await this.client.getLatestRates(fromCurrency.toUpperCase())\n return rates[toCurrency.toUpperCase()]\n }",
"score": 6.843589917807679
},
{
"filename": "src/client/exchange-host.client.ts",
"retrieved_chunk": " getLatestRates(baseCurrency: string): Promise<Rates> {\n this.logger.log({\n message: 'Fetching latest rates',\n baseCurrency\n })\n return lastValueFrom(\n this.http\n .request<unknown>({\n method: 'GET',\n url: `${ExchangeHostClient.BASE_URL}/latest`,",
"score": 6.655479778284534
}
] | typescript | return this.hostExchangeRateRepository.getSpotPrice(fromCurrency, toCurrency)
} |
import { Builder } from "./builder";
import { Mutator } from "./mutator";
import { Evaluator } from "./evaluator";
import { ValidationResult, Validator } from "./validator";
import { Rule } from "../types/rule";
import { RuleError } from "../types/error";
export class RulePilot {
private static _rulePilot = new RulePilot();
private _mutator: Mutator = new Mutator();
private _validator: Validator = new Validator();
private _evaluator: Evaluator = new Evaluator();
/**
* Returns a rule builder class instance.
* Allows for the construction of rules using a fluent interface.
*/
builder(): Builder {
return new Builder(this._validator);
}
/**
* Adds a mutation to the rule pilot instance.
* Mutations allow for the modification of the criteria before
* it is evaluated against a rule.
*
* @param name The name of the mutation.
* @param mutation The mutation function.
*/
addMutation(name: string, mutation: Function): RulePilot {
this._mutator.add(name, mutation);
return this;
}
/**
* Removes a mutation to the rule pilot instance.
* Any cached mutation values for this mutation will be purged.
*
* @param name The name of the mutation.
*/
removeMutation(name: string): RulePilot {
this._mutator.remove(name);
return this;
}
/**
* Clears the mutator cache.
* The entire cache, or cache for a specific mutator, can be cleared
* by passing or omitting the mutator name as an argument.
*
* @param name The mutator name to clear the cache for.
*/
clearMutationCache(name?: string): RulePilot {
this._mutator.clearCache(name);
return this;
}
/**
* Evaluates a rule against a set of criteria and returns the result.
* If the criteria is an array (indicating multiple criteria to test),
* the rule will be evaluated against each item in the array and
* an array of results will be returned.
*
* @param rule The rule to evaluate.
* @param criteria The criteria to evaluate the rule against.
* @param trustRule Set true to avoid validating the rule before evaluating it (faster).
* @throws Error if the rule is invalid.
*/
async evaluate<T>(
rule: Rule,
criteria: object | object[],
trustRule = false
): Promise<T> {
// Before we evaluate the rule, we should validate it.
// If `trustRuleset` is set to true, we will skip validation.
const validationResult = !trustRule && this.validate(rule);
if (!trustRule && !validationResult.isValid) {
throw new RuleError(validationResult);
}
| return this._evaluator.evaluate(rule, await this._mutator.mutate(criteria)); |
}
/**
* Takes in a rule as a parameter and returns a ValidationResult
* indicating whether the rule is valid or not.
*
* Invalid rules will contain an error property which contains a message and the element
* that caused the validation to fail.
*
* @param rule The rule to validate.
*/
validate(rule: Rule): ValidationResult {
return this._validator.validate(rule);
}
/**
* Returns a rule builder class instance.
* Allows for the construction of rules using a fluent interface.
*/
static builder(): Builder {
return this._rulePilot.builder();
}
/**
* Evaluates a rule against a set of criteria and returns the result.
* If the criteria is an array (indicating multiple criteria to test),
* the rule will be evaluated against each item in the array and
* an array of results will be returned.
*
* @param rule The rule to evaluate.
* @param criteria The criteria to evaluate the rule against.
* @param trustRule Set true to avoid validating the rule before evaluating it (faster).
* @throws Error if the rule is invalid.
*/
static async evaluate<T>(
rule: Rule,
criteria: object | object[],
trustRule = false
): Promise<T> {
return RulePilot._rulePilot.evaluate<T>(rule, criteria, trustRule);
}
/**
* Takes in a rule as a parameter and returns a ValidationResult
* indicating whether the rule is valid or not.
*
* Invalid rules will contain an error property which contains a message and the element
* that caused the validation to fail.
*
* @param rule The rule to validate.
*/
static validate(rule: Rule): ValidationResult {
return RulePilot._rulePilot.validate(rule);
}
/**
* Adds a mutation.
*
* Mutations allow for the modification of the criteria before
* it is evaluated against a rule.
*
* @param name The name of the mutation.
* @param mutation The mutation function.
*/
static addMutation(name: string, mutation: Function): RulePilot {
return RulePilot._rulePilot.addMutation(name, mutation);
}
/**
* Removes a mutation to the rule pilot instance.
* Any cached mutation values for this mutation will be purged.
*
* @param name The name of the mutation.
*/
static removeMutation(name: string): RulePilot {
return RulePilot._rulePilot.removeMutation(name);
}
/**
* Clears the mutator cache.
* The entire cache, or cache for a specific mutator, can be cleared
* by passing or omitting the mutator name as an argument.
*
* @param name The mutator name to clear the cache for.
*/
static clearMutationCache(name?: string): RulePilot {
return RulePilot._rulePilot.clearMutationCache(name);
}
}
| src/services/rule-pilot.ts | andrewbrg-rulepilot-517f473 | [
{
"filename": "src/services/builder.ts",
"retrieved_chunk": " return this.rule;\n }\n const validationResult = this.validator.validate(this.rule);\n if (validationResult.isValid) {\n return this.rule;\n }\n throw new RuleError(validationResult);\n }\n /**\n * Creates a new condition node",
"score": 45.29196532392652
},
{
"filename": "src/services/evaluator.ts",
"retrieved_chunk": " * @param criteria The criteria to evaluate the constraint with.\n */\n private checkConstraint(constraint: Constraint, criteria: object): boolean {\n // If the value contains '.' we should assume it is a nested property\n const criterion = constraint.field.includes(\".\")\n ? this._objectDiscovery.resolveNestedProperty(constraint.field, criteria)\n : criteria[constraint.field];\n // If the criteria object does not have the field\n // we are looking for, we should return false.\n if (!criterion) {",
"score": 28.73698259604547
},
{
"filename": "src/services/builder.ts",
"retrieved_chunk": " this.rule.default = value;\n return this;\n }\n /**\n * Builds the rule being and returns it\n * @param validate Whether to validate the rule before returning it\n * @throws Error if validation is enabled and the rule is invalid\n */\n build(validate?: boolean): Rule {\n if (!validate) {",
"score": 25.08330201163358
},
{
"filename": "src/services/evaluator.ts",
"retrieved_chunk": " const result = this.evaluateCondition(condition, criteria);\n if (result) {\n return condition?.result ?? true;\n }\n }\n // If no conditions pass, we should return the default result of\n // the rule or false if no default result is provided.\n return defaultResult ?? false;\n }\n /**",
"score": 23.895828975088726
},
{
"filename": "src/services/mutator.ts",
"retrieved_chunk": " await this.applyMutations(copy);\n return copy;\n };\n // If the criteria is an array, we want to apply the mutations\n // to each item in the array in parallel.\n if (criteria instanceof Array) {\n return await Promise.all(\n criteria.map(\n (c) =>\n new Promise(async (resolve) => {",
"score": 23.525276624344237
}
] | typescript | return this._evaluator.evaluate(rule, await this._mutator.mutate(criteria)); |
import type { FastifyInstance, FastifyRequest } from 'fastify'
import { wechatApiPath } from '../const'
import { toSha1 } from '../utils/encryptor'
import type { VerifyQuery } from './types'
export function checkIsWechatRequest(request: FastifyRequest) {
const q = request.query as VerifyQuery
try {
const arr: string[] = [process.env.WECHAT_TOKEN, q.timestamp.toString(), q.nonce.toString()]
arr.sort()
const sha1 = toSha1(arr.join(''))
if (sha1 === q.signature) {
// Success.
return true
}
else {
return false
}
}
catch (error) {
console.error(error)
return false
}
}
function route(server: FastifyInstance) {
// setup hook
server.addHook('onRequest', (request, reply, done) => {
// TODO: Do we need to add this hook for all wechat request?
if (request?.url?.startsWith(wechatApiPath)) {
if (checkIsWechatRequest(request)) {
// Continue.
done()
}
else {
reply.send('who are you?')
}
}
else {
done()
}
})
server.get(wechatApiPath, (request: FastifyRequest, reply) => {
const q = request.query as VerifyQuery
if (checkIsWechatRequest(request)) {
// Success.
| reply.send(q.echostr)
} |
else {
reply.send('who are you?')
}
})
}
export default route
| src/wechat/verify.ts | zhouchaoyuan-azure-openai-node-wechat-624e8f4 | [
{
"filename": "src/wechat/acceptor.ts",
"retrieved_chunk": "function getChatHistoryForUser(requestKey: string) {\n if (!chatHistory.has(requestKey))\n chatHistory.set(requestKey, new FixedQueue<ChatCompletionRequestMessage>(pastMessagesIncluded))\n return chatHistory.get(requestKey)\n}\nfunction route(server: FastifyInstance) {\n server.post(wechatApiPath, (request, reply) => {\n const xml = request.body as any\n handleMsg(xml.xml, reply)\n })",
"score": 18.175115740278954
},
{
"filename": "src/azureopenai/acceptor.ts",
"retrieved_chunk": "import type { FastifyInstance, FastifyReply } from 'fastify'\nimport { chatPath, promptPath } from '../const'\nimport { GetAzureOpenAIAnswerAsync, GetAzureOpenAIChatAnswerAsync } from '../azureopenai/chatgpt'\nfunction route(server: FastifyInstance) {\n server.post(promptPath, (request, reply) => {\n // eslint-disable-next-line no-console\n console.log('prompt')\n handlePrompt(request.body, reply)\n })\n server.post(chatPath, (request, reply) => {",
"score": 14.075823205651641
},
{
"filename": "src/router.ts",
"retrieved_chunk": "import type { FastifyInstance } from 'fastify'\nimport verify from './wechat/verify'\nimport wechatAcceptor from './wechat/acceptor'\nimport openAIAcceptor from './azureopenai/acceptor'\nfunction setUpRouter(server: FastifyInstance) {\n // verify wechat request\n verify(server)\n // accept wechat request\n wechatAcceptor(server)\n // Azure openai sample api receive the request",
"score": 11.394923539661049
},
{
"filename": "src/utils/parser.ts",
"retrieved_chunk": "import { XMLParser } from 'fast-xml-parser'\nimport type { FastifyInstance } from 'fastify'\nconst xmlParser = new XMLParser()\nexport default function configureParser(server: FastifyInstance) {\n server.addContentTypeParser(['text/xml', 'application/xml'], (\n request, payload, done,\n ) => {\n const chunks: Uint8Array[] = []\n payload.on('data', (chunk) => {\n chunks.push(chunk)",
"score": 10.768357540309065
},
{
"filename": "src/azureopenai/acceptor.ts",
"retrieved_chunk": " handleChat(request.body, reply)\n })\n}\nasync function handlePrompt(requestBody: any, reply: FastifyReply) {\n GetAzureOpenAIAnswerAsync(requestBody.prompt, 'prompt restapi').then((response) => {\n reply.send(response)\n }).catch((reason) => {\n reply.send(reason)\n })\n}",
"score": 10.688097284512963
}
] | typescript | reply.send(q.echostr)
} |
import { Action, InputDefinition, Output, OutputDefinition } from '@binsoul/node-red-bundle-processing';
import { ModbusRtu } from '@binsoul/nodejs-modbus';
import { SolarmanV5 } from '@binsoul/nodejs-solarman';
import * as net from 'net';
import { NodeStatus } from 'node-red';
import type { Configuration } from '../Configuration';
import { DeyeRegisters } from '../DeyeRegisters';
import { Storage } from '../Storage';
export class UpdateAction implements Action {
private readonly configuration: Configuration;
private readonly storage: Storage;
private readonly outputCallback: () => void;
private readonly nodeStatusCallback: (status: NodeStatus) => void;
constructor(configuration: Configuration, storage: Storage, outputCallback: () => void, nodeStatusCallback: (status: NodeStatus) => void) {
this.configuration = configuration;
this.storage = storage;
this.outputCallback = outputCallback;
this.nodeStatusCallback = nodeStatusCallback;
}
defineInput(): InputDefinition {
return new InputDefinition();
}
defineOutput(): OutputDefinition {
return new OutputDefinition();
}
execute(): Output {
const client = new net.Socket();
client.setTimeout(5000);
let hasConnected = false;
let errorMessage = '';
let retryCount = 0;
const unitAddress = 1;
const firstRegister = 0x0003;
const lastRegister = 0x0080;
const modbus = new ModbusRtu(unitAddress);
const modbusFrame = modbus.requestHoldingRegisters(firstRegister, lastRegister);
const solarman = new SolarmanV5(this.configuration.deviceSerialNumber, true);
const request = solarman.wrapModbusFrame(modbusFrame);
// Functions to handle socket events
const makeConnection = () => {
client.connect({ host: this.configuration.deviceIp, port: 8899 });
};
const connectEventHandler = () => {
hasConnected = true;
this.storage.setConnected();
client.write(request);
};
const dataEventHandler = (data: Buffer) => {
try {
const modbusFrame = solarman.unwrapModbusFrame(data);
const values = modbus.fetchHoldingRegisters(modbusFrame);
| const parser = new DeyeRegisters(); |
this.storage.setData(parser.parse(values));
this.outputCallback();
} catch (error) {
if (error instanceof Error) {
this.nodeStatusCallback({
fill: 'red',
shape: 'dot',
text: error.message,
});
}
}
client.end();
};
const timeoutEventHandler = () => {
errorMessage = 'Connection timed out';
client.end();
};
const errorEventHandler = (error: Error) => {
errorMessage = error.message;
client.end();
};
const closeEventHandler = () => {
if (hasConnected) {
return;
}
if (!this.storage.isAvailable()) {
this.nodeStatusCallback({
fill: 'yellow',
shape: 'dot',
text: 'unavailable',
});
} else if (retryCount < 5) {
retryCount++;
this.nodeStatusCallback({
fill: 'yellow',
shape: 'dot',
text: 'retry ' + retryCount,
});
setTimeout(makeConnection, 5000);
} else {
this.nodeStatusCallback({
fill: 'red',
shape: 'dot',
text: errorMessage,
});
}
};
client.on('connect', connectEventHandler);
client.on('data', dataEventHandler);
client.on('timeout', timeoutEventHandler);
client.on('error', errorEventHandler);
client.on('close', closeEventHandler);
this.nodeStatusCallback({
fill: 'yellow',
shape: 'dot',
text: 'updating',
});
makeConnection();
return new Output();
}
}
| src/deye-sun-g3/Action/UpdateAction.ts | binsoul-node-red-contrib-deye-sun-g3-f1f71cc | [
{
"filename": "src/deye-sun-g3/Action/UnavailableAction.ts",
"retrieved_chunk": " });\n return result;\n }\n execute(): Output {\n const result = new Output();\n this.storage.setAvailable(true);\n this.storage.resetRuntime();\n const data = this.storage.getData();\n this.storage.setAvailable(false);\n if (data !== null) {",
"score": 15.331925413877112
},
{
"filename": "src/deye-sun-g3/Action/DailyResetAction.ts",
"retrieved_chunk": " });\n return result;\n }\n execute(): Output {\n const result = new Output();\n const isAvailable = this.storage.isAvailable();\n this.storage.setAvailable(true);\n this.storage.resetCounters();\n const data = this.storage.getData();\n this.storage.setAvailable(isAvailable);",
"score": 14.747980983385961
},
{
"filename": "src/deye-sun-g3/Action/OutputAction.ts",
"retrieved_chunk": " });\n return result;\n }\n execute(): Output {\n const result = new Output();\n const data = this.storage.getData();\n if (data !== null) {\n result.setValue('output', data);\n result.setNodeStatus({\n fill: 'green',",
"score": 12.424118090977464
},
{
"filename": "src/deye-sun-g3/ActionFactory.ts",
"retrieved_chunk": " constructor(RED: NodeAPI, node: Node, configuration: Configuration) {\n this.RED = RED;\n this.node = node;\n this.configuration = configuration;\n this.storage = new Storage(configuration);\n }\n build(message: Message): Action | Array<Action> | null {\n const data: MessageData = message.data;\n const command = data.command;\n if (this.firstMessage) {",
"score": 11.246523841207472
},
{
"filename": "src/deye-sun-g3/Storage.ts",
"retrieved_chunk": " const pv4 = {\n voltage: this.data.pv4Voltage,\n current: this.data.pv4Current,\n power: this.round(this.data.pv4Voltage * this.data.pv4Current, '4'),\n };\n const output = {\n power: this.data.acPower,\n voltage: this.data.acVoltage,\n current: this.data.acCurrent,\n frequency: this.data.acFrequency,",
"score": 10.180019805822702
}
] | typescript | const parser = new DeyeRegisters(); |
import { Action, ActionFactory as ActionFactoryInterface, Message } from '@binsoul/node-red-bundle-processing';
import type { Node, NodeAPI } from '@node-red/registry';
import { NodeMessageInFlow, NodeStatus } from 'node-red';
import { clearTimeout, setTimeout } from 'timers';
import { DailyResetAction } from './Action/DailyResetAction';
import { OutputAction } from './Action/OutputAction';
import { UnavailableAction } from './Action/UnavailableAction';
import { UpdateAction } from './Action/UpdateAction';
import type { Configuration } from './Configuration';
import { Storage } from './Storage';
interface MessageData extends NodeMessageInFlow {
command?: string;
timestamp?: number;
}
function formatTime(timestamp: number) {
const date = new Date(timestamp);
return date.getHours().toString().padStart(2, '0') + ':' + date.getMinutes().toString().padStart(2, '0');
}
/**
* Generates actions.
*/
export class ActionFactory implements ActionFactoryInterface {
private readonly configuration: Configuration;
private readonly RED: NodeAPI;
private readonly node: Node;
private readonly storage: Storage;
private firstMessage = true;
private updateTimer: NodeJS.Timeout | null = null;
private dailyResetTimer: NodeJS.Timeout | null = null;
private unavailableTimer: NodeJS.Timeout | null = null;
constructor(RED: NodeAPI, node: Node, configuration: Configuration) {
this.RED = RED;
this.node = node;
this.configuration = configuration;
this.storage = new Storage(configuration);
}
build(message: Message): Action | Array<Action> | null {
const data: MessageData = message.data;
const command = data.command;
if (this.firstMessage) {
this.firstMessage = false;
this.scheduleUnavailableCheck();
}
if (typeof command !== 'undefined' && ('' + command).trim() !== '') {
switch (command.toLowerCase()) {
case 'update':
this.storage.setUpdating(true);
return new UpdateAction(
this.configuration,
this.storage,
() => this.outputCallback(),
(status: NodeStatus) => this.nodeStatusCallback(status),
);
case 'output':
this.storage.setUpdating(false);
this.scheduleUnavailableCheck();
| return new OutputAction(this.configuration, this.storage); |
case 'dailyreset':
return new DailyResetAction(this.configuration, this.storage);
case 'unavailable':
return new UnavailableAction(this.configuration, this.storage);
}
}
if (!this.storage.isUpdating()) {
if (this.updateTimer !== null) {
clearTimeout(this.updateTimer);
this.updateTimer = null;
}
this.scheduleUpdate();
this.storage.setUpdating(true);
return new UpdateAction(
this.configuration,
this.storage,
() => this.outputCallback(),
(status: NodeStatus) => this.nodeStatusCallback(status),
);
}
return null;
}
setup(): void {
if (this.configuration.updateMode === 'never') {
this.node.status({
fill: 'yellow',
shape: 'dot',
text: 'waiting for message',
});
return;
}
const now = Date.now();
const firstUpdateAt = Math.ceil(now / (this.configuration.updateFrequency * 60000)) * this.configuration.updateFrequency * 60000;
this.updateTimer = setTimeout(() => this.executeUpdate(), firstUpdateAt - now + 1000);
const tomorrow = new Date();
tomorrow.setDate(tomorrow.getDate() + 1);
tomorrow.setHours(0, 0, 0);
this.dailyResetTimer = setTimeout(() => this.executeDailyReset(), tomorrow.getTime() - now);
this.node.status({
fill: 'yellow',
shape: 'dot',
text: `waiting until ${formatTime(firstUpdateAt)}`,
});
}
teardown(): void {
if (this.updateTimer !== null) {
clearTimeout(this.updateTimer);
this.updateTimer = null;
}
if (this.dailyResetTimer !== null) {
clearTimeout(this.dailyResetTimer);
this.dailyResetTimer = null;
}
if (this.unavailableTimer !== null) {
clearTimeout(this.unavailableTimer);
this.unavailableTimer = null;
}
}
/**
* Starts a timer if automatic updates are enabled and no timer exists.
*/
private scheduleUpdate(): void {
if (this.updateTimer !== null || this.configuration.updateMode === 'never') {
return;
}
const now = Date.now();
this.updateTimer = setTimeout(() => this.executeUpdate(), this.getStartOfSlot(now) - now + this.configuration.updateFrequency * 60000 + 1000);
}
/**
* Handles automatic updates.
*/
executeUpdate(): void {
const now = new Date().getTime();
const nextUpdateAt = this.getStartOfSlot(now) + this.configuration.updateFrequency * 60000 + 1000;
this.updateTimer = setTimeout(() => this.executeUpdate(), nextUpdateAt - now);
// trigger node.on('input', () => {})
this.node.receive(<MessageData>{
command: 'update',
timestamp: now,
});
}
/**
* Handles daily resets of counters.
*/
executeDailyReset(): void {
const now = Date.now();
const tomorrow = new Date();
tomorrow.setDate(tomorrow.getDate() + 1);
tomorrow.setHours(0, 0, 0);
this.dailyResetTimer = setTimeout(() => this.executeDailyReset(), tomorrow.getTime() - now);
// trigger node.on('input', () => {})
this.node.receive(<MessageData>{
command: 'dailyReset',
timestamp: now,
});
}
/**
* Starts a timer which changes the device status to unavailable.
*/
private scheduleUnavailableCheck(): void {
if (this.unavailableTimer !== null) {
clearTimeout(this.unavailableTimer);
this.unavailableTimer = null;
}
const now = Date.now();
this.unavailableTimer = setTimeout(() => this.executeUnavailableCheck(), this.getStartOfSlot(now) - now + this.configuration.deviceTimeout * 60000);
}
private executeUnavailableCheck(): void {
this.unavailableTimer = null;
this.node.receive(<MessageData>{
command: 'unavailable',
});
}
outputCallback(): void {
this.node.receive(<MessageData>{
command: 'output',
});
}
nodeStatusCallback(status: NodeStatus): void {
this.node.status(status);
}
private getStartOfSlot(timestamp: number) {
return Math.floor(timestamp / 60000) * 60000;
}
}
| src/deye-sun-g3/ActionFactory.ts | binsoul-node-red-contrib-deye-sun-g3-f1f71cc | [
{
"filename": "src/deye-sun-g3/Action/UpdateAction.ts",
"retrieved_chunk": " private readonly storage: Storage;\n private readonly outputCallback: () => void;\n private readonly nodeStatusCallback: (status: NodeStatus) => void;\n constructor(configuration: Configuration, storage: Storage, outputCallback: () => void, nodeStatusCallback: (status: NodeStatus) => void) {\n this.configuration = configuration;\n this.storage = storage;\n this.outputCallback = outputCallback;\n this.nodeStatusCallback = nodeStatusCallback;\n }\n defineInput(): InputDefinition {",
"score": 48.79839730148545
},
{
"filename": "src/deye-sun-g3/Action/UnavailableAction.ts",
"retrieved_chunk": " });\n return result;\n }\n execute(): Output {\n const result = new Output();\n this.storage.setAvailable(true);\n this.storage.resetRuntime();\n const data = this.storage.getData();\n this.storage.setAvailable(false);\n if (data !== null) {",
"score": 29.24695740829474
},
{
"filename": "src/deye-sun-g3/Action/DailyResetAction.ts",
"retrieved_chunk": " });\n return result;\n }\n execute(): Output {\n const result = new Output();\n const isAvailable = this.storage.isAvailable();\n this.storage.setAvailable(true);\n this.storage.resetCounters();\n const data = this.storage.getData();\n this.storage.setAvailable(isAvailable);",
"score": 27.356638470399265
},
{
"filename": "src/deye-sun-g3/Action/OutputAction.ts",
"retrieved_chunk": "import { Action, InputDefinition, Output, OutputDefinition } from '@binsoul/node-red-bundle-processing';\nimport type { Configuration } from '../Configuration';\nimport { Storage } from '../Storage';\nexport class OutputAction implements Action {\n private readonly configuration: Configuration;\n private storage: Storage;\n constructor(configuration: Configuration, storage: Storage) {\n this.configuration = configuration;\n this.storage = storage;\n }",
"score": 24.861934625949125
},
{
"filename": "src/deye-sun-g3/Action/UpdateAction.ts",
"retrieved_chunk": " const values = modbus.fetchHoldingRegisters(modbusFrame);\n const parser = new DeyeRegisters();\n this.storage.setData(parser.parse(values));\n this.outputCallback();\n } catch (error) {\n if (error instanceof Error) {\n this.nodeStatusCallback({\n fill: 'red',\n shape: 'dot',\n text: error.message,",
"score": 24.31109372611217
}
] | typescript | return new OutputAction(this.configuration, this.storage); |
import type { FastifyInstance, FastifyRequest } from 'fastify'
import { wechatApiPath } from '../const'
import { toSha1 } from '../utils/encryptor'
import type { VerifyQuery } from './types'
export function checkIsWechatRequest(request: FastifyRequest) {
const q = request.query as VerifyQuery
try {
const arr: string[] = [process.env.WECHAT_TOKEN, q.timestamp.toString(), q.nonce.toString()]
arr.sort()
const sha1 = toSha1(arr.join(''))
if (sha1 === q.signature) {
// Success.
return true
}
else {
return false
}
}
catch (error) {
console.error(error)
return false
}
}
function route(server: FastifyInstance) {
// setup hook
server.addHook('onRequest', (request, reply, done) => {
// TODO: Do we need to add this hook for all wechat request?
if (request?.url?.startsWith(wechatApiPath)) {
if (checkIsWechatRequest(request)) {
// Continue.
done()
}
else {
reply.send('who are you?')
}
}
else {
done()
}
})
| server.get(wechatApiPath, (request: FastifyRequest, reply) => { |
const q = request.query as VerifyQuery
if (checkIsWechatRequest(request)) {
// Success.
reply.send(q.echostr)
}
else {
reply.send('who are you?')
}
})
}
export default route
| src/wechat/verify.ts | zhouchaoyuan-azure-openai-node-wechat-624e8f4 | [
{
"filename": "src/wechat/acceptor.ts",
"retrieved_chunk": "function getChatHistoryForUser(requestKey: string) {\n if (!chatHistory.has(requestKey))\n chatHistory.set(requestKey, new FixedQueue<ChatCompletionRequestMessage>(pastMessagesIncluded))\n return chatHistory.get(requestKey)\n}\nfunction route(server: FastifyInstance) {\n server.post(wechatApiPath, (request, reply) => {\n const xml = request.body as any\n handleMsg(xml.xml, reply)\n })",
"score": 10.179617100193912
},
{
"filename": "src/azureopenai/acceptor.ts",
"retrieved_chunk": "import type { FastifyInstance, FastifyReply } from 'fastify'\nimport { chatPath, promptPath } from '../const'\nimport { GetAzureOpenAIAnswerAsync, GetAzureOpenAIChatAnswerAsync } from '../azureopenai/chatgpt'\nfunction route(server: FastifyInstance) {\n server.post(promptPath, (request, reply) => {\n // eslint-disable-next-line no-console\n console.log('prompt')\n handlePrompt(request.body, reply)\n })\n server.post(chatPath, (request, reply) => {",
"score": 7.610991937877356
},
{
"filename": "src/wechat/acceptor.ts",
"retrieved_chunk": " reply.send(generateTextResponse(xml.FromUserName, xml.ToUserName, resp))\n }\n else {\n const checkTime = checkTimes.get(requestKey) as number\n if (checkTime === 2) { // this is the third retry from wechat, we need to response the result within 5s\n const resp = cacheMap.get(requestKey)\n if (resp != null) {\n reply.send(generateTextResponse(xml.FromUserName, xml.ToUserName, resp))\n }\n else {",
"score": 7.236105195024722
},
{
"filename": "src/azureopenai/acceptor.ts",
"retrieved_chunk": " handleChat(request.body, reply)\n })\n}\nasync function handlePrompt(requestBody: any, reply: FastifyReply) {\n GetAzureOpenAIAnswerAsync(requestBody.prompt, 'prompt restapi').then((response) => {\n reply.send(response)\n }).catch((reason) => {\n reply.send(reason)\n })\n}",
"score": 6.466469741606317
},
{
"filename": "src/wechat/acceptor.ts",
"retrieved_chunk": " else {\n if (isUUID(msg)) {\n if (queryCacheMap.has(msg)) {\n const requestKey = queryCacheMap.get(msg)\n if (cacheMap.has(requestKey)) {\n const resp = cacheMap.get(requestKey)\n if (resp != null) {\n reply.send(generateTextResponse(xml.FromUserName, xml.ToUserName, resp))\n return\n }",
"score": 6.4049053254222965
}
] | typescript | server.get(wechatApiPath, (request: FastifyRequest, reply) => { |
import { Action, InputDefinition, Output, OutputDefinition } from '@binsoul/node-red-bundle-processing';
import { ModbusRtu } from '@binsoul/nodejs-modbus';
import { SolarmanV5 } from '@binsoul/nodejs-solarman';
import * as net from 'net';
import { NodeStatus } from 'node-red';
import type { Configuration } from '../Configuration';
import { DeyeRegisters } from '../DeyeRegisters';
import { Storage } from '../Storage';
export class UpdateAction implements Action {
private readonly configuration: Configuration;
private readonly storage: Storage;
private readonly outputCallback: () => void;
private readonly nodeStatusCallback: (status: NodeStatus) => void;
constructor(configuration: Configuration, storage: Storage, outputCallback: () => void, nodeStatusCallback: (status: NodeStatus) => void) {
this.configuration = configuration;
this.storage = storage;
this.outputCallback = outputCallback;
this.nodeStatusCallback = nodeStatusCallback;
}
defineInput(): InputDefinition {
return new InputDefinition();
}
defineOutput(): OutputDefinition {
return new OutputDefinition();
}
execute(): Output {
const client = new net.Socket();
client.setTimeout(5000);
let hasConnected = false;
let errorMessage = '';
let retryCount = 0;
const unitAddress = 1;
const firstRegister = 0x0003;
const lastRegister = 0x0080;
const modbus = new ModbusRtu(unitAddress);
const modbusFrame = modbus.requestHoldingRegisters(firstRegister, lastRegister);
const solarman = new SolarmanV5(this.configuration.deviceSerialNumber, true);
const request = solarman.wrapModbusFrame(modbusFrame);
// Functions to handle socket events
const makeConnection = () => {
client.connect({ host: this.configuration.deviceIp, port: 8899 });
};
const connectEventHandler = () => {
hasConnected = true;
this.storage.setConnected();
client.write(request);
};
const dataEventHandler = (data: Buffer) => {
try {
const modbusFrame = solarman.unwrapModbusFrame(data);
const values = modbus.fetchHoldingRegisters(modbusFrame);
const parser = new DeyeRegisters();
this | .storage.setData(parser.parse(values)); |
this.outputCallback();
} catch (error) {
if (error instanceof Error) {
this.nodeStatusCallback({
fill: 'red',
shape: 'dot',
text: error.message,
});
}
}
client.end();
};
const timeoutEventHandler = () => {
errorMessage = 'Connection timed out';
client.end();
};
const errorEventHandler = (error: Error) => {
errorMessage = error.message;
client.end();
};
const closeEventHandler = () => {
if (hasConnected) {
return;
}
if (!this.storage.isAvailable()) {
this.nodeStatusCallback({
fill: 'yellow',
shape: 'dot',
text: 'unavailable',
});
} else if (retryCount < 5) {
retryCount++;
this.nodeStatusCallback({
fill: 'yellow',
shape: 'dot',
text: 'retry ' + retryCount,
});
setTimeout(makeConnection, 5000);
} else {
this.nodeStatusCallback({
fill: 'red',
shape: 'dot',
text: errorMessage,
});
}
};
client.on('connect', connectEventHandler);
client.on('data', dataEventHandler);
client.on('timeout', timeoutEventHandler);
client.on('error', errorEventHandler);
client.on('close', closeEventHandler);
this.nodeStatusCallback({
fill: 'yellow',
shape: 'dot',
text: 'updating',
});
makeConnection();
return new Output();
}
}
| src/deye-sun-g3/Action/UpdateAction.ts | binsoul-node-red-contrib-deye-sun-g3-f1f71cc | [
{
"filename": "src/deye-sun-g3/Action/UnavailableAction.ts",
"retrieved_chunk": " });\n return result;\n }\n execute(): Output {\n const result = new Output();\n this.storage.setAvailable(true);\n this.storage.resetRuntime();\n const data = this.storage.getData();\n this.storage.setAvailable(false);\n if (data !== null) {",
"score": 17.36150364309605
},
{
"filename": "src/deye-sun-g3/Action/DailyResetAction.ts",
"retrieved_chunk": " });\n return result;\n }\n execute(): Output {\n const result = new Output();\n const isAvailable = this.storage.isAvailable();\n this.storage.setAvailable(true);\n this.storage.resetCounters();\n const data = this.storage.getData();\n this.storage.setAvailable(isAvailable);",
"score": 16.92684172198001
},
{
"filename": "src/deye-sun-g3/Action/OutputAction.ts",
"retrieved_chunk": " });\n return result;\n }\n execute(): Output {\n const result = new Output();\n const data = this.storage.getData();\n if (data !== null) {\n result.setValue('output', data);\n result.setNodeStatus({\n fill: 'green',",
"score": 14.471787885185446
},
{
"filename": "src/deye-sun-g3/ActionFactory.ts",
"retrieved_chunk": " constructor(RED: NodeAPI, node: Node, configuration: Configuration) {\n this.RED = RED;\n this.node = node;\n this.configuration = configuration;\n this.storage = new Storage(configuration);\n }\n build(message: Message): Action | Array<Action> | null {\n const data: MessageData = message.data;\n const command = data.command;\n if (this.firstMessage) {",
"score": 13.597701274878297
},
{
"filename": "src/deye-sun-g3/Storage.ts",
"retrieved_chunk": " temperature: this.data.temperature,\n isAvailable: this.available,\n };\n }\n public setData(data: RegisterValues) {\n if (this.data !== null && this.data.totalEnergy > data.totalEnergy) {\n // totalEnergy should always increase while the node is running\n return;\n }\n this.data = data;",
"score": 12.176880205699613
}
] | typescript | .storage.setData(parser.parse(values)); |
import { Action, ActionFactory as ActionFactoryInterface, Message } from '@binsoul/node-red-bundle-processing';
import type { Node, NodeAPI } from '@node-red/registry';
import { NodeMessageInFlow, NodeStatus } from 'node-red';
import { clearTimeout, setTimeout } from 'timers';
import { DailyResetAction } from './Action/DailyResetAction';
import { OutputAction } from './Action/OutputAction';
import { UnavailableAction } from './Action/UnavailableAction';
import { UpdateAction } from './Action/UpdateAction';
import type { Configuration } from './Configuration';
import { Storage } from './Storage';
interface MessageData extends NodeMessageInFlow {
command?: string;
timestamp?: number;
}
function formatTime(timestamp: number) {
const date = new Date(timestamp);
return date.getHours().toString().padStart(2, '0') + ':' + date.getMinutes().toString().padStart(2, '0');
}
/**
* Generates actions.
*/
export class ActionFactory implements ActionFactoryInterface {
private readonly configuration: Configuration;
private readonly RED: NodeAPI;
private readonly node: Node;
private readonly storage: Storage;
private firstMessage = true;
private updateTimer: NodeJS.Timeout | null = null;
private dailyResetTimer: NodeJS.Timeout | null = null;
private unavailableTimer: NodeJS.Timeout | null = null;
constructor(RED: NodeAPI, node: Node, configuration: Configuration) {
this.RED = RED;
this.node = node;
this.configuration = configuration;
this.storage = new Storage(configuration);
}
build(message: Message): Action | Array<Action> | null {
const data: MessageData = message.data;
const command = data.command;
if (this.firstMessage) {
this.firstMessage = false;
this.scheduleUnavailableCheck();
}
if (typeof command !== 'undefined' && ('' + command).trim() !== '') {
switch (command.toLowerCase()) {
case 'update':
this.storage.setUpdating(true);
return new UpdateAction(
this.configuration,
this.storage,
() => this.outputCallback(),
(status: NodeStatus) => this.nodeStatusCallback(status),
);
case 'output':
this.storage.setUpdating(false);
this.scheduleUnavailableCheck();
return new OutputAction(this.configuration, this.storage);
case 'dailyreset':
| return new DailyResetAction(this.configuration, this.storage); |
case 'unavailable':
return new UnavailableAction(this.configuration, this.storage);
}
}
if (!this.storage.isUpdating()) {
if (this.updateTimer !== null) {
clearTimeout(this.updateTimer);
this.updateTimer = null;
}
this.scheduleUpdate();
this.storage.setUpdating(true);
return new UpdateAction(
this.configuration,
this.storage,
() => this.outputCallback(),
(status: NodeStatus) => this.nodeStatusCallback(status),
);
}
return null;
}
setup(): void {
if (this.configuration.updateMode === 'never') {
this.node.status({
fill: 'yellow',
shape: 'dot',
text: 'waiting for message',
});
return;
}
const now = Date.now();
const firstUpdateAt = Math.ceil(now / (this.configuration.updateFrequency * 60000)) * this.configuration.updateFrequency * 60000;
this.updateTimer = setTimeout(() => this.executeUpdate(), firstUpdateAt - now + 1000);
const tomorrow = new Date();
tomorrow.setDate(tomorrow.getDate() + 1);
tomorrow.setHours(0, 0, 0);
this.dailyResetTimer = setTimeout(() => this.executeDailyReset(), tomorrow.getTime() - now);
this.node.status({
fill: 'yellow',
shape: 'dot',
text: `waiting until ${formatTime(firstUpdateAt)}`,
});
}
teardown(): void {
if (this.updateTimer !== null) {
clearTimeout(this.updateTimer);
this.updateTimer = null;
}
if (this.dailyResetTimer !== null) {
clearTimeout(this.dailyResetTimer);
this.dailyResetTimer = null;
}
if (this.unavailableTimer !== null) {
clearTimeout(this.unavailableTimer);
this.unavailableTimer = null;
}
}
/**
* Starts a timer if automatic updates are enabled and no timer exists.
*/
private scheduleUpdate(): void {
if (this.updateTimer !== null || this.configuration.updateMode === 'never') {
return;
}
const now = Date.now();
this.updateTimer = setTimeout(() => this.executeUpdate(), this.getStartOfSlot(now) - now + this.configuration.updateFrequency * 60000 + 1000);
}
/**
* Handles automatic updates.
*/
executeUpdate(): void {
const now = new Date().getTime();
const nextUpdateAt = this.getStartOfSlot(now) + this.configuration.updateFrequency * 60000 + 1000;
this.updateTimer = setTimeout(() => this.executeUpdate(), nextUpdateAt - now);
// trigger node.on('input', () => {})
this.node.receive(<MessageData>{
command: 'update',
timestamp: now,
});
}
/**
* Handles daily resets of counters.
*/
executeDailyReset(): void {
const now = Date.now();
const tomorrow = new Date();
tomorrow.setDate(tomorrow.getDate() + 1);
tomorrow.setHours(0, 0, 0);
this.dailyResetTimer = setTimeout(() => this.executeDailyReset(), tomorrow.getTime() - now);
// trigger node.on('input', () => {})
this.node.receive(<MessageData>{
command: 'dailyReset',
timestamp: now,
});
}
/**
* Starts a timer which changes the device status to unavailable.
*/
private scheduleUnavailableCheck(): void {
if (this.unavailableTimer !== null) {
clearTimeout(this.unavailableTimer);
this.unavailableTimer = null;
}
const now = Date.now();
this.unavailableTimer = setTimeout(() => this.executeUnavailableCheck(), this.getStartOfSlot(now) - now + this.configuration.deviceTimeout * 60000);
}
private executeUnavailableCheck(): void {
this.unavailableTimer = null;
this.node.receive(<MessageData>{
command: 'unavailable',
});
}
outputCallback(): void {
this.node.receive(<MessageData>{
command: 'output',
});
}
nodeStatusCallback(status: NodeStatus): void {
this.node.status(status);
}
private getStartOfSlot(timestamp: number) {
return Math.floor(timestamp / 60000) * 60000;
}
}
| src/deye-sun-g3/ActionFactory.ts | binsoul-node-red-contrib-deye-sun-g3-f1f71cc | [
{
"filename": "src/deye-sun-g3/Action/UpdateAction.ts",
"retrieved_chunk": " private readonly storage: Storage;\n private readonly outputCallback: () => void;\n private readonly nodeStatusCallback: (status: NodeStatus) => void;\n constructor(configuration: Configuration, storage: Storage, outputCallback: () => void, nodeStatusCallback: (status: NodeStatus) => void) {\n this.configuration = configuration;\n this.storage = storage;\n this.outputCallback = outputCallback;\n this.nodeStatusCallback = nodeStatusCallback;\n }\n defineInput(): InputDefinition {",
"score": 53.26807132498878
},
{
"filename": "src/deye-sun-g3/Action/UnavailableAction.ts",
"retrieved_chunk": " });\n return result;\n }\n execute(): Output {\n const result = new Output();\n this.storage.setAvailable(true);\n this.storage.resetRuntime();\n const data = this.storage.getData();\n this.storage.setAvailable(false);\n if (data !== null) {",
"score": 34.08384111460934
},
{
"filename": "src/deye-sun-g3/Action/DailyResetAction.ts",
"retrieved_chunk": " });\n return result;\n }\n execute(): Output {\n const result = new Output();\n const isAvailable = this.storage.isAvailable();\n this.storage.setAvailable(true);\n this.storage.resetCounters();\n const data = this.storage.getData();\n this.storage.setAvailable(isAvailable);",
"score": 32.39500649512154
},
{
"filename": "src/deye-sun-g3/Action/OutputAction.ts",
"retrieved_chunk": "import { Action, InputDefinition, Output, OutputDefinition } from '@binsoul/node-red-bundle-processing';\nimport type { Configuration } from '../Configuration';\nimport { Storage } from '../Storage';\nexport class OutputAction implements Action {\n private readonly configuration: Configuration;\n private storage: Storage;\n constructor(configuration: Configuration, storage: Storage) {\n this.configuration = configuration;\n this.storage = storage;\n }",
"score": 28.890774498793697
},
{
"filename": "src/deye-sun-g3/Action/DailyResetAction.ts",
"retrieved_chunk": "import { Action, InputDefinition, Output, OutputDefinition } from '@binsoul/node-red-bundle-processing';\nimport type { Configuration } from '../Configuration';\nimport { Storage } from '../Storage';\nexport class DailyResetAction implements Action {\n private readonly configuration: Configuration;\n private storage: Storage;\n constructor(configuration: Configuration, storage: Storage) {\n this.configuration = configuration;\n this.storage = storage;\n }",
"score": 28.890774498793697
}
] | typescript | return new DailyResetAction(this.configuration, this.storage); |
import { GeneratorContext } from './generator-context'
import { DecIndent, DecIndentAndCloseBlock, DocumentParts, IncIndent, inline, jsDoc, NewLine } from '../output/writer'
import * as algokit from '@algorandfoundation/algokit-utils'
import { getEquivalentType } from './helpers/get-equivalent-type'
import { makeSafePropertyIdentifier, makeSafeTypeIdentifier, makeSafeVariableIdentifier } from '../util/sanitization'
export function* appTypes(ctx: GeneratorContext): DocumentParts {
const { app, methodSignatureToUniqueName, name } = ctx
yield* jsDoc(`Defines the types of available calls and state of the ${name} smart contract.`)
yield `export type ${name} = {`
yield IncIndent
yield* jsDoc('Maps method signatures / names to their argument and return types.')
yield 'methods:'
yield IncIndent
for (const method of app.contract.methods) {
const methodSig = algokit.getABIMethodSignature(method)
const uniqueName = methodSignatureToUniqueName[methodSig]
yield `& Record<'${methodSig}'${methodSig !== uniqueName ? ` | '${uniqueName}'` : ''}, {`
yield IncIndent
yield `argsObj: {`
yield IncIndent
const argsMeta = method.args.map((arg) => ({
...arg,
hasDefault: app.hints?.[methodSig]?.default_arguments?.[arg.name],
tsType: getEquivalentType(arg.type, 'input'),
}))
for (const arg of argsMeta) {
if (arg.desc) yield* jsDoc(arg.desc)
yield `${makeSafePropertyIdentifier(arg.name)}${arg.hasDefault ? '?' : ''}: ${arg.tsType}`
}
yield DecIndentAndCloseBlock
yield* inline(
`argsTuple: [`,
argsMeta
.map(
(arg) =>
`${makeSafeVariableIdentifier(arg.name)}: ${getEquivalentType(arg.type, 'input')}${arg.hasDefault ? ' | undefined' : ''}`,
)
.join(', '),
']',
)
const outputStruct = ctx.app.hints?.[methodSig]?.structs?.output
if (method.returns.desc) yield* jsDoc(method.returns.desc)
if (outputStruct) {
yield `returns: ${makeSafeTypeIdentifier(outputStruct.name)}`
} else {
yield `returns: ${getEquivalentType(method.returns.type ?? 'void', 'output')}`
}
yield | DecIndent
yield '}>'
} |
yield DecIndent
yield* appState(ctx)
yield DecIndentAndCloseBlock
yield* jsDoc('Defines the possible abi call signatures')
yield `export type ${name}Sig = keyof ${name}['methods']`
yield* jsDoc(
'Defines an object containing all relevant parameters for a single call to the contract. Where TSignature is undefined, a' +
' bare call is made',
)
yield `export type TypedCallParams<TSignature extends ${name}Sig | undefined> = {`
yield IncIndent
yield 'method: TSignature'
yield 'methodArgs: TSignature extends undefined ? undefined : Array<ABIAppCallArg | undefined>'
yield DecIndent
yield '} & AppClientCallCoreParams & CoreAppCallArgs'
yield* jsDoc('Defines the arguments required for a bare call')
yield `export type BareCallArgs = Omit<RawAppCallArgs, keyof CoreAppCallArgs>`
yield* structs(ctx)
yield* jsDoc(`Maps a method signature from the ${name} smart contract to the method's arguments in either tuple of struct form`)
yield `export type MethodArgs<TSignature extends ${name}Sig> = ${name}['methods'][TSignature]['argsObj' | 'argsTuple']`
yield* jsDoc(`Maps a method signature from the ${name} smart contract to the method's return type`)
yield `export type MethodReturn<TSignature extends ${name}Sig> = ${name}['methods'][TSignature]['returns']`
yield NewLine
}
function* structs({ app }: GeneratorContext): DocumentParts {
if (app.hints === undefined) return
for (const methodHint of Object.values(app.hints)) {
if (methodHint.structs === undefined) continue
for (const struct of Object.values(methodHint.structs)) {
yield* jsDoc(`Represents a ${struct.name} result as a struct`)
yield `export type ${makeSafeTypeIdentifier(struct.name)} = {`
yield IncIndent
for (const [key, type] of struct.elements) {
yield `${makeSafePropertyIdentifier(key)}: ${getEquivalentType(type, 'output')}`
}
yield DecIndentAndCloseBlock
yield* jsDoc(`Converts the tuple representation of a ${struct.name} to the struct representation`)
yield* inline(
`export function ${makeSafeTypeIdentifier(struct.name)}(`,
`[${struct.elements.map(([key]) => makeSafeVariableIdentifier(key)).join(', ')}]: `,
`[${struct.elements.map(([_, type]) => getEquivalentType(type, 'output')).join(', ')}] ) {`,
)
yield IncIndent
yield `return {`
yield IncIndent
for (const [key] of struct.elements) {
const prop = makeSafePropertyIdentifier(key)
const param = makeSafeVariableIdentifier(key)
yield `${prop}${prop !== param ? `: ${param}` : ''},`
}
yield DecIndentAndCloseBlock
yield DecIndentAndCloseBlock
}
}
}
function* appState({ app }: GeneratorContext): DocumentParts {
const hasLocal = app.schema.local?.declared && Object.keys(app.schema.local.declared).length
const hasGlobal = app.schema.global?.declared && Object.keys(app.schema.global.declared).length
if (hasLocal || hasGlobal) {
yield* jsDoc('Defines the shape of the global and local state of the application.')
yield 'state: {'
yield IncIndent
if (hasGlobal) {
yield 'global: {'
yield IncIndent
for (const prop of Object.values(app.schema.global!.declared!)) {
if (prop.descr) {
yield* jsDoc(prop.descr)
}
yield `'${prop.key}'?: ${prop.type === 'uint64' ? 'IntegerState' : 'BinaryState'}`
}
yield DecIndentAndCloseBlock
}
if (hasLocal) {
yield 'local: {'
yield IncIndent
for (const prop of Object.values(app.schema.local!.declared!)) {
if (prop.descr) {
yield* jsDoc(prop.descr)
}
yield `'${prop.key}'?: ${prop.type === 'uint64' ? 'IntegerState' : 'BinaryState'}`
}
yield DecIndentAndCloseBlock
}
yield DecIndentAndCloseBlock
}
}
| src/client/app-types.ts | algorandfoundation-algokit-client-generator-ts-2de43ed | [
{
"filename": "src/client/call-client.ts",
"retrieved_chunk": " params: {\n args: `The arguments for the contract call`,\n params: `Any additional parameters for the call`,\n },\n returns: `The result of the call${method?.returns?.desc ? `: ${method.returns.desc}` : ''}`,\n })\n yield `public ${methodName}(args: MethodArgs<'${methodSignature}'>, params: AppClientCallCoreParams & CoreAppCallArgs = {}) {`\n yield IncIndent\n const outputTypeName = app.hints?.[methodSignature]?.structs?.output?.name\n yield `return this.call(${name}CallFactory.${methodName}(args, params)${",
"score": 33.92927504655952
},
{
"filename": "src/client/call-client.ts",
"retrieved_chunk": " const method = app.contract.methods.find((m) => algokit.getABIMethodSignature(m) === methodSig)\n yield* jsDoc({\n description: `${description} using the ${methodSig} ABI method.`,\n params: {\n args: `The arguments for the smart contract call`,\n params: `Any additional parameters for the call`,\n },\n returns: `The ${verb} result${method?.returns?.desc ? `: ${method.returns.desc}` : ''}`,\n })\n yield `async ${makeSafeMethodIdentifier(uniqueName)}(args: MethodArgs<'${methodSig}'>, params: AppClientCallCoreParams${",
"score": 33.01805857612038
},
{
"filename": "src/client/deploy-types.ts",
"retrieved_chunk": " if (method === BARE_CALL) {\n yield `| TypedCallParams<undefined>`\n } else {\n yield `| TypedCallParams<'${method}'>`\n }\n }\n yield DecIndent\n }\n yield* jsDoc('Defines arguments required for the deploy method.')\n yield `export type ${name}DeployArgs = {`",
"score": 26.93631037141744
},
{
"filename": "src/output/writer.ts",
"retrieved_chunk": " yield ` * @param ${paramName} ${paramDesc}`\n }\n if (docs.returns) yield ` * @returns ${docs.returns}`\n }\n yield ' */'\n}\nfunction writeDocumentPartsTo(document: DocumentParts, { indent = ' ', ...options }: WriteOptions, writer: StringWriter): void {\n if (options.header) writer.write(`${options.header}\\n`)\n if (options.disableEslint) writer.write('/* eslint-disable */\\n')\n const lineModes = [NewLineMode]",
"score": 26.72649514200401
},
{
"filename": "src/client/deploy-types.ts",
"retrieved_chunk": " if (method === BARE_CALL) {\n yield `| (TypedCallParams<undefined> & ${onComplete.type})`\n } else {\n yield `| (TypedCallParams<'${method}'> & ${onComplete.type})`\n }\n }\n yield DecIndent\n }\n if (callConfig.updateMethods.length > 0) {\n yield* jsDoc(`A factory for available 'update' calls`)",
"score": 25.28429816572721
}
] | typescript | DecIndent
yield '}>'
} |
import * as algokit from '@algorandfoundation/algokit-utils'
import { DecIndent, DecIndentAndCloseBlock, DocumentParts, IncIndent, indent, inline, jsDoc, NewLine } from '../output/writer'
import { makeSafeMethodIdentifier, makeSafeTypeIdentifier } from '../util/sanitization'
import { BARE_CALL, MethodList } from './helpers/get-call-config-summary'
import { GeneratorContext } from './generator-context'
import { getCreateOnCompleteOptions } from './deploy-types'
import { composeMethod } from './call-composer'
export function* callClient(ctx: GeneratorContext): DocumentParts {
const { app, name } = ctx
yield* jsDoc(`A client to make calls to the ${app.contract.name} smart contract`)
yield `export class ${makeSafeTypeIdentifier(app.contract.name)}Client {`
yield IncIndent
yield* jsDoc(`The underlying \`ApplicationClient\` for when you want to have more flexibility`)
yield 'public readonly appClient: ApplicationClient'
yield NewLine
yield `private readonly sender: SendTransactionFrom | undefined`
yield NewLine
yield* jsDoc({
description: `Creates a new instance of \`${makeSafeTypeIdentifier(app.contract.name)}Client\``,
params: {
appDetails: 'appDetails The details to identify the app to deploy',
algod: 'An algod client instance',
},
})
yield `constructor(appDetails: AppDetails, private algod: Algodv2) {`
yield IncIndent
yield `this.sender = appDetails.sender`
yield 'this.appClient = algokit.getAppClient({'
yield* indent('...appDetails,', 'app: APP_SPEC')
yield '}, algod)'
yield DecIndent
yield '}'
yield NewLine
yield* jsDoc({
description: 'Checks for decode errors on the AppCallTransactionResult and maps the return value to the specified generic type',
params: {
result: 'The AppCallTransactionResult to be mapped',
returnValueFormatter: 'An optional delegate to format the return value if required',
},
returns: 'The smart contract response with an updated return value',
})
yield* inline(
`protected mapReturnValue<TReturn>`,
`(result: AppCallTransactionResult, returnValueFormatter?: (value: any) => TReturn): `,
`AppCallTransactionResultOfType<TReturn> {`,
)
yield IncIndent
yield `if(result.return?.decodeError) {`
yield* indent(`throw result.return.decodeError`)
yield `}`
yield `const returnValue = result.return?.returnValue !== undefined && returnValueFormatter !== undefined`
yield IncIndent
yield `? returnValueFormatter(result.return.returnValue)`
yield `: result.return?.returnValue as TReturn | undefined`
yield `return { ...result, return: returnValue }`
yield DecIndent
yield DecIndentAndCloseBlock
yield NewLine
yield* jsDoc({
description: 'Calls the ABI method with the matching signature using an onCompletion code of NO_OP',
params: {
typedCallParams: 'An object containing the method signature, args, and any other relevant parameters',
returnValueFormatter: 'An optional delegate which when provided will be used to map non-undefined return values to the target type',
},
returns: 'The result of the smart contract call',
})
yield `public async call<TSignature extends keyof ${name}['methods']>(typedCallParams: TypedCallParams<TSignature>, returnValueFormatter?: (value: any) => MethodReturn<TSignature>) {`
yield IncIndent
yield `return this.mapReturnValue<MethodReturn<TSignature>>(await this.appClient.call(typedCallParams), returnValueFormatter)`
yield DecIndentAndCloseBlock
yield NewLine
yield* opMethods(ctx)
yield* clearState(ctx)
yield* noopMethods(ctx)
yield* getStateMethods(ctx)
yield* composeMethod(ctx)
yield DecIndentAndCloseBlock
}
function* opMethods(ctx: GeneratorContext): DocumentParts {
const { app, callConfig, name } = ctx
yield* jsDoc({
description: `Idempotently deploys the ${app.contract.name} smart contract.`,
params: {
params: 'The arguments for the contract calls and any additional parameters for the call',
},
returns: 'The deployment result',
})
yield `public deploy(params: ${name}DeployArgs & AppClientDeployCoreParams = {}): ReturnType<ApplicationClient['deploy']> {`
yield IncIndent
if (callConfig.createMethods.length) yield `const createArgs = params.createCall?.(${name}CallFactory.create)`
if (callConfig.updateMethods.length) yield `const updateArgs = params.updateCall?.(${name}CallFactory.update)`
if (callConfig.deleteMethods.length) yield `const deleteArgs = params.deleteCall?.(${name}CallFactory.delete)`
yield `return this.appClient.deploy({`
yield IncIndent
yield `...params,`
if (callConfig.updateMethods.length) yield 'updateArgs,'
if (callConfig.deleteMethods.length) yield 'deleteArgs,'
if (callConfig.createMethods.length) {
yield 'createArgs,'
yield `createOnCompleteAction: createArgs?.onCompleteAction,`
}
yield DecIndent
yield `})`
yield DecIndentAndCloseBlock
yield NewLine
yield* operationMethod(ctx, `Creates a new instance of the ${app.contract.name} smart contract`, callConfig.createMethods, 'create', true)
yield* operationMethod(
ctx,
`Updates an existing instance of the ${app.contract.name} smart contract`,
callConfig.updateMethods,
'update',
true,
)
yield* operationMethod(ctx, `Deletes an existing instance of the ${app.contract.name} smart contract`, callConfig.deleteMethods, 'delete')
yield* operationMethod(
ctx,
`Opts the user into an existing instance of the ${app.contract.name} smart contract`,
callConfig.optInMethods,
'optIn',
)
yield* operationMethod(
ctx,
`Makes a close out call to an existing instance of the ${app.contract.name} smart contract`,
callConfig.closeOutMethods,
'closeOut',
)
}
function* operationMethod(
{ app, methodSignatureToUniqueName, name }: GeneratorContext,
description: string,
methods: MethodList,
verb: 'create' | 'update' | 'optIn' | 'closeOut' | 'delete',
includeCompilation?: boolean,
): DocumentParts {
if (methods.length) {
yield* jsDoc(`Gets available ${verb} methods`)
yield `public get ${verb}() {`
yield IncIndent
yield `const $this = this`
yield `return {`
yield IncIndent
for (const methodSig of methods) {
const onComplete = verb === 'create' ? getCreateOnCompleteOptions(methodSig, app) : undefined
if (methodSig === BARE_CALL) {
yield* jsDoc({
description: `${description} using a bare call.`,
params: {
args: `The arguments for the bare call`,
},
returns: `The ${verb} result`,
})
yield `bare(args: BareCallArgs & AppClientCallCoreParams ${
includeCompilation ? '& AppClientCompilationParams ' : ''
}& CoreAppCallArgs${onComplete?.type ? ` & ${onComplete.type}` : ''}${
onComplete?.isOptional !== false ? ' = {}' : ''
}): Promise<AppCallTransactionResultOfType<undefined>> {`
yield* indent(`return $this.appClient.${verb}(args) as unknown as Promise<AppCallTransactionResultOfType<undefined>>`)
yield '},'
} else {
const uniqueName = methodSignatureToUniqueName[methodSig]
const method = app.contract.methods.find((m) => algokit.getABIMethodSignature(m) === methodSig)
yield* jsDoc({
description: `${description} using the ${methodSig} ABI method.`,
params: {
args: `The arguments for the smart contract call`,
params: `Any additional parameters for the call`,
},
returns: `The ${verb} result${method?.returns?.desc ? `: ${method.returns.desc}` : ''}`,
})
| yield `async ${makeSafeMethodIdentifier(uniqueName)}(args: MethodArgs<'${methodSig}'>, params: AppClientCallCoreParams${ |
includeCompilation ? ' & AppClientCompilationParams' : ''
}${onComplete?.type ? ` & ${onComplete.type}` : ''}${
onComplete?.isOptional !== false ? ' = {}' : ''
}): Promise<AppCallTransactionResultOfType<MethodReturn<'${methodSig}'>>> {`
yield* indent(
`return $this.mapReturnValue(await $this.appClient.${verb}(${name}CallFactory.${verb}.${makeSafeMethodIdentifier(
uniqueName,
)}(args, params)))`,
)
yield '},'
}
}
yield DecIndentAndCloseBlock
yield DecIndentAndCloseBlock
yield NewLine
}
}
function* clearState({ app }: GeneratorContext): DocumentParts {
yield* jsDoc({
description: `Makes a clear_state call to an existing instance of the ${app.contract.name} smart contract.`,
params: {
args: `The arguments for the bare call`,
},
returns: `The clear_state result`,
})
yield `public clearState(args: BareCallArgs & AppClientCallCoreParams & CoreAppCallArgs = {}) {`
yield IncIndent
yield `return this.appClient.clearState(args)`
yield DecIndentAndCloseBlock
yield NewLine
}
function* noopMethods({ app, name, callConfig, methodSignatureToUniqueName }: GeneratorContext): DocumentParts {
for (const method of app.contract.methods) {
const methodSignature = algokit.getABIMethodSignature(method)
const methodName = makeSafeMethodIdentifier(methodSignatureToUniqueName[methodSignature])
// Skip methods which don't support a no_op call config
if (!callConfig.callMethods.includes(methodSignature)) continue
yield* jsDoc({
description: `Calls the ${algokit.getABIMethodSignature(method)} ABI method.`,
abiDescription: method.desc,
params: {
args: `The arguments for the contract call`,
params: `Any additional parameters for the call`,
},
returns: `The result of the call${method?.returns?.desc ? `: ${method.returns.desc}` : ''}`,
})
yield `public ${methodName}(args: MethodArgs<'${methodSignature}'>, params: AppClientCallCoreParams & CoreAppCallArgs = {}) {`
yield IncIndent
const outputTypeName = app.hints?.[methodSignature]?.structs?.output?.name
yield `return this.call(${name}CallFactory.${methodName}(args, params)${
outputTypeName === undefined ? '' : `, ${makeSafeTypeIdentifier(outputTypeName)}`
})`
yield DecIndent
yield '}'
yield NewLine
}
}
function* getStateMethods({ app, name }: GeneratorContext): DocumentParts {
const globalStateValues = app.schema.global?.declared && Object.values(app.schema.global?.declared)
const localStateValues = app.schema.local?.declared && Object.values(app.schema.local?.declared)
if (globalStateValues?.length || localStateValues?.length) {
yield* jsDoc({
description: 'Extracts a binary state value out of an AppState dictionary',
params: {
state: 'The state dictionary containing the state value',
key: 'The key of the state value',
},
returns: 'A BinaryState instance containing the state value, or undefined if the key was not found',
})
yield `private static getBinaryState(state: AppState, key: string): BinaryState | undefined {`
yield IncIndent
yield `const value = state[key]`
yield `if (!value) return undefined`
yield `if (!('valueRaw' in value))`
yield* indent(`throw new Error(\`Failed to parse state value for \${key}; received an int when expected a byte array\`)`)
yield `return {`
yield IncIndent
yield `asString(): string {`
yield* indent(`return value.value`)
yield `},`
yield `asByteArray(): Uint8Array {`
yield* indent(`return value.valueRaw`)
yield `}`
yield DecIndentAndCloseBlock
yield DecIndentAndCloseBlock
yield NewLine
yield* jsDoc({
description: 'Extracts a integer state value out of an AppState dictionary',
params: {
state: 'The state dictionary containing the state value',
key: 'The key of the state value',
},
returns: 'An IntegerState instance containing the state value, or undefined if the key was not found',
})
yield `private static getIntegerState(state: AppState, key: string): IntegerState | undefined {`
yield IncIndent
yield `const value = state[key]`
yield `if (!value) return undefined`
yield `if ('valueRaw' in value)`
yield* indent(`throw new Error(\`Failed to parse state value for \${key}; received a byte array when expected a number\`)`)
yield `return {`
yield IncIndent
yield `asBigInt() {`
yield* indent(`return typeof value.value === 'bigint' ? value.value : BigInt(value.value)`)
yield `},`
yield `asNumber(): number {`
yield* indent(`return typeof value.value === 'bigint' ? Number(value.value) : value.value`)
yield `},`
yield DecIndentAndCloseBlock
yield DecIndentAndCloseBlock
yield NewLine
}
if (globalStateValues?.length) {
yield* jsDoc(`Returns the smart contract's global state wrapped in a strongly typed accessor with options to format the stored value`)
yield `public async getGlobalState(): Promise<${name}['state']['global']> {`
yield IncIndent
yield `const state = await this.appClient.getGlobalState()`
yield `return {`
yield IncIndent
for (const stateValue of globalStateValues) {
yield `get ${stateValue.key}() {`
if (stateValue.type === 'uint64') {
yield* indent(`return ${name}Client.getIntegerState(state, '${stateValue.key}')`)
} else {
yield* indent(`return ${name}Client.getBinaryState(state, '${stateValue.key}')`)
}
yield '},'
}
yield DecIndentAndCloseBlock
yield DecIndentAndCloseBlock
yield NewLine
}
if (localStateValues?.length) {
yield* jsDoc({
description: `Returns the smart contract's local state wrapped in a strongly typed accessor with options to format the stored value`,
params: {
account: `The address of the account for which to read local state from`,
},
})
yield `public async getLocalState(account: string | SendTransactionFrom): Promise<${name}['state']['local']> {`
yield IncIndent
yield `const state = await this.appClient.getLocalState(account)`
yield `return {`
yield IncIndent
for (const stateValue of localStateValues) {
yield `get ${stateValue.key}() {`
if (stateValue.type === 'uint64') {
yield* indent(`return ${name}Client.getIntegerState(state, '${stateValue.key}')`)
} else {
yield* indent(`return ${name}Client.getBinaryState(state, '${stateValue.key}')`)
}
yield '},'
}
yield DecIndentAndCloseBlock
yield DecIndentAndCloseBlock
yield NewLine
}
}
| src/client/call-client.ts | algorandfoundation-algokit-client-generator-ts-2de43ed | [
{
"filename": "src/client/call-factory.ts",
"retrieved_chunk": " includeCompilation ? ' & AppClientCompilationParams' : ''\n }${onComplete?.type ? ` & ${onComplete.type}` : ''}${onComplete?.isOptional !== false ? ' = {}' : ''}`,\n })\n } else {\n const method = app.contract.methods.find((m) => algokit.getABIMethodSignature(m) === methodSig)!\n const uniqueName = methodSignatureToUniqueName[methodSig]\n yield* jsDoc({\n description: `${description} using the ${methodSig} ABI method`,\n params: {\n args: `Any args for the contract call`,",
"score": 78.59486891309905
},
{
"filename": "src/client/call-composer-types.ts",
"retrieved_chunk": " yield* jsDoc({\n description: `${description} using the ${methodSig} ABI method.`,\n params: {\n args: `The arguments for the smart contract call`,\n params: `Any additional parameters for the call`,\n },\n returns: `The typed transaction composer so you can fluently chain multiple calls or call execute to execute all queued up transactions`,\n })\n yield `${makeSafeMethodIdentifier(uniqueName)}(args: MethodArgs<'${methodSig}'>, params${\n onComplete?.isOptional !== false ? '?' : ''",
"score": 75.61518654877946
},
{
"filename": "src/client/call-composer-types.ts",
"retrieved_chunk": " if (!callConfig.callMethods.includes(methodSignature)) continue\n yield* jsDoc({\n description: `Calls the ${algokit.getABIMethodSignature(method)} ABI method.`,\n abiDescription: method.desc,\n params: {\n args: `The arguments for the contract call`,\n params: `Any additional parameters for the call`,\n },\n returns: `The typed transaction composer so you can fluently chain multiple calls or call execute to execute all queued up transactions`,\n })",
"score": 64.10972824473157
},
{
"filename": "src/client/call-factory.ts",
"retrieved_chunk": " params: `Any additional parameters for the call`,\n },\n returns: `A TypedCallParams object for the call`,\n })\n yield* factoryMethod({\n isNested: true,\n name: makeSafeMethodIdentifier(uniqueName),\n signature: methodSig,\n args: method.args,\n paramTypes: `AppClientCallCoreParams & CoreAppCallArgs${includeCompilation ? ' & AppClientCompilationParams' : ''}${",
"score": 58.69520447773919
},
{
"filename": "src/client/call-factory.ts",
"retrieved_chunk": "function* callFactoryMethod({ methodSignatureToUniqueName, callConfig }: GeneratorContext, method: ContractMethod) {\n const methodSignature = algokit.getABIMethodSignature(method)\n if (!callConfig.callMethods.includes(methodSignature)) return\n yield* jsDoc({\n description: `Constructs a no op call for the ${methodSignature} ABI method`,\n abiDescription: method.desc,\n params: {\n args: `Any args for the contract call`,\n params: `Any additional parameters for the call`,\n },",
"score": 58.69209730674619
}
] | typescript | yield `async ${makeSafeMethodIdentifier(uniqueName)}(args: MethodArgs<'${methodSig}'>, params: AppClientCallCoreParams${ |
import * as algokit from '@algorandfoundation/algokit-utils'
import { DecIndent, DecIndentAndCloseBlock, DocumentParts, IncIndent, indent, inline, jsDoc, NewLine } from '../output/writer'
import { makeSafeMethodIdentifier, makeSafeTypeIdentifier } from '../util/sanitization'
import { BARE_CALL, MethodList } from './helpers/get-call-config-summary'
import { GeneratorContext } from './generator-context'
import { getCreateOnCompleteOptions } from './deploy-types'
import { composeMethod } from './call-composer'
export function* callClient(ctx: GeneratorContext): DocumentParts {
const { app, name } = ctx
yield* jsDoc(`A client to make calls to the ${app.contract.name} smart contract`)
yield `export class ${makeSafeTypeIdentifier(app.contract.name)}Client {`
yield IncIndent
yield* jsDoc(`The underlying \`ApplicationClient\` for when you want to have more flexibility`)
yield 'public readonly appClient: ApplicationClient'
yield NewLine
yield `private readonly sender: SendTransactionFrom | undefined`
yield NewLine
yield* jsDoc({
description: `Creates a new instance of \`${makeSafeTypeIdentifier(app.contract.name)}Client\``,
params: {
appDetails: 'appDetails The details to identify the app to deploy',
algod: 'An algod client instance',
},
})
yield `constructor(appDetails: AppDetails, private algod: Algodv2) {`
yield IncIndent
yield `this.sender = appDetails.sender`
yield 'this.appClient = algokit.getAppClient({'
yield* indent('...appDetails,', 'app: APP_SPEC')
yield '}, algod)'
yield DecIndent
yield '}'
yield NewLine
yield* jsDoc({
description: 'Checks for decode errors on the AppCallTransactionResult and maps the return value to the specified generic type',
params: {
result: 'The AppCallTransactionResult to be mapped',
returnValueFormatter: 'An optional delegate to format the return value if required',
},
returns: 'The smart contract response with an updated return value',
})
yield* inline(
`protected mapReturnValue<TReturn>`,
`(result: AppCallTransactionResult, returnValueFormatter?: (value: any) => TReturn): `,
`AppCallTransactionResultOfType<TReturn> {`,
)
yield IncIndent
yield `if(result.return?.decodeError) {`
yield* indent(`throw result.return.decodeError`)
yield `}`
yield `const returnValue = result.return?.returnValue !== undefined && returnValueFormatter !== undefined`
yield IncIndent
yield `? returnValueFormatter(result.return.returnValue)`
yield `: result.return?.returnValue as TReturn | undefined`
yield `return { ...result, return: returnValue }`
yield DecIndent
yield DecIndentAndCloseBlock
yield NewLine
yield* jsDoc({
description: 'Calls the ABI method with the matching signature using an onCompletion code of NO_OP',
params: {
typedCallParams: 'An object containing the method signature, args, and any other relevant parameters',
returnValueFormatter: 'An optional delegate which when provided will be used to map non-undefined return values to the target type',
},
returns: 'The result of the smart contract call',
})
yield `public async call<TSignature extends keyof ${name}['methods']>(typedCallParams: TypedCallParams<TSignature>, returnValueFormatter?: (value: any) => MethodReturn<TSignature>) {`
yield IncIndent
yield `return this.mapReturnValue<MethodReturn<TSignature>>(await this.appClient.call(typedCallParams), returnValueFormatter)`
yield DecIndentAndCloseBlock
yield NewLine
yield* opMethods(ctx)
yield* clearState(ctx)
yield* noopMethods(ctx)
yield* getStateMethods(ctx)
yield* composeMethod(ctx)
yield DecIndentAndCloseBlock
}
function* opMethods(ctx: GeneratorContext): DocumentParts {
const { app, callConfig, name } = ctx
yield* jsDoc({
description: `Idempotently deploys the ${app.contract.name} smart contract.`,
params: {
params: 'The arguments for the contract calls and any additional parameters for the call',
},
returns: 'The deployment result',
})
yield `public deploy(params: ${name}DeployArgs & AppClientDeployCoreParams = {}): ReturnType<ApplicationClient['deploy']> {`
yield IncIndent
if (callConfig.createMethods.length) yield `const createArgs = params.createCall?.(${name}CallFactory.create)`
if (callConfig.updateMethods.length) yield `const updateArgs = params.updateCall?.(${name}CallFactory.update)`
if (callConfig.deleteMethods.length) yield `const deleteArgs = params.deleteCall?.(${name}CallFactory.delete)`
yield `return this.appClient.deploy({`
yield IncIndent
yield `...params,`
if (callConfig.updateMethods.length) yield 'updateArgs,'
if (callConfig.deleteMethods.length) yield 'deleteArgs,'
if (callConfig.createMethods.length) {
yield 'createArgs,'
yield `createOnCompleteAction: createArgs?.onCompleteAction,`
}
yield DecIndent
yield `})`
yield DecIndentAndCloseBlock
yield NewLine
yield* operationMethod(ctx, `Creates a new instance of the ${app.contract.name} smart contract`, callConfig.createMethods, 'create', true)
yield* operationMethod(
ctx,
`Updates an existing instance of the ${app.contract.name} smart contract`,
callConfig.updateMethods,
'update',
true,
)
yield* operationMethod(ctx, `Deletes an existing instance of the ${app.contract.name} smart contract`, callConfig.deleteMethods, 'delete')
yield* operationMethod(
ctx,
`Opts the user into an existing instance of the ${app.contract.name} smart contract`,
callConfig.optInMethods,
'optIn',
)
yield* operationMethod(
ctx,
`Makes a close out call to an existing instance of the ${app.contract.name} smart contract`,
callConfig.closeOutMethods,
'closeOut',
)
}
function* operationMethod(
{ app, methodSignatureToUniqueName, name }: GeneratorContext,
description: string,
methods: MethodList,
verb: 'create' | 'update' | 'optIn' | 'closeOut' | 'delete',
includeCompilation?: boolean,
): DocumentParts {
if (methods.length) {
yield* jsDoc(`Gets available ${verb} methods`)
yield `public get ${verb}() {`
yield IncIndent
yield `const $this = this`
yield `return {`
yield IncIndent
for (const methodSig of methods) {
const onComplete = verb === 'create' ? getCreateOnCompleteOptions(methodSig, app) : undefined
if (methodSig === BARE_CALL) {
yield* jsDoc({
description: `${description} using a bare call.`,
params: {
args: `The arguments for the bare call`,
},
returns: `The ${verb} result`,
})
yield `bare(args: BareCallArgs & AppClientCallCoreParams ${
includeCompilation ? '& AppClientCompilationParams ' : ''
}& CoreAppCallArgs${onComplete?.type ? ` & ${onComplete.type}` : ''}${
onComplete?.isOptional !== false ? ' = {}' : ''
}): Promise<AppCallTransactionResultOfType<undefined>> {`
yield* indent(`return $this.appClient.${verb}(args) as unknown as Promise<AppCallTransactionResultOfType<undefined>>`)
yield '},'
} else {
const uniqueName = methodSignatureToUniqueName[methodSig]
const method = app.contract.methods.find | ((m) => algokit.getABIMethodSignature(m) === methodSig)
yield* jsDoc({ |
description: `${description} using the ${methodSig} ABI method.`,
params: {
args: `The arguments for the smart contract call`,
params: `Any additional parameters for the call`,
},
returns: `The ${verb} result${method?.returns?.desc ? `: ${method.returns.desc}` : ''}`,
})
yield `async ${makeSafeMethodIdentifier(uniqueName)}(args: MethodArgs<'${methodSig}'>, params: AppClientCallCoreParams${
includeCompilation ? ' & AppClientCompilationParams' : ''
}${onComplete?.type ? ` & ${onComplete.type}` : ''}${
onComplete?.isOptional !== false ? ' = {}' : ''
}): Promise<AppCallTransactionResultOfType<MethodReturn<'${methodSig}'>>> {`
yield* indent(
`return $this.mapReturnValue(await $this.appClient.${verb}(${name}CallFactory.${verb}.${makeSafeMethodIdentifier(
uniqueName,
)}(args, params)))`,
)
yield '},'
}
}
yield DecIndentAndCloseBlock
yield DecIndentAndCloseBlock
yield NewLine
}
}
function* clearState({ app }: GeneratorContext): DocumentParts {
yield* jsDoc({
description: `Makes a clear_state call to an existing instance of the ${app.contract.name} smart contract.`,
params: {
args: `The arguments for the bare call`,
},
returns: `The clear_state result`,
})
yield `public clearState(args: BareCallArgs & AppClientCallCoreParams & CoreAppCallArgs = {}) {`
yield IncIndent
yield `return this.appClient.clearState(args)`
yield DecIndentAndCloseBlock
yield NewLine
}
function* noopMethods({ app, name, callConfig, methodSignatureToUniqueName }: GeneratorContext): DocumentParts {
for (const method of app.contract.methods) {
const methodSignature = algokit.getABIMethodSignature(method)
const methodName = makeSafeMethodIdentifier(methodSignatureToUniqueName[methodSignature])
// Skip methods which don't support a no_op call config
if (!callConfig.callMethods.includes(methodSignature)) continue
yield* jsDoc({
description: `Calls the ${algokit.getABIMethodSignature(method)} ABI method.`,
abiDescription: method.desc,
params: {
args: `The arguments for the contract call`,
params: `Any additional parameters for the call`,
},
returns: `The result of the call${method?.returns?.desc ? `: ${method.returns.desc}` : ''}`,
})
yield `public ${methodName}(args: MethodArgs<'${methodSignature}'>, params: AppClientCallCoreParams & CoreAppCallArgs = {}) {`
yield IncIndent
const outputTypeName = app.hints?.[methodSignature]?.structs?.output?.name
yield `return this.call(${name}CallFactory.${methodName}(args, params)${
outputTypeName === undefined ? '' : `, ${makeSafeTypeIdentifier(outputTypeName)}`
})`
yield DecIndent
yield '}'
yield NewLine
}
}
function* getStateMethods({ app, name }: GeneratorContext): DocumentParts {
const globalStateValues = app.schema.global?.declared && Object.values(app.schema.global?.declared)
const localStateValues = app.schema.local?.declared && Object.values(app.schema.local?.declared)
if (globalStateValues?.length || localStateValues?.length) {
yield* jsDoc({
description: 'Extracts a binary state value out of an AppState dictionary',
params: {
state: 'The state dictionary containing the state value',
key: 'The key of the state value',
},
returns: 'A BinaryState instance containing the state value, or undefined if the key was not found',
})
yield `private static getBinaryState(state: AppState, key: string): BinaryState | undefined {`
yield IncIndent
yield `const value = state[key]`
yield `if (!value) return undefined`
yield `if (!('valueRaw' in value))`
yield* indent(`throw new Error(\`Failed to parse state value for \${key}; received an int when expected a byte array\`)`)
yield `return {`
yield IncIndent
yield `asString(): string {`
yield* indent(`return value.value`)
yield `},`
yield `asByteArray(): Uint8Array {`
yield* indent(`return value.valueRaw`)
yield `}`
yield DecIndentAndCloseBlock
yield DecIndentAndCloseBlock
yield NewLine
yield* jsDoc({
description: 'Extracts a integer state value out of an AppState dictionary',
params: {
state: 'The state dictionary containing the state value',
key: 'The key of the state value',
},
returns: 'An IntegerState instance containing the state value, or undefined if the key was not found',
})
yield `private static getIntegerState(state: AppState, key: string): IntegerState | undefined {`
yield IncIndent
yield `const value = state[key]`
yield `if (!value) return undefined`
yield `if ('valueRaw' in value)`
yield* indent(`throw new Error(\`Failed to parse state value for \${key}; received a byte array when expected a number\`)`)
yield `return {`
yield IncIndent
yield `asBigInt() {`
yield* indent(`return typeof value.value === 'bigint' ? value.value : BigInt(value.value)`)
yield `},`
yield `asNumber(): number {`
yield* indent(`return typeof value.value === 'bigint' ? Number(value.value) : value.value`)
yield `},`
yield DecIndentAndCloseBlock
yield DecIndentAndCloseBlock
yield NewLine
}
if (globalStateValues?.length) {
yield* jsDoc(`Returns the smart contract's global state wrapped in a strongly typed accessor with options to format the stored value`)
yield `public async getGlobalState(): Promise<${name}['state']['global']> {`
yield IncIndent
yield `const state = await this.appClient.getGlobalState()`
yield `return {`
yield IncIndent
for (const stateValue of globalStateValues) {
yield `get ${stateValue.key}() {`
if (stateValue.type === 'uint64') {
yield* indent(`return ${name}Client.getIntegerState(state, '${stateValue.key}')`)
} else {
yield* indent(`return ${name}Client.getBinaryState(state, '${stateValue.key}')`)
}
yield '},'
}
yield DecIndentAndCloseBlock
yield DecIndentAndCloseBlock
yield NewLine
}
if (localStateValues?.length) {
yield* jsDoc({
description: `Returns the smart contract's local state wrapped in a strongly typed accessor with options to format the stored value`,
params: {
account: `The address of the account for which to read local state from`,
},
})
yield `public async getLocalState(account: string | SendTransactionFrom): Promise<${name}['state']['local']> {`
yield IncIndent
yield `const state = await this.appClient.getLocalState(account)`
yield `return {`
yield IncIndent
for (const stateValue of localStateValues) {
yield `get ${stateValue.key}() {`
if (stateValue.type === 'uint64') {
yield* indent(`return ${name}Client.getIntegerState(state, '${stateValue.key}')`)
} else {
yield* indent(`return ${name}Client.getBinaryState(state, '${stateValue.key}')`)
}
yield '},'
}
yield DecIndentAndCloseBlock
yield DecIndentAndCloseBlock
yield NewLine
}
}
| src/client/call-client.ts | algorandfoundation-algokit-client-generator-ts-2de43ed | [
{
"filename": "src/client/call-factory.ts",
"retrieved_chunk": " includeCompilation ? ' & AppClientCompilationParams' : ''\n }${onComplete?.type ? ` & ${onComplete.type}` : ''}${onComplete?.isOptional !== false ? ' = {}' : ''}`,\n })\n } else {\n const method = app.contract.methods.find((m) => algokit.getABIMethodSignature(m) === methodSig)!\n const uniqueName = methodSignatureToUniqueName[methodSig]\n yield* jsDoc({\n description: `${description} using the ${methodSig} ABI method`,\n params: {\n args: `Any args for the contract call`,",
"score": 61.35790773390775
},
{
"filename": "src/client/call-composer.ts",
"retrieved_chunk": " if (methods.length) {\n yield `get ${verb}() {`\n yield IncIndent\n yield `const $this = this`\n yield `return {`\n yield IncIndent\n for (const methodSig of methods) {\n const onComplete = verb === 'create' ? getCreateOnCompleteOptions(methodSig, app) : undefined\n if (methodSig === BARE_CALL) {\n yield `bare(args${onComplete?.isOptional !== false ? '?' : ''}: BareCallArgs & AppClientCallCoreParams ${",
"score": 39.017281980281645
},
{
"filename": "src/client/call-composer.ts",
"retrieved_chunk": " includeCompilation ? '& AppClientCompilationParams ' : ''\n }& CoreAppCallArgs${onComplete?.type ? ` & ${onComplete.type}` : ''}) {`\n yield IncIndent\n yield `promiseChain = promiseChain.then(() => client.${verb}.bare({...args, sendParams: {...args?.sendParams, skipSending: true, atc}}))`\n yield `resultMappers.push(undefined)`\n yield `return $this`\n yield DecIndent\n yield '},'\n } else {\n const uniqueName = methodSignatureToUniqueName[methodSig]",
"score": 37.576109605352826
},
{
"filename": "src/client/call-composer.ts",
"retrieved_chunk": " const methodName = makeSafeMethodIdentifier(uniqueName)\n yield `${methodName}(args: MethodArgs<'${methodSig}'>, params${\n onComplete?.isOptional !== false ? '?' : ''\n }: AppClientCallCoreParams${includeCompilation ? ' & AppClientCompilationParams' : ''}${\n onComplete?.type ? ` & ${onComplete.type}` : ''\n }) {`\n yield IncIndent\n yield `promiseChain = promiseChain.then(() => client.${verb}.${methodName}(args, {...params, sendParams: {...params?.sendParams, skipSending: true, atc}}))`\n const outputTypeName = app.hints?.[methodSig]?.structs?.output?.name\n yield `resultMappers.push(${outputTypeName ?? 'undefined'})`",
"score": 34.11640736773981
},
{
"filename": "src/client/call-composer-types.ts",
"retrieved_chunk": " params: {\n args: `The arguments for the bare call`,\n },\n returns: `The typed transaction composer so you can fluently chain multiple calls or call execute to execute all queued up transactions`,\n })\n yield `bare(args${onComplete?.isOptional !== false ? '?' : ''}: BareCallArgs & AppClientCallCoreParams ${\n includeCompilation ? '& AppClientCompilationParams ' : ''\n }& CoreAppCallArgs${onComplete?.type ? ` & ${onComplete.type}` : ''}): ${name}Composer<[...TReturns, undefined]>`\n } else {\n const uniqueName = methodSignatureToUniqueName[methodSig]",
"score": 33.58465042854316
}
] | typescript | ((m) => algokit.getABIMethodSignature(m) === methodSig)
yield* jsDoc({ |
import { GeneratorContext } from './generator-context'
import { DecIndent, DecIndentAndCloseBlock, DocumentParts, IncIndent, inline, jsDoc, NewLine } from '../output/writer'
import * as algokit from '@algorandfoundation/algokit-utils'
import { getEquivalentType } from './helpers/get-equivalent-type'
import { makeSafePropertyIdentifier, makeSafeTypeIdentifier, makeSafeVariableIdentifier } from '../util/sanitization'
export function* appTypes(ctx: GeneratorContext): DocumentParts {
const { app, methodSignatureToUniqueName, name } = ctx
yield* jsDoc(`Defines the types of available calls and state of the ${name} smart contract.`)
yield `export type ${name} = {`
yield IncIndent
yield* jsDoc('Maps method signatures / names to their argument and return types.')
yield 'methods:'
yield IncIndent
for (const method of app.contract.methods) {
const methodSig = algokit.getABIMethodSignature(method)
const uniqueName = methodSignatureToUniqueName[methodSig]
yield `& Record<'${methodSig}'${methodSig !== uniqueName ? ` | '${uniqueName}'` : ''}, {`
yield IncIndent
yield `argsObj: {`
yield IncIndent
const argsMeta = method.args.map((arg) => ({
...arg,
hasDefault: app.hints?.[methodSig]?.default_arguments?.[arg.name],
tsType: getEquivalentType(arg.type, 'input'),
}))
for (const arg of argsMeta) {
if (arg.desc) yield* jsDoc(arg.desc)
yield `${makeSafePropertyIdentifier(arg.name)}${arg.hasDefault ? '?' : ''}: ${arg.tsType}`
}
yield DecIndentAndCloseBlock
yield* inline(
`argsTuple: [`,
argsMeta
.map(
(arg) =>
`${makeSafeVariableIdentifier(arg.name)}: ${getEquivalentType(arg.type, 'input')}${arg.hasDefault ? ' | undefined' : ''}`,
)
.join(', '),
']',
)
const outputStruct = ctx.app.hints?.[methodSig]?.structs?.output
if (method.returns.desc) yield* jsDoc(method.returns.desc)
if (outputStruct) {
yield `returns: ${makeSafeTypeIdentifier(outputStruct.name)}`
} else {
yield `returns: ${getEquivalentType(method.returns.type ?? 'void', 'output')}`
}
yield DecIndent
yield '}>'
}
yield DecIndent
yield* appState(ctx)
yield DecIndentAndCloseBlock
yield* jsDoc('Defines the possible abi call signatures')
yield `export type ${name}Sig = keyof ${name}['methods']`
yield* jsDoc(
'Defines an object containing all relevant parameters for a single call to the contract. Where TSignature is undefined, a' +
' bare call is made',
)
yield `export type TypedCallParams<TSignature extends ${name}Sig | undefined> = {`
yield IncIndent
yield 'method: TSignature'
yield 'methodArgs: TSignature extends undefined ? undefined : Array<ABIAppCallArg | undefined>'
yield DecIndent
yield '} & AppClientCallCoreParams & CoreAppCallArgs'
yield* jsDoc('Defines the arguments required for a bare call')
yield `export type BareCallArgs = Omit<RawAppCallArgs, keyof CoreAppCallArgs>`
yield* structs(ctx)
yield* jsDoc(`Maps a method signature from the ${name} smart contract to the method's arguments in either tuple of struct form`)
yield `export type MethodArgs<TSignature extends ${name}Sig> = ${name}['methods'][TSignature]['argsObj' | 'argsTuple']`
yield* jsDoc(`Maps a method signature from the ${name} smart contract to the method's return type`)
yield `export type MethodReturn<TSignature extends ${name}Sig> = ${name}['methods'][TSignature]['returns']`
yield NewLine
}
function* structs({ app }: GeneratorContext): DocumentParts {
if (app.hints === undefined) return
for (const methodHint of Object.values(app.hints)) {
if (methodHint.structs === undefined) continue
for (const struct of Object.values(methodHint.structs)) {
yield* jsDoc(`Represents a ${struct.name} result as a struct`)
yield `export type ${makeSafeTypeIdentifier(struct.name)} = {`
yield IncIndent
for (const [key, type] of struct.elements) {
yield `${makeSafePropertyIdentifier(key)}: ${getEquivalentType(type, 'output')}`
}
yield DecIndentAndCloseBlock
yield* jsDoc(`Converts the tuple representation of a ${struct.name} to the struct representation`)
yield* inline(
`export function ${makeSafeTypeIdentifier(struct.name)}(`,
`[${struct.elements.map(([key]) => makeSafeVariableIdentifier(key)).join(', ')}]: `,
`[${struct.elements.map(([_, type]) => getEquivalentType(type, 'output')).join(', ')}] ) {`,
)
yield IncIndent
yield `return {`
yield IncIndent
for (const [key] of struct.elements) {
const prop = makeSafePropertyIdentifier(key)
const param = makeSafeVariableIdentifier(key)
yield `${prop}${prop !== param ? `: ${param}` : ''},`
}
yield DecIndentAndCloseBlock
yield DecIndentAndCloseBlock
}
}
}
function* appState({ app }: GeneratorContext): DocumentParts {
const hasLocal = app.schema.local?.declared && Object.keys(app.schema.local.declared).length
const hasGlobal = app.schema.global?.declared && Object.keys(app.schema.global.declared).length
if (hasLocal || hasGlobal) {
yield* jsDoc('Defines the shape of the global and local state of the application.')
yield 'state: {'
yield IncIndent
if (hasGlobal) {
yield 'global: {'
yield IncIndent
for (const prop of Object.values(app.schema.global!.declared!)) {
| if (prop.descr) { |
yield* jsDoc(prop.descr)
}
yield `'${prop.key}'?: ${prop.type === 'uint64' ? 'IntegerState' : 'BinaryState'}`
}
yield DecIndentAndCloseBlock
}
if (hasLocal) {
yield 'local: {'
yield IncIndent
for (const prop of Object.values(app.schema.local!.declared!)) {
if (prop.descr) {
yield* jsDoc(prop.descr)
}
yield `'${prop.key}'?: ${prop.type === 'uint64' ? 'IntegerState' : 'BinaryState'}`
}
yield DecIndentAndCloseBlock
}
yield DecIndentAndCloseBlock
}
}
| src/client/app-types.ts | algorandfoundation-algokit-client-generator-ts-2de43ed | [
{
"filename": "src/client/call-client.ts",
"retrieved_chunk": " outputTypeName === undefined ? '' : `, ${makeSafeTypeIdentifier(outputTypeName)}`\n })`\n yield DecIndent\n yield '}'\n yield NewLine\n }\n}\nfunction* getStateMethods({ app, name }: GeneratorContext): DocumentParts {\n const globalStateValues = app.schema.global?.declared && Object.values(app.schema.global?.declared)\n const localStateValues = app.schema.local?.declared && Object.values(app.schema.local?.declared)",
"score": 93.15510873645883
},
{
"filename": "src/client/call-client.ts",
"retrieved_chunk": " yield NewLine\n }\n if (globalStateValues?.length) {\n yield* jsDoc(`Returns the smart contract's global state wrapped in a strongly typed accessor with options to format the stored value`)\n yield `public async getGlobalState(): Promise<${name}['state']['global']> {`\n yield IncIndent\n yield `const state = await this.appClient.getGlobalState()`\n yield `return {`\n yield IncIndent\n for (const stateValue of globalStateValues) {",
"score": 50.71788217375549
},
{
"filename": "src/schema/application.d.ts",
"retrieved_chunk": " * Catch all for fixed length arrays and tuples\n */\n type: string;\n };\n}\n/**\n * The schema for global and local storage\n */\nexport interface SchemaSpec {\n global?: Schema;",
"score": 48.01068915525029
},
{
"filename": "src/schema/application.d.ts",
"retrieved_chunk": " source: \"abi-method\";\n data: ContractMethod;\n }\n | {\n /**\n * The default value should be fetched from global state\n */\n source: \"global-state\";\n /**\n * The key of the state variable",
"score": 41.9672533326132
},
{
"filename": "src/client/call-client.ts",
"retrieved_chunk": " yield NewLine\n }\n if (localStateValues?.length) {\n yield* jsDoc({\n description: `Returns the smart contract's local state wrapped in a strongly typed accessor with options to format the stored value`,\n params: {\n account: `The address of the account for which to read local state from`,\n },\n })\n yield `public async getLocalState(account: string | SendTransactionFrom): Promise<${name}['state']['local']> {`",
"score": 29.917782546240506
}
] | typescript | if (prop.descr) { |
import * as algokit from '@algorandfoundation/algokit-utils'
import { DecIndent, DecIndentAndCloseBlock, DocumentParts, IncIndent, indent, inline, jsDoc, NewLine } from '../output/writer'
import { makeSafeMethodIdentifier, makeSafeTypeIdentifier } from '../util/sanitization'
import { BARE_CALL, MethodList } from './helpers/get-call-config-summary'
import { GeneratorContext } from './generator-context'
import { getCreateOnCompleteOptions } from './deploy-types'
import { composeMethod } from './call-composer'
export function* callClient(ctx: GeneratorContext): DocumentParts {
const { app, name } = ctx
yield* jsDoc(`A client to make calls to the ${app.contract.name} smart contract`)
yield `export class ${makeSafeTypeIdentifier(app.contract.name)}Client {`
yield IncIndent
yield* jsDoc(`The underlying \`ApplicationClient\` for when you want to have more flexibility`)
yield 'public readonly appClient: ApplicationClient'
yield NewLine
yield `private readonly sender: SendTransactionFrom | undefined`
yield NewLine
yield* jsDoc({
description: `Creates a new instance of \`${makeSafeTypeIdentifier(app.contract.name)}Client\``,
params: {
appDetails: 'appDetails The details to identify the app to deploy',
algod: 'An algod client instance',
},
})
yield `constructor(appDetails: AppDetails, private algod: Algodv2) {`
yield IncIndent
yield `this.sender = appDetails.sender`
yield 'this.appClient = algokit.getAppClient({'
yield* indent('...appDetails,', 'app: APP_SPEC')
yield '}, algod)'
yield DecIndent
yield '}'
yield NewLine
yield* jsDoc({
description: 'Checks for decode errors on the AppCallTransactionResult and maps the return value to the specified generic type',
params: {
result: 'The AppCallTransactionResult to be mapped',
returnValueFormatter: 'An optional delegate to format the return value if required',
},
returns: 'The smart contract response with an updated return value',
})
yield* inline(
`protected mapReturnValue<TReturn>`,
`(result: AppCallTransactionResult, returnValueFormatter?: (value: any) => TReturn): `,
`AppCallTransactionResultOfType<TReturn> {`,
)
yield IncIndent
yield `if(result.return?.decodeError) {`
yield* indent(`throw result.return.decodeError`)
yield `}`
yield `const returnValue = result.return?.returnValue !== undefined && returnValueFormatter !== undefined`
yield IncIndent
yield `? returnValueFormatter(result.return.returnValue)`
yield `: result.return?.returnValue as TReturn | undefined`
yield `return { ...result, return: returnValue }`
yield DecIndent
yield DecIndentAndCloseBlock
yield NewLine
yield* jsDoc({
description: 'Calls the ABI method with the matching signature using an onCompletion code of NO_OP',
params: {
typedCallParams: 'An object containing the method signature, args, and any other relevant parameters',
returnValueFormatter: 'An optional delegate which when provided will be used to map non-undefined return values to the target type',
},
returns: 'The result of the smart contract call',
})
yield `public async call<TSignature extends keyof ${name}['methods']>(typedCallParams: TypedCallParams<TSignature>, returnValueFormatter?: (value: any) => MethodReturn<TSignature>) {`
yield IncIndent
yield `return this.mapReturnValue<MethodReturn<TSignature>>(await this.appClient.call(typedCallParams), returnValueFormatter)`
yield DecIndentAndCloseBlock
yield NewLine
yield* opMethods(ctx)
yield* clearState(ctx)
yield* noopMethods(ctx)
yield* getStateMethods(ctx)
yield* composeMethod(ctx)
yield DecIndentAndCloseBlock
}
function* opMethods(ctx: GeneratorContext): DocumentParts {
const { app, callConfig, name } = ctx
yield* jsDoc({
description: `Idempotently deploys the ${app.contract.name} smart contract.`,
params: {
params: 'The arguments for the contract calls and any additional parameters for the call',
},
returns: 'The deployment result',
})
yield `public deploy(params: ${name}DeployArgs & AppClientDeployCoreParams = {}): ReturnType<ApplicationClient['deploy']> {`
yield IncIndent
if (callConfig.createMethods.length) yield `const createArgs = params.createCall?.(${name}CallFactory.create)`
if (callConfig.updateMethods.length) yield `const updateArgs = params.updateCall?.(${name}CallFactory.update)`
if (callConfig.deleteMethods.length) yield `const deleteArgs = params.deleteCall?.(${name}CallFactory.delete)`
yield `return this.appClient.deploy({`
yield IncIndent
yield `...params,`
if (callConfig.updateMethods.length) yield 'updateArgs,'
if (callConfig.deleteMethods.length) yield 'deleteArgs,'
if (callConfig.createMethods.length) {
yield 'createArgs,'
yield `createOnCompleteAction: createArgs?.onCompleteAction,`
}
yield DecIndent
yield `})`
yield DecIndentAndCloseBlock
yield NewLine
yield* operationMethod(ctx, `Creates a new instance of the ${app.contract.name} smart contract`, callConfig.createMethods, 'create', true)
yield* operationMethod(
ctx,
`Updates an existing instance of the ${app.contract.name} smart contract`,
callConfig.updateMethods,
'update',
true,
)
yield* operationMethod(ctx, `Deletes an existing instance of the ${app.contract.name} smart contract`, callConfig.deleteMethods, 'delete')
yield* operationMethod(
ctx,
`Opts the user into an existing instance of the ${app.contract.name} smart contract`,
callConfig.optInMethods,
'optIn',
)
yield* operationMethod(
ctx,
`Makes a close out call to an existing instance of the ${app.contract.name} smart contract`,
callConfig.closeOutMethods,
'closeOut',
)
}
function* operationMethod(
{ app, methodSignatureToUniqueName, name }: GeneratorContext,
description: string,
methods: MethodList,
verb: 'create' | 'update' | 'optIn' | 'closeOut' | 'delete',
includeCompilation?: boolean,
): DocumentParts {
if (methods.length) {
yield* jsDoc(`Gets available ${verb} methods`)
yield `public get ${verb}() {`
yield IncIndent
yield `const $this = this`
yield `return {`
yield IncIndent
for (const methodSig of methods) {
const onComplete = verb === 'create' ? getCreateOnCompleteOptions(methodSig, app) : undefined
if (methodSig === BARE_CALL) {
yield* jsDoc({
description: `${description} using a bare call.`,
params: {
args: `The arguments for the bare call`,
},
returns: `The ${verb} result`,
})
yield `bare(args: BareCallArgs & AppClientCallCoreParams ${
includeCompilation ? '& AppClientCompilationParams ' : ''
}& CoreAppCallArgs${onComplete?.type ? ` & ${onComplete.type}` : ''}${
onComplete?.isOptional !== false ? ' = {}' : ''
}): Promise<AppCallTransactionResultOfType<undefined>> {`
yield* indent(`return $this.appClient.${verb}(args) as unknown as Promise<AppCallTransactionResultOfType<undefined>>`)
yield '},'
} else {
const uniqueName = methodSignatureToUniqueName[methodSig]
| const method = app.contract.methods.find((m) => algokit.getABIMethodSignature(m) === methodSig)
yield* jsDoc({ |
description: `${description} using the ${methodSig} ABI method.`,
params: {
args: `The arguments for the smart contract call`,
params: `Any additional parameters for the call`,
},
returns: `The ${verb} result${method?.returns?.desc ? `: ${method.returns.desc}` : ''}`,
})
yield `async ${makeSafeMethodIdentifier(uniqueName)}(args: MethodArgs<'${methodSig}'>, params: AppClientCallCoreParams${
includeCompilation ? ' & AppClientCompilationParams' : ''
}${onComplete?.type ? ` & ${onComplete.type}` : ''}${
onComplete?.isOptional !== false ? ' = {}' : ''
}): Promise<AppCallTransactionResultOfType<MethodReturn<'${methodSig}'>>> {`
yield* indent(
`return $this.mapReturnValue(await $this.appClient.${verb}(${name}CallFactory.${verb}.${makeSafeMethodIdentifier(
uniqueName,
)}(args, params)))`,
)
yield '},'
}
}
yield DecIndentAndCloseBlock
yield DecIndentAndCloseBlock
yield NewLine
}
}
function* clearState({ app }: GeneratorContext): DocumentParts {
yield* jsDoc({
description: `Makes a clear_state call to an existing instance of the ${app.contract.name} smart contract.`,
params: {
args: `The arguments for the bare call`,
},
returns: `The clear_state result`,
})
yield `public clearState(args: BareCallArgs & AppClientCallCoreParams & CoreAppCallArgs = {}) {`
yield IncIndent
yield `return this.appClient.clearState(args)`
yield DecIndentAndCloseBlock
yield NewLine
}
function* noopMethods({ app, name, callConfig, methodSignatureToUniqueName }: GeneratorContext): DocumentParts {
for (const method of app.contract.methods) {
const methodSignature = algokit.getABIMethodSignature(method)
const methodName = makeSafeMethodIdentifier(methodSignatureToUniqueName[methodSignature])
// Skip methods which don't support a no_op call config
if (!callConfig.callMethods.includes(methodSignature)) continue
yield* jsDoc({
description: `Calls the ${algokit.getABIMethodSignature(method)} ABI method.`,
abiDescription: method.desc,
params: {
args: `The arguments for the contract call`,
params: `Any additional parameters for the call`,
},
returns: `The result of the call${method?.returns?.desc ? `: ${method.returns.desc}` : ''}`,
})
yield `public ${methodName}(args: MethodArgs<'${methodSignature}'>, params: AppClientCallCoreParams & CoreAppCallArgs = {}) {`
yield IncIndent
const outputTypeName = app.hints?.[methodSignature]?.structs?.output?.name
yield `return this.call(${name}CallFactory.${methodName}(args, params)${
outputTypeName === undefined ? '' : `, ${makeSafeTypeIdentifier(outputTypeName)}`
})`
yield DecIndent
yield '}'
yield NewLine
}
}
function* getStateMethods({ app, name }: GeneratorContext): DocumentParts {
const globalStateValues = app.schema.global?.declared && Object.values(app.schema.global?.declared)
const localStateValues = app.schema.local?.declared && Object.values(app.schema.local?.declared)
if (globalStateValues?.length || localStateValues?.length) {
yield* jsDoc({
description: 'Extracts a binary state value out of an AppState dictionary',
params: {
state: 'The state dictionary containing the state value',
key: 'The key of the state value',
},
returns: 'A BinaryState instance containing the state value, or undefined if the key was not found',
})
yield `private static getBinaryState(state: AppState, key: string): BinaryState | undefined {`
yield IncIndent
yield `const value = state[key]`
yield `if (!value) return undefined`
yield `if (!('valueRaw' in value))`
yield* indent(`throw new Error(\`Failed to parse state value for \${key}; received an int when expected a byte array\`)`)
yield `return {`
yield IncIndent
yield `asString(): string {`
yield* indent(`return value.value`)
yield `},`
yield `asByteArray(): Uint8Array {`
yield* indent(`return value.valueRaw`)
yield `}`
yield DecIndentAndCloseBlock
yield DecIndentAndCloseBlock
yield NewLine
yield* jsDoc({
description: 'Extracts a integer state value out of an AppState dictionary',
params: {
state: 'The state dictionary containing the state value',
key: 'The key of the state value',
},
returns: 'An IntegerState instance containing the state value, or undefined if the key was not found',
})
yield `private static getIntegerState(state: AppState, key: string): IntegerState | undefined {`
yield IncIndent
yield `const value = state[key]`
yield `if (!value) return undefined`
yield `if ('valueRaw' in value)`
yield* indent(`throw new Error(\`Failed to parse state value for \${key}; received a byte array when expected a number\`)`)
yield `return {`
yield IncIndent
yield `asBigInt() {`
yield* indent(`return typeof value.value === 'bigint' ? value.value : BigInt(value.value)`)
yield `},`
yield `asNumber(): number {`
yield* indent(`return typeof value.value === 'bigint' ? Number(value.value) : value.value`)
yield `},`
yield DecIndentAndCloseBlock
yield DecIndentAndCloseBlock
yield NewLine
}
if (globalStateValues?.length) {
yield* jsDoc(`Returns the smart contract's global state wrapped in a strongly typed accessor with options to format the stored value`)
yield `public async getGlobalState(): Promise<${name}['state']['global']> {`
yield IncIndent
yield `const state = await this.appClient.getGlobalState()`
yield `return {`
yield IncIndent
for (const stateValue of globalStateValues) {
yield `get ${stateValue.key}() {`
if (stateValue.type === 'uint64') {
yield* indent(`return ${name}Client.getIntegerState(state, '${stateValue.key}')`)
} else {
yield* indent(`return ${name}Client.getBinaryState(state, '${stateValue.key}')`)
}
yield '},'
}
yield DecIndentAndCloseBlock
yield DecIndentAndCloseBlock
yield NewLine
}
if (localStateValues?.length) {
yield* jsDoc({
description: `Returns the smart contract's local state wrapped in a strongly typed accessor with options to format the stored value`,
params: {
account: `The address of the account for which to read local state from`,
},
})
yield `public async getLocalState(account: string | SendTransactionFrom): Promise<${name}['state']['local']> {`
yield IncIndent
yield `const state = await this.appClient.getLocalState(account)`
yield `return {`
yield IncIndent
for (const stateValue of localStateValues) {
yield `get ${stateValue.key}() {`
if (stateValue.type === 'uint64') {
yield* indent(`return ${name}Client.getIntegerState(state, '${stateValue.key}')`)
} else {
yield* indent(`return ${name}Client.getBinaryState(state, '${stateValue.key}')`)
}
yield '},'
}
yield DecIndentAndCloseBlock
yield DecIndentAndCloseBlock
yield NewLine
}
}
| src/client/call-client.ts | algorandfoundation-algokit-client-generator-ts-2de43ed | [
{
"filename": "src/client/call-factory.ts",
"retrieved_chunk": " includeCompilation ? ' & AppClientCompilationParams' : ''\n }${onComplete?.type ? ` & ${onComplete.type}` : ''}${onComplete?.isOptional !== false ? ' = {}' : ''}`,\n })\n } else {\n const method = app.contract.methods.find((m) => algokit.getABIMethodSignature(m) === methodSig)!\n const uniqueName = methodSignatureToUniqueName[methodSig]\n yield* jsDoc({\n description: `${description} using the ${methodSig} ABI method`,\n params: {\n args: `Any args for the contract call`,",
"score": 66.45476921445457
},
{
"filename": "src/client/call-composer.ts",
"retrieved_chunk": " includeCompilation ? '& AppClientCompilationParams ' : ''\n }& CoreAppCallArgs${onComplete?.type ? ` & ${onComplete.type}` : ''}) {`\n yield IncIndent\n yield `promiseChain = promiseChain.then(() => client.${verb}.bare({...args, sendParams: {...args?.sendParams, skipSending: true, atc}}))`\n yield `resultMappers.push(undefined)`\n yield `return $this`\n yield DecIndent\n yield '},'\n } else {\n const uniqueName = methodSignatureToUniqueName[methodSig]",
"score": 42.92444931044365
},
{
"filename": "src/client/call-composer.ts",
"retrieved_chunk": " if (methods.length) {\n yield `get ${verb}() {`\n yield IncIndent\n yield `const $this = this`\n yield `return {`\n yield IncIndent\n for (const methodSig of methods) {\n const onComplete = verb === 'create' ? getCreateOnCompleteOptions(methodSig, app) : undefined\n if (methodSig === BARE_CALL) {\n yield `bare(args${onComplete?.isOptional !== false ? '?' : ''}: BareCallArgs & AppClientCallCoreParams ${",
"score": 39.017281980281645
},
{
"filename": "src/client/call-composer.ts",
"retrieved_chunk": " const methodName = makeSafeMethodIdentifier(uniqueName)\n yield `${methodName}(args: MethodArgs<'${methodSig}'>, params${\n onComplete?.isOptional !== false ? '?' : ''\n }: AppClientCallCoreParams${includeCompilation ? ' & AppClientCompilationParams' : ''}${\n onComplete?.type ? ` & ${onComplete.type}` : ''\n }) {`\n yield IncIndent\n yield `promiseChain = promiseChain.then(() => client.${verb}.${methodName}(args, {...params, sendParams: {...params?.sendParams, skipSending: true, atc}}))`\n const outputTypeName = app.hints?.[methodSig]?.structs?.output?.name\n yield `resultMappers.push(${outputTypeName ?? 'undefined'})`",
"score": 38.7751609002009
},
{
"filename": "src/client/call-composer-types.ts",
"retrieved_chunk": " params: {\n args: `The arguments for the bare call`,\n },\n returns: `The typed transaction composer so you can fluently chain multiple calls or call execute to execute all queued up transactions`,\n })\n yield `bare(args${onComplete?.isOptional !== false ? '?' : ''}: BareCallArgs & AppClientCallCoreParams ${\n includeCompilation ? '& AppClientCompilationParams ' : ''\n }& CoreAppCallArgs${onComplete?.type ? ` & ${onComplete.type}` : ''}): ${name}Composer<[...TReturns, undefined]>`\n } else {\n const uniqueName = methodSignatureToUniqueName[methodSig]",
"score": 38.09792463210611
}
] | typescript | const method = app.contract.methods.find((m) => algokit.getABIMethodSignature(m) === methodSig)
yield* jsDoc({ |
import { GeneratorContext } from './generator-context'
import { DecIndent, DecIndentAndCloseBlock, DocumentParts, IncIndent, inline, jsDoc, NewLine } from '../output/writer'
import * as algokit from '@algorandfoundation/algokit-utils'
import { getEquivalentType } from './helpers/get-equivalent-type'
import { makeSafePropertyIdentifier, makeSafeTypeIdentifier, makeSafeVariableIdentifier } from '../util/sanitization'
export function* appTypes(ctx: GeneratorContext): DocumentParts {
const { app, methodSignatureToUniqueName, name } = ctx
yield* jsDoc(`Defines the types of available calls and state of the ${name} smart contract.`)
yield `export type ${name} = {`
yield IncIndent
yield* jsDoc('Maps method signatures / names to their argument and return types.')
yield 'methods:'
yield IncIndent
for (const method of app.contract.methods) {
const methodSig = algokit.getABIMethodSignature(method)
const uniqueName = methodSignatureToUniqueName[methodSig]
yield `& Record<'${methodSig}'${methodSig !== uniqueName ? ` | '${uniqueName}'` : ''}, {`
yield IncIndent
yield `argsObj: {`
yield IncIndent
const argsMeta = method.args.map((arg) => ({
...arg,
hasDefault: app.hints?.[methodSig]?.default_arguments?.[arg.name],
tsType: getEquivalentType(arg.type, 'input'),
}))
for (const arg of argsMeta) {
if (arg.desc) yield* jsDoc(arg.desc)
yield `${makeSafePropertyIdentifier(arg.name)}${arg.hasDefault ? '?' : ''}: ${arg.tsType}`
}
yield DecIndentAndCloseBlock
yield* inline(
`argsTuple: [`,
argsMeta
.map(
(arg) =>
`${makeSafeVariableIdentifier(arg.name)}: ${getEquivalentType(arg.type, 'input')}${arg.hasDefault ? ' | undefined' : ''}`,
)
.join(', '),
']',
)
const outputStruct = ctx.app.hints?.[methodSig]?.structs?.output
if (method.returns.desc) yield* jsDoc(method.returns.desc)
if (outputStruct) {
yield `returns: ${makeSafeTypeIdentifier(outputStruct.name)}`
} else {
yield `returns: ${getEquivalentType(method.returns.type ?? 'void', 'output')}`
}
yield DecIndent
yield '}>'
}
yield DecIndent
yield* appState(ctx)
yield DecIndentAndCloseBlock
yield* jsDoc('Defines the possible abi call signatures')
yield `export type ${name}Sig = keyof ${name}['methods']`
yield* jsDoc(
'Defines an object containing all relevant parameters for a single call to the contract. Where TSignature is undefined, a' +
' bare call is made',
)
yield `export type TypedCallParams<TSignature extends ${name}Sig | undefined> = {`
yield IncIndent
yield 'method: TSignature'
yield 'methodArgs: TSignature extends undefined ? undefined : Array<ABIAppCallArg | undefined>'
yield DecIndent
yield '} & AppClientCallCoreParams & CoreAppCallArgs'
yield* jsDoc('Defines the arguments required for a bare call')
yield `export type BareCallArgs = Omit<RawAppCallArgs, keyof CoreAppCallArgs>`
yield* structs(ctx)
yield* jsDoc(`Maps a method signature from the ${name} smart contract to the method's arguments in either tuple of struct form`)
yield `export type MethodArgs<TSignature extends ${name}Sig> = ${name}['methods'][TSignature]['argsObj' | 'argsTuple']`
yield* jsDoc(`Maps a method signature from the ${name} smart contract to the method's return type`)
yield `export type MethodReturn<TSignature extends ${name}Sig> = ${name}['methods'][TSignature]['returns']`
yield NewLine
}
function* structs({ app }: GeneratorContext): DocumentParts {
if (app.hints === undefined) return
for (const methodHint of Object.values(app.hints)) {
| if (methodHint.structs === undefined) continue
for (const struct of Object.values(methodHint.structs)) { |
yield* jsDoc(`Represents a ${struct.name} result as a struct`)
yield `export type ${makeSafeTypeIdentifier(struct.name)} = {`
yield IncIndent
for (const [key, type] of struct.elements) {
yield `${makeSafePropertyIdentifier(key)}: ${getEquivalentType(type, 'output')}`
}
yield DecIndentAndCloseBlock
yield* jsDoc(`Converts the tuple representation of a ${struct.name} to the struct representation`)
yield* inline(
`export function ${makeSafeTypeIdentifier(struct.name)}(`,
`[${struct.elements.map(([key]) => makeSafeVariableIdentifier(key)).join(', ')}]: `,
`[${struct.elements.map(([_, type]) => getEquivalentType(type, 'output')).join(', ')}] ) {`,
)
yield IncIndent
yield `return {`
yield IncIndent
for (const [key] of struct.elements) {
const prop = makeSafePropertyIdentifier(key)
const param = makeSafeVariableIdentifier(key)
yield `${prop}${prop !== param ? `: ${param}` : ''},`
}
yield DecIndentAndCloseBlock
yield DecIndentAndCloseBlock
}
}
}
function* appState({ app }: GeneratorContext): DocumentParts {
const hasLocal = app.schema.local?.declared && Object.keys(app.schema.local.declared).length
const hasGlobal = app.schema.global?.declared && Object.keys(app.schema.global.declared).length
if (hasLocal || hasGlobal) {
yield* jsDoc('Defines the shape of the global and local state of the application.')
yield 'state: {'
yield IncIndent
if (hasGlobal) {
yield 'global: {'
yield IncIndent
for (const prop of Object.values(app.schema.global!.declared!)) {
if (prop.descr) {
yield* jsDoc(prop.descr)
}
yield `'${prop.key}'?: ${prop.type === 'uint64' ? 'IntegerState' : 'BinaryState'}`
}
yield DecIndentAndCloseBlock
}
if (hasLocal) {
yield 'local: {'
yield IncIndent
for (const prop of Object.values(app.schema.local!.declared!)) {
if (prop.descr) {
yield* jsDoc(prop.descr)
}
yield `'${prop.key}'?: ${prop.type === 'uint64' ? 'IntegerState' : 'BinaryState'}`
}
yield DecIndentAndCloseBlock
}
yield DecIndentAndCloseBlock
}
}
| src/client/app-types.ts | algorandfoundation-algokit-client-generator-ts-2de43ed | [
{
"filename": "src/client/call-client.ts",
"retrieved_chunk": " params: {\n typedCallParams: 'An object containing the method signature, args, and any other relevant parameters',\n returnValueFormatter: 'An optional delegate which when provided will be used to map non-undefined return values to the target type',\n },\n returns: 'The result of the smart contract call',\n })\n yield `public async call<TSignature extends keyof ${name}['methods']>(typedCallParams: TypedCallParams<TSignature>, returnValueFormatter?: (value: any) => MethodReturn<TSignature>) {`\n yield IncIndent\n yield `return this.mapReturnValue<MethodReturn<TSignature>>(await this.appClient.call(typedCallParams), returnValueFormatter)`\n yield DecIndentAndCloseBlock",
"score": 71.50571511255502
},
{
"filename": "src/client/call-client.ts",
"retrieved_chunk": " outputTypeName === undefined ? '' : `, ${makeSafeTypeIdentifier(outputTypeName)}`\n })`\n yield DecIndent\n yield '}'\n yield NewLine\n }\n}\nfunction* getStateMethods({ app, name }: GeneratorContext): DocumentParts {\n const globalStateValues = app.schema.global?.declared && Object.values(app.schema.global?.declared)\n const localStateValues = app.schema.local?.declared && Object.values(app.schema.local?.declared)",
"score": 45.96959685687961
},
{
"filename": "src/client/call-composer.ts",
"retrieved_chunk": " for (const method of app.contract.methods) {\n const methodSignature = algokit.getABIMethodSignature(method)\n const methodName = makeSafeMethodIdentifier(methodSignatureToUniqueName[methodSignature])\n // Skip methods which don't support a no_op call config\n if (!callConfig.callMethods.includes(methodSignature)) continue\n yield `${methodName}(args: MethodArgs<'${methodSignature}'>, params?: AppClientCallCoreParams & CoreAppCallArgs) {`\n yield IncIndent\n yield `promiseChain = promiseChain.then(() => client.${methodName}(args, {...params, sendParams: {...params?.sendParams, skipSending: true, atc}}))`\n const outputTypeName = app.hints?.[methodSignature]?.structs?.output?.name\n yield `resultMappers.push(${outputTypeName ?? 'undefined'})`",
"score": 43.33369719870043
},
{
"filename": "src/client/call-client.ts",
"retrieved_chunk": " params: {\n args: `The arguments for the contract call`,\n params: `Any additional parameters for the call`,\n },\n returns: `The result of the call${method?.returns?.desc ? `: ${method.returns.desc}` : ''}`,\n })\n yield `public ${methodName}(args: MethodArgs<'${methodSignature}'>, params: AppClientCallCoreParams & CoreAppCallArgs = {}) {`\n yield IncIndent\n const outputTypeName = app.hints?.[methodSignature]?.structs?.output?.name\n yield `return this.call(${name}CallFactory.${methodName}(args, params)${",
"score": 42.79832113141446
},
{
"filename": "src/client/deploy-types.ts",
"retrieved_chunk": "export function* deployTypes({ app, callConfig }: GeneratorContext): DocumentParts {\n const name = makeSafeTypeIdentifier(app.contract.name)\n if (callConfig.createMethods.length > 0) {\n yield* jsDoc(`A factory for available 'create' calls`)\n yield `export type ${name}CreateCalls = (typeof ${name}CallFactory)['create']`\n yield* jsDoc('Defines supported create methods for this smart contract')\n yield `export type ${name}CreateCallParams =`\n yield IncIndent\n for (const method of callConfig.createMethods) {\n const onComplete = getCreateOnCompleteOptions(method, app)",
"score": 41.63468397992876
}
] | typescript | if (methodHint.structs === undefined) continue
for (const struct of Object.values(methodHint.structs)) { |
import * as algokit from '@algorandfoundation/algokit-utils'
import { DecIndent, DecIndentAndCloseBlock, DocumentParts, IncIndent, indent, inline, jsDoc, NewLine } from '../output/writer'
import { makeSafeMethodIdentifier, makeSafeTypeIdentifier } from '../util/sanitization'
import { BARE_CALL, MethodList } from './helpers/get-call-config-summary'
import { GeneratorContext } from './generator-context'
import { getCreateOnCompleteOptions } from './deploy-types'
import { composeMethod } from './call-composer'
export function* callClient(ctx: GeneratorContext): DocumentParts {
const { app, name } = ctx
yield* jsDoc(`A client to make calls to the ${app.contract.name} smart contract`)
yield `export class ${makeSafeTypeIdentifier(app.contract.name)}Client {`
yield IncIndent
yield* jsDoc(`The underlying \`ApplicationClient\` for when you want to have more flexibility`)
yield 'public readonly appClient: ApplicationClient'
yield NewLine
yield `private readonly sender: SendTransactionFrom | undefined`
yield NewLine
yield* jsDoc({
description: `Creates a new instance of \`${makeSafeTypeIdentifier(app.contract.name)}Client\``,
params: {
appDetails: 'appDetails The details to identify the app to deploy',
algod: 'An algod client instance',
},
})
yield `constructor(appDetails: AppDetails, private algod: Algodv2) {`
yield IncIndent
yield `this.sender = appDetails.sender`
yield 'this.appClient = algokit.getAppClient({'
yield* indent('...appDetails,', 'app: APP_SPEC')
yield '}, algod)'
yield DecIndent
yield '}'
yield NewLine
yield* jsDoc({
description: 'Checks for decode errors on the AppCallTransactionResult and maps the return value to the specified generic type',
params: {
result: 'The AppCallTransactionResult to be mapped',
returnValueFormatter: 'An optional delegate to format the return value if required',
},
returns: 'The smart contract response with an updated return value',
})
yield* inline(
`protected mapReturnValue<TReturn>`,
`(result: AppCallTransactionResult, returnValueFormatter?: (value: any) => TReturn): `,
`AppCallTransactionResultOfType<TReturn> {`,
)
yield IncIndent
yield `if(result.return?.decodeError) {`
yield* indent(`throw result.return.decodeError`)
yield `}`
yield `const returnValue = result.return?.returnValue !== undefined && returnValueFormatter !== undefined`
yield IncIndent
yield `? returnValueFormatter(result.return.returnValue)`
yield `: result.return?.returnValue as TReturn | undefined`
yield `return { ...result, return: returnValue }`
yield DecIndent
yield DecIndentAndCloseBlock
yield NewLine
yield* jsDoc({
description: 'Calls the ABI method with the matching signature using an onCompletion code of NO_OP',
params: {
typedCallParams: 'An object containing the method signature, args, and any other relevant parameters',
returnValueFormatter: 'An optional delegate which when provided will be used to map non-undefined return values to the target type',
},
returns: 'The result of the smart contract call',
})
yield `public async call<TSignature extends keyof ${name}['methods']>(typedCallParams: TypedCallParams<TSignature>, returnValueFormatter?: (value: any) => MethodReturn<TSignature>) {`
yield IncIndent
yield `return this.mapReturnValue<MethodReturn<TSignature>>(await this.appClient.call(typedCallParams), returnValueFormatter)`
yield DecIndentAndCloseBlock
yield NewLine
yield* opMethods(ctx)
yield* clearState(ctx)
yield* noopMethods(ctx)
yield* getStateMethods(ctx)
yield* | composeMethod(ctx)
yield DecIndentAndCloseBlock
} |
function* opMethods(ctx: GeneratorContext): DocumentParts {
const { app, callConfig, name } = ctx
yield* jsDoc({
description: `Idempotently deploys the ${app.contract.name} smart contract.`,
params: {
params: 'The arguments for the contract calls and any additional parameters for the call',
},
returns: 'The deployment result',
})
yield `public deploy(params: ${name}DeployArgs & AppClientDeployCoreParams = {}): ReturnType<ApplicationClient['deploy']> {`
yield IncIndent
if (callConfig.createMethods.length) yield `const createArgs = params.createCall?.(${name}CallFactory.create)`
if (callConfig.updateMethods.length) yield `const updateArgs = params.updateCall?.(${name}CallFactory.update)`
if (callConfig.deleteMethods.length) yield `const deleteArgs = params.deleteCall?.(${name}CallFactory.delete)`
yield `return this.appClient.deploy({`
yield IncIndent
yield `...params,`
if (callConfig.updateMethods.length) yield 'updateArgs,'
if (callConfig.deleteMethods.length) yield 'deleteArgs,'
if (callConfig.createMethods.length) {
yield 'createArgs,'
yield `createOnCompleteAction: createArgs?.onCompleteAction,`
}
yield DecIndent
yield `})`
yield DecIndentAndCloseBlock
yield NewLine
yield* operationMethod(ctx, `Creates a new instance of the ${app.contract.name} smart contract`, callConfig.createMethods, 'create', true)
yield* operationMethod(
ctx,
`Updates an existing instance of the ${app.contract.name} smart contract`,
callConfig.updateMethods,
'update',
true,
)
yield* operationMethod(ctx, `Deletes an existing instance of the ${app.contract.name} smart contract`, callConfig.deleteMethods, 'delete')
yield* operationMethod(
ctx,
`Opts the user into an existing instance of the ${app.contract.name} smart contract`,
callConfig.optInMethods,
'optIn',
)
yield* operationMethod(
ctx,
`Makes a close out call to an existing instance of the ${app.contract.name} smart contract`,
callConfig.closeOutMethods,
'closeOut',
)
}
function* operationMethod(
{ app, methodSignatureToUniqueName, name }: GeneratorContext,
description: string,
methods: MethodList,
verb: 'create' | 'update' | 'optIn' | 'closeOut' | 'delete',
includeCompilation?: boolean,
): DocumentParts {
if (methods.length) {
yield* jsDoc(`Gets available ${verb} methods`)
yield `public get ${verb}() {`
yield IncIndent
yield `const $this = this`
yield `return {`
yield IncIndent
for (const methodSig of methods) {
const onComplete = verb === 'create' ? getCreateOnCompleteOptions(methodSig, app) : undefined
if (methodSig === BARE_CALL) {
yield* jsDoc({
description: `${description} using a bare call.`,
params: {
args: `The arguments for the bare call`,
},
returns: `The ${verb} result`,
})
yield `bare(args: BareCallArgs & AppClientCallCoreParams ${
includeCompilation ? '& AppClientCompilationParams ' : ''
}& CoreAppCallArgs${onComplete?.type ? ` & ${onComplete.type}` : ''}${
onComplete?.isOptional !== false ? ' = {}' : ''
}): Promise<AppCallTransactionResultOfType<undefined>> {`
yield* indent(`return $this.appClient.${verb}(args) as unknown as Promise<AppCallTransactionResultOfType<undefined>>`)
yield '},'
} else {
const uniqueName = methodSignatureToUniqueName[methodSig]
const method = app.contract.methods.find((m) => algokit.getABIMethodSignature(m) === methodSig)
yield* jsDoc({
description: `${description} using the ${methodSig} ABI method.`,
params: {
args: `The arguments for the smart contract call`,
params: `Any additional parameters for the call`,
},
returns: `The ${verb} result${method?.returns?.desc ? `: ${method.returns.desc}` : ''}`,
})
yield `async ${makeSafeMethodIdentifier(uniqueName)}(args: MethodArgs<'${methodSig}'>, params: AppClientCallCoreParams${
includeCompilation ? ' & AppClientCompilationParams' : ''
}${onComplete?.type ? ` & ${onComplete.type}` : ''}${
onComplete?.isOptional !== false ? ' = {}' : ''
}): Promise<AppCallTransactionResultOfType<MethodReturn<'${methodSig}'>>> {`
yield* indent(
`return $this.mapReturnValue(await $this.appClient.${verb}(${name}CallFactory.${verb}.${makeSafeMethodIdentifier(
uniqueName,
)}(args, params)))`,
)
yield '},'
}
}
yield DecIndentAndCloseBlock
yield DecIndentAndCloseBlock
yield NewLine
}
}
function* clearState({ app }: GeneratorContext): DocumentParts {
yield* jsDoc({
description: `Makes a clear_state call to an existing instance of the ${app.contract.name} smart contract.`,
params: {
args: `The arguments for the bare call`,
},
returns: `The clear_state result`,
})
yield `public clearState(args: BareCallArgs & AppClientCallCoreParams & CoreAppCallArgs = {}) {`
yield IncIndent
yield `return this.appClient.clearState(args)`
yield DecIndentAndCloseBlock
yield NewLine
}
function* noopMethods({ app, name, callConfig, methodSignatureToUniqueName }: GeneratorContext): DocumentParts {
for (const method of app.contract.methods) {
const methodSignature = algokit.getABIMethodSignature(method)
const methodName = makeSafeMethodIdentifier(methodSignatureToUniqueName[methodSignature])
// Skip methods which don't support a no_op call config
if (!callConfig.callMethods.includes(methodSignature)) continue
yield* jsDoc({
description: `Calls the ${algokit.getABIMethodSignature(method)} ABI method.`,
abiDescription: method.desc,
params: {
args: `The arguments for the contract call`,
params: `Any additional parameters for the call`,
},
returns: `The result of the call${method?.returns?.desc ? `: ${method.returns.desc}` : ''}`,
})
yield `public ${methodName}(args: MethodArgs<'${methodSignature}'>, params: AppClientCallCoreParams & CoreAppCallArgs = {}) {`
yield IncIndent
const outputTypeName = app.hints?.[methodSignature]?.structs?.output?.name
yield `return this.call(${name}CallFactory.${methodName}(args, params)${
outputTypeName === undefined ? '' : `, ${makeSafeTypeIdentifier(outputTypeName)}`
})`
yield DecIndent
yield '}'
yield NewLine
}
}
function* getStateMethods({ app, name }: GeneratorContext): DocumentParts {
const globalStateValues = app.schema.global?.declared && Object.values(app.schema.global?.declared)
const localStateValues = app.schema.local?.declared && Object.values(app.schema.local?.declared)
if (globalStateValues?.length || localStateValues?.length) {
yield* jsDoc({
description: 'Extracts a binary state value out of an AppState dictionary',
params: {
state: 'The state dictionary containing the state value',
key: 'The key of the state value',
},
returns: 'A BinaryState instance containing the state value, or undefined if the key was not found',
})
yield `private static getBinaryState(state: AppState, key: string): BinaryState | undefined {`
yield IncIndent
yield `const value = state[key]`
yield `if (!value) return undefined`
yield `if (!('valueRaw' in value))`
yield* indent(`throw new Error(\`Failed to parse state value for \${key}; received an int when expected a byte array\`)`)
yield `return {`
yield IncIndent
yield `asString(): string {`
yield* indent(`return value.value`)
yield `},`
yield `asByteArray(): Uint8Array {`
yield* indent(`return value.valueRaw`)
yield `}`
yield DecIndentAndCloseBlock
yield DecIndentAndCloseBlock
yield NewLine
yield* jsDoc({
description: 'Extracts a integer state value out of an AppState dictionary',
params: {
state: 'The state dictionary containing the state value',
key: 'The key of the state value',
},
returns: 'An IntegerState instance containing the state value, or undefined if the key was not found',
})
yield `private static getIntegerState(state: AppState, key: string): IntegerState | undefined {`
yield IncIndent
yield `const value = state[key]`
yield `if (!value) return undefined`
yield `if ('valueRaw' in value)`
yield* indent(`throw new Error(\`Failed to parse state value for \${key}; received a byte array when expected a number\`)`)
yield `return {`
yield IncIndent
yield `asBigInt() {`
yield* indent(`return typeof value.value === 'bigint' ? value.value : BigInt(value.value)`)
yield `},`
yield `asNumber(): number {`
yield* indent(`return typeof value.value === 'bigint' ? Number(value.value) : value.value`)
yield `},`
yield DecIndentAndCloseBlock
yield DecIndentAndCloseBlock
yield NewLine
}
if (globalStateValues?.length) {
yield* jsDoc(`Returns the smart contract's global state wrapped in a strongly typed accessor with options to format the stored value`)
yield `public async getGlobalState(): Promise<${name}['state']['global']> {`
yield IncIndent
yield `const state = await this.appClient.getGlobalState()`
yield `return {`
yield IncIndent
for (const stateValue of globalStateValues) {
yield `get ${stateValue.key}() {`
if (stateValue.type === 'uint64') {
yield* indent(`return ${name}Client.getIntegerState(state, '${stateValue.key}')`)
} else {
yield* indent(`return ${name}Client.getBinaryState(state, '${stateValue.key}')`)
}
yield '},'
}
yield DecIndentAndCloseBlock
yield DecIndentAndCloseBlock
yield NewLine
}
if (localStateValues?.length) {
yield* jsDoc({
description: `Returns the smart contract's local state wrapped in a strongly typed accessor with options to format the stored value`,
params: {
account: `The address of the account for which to read local state from`,
},
})
yield `public async getLocalState(account: string | SendTransactionFrom): Promise<${name}['state']['local']> {`
yield IncIndent
yield `const state = await this.appClient.getLocalState(account)`
yield `return {`
yield IncIndent
for (const stateValue of localStateValues) {
yield `get ${stateValue.key}() {`
if (stateValue.type === 'uint64') {
yield* indent(`return ${name}Client.getIntegerState(state, '${stateValue.key}')`)
} else {
yield* indent(`return ${name}Client.getBinaryState(state, '${stateValue.key}')`)
}
yield '},'
}
yield DecIndentAndCloseBlock
yield DecIndentAndCloseBlock
yield NewLine
}
}
| src/client/call-client.ts | algorandfoundation-algokit-client-generator-ts-2de43ed | [
{
"filename": "src/client/call-factory.ts",
"retrieved_chunk": " yield IncIndent\n yield* opMethods(ctx)\n for (const method of ctx.app.contract.methods) {\n yield* callFactoryMethod(ctx, method)\n }\n yield DecIndent\n yield '}'\n}\nfunction* opMethods(ctx: GeneratorContext): DocumentParts {\n const { app, callConfig } = ctx",
"score": 25.79906213045578
},
{
"filename": "src/client/generate.ts",
"retrieved_chunk": " yield NewLine\n yield* utilityTypes()\n yield NewLine\n yield* appTypes(ctx)\n yield* deployTypes(ctx)\n yield NewLine\n // Write a call factory\n yield* callFactory(ctx)\n yield NewLine\n // Write a client",
"score": 21.05078107089458
},
{
"filename": "src/client/generate.ts",
"retrieved_chunk": " yield* callClient(ctx)\n yield* callComposerType(ctx)\n}",
"score": 18.571013507431477
},
{
"filename": "src/client/call-composer.ts",
"retrieved_chunk": "import { DecIndent, DecIndentAndCloseBlock, DocumentParts, IncIndent } from '../output/writer'\nimport { GeneratorContext } from './generator-context'\nimport * as algokit from '@algorandfoundation/algokit-utils'\nimport { makeSafeMethodIdentifier } from '../util/sanitization'\nimport { BARE_CALL, MethodList } from './helpers/get-call-config-summary'\nimport { getCreateOnCompleteOptions } from './deploy-types'\nexport function* composeMethod(ctx: GeneratorContext): DocumentParts {\n const { name, callConfig } = ctx\n yield `public compose(): ${name}Composer {`\n yield IncIndent",
"score": 17.53581375124485
},
{
"filename": "src/client/call-composer-types.ts",
"retrieved_chunk": " yield* callComposerTypeNoops(ctx)\n yield* callComposerOperationMethodType(\n ctx,\n `Updates an existing instance of the ${app.contract.name} smart contract`,\n callConfig.updateMethods,\n 'update',\n true,\n )\n yield* callComposerOperationMethodType(\n ctx,",
"score": 17.264388452836947
}
] | typescript | composeMethod(ctx)
yield DecIndentAndCloseBlock
} |
import { ContractMethod } from '../schema/application'
import { DecIndent, DecIndentAndCloseBlock, DocumentParts, IncIndent, jsDoc, NewLine } from '../output/writer'
import { isSafeVariableIdentifier, makeSafeMethodIdentifier, makeSafePropertyIdentifier } from '../util/sanitization'
import * as algokit from '@algorandfoundation/algokit-utils'
import { GeneratorContext } from './generator-context'
import { BARE_CALL, MethodList } from './helpers/get-call-config-summary'
import { getCreateOnCompleteOptions } from './deploy-types'
export function* callFactory(ctx: GeneratorContext): DocumentParts {
yield* jsDoc('Exposes methods for constructing all available smart contract calls')
yield `export abstract class ${ctx.name}CallFactory {`
yield IncIndent
yield* opMethods(ctx)
for (const method of ctx.app.contract.methods) {
yield* callFactoryMethod(ctx, method)
}
yield DecIndent
yield '}'
}
function* opMethods(ctx: GeneratorContext): DocumentParts {
const { app, callConfig } = ctx
yield* operationMethod(
ctx,
`Constructs a create call for the ${app.contract.name} smart contract`,
callConfig.createMethods,
'create',
true,
)
yield* operationMethod(
ctx,
`Constructs an update call for the ${app.contract.name} smart contract`,
callConfig.updateMethods,
'update',
true,
)
yield* operationMethod(ctx, `Constructs a delete call for the ${app.contract.name} smart contract`, callConfig.deleteMethods, 'delete')
yield* operationMethod(ctx, `Constructs an opt in call for the ${app.contract.name} smart contract`, callConfig.optInMethods, 'optIn')
yield* operationMethod(
ctx,
`Constructs a close out call for the ${app.contract.name} smart contract`,
callConfig.closeOutMethods,
'closeOut',
)
}
function* operationMethod(
{ app, methodSignatureToUniqueName }: GeneratorContext,
description: string,
methods: MethodList,
verb: 'create' | 'update' | 'optIn' | 'closeOut' | 'delete',
includeCompilation?: boolean,
): DocumentParts {
if (methods.length) {
yield* jsDoc(`Gets available ${verb} call factories`)
yield `static get ${verb}() {`
yield IncIndent
yield `return {`
yield IncIndent
for (const methodSig of methods) {
const onComplete = verb === 'create' ? getCreateOnCompleteOptions(methodSig, app) : undefined
if (methodSig === BARE_CALL) {
yield* jsDoc({
description: `${description} using a bare call`,
params: {
params: `Any parameters for the call`,
},
returns: `A TypedCallParams object for the call`,
})
yield* factoryMethod({
isNested: true,
name: 'bare',
paramTypes: `BareCallArgs & AppClientCallCoreParams & CoreAppCallArgs${
includeCompilation ? ' & AppClientCompilationParams' : ''
}${onComplete?.type ? ` & ${onComplete.type}` : ''}${onComplete?.isOptional !== false ? ' = {}' : ''}`,
})
} else {
const method = app.contract.methods.find((m) => algokit.getABIMethodSignature(m) === methodSig)!
const uniqueName = methodSignatureToUniqueName[methodSig]
yield* jsDoc({
description: `${description} using the ${methodSig} ABI method`,
params: {
args: `Any args for the contract call`,
params: `Any additional parameters for the call`,
},
returns: `A TypedCallParams object for the call`,
})
yield* factoryMethod({
isNested: true,
name: makeSafeMethodIdentifier(uniqueName),
signature: methodSig,
args: method.args,
paramTypes: `AppClientCallCoreParams & CoreAppCallArgs${includeCompilation ? ' & AppClientCompilationParams' : ''}${
onComplete?.type ? ` & ${onComplete.type}` : ''
}${onComplete?.isOptional !== false ? ' = {}' : ''}`,
})
}
}
yield DecIndentAndCloseBlock
yield DecIndentAndCloseBlock
yield NewLine
}
}
| function* callFactoryMethod({ methodSignatureToUniqueName, callConfig }: GeneratorContext, method: ContractMethod) { |
const methodSignature = algokit.getABIMethodSignature(method)
if (!callConfig.callMethods.includes(methodSignature)) return
yield* jsDoc({
description: `Constructs a no op call for the ${methodSignature} ABI method`,
abiDescription: method.desc,
params: {
args: `Any args for the contract call`,
params: `Any additional parameters for the call`,
},
returns: `A TypedCallParams object for the call`,
})
yield* factoryMethod({
isNested: false,
name: makeSafeMethodIdentifier(methodSignatureToUniqueName[methodSignature]),
signature: methodSignature,
args: method.args,
paramTypes: 'AppClientCallCoreParams & CoreAppCallArgs',
})
}
function* factoryMethod({
isNested,
name,
signature,
args,
paramTypes,
}:
| {
isNested: boolean
name?: string
signature?: undefined
args?: undefined
paramTypes: string
}
| {
isNested: boolean
name?: string
signature: string
args: Array<{ name: string }>
paramTypes: string
}) {
yield `${isNested ? '' : 'static '}${name}(${signature === undefined ? '' : `args: MethodArgs<'${signature}'>, `}params: ${paramTypes}) {`
yield IncIndent
yield `return {`
yield IncIndent
if (signature) {
yield `method: '${signature}' as const,`
yield `methodArgs: Array.isArray(args) ? args : [${args
.map((a) => (isSafeVariableIdentifier(a.name) ? `args.${a.name}` : `args['${makeSafePropertyIdentifier(a.name)}']`))
.join(', ')}],`
} else {
yield `method: undefined,`
yield `methodArgs: undefined,`
}
yield '...params,'
yield DecIndent
yield '}'
yield DecIndent
yield `}${isNested ? ',' : ''}`
}
| src/client/call-factory.ts | algorandfoundation-algokit-client-generator-ts-2de43ed | [
{
"filename": "src/client/call-client.ts",
"retrieved_chunk": " })\n yield `bare(args: BareCallArgs & AppClientCallCoreParams ${\n includeCompilation ? '& AppClientCompilationParams ' : ''\n }& CoreAppCallArgs${onComplete?.type ? ` & ${onComplete.type}` : ''}${\n onComplete?.isOptional !== false ? ' = {}' : ''\n }): Promise<AppCallTransactionResultOfType<undefined>> {`\n yield* indent(`return $this.appClient.${verb}(args) as unknown as Promise<AppCallTransactionResultOfType<undefined>>`)\n yield '},'\n } else {\n const uniqueName = methodSignatureToUniqueName[methodSig]",
"score": 17.278509815140783
},
{
"filename": "src/client/call-composer.ts",
"retrieved_chunk": " yield IncIndent\n yield `...result,`\n yield `returns: result.returns?.map((val, i) => resultMappers[i] !== undefined ? resultMappers[i]!(val.returnValue) : val.returnValue)`\n yield DecIndentAndCloseBlock\n yield DecIndentAndCloseBlock\n yield DecIndent\n yield `} as unknown as ${name}Composer`\n yield DecIndentAndCloseBlock\n}\nfunction* callComposerNoops({ app, callConfig, methodSignatureToUniqueName }: GeneratorContext): DocumentParts {",
"score": 17.080937444909242
},
{
"filename": "src/client/call-client.ts",
"retrieved_chunk": " yield NewLine\n yield* opMethods(ctx)\n yield* clearState(ctx)\n yield* noopMethods(ctx)\n yield* getStateMethods(ctx)\n yield* composeMethod(ctx)\n yield DecIndentAndCloseBlock\n}\nfunction* opMethods(ctx: GeneratorContext): DocumentParts {\n const { app, callConfig, name } = ctx",
"score": 16.152957168540734
},
{
"filename": "src/client/call-client.ts",
"retrieved_chunk": " includeCompilation ? ' & AppClientCompilationParams' : ''\n }${onComplete?.type ? ` & ${onComplete.type}` : ''}${\n onComplete?.isOptional !== false ? ' = {}' : ''\n }): Promise<AppCallTransactionResultOfType<MethodReturn<'${methodSig}'>>> {`\n yield* indent(\n `return $this.mapReturnValue(await $this.appClient.${verb}(${name}CallFactory.${verb}.${makeSafeMethodIdentifier(\n uniqueName,\n )}(args, params)))`,\n )\n yield '},'",
"score": 15.30722323894242
},
{
"filename": "src/client/call-composer-types.ts",
"retrieved_chunk": " }: AppClientCallCoreParams${includeCompilation ? ' & AppClientCompilationParams' : ''}${\n onComplete?.type ? ` & ${onComplete.type}` : ''\n }): ${name}Composer<[...TReturns, MethodReturn<'${methodSig}'>]>`\n }\n }\n yield DecIndentAndCloseBlock\n yield NewLine\n }\n}",
"score": 15.086171526789876
}
] | typescript | function* callFactoryMethod({ methodSignatureToUniqueName, callConfig }: GeneratorContext, method: ContractMethod) { |
import { GeneratorContext } from './generator-context'
import { DecIndent, DecIndentAndCloseBlock, DocumentParts, IncIndent, inline, jsDoc, NewLine } from '../output/writer'
import * as algokit from '@algorandfoundation/algokit-utils'
import { getEquivalentType } from './helpers/get-equivalent-type'
import { makeSafePropertyIdentifier, makeSafeTypeIdentifier, makeSafeVariableIdentifier } from '../util/sanitization'
export function* appTypes(ctx: GeneratorContext): DocumentParts {
const { app, methodSignatureToUniqueName, name } = ctx
yield* jsDoc(`Defines the types of available calls and state of the ${name} smart contract.`)
yield `export type ${name} = {`
yield IncIndent
yield* jsDoc('Maps method signatures / names to their argument and return types.')
yield 'methods:'
yield IncIndent
for (const method of app.contract.methods) {
const methodSig = algokit.getABIMethodSignature(method)
const uniqueName = methodSignatureToUniqueName[methodSig]
yield `& Record<'${methodSig}'${methodSig !== uniqueName ? ` | '${uniqueName}'` : ''}, {`
yield IncIndent
yield `argsObj: {`
yield IncIndent
const argsMeta = method.args.map((arg) => ({
...arg,
hasDefault: app.hints?.[methodSig]?.default_arguments?.[arg.name],
tsType: getEquivalentType(arg.type, 'input'),
}))
for (const arg of argsMeta) {
if (arg.desc) yield* jsDoc(arg.desc)
yield `${makeSafePropertyIdentifier(arg.name)}${arg.hasDefault ? '?' : ''}: ${arg.tsType}`
}
yield DecIndentAndCloseBlock
yield* inline(
`argsTuple: [`,
argsMeta
.map(
(arg) =>
`${makeSafeVariableIdentifier(arg.name)}: ${getEquivalentType(arg.type, 'input')}${arg.hasDefault ? ' | undefined' : ''}`,
)
.join(', '),
']',
)
const outputStruct = ctx.app.hints?.[methodSig]?.structs?.output
if (method.returns.desc) yield* jsDoc(method.returns.desc)
if (outputStruct) {
| yield `returns: ${makeSafeTypeIdentifier(outputStruct.name)}`
} else { |
yield `returns: ${getEquivalentType(method.returns.type ?? 'void', 'output')}`
}
yield DecIndent
yield '}>'
}
yield DecIndent
yield* appState(ctx)
yield DecIndentAndCloseBlock
yield* jsDoc('Defines the possible abi call signatures')
yield `export type ${name}Sig = keyof ${name}['methods']`
yield* jsDoc(
'Defines an object containing all relevant parameters for a single call to the contract. Where TSignature is undefined, a' +
' bare call is made',
)
yield `export type TypedCallParams<TSignature extends ${name}Sig | undefined> = {`
yield IncIndent
yield 'method: TSignature'
yield 'methodArgs: TSignature extends undefined ? undefined : Array<ABIAppCallArg | undefined>'
yield DecIndent
yield '} & AppClientCallCoreParams & CoreAppCallArgs'
yield* jsDoc('Defines the arguments required for a bare call')
yield `export type BareCallArgs = Omit<RawAppCallArgs, keyof CoreAppCallArgs>`
yield* structs(ctx)
yield* jsDoc(`Maps a method signature from the ${name} smart contract to the method's arguments in either tuple of struct form`)
yield `export type MethodArgs<TSignature extends ${name}Sig> = ${name}['methods'][TSignature]['argsObj' | 'argsTuple']`
yield* jsDoc(`Maps a method signature from the ${name} smart contract to the method's return type`)
yield `export type MethodReturn<TSignature extends ${name}Sig> = ${name}['methods'][TSignature]['returns']`
yield NewLine
}
function* structs({ app }: GeneratorContext): DocumentParts {
if (app.hints === undefined) return
for (const methodHint of Object.values(app.hints)) {
if (methodHint.structs === undefined) continue
for (const struct of Object.values(methodHint.structs)) {
yield* jsDoc(`Represents a ${struct.name} result as a struct`)
yield `export type ${makeSafeTypeIdentifier(struct.name)} = {`
yield IncIndent
for (const [key, type] of struct.elements) {
yield `${makeSafePropertyIdentifier(key)}: ${getEquivalentType(type, 'output')}`
}
yield DecIndentAndCloseBlock
yield* jsDoc(`Converts the tuple representation of a ${struct.name} to the struct representation`)
yield* inline(
`export function ${makeSafeTypeIdentifier(struct.name)}(`,
`[${struct.elements.map(([key]) => makeSafeVariableIdentifier(key)).join(', ')}]: `,
`[${struct.elements.map(([_, type]) => getEquivalentType(type, 'output')).join(', ')}] ) {`,
)
yield IncIndent
yield `return {`
yield IncIndent
for (const [key] of struct.elements) {
const prop = makeSafePropertyIdentifier(key)
const param = makeSafeVariableIdentifier(key)
yield `${prop}${prop !== param ? `: ${param}` : ''},`
}
yield DecIndentAndCloseBlock
yield DecIndentAndCloseBlock
}
}
}
function* appState({ app }: GeneratorContext): DocumentParts {
const hasLocal = app.schema.local?.declared && Object.keys(app.schema.local.declared).length
const hasGlobal = app.schema.global?.declared && Object.keys(app.schema.global.declared).length
if (hasLocal || hasGlobal) {
yield* jsDoc('Defines the shape of the global and local state of the application.')
yield 'state: {'
yield IncIndent
if (hasGlobal) {
yield 'global: {'
yield IncIndent
for (const prop of Object.values(app.schema.global!.declared!)) {
if (prop.descr) {
yield* jsDoc(prop.descr)
}
yield `'${prop.key}'?: ${prop.type === 'uint64' ? 'IntegerState' : 'BinaryState'}`
}
yield DecIndentAndCloseBlock
}
if (hasLocal) {
yield 'local: {'
yield IncIndent
for (const prop of Object.values(app.schema.local!.declared!)) {
if (prop.descr) {
yield* jsDoc(prop.descr)
}
yield `'${prop.key}'?: ${prop.type === 'uint64' ? 'IntegerState' : 'BinaryState'}`
}
yield DecIndentAndCloseBlock
}
yield DecIndentAndCloseBlock
}
}
| src/client/app-types.ts | algorandfoundation-algokit-client-generator-ts-2de43ed | [
{
"filename": "src/client/call-client.ts",
"retrieved_chunk": " params: {\n args: `The arguments for the contract call`,\n params: `Any additional parameters for the call`,\n },\n returns: `The result of the call${method?.returns?.desc ? `: ${method.returns.desc}` : ''}`,\n })\n yield `public ${methodName}(args: MethodArgs<'${methodSignature}'>, params: AppClientCallCoreParams & CoreAppCallArgs = {}) {`\n yield IncIndent\n const outputTypeName = app.hints?.[methodSignature]?.structs?.output?.name\n yield `return this.call(${name}CallFactory.${methodName}(args, params)${",
"score": 30.18463008071757
},
{
"filename": "src/client/call-client.ts",
"retrieved_chunk": " const method = app.contract.methods.find((m) => algokit.getABIMethodSignature(m) === methodSig)\n yield* jsDoc({\n description: `${description} using the ${methodSig} ABI method.`,\n params: {\n args: `The arguments for the smart contract call`,\n params: `Any additional parameters for the call`,\n },\n returns: `The ${verb} result${method?.returns?.desc ? `: ${method.returns.desc}` : ''}`,\n })\n yield `async ${makeSafeMethodIdentifier(uniqueName)}(args: MethodArgs<'${methodSig}'>, params: AppClientCallCoreParams${",
"score": 26.744189988085758
},
{
"filename": "src/schema/application.d.ts",
"retrieved_chunk": " };\n };\n}\nexport interface ContractMethod1 {\n name: string;\n args: ContractMethodArg[];\n desc?: string;\n returns: {\n desc?: string;\n /**",
"score": 19.02232841282475
},
{
"filename": "src/client/deploy-types.ts",
"retrieved_chunk": " if (method === BARE_CALL) {\n yield `| TypedCallParams<undefined>`\n } else {\n yield `| TypedCallParams<'${method}'>`\n }\n }\n yield DecIndent\n }\n yield* jsDoc('Defines arguments required for the deploy method.')\n yield `export type ${name}DeployArgs = {`",
"score": 19.020207081977702
},
{
"filename": "src/client/call-composer.ts",
"retrieved_chunk": " const methodName = makeSafeMethodIdentifier(uniqueName)\n yield `${methodName}(args: MethodArgs<'${methodSig}'>, params${\n onComplete?.isOptional !== false ? '?' : ''\n }: AppClientCallCoreParams${includeCompilation ? ' & AppClientCompilationParams' : ''}${\n onComplete?.type ? ` & ${onComplete.type}` : ''\n }) {`\n yield IncIndent\n yield `promiseChain = promiseChain.then(() => client.${verb}.${methodName}(args, {...params, sendParams: {...params?.sendParams, skipSending: true, atc}}))`\n const outputTypeName = app.hints?.[methodSig]?.structs?.output?.name\n yield `resultMappers.push(${outputTypeName ?? 'undefined'})`",
"score": 18.68529667132765
}
] | typescript | yield `returns: ${makeSafeTypeIdentifier(outputStruct.name)}`
} else { |
import * as algokit from '@algorandfoundation/algokit-utils'
import { DecIndent, DecIndentAndCloseBlock, DocumentParts, IncIndent, indent, inline, jsDoc, NewLine } from '../output/writer'
import { makeSafeMethodIdentifier, makeSafeTypeIdentifier } from '../util/sanitization'
import { BARE_CALL, MethodList } from './helpers/get-call-config-summary'
import { GeneratorContext } from './generator-context'
import { getCreateOnCompleteOptions } from './deploy-types'
import { composeMethod } from './call-composer'
export function* callClient(ctx: GeneratorContext): DocumentParts {
const { app, name } = ctx
yield* jsDoc(`A client to make calls to the ${app.contract.name} smart contract`)
yield `export class ${makeSafeTypeIdentifier(app.contract.name)}Client {`
yield IncIndent
yield* jsDoc(`The underlying \`ApplicationClient\` for when you want to have more flexibility`)
yield 'public readonly appClient: ApplicationClient'
yield NewLine
yield `private readonly sender: SendTransactionFrom | undefined`
yield NewLine
yield* jsDoc({
description: `Creates a new instance of \`${makeSafeTypeIdentifier(app.contract.name)}Client\``,
params: {
appDetails: 'appDetails The details to identify the app to deploy',
algod: 'An algod client instance',
},
})
yield `constructor(appDetails: AppDetails, private algod: Algodv2) {`
yield IncIndent
yield `this.sender = appDetails.sender`
yield 'this.appClient = algokit.getAppClient({'
yield* indent('...appDetails,', 'app: APP_SPEC')
yield '}, algod)'
yield DecIndent
yield '}'
yield NewLine
yield* jsDoc({
description: 'Checks for decode errors on the AppCallTransactionResult and maps the return value to the specified generic type',
params: {
result: 'The AppCallTransactionResult to be mapped',
returnValueFormatter: 'An optional delegate to format the return value if required',
},
returns: 'The smart contract response with an updated return value',
})
yield* inline(
`protected mapReturnValue<TReturn>`,
`(result: AppCallTransactionResult, returnValueFormatter?: (value: any) => TReturn): `,
`AppCallTransactionResultOfType<TReturn> {`,
)
yield IncIndent
yield `if(result.return?.decodeError) {`
yield* indent(`throw result.return.decodeError`)
yield `}`
yield `const returnValue = result.return?.returnValue !== undefined && returnValueFormatter !== undefined`
yield IncIndent
yield `? returnValueFormatter(result.return.returnValue)`
yield `: result.return?.returnValue as TReturn | undefined`
yield `return { ...result, return: returnValue }`
yield DecIndent
yield | DecIndentAndCloseBlock
yield NewLine
yield* jsDoc({ |
description: 'Calls the ABI method with the matching signature using an onCompletion code of NO_OP',
params: {
typedCallParams: 'An object containing the method signature, args, and any other relevant parameters',
returnValueFormatter: 'An optional delegate which when provided will be used to map non-undefined return values to the target type',
},
returns: 'The result of the smart contract call',
})
yield `public async call<TSignature extends keyof ${name}['methods']>(typedCallParams: TypedCallParams<TSignature>, returnValueFormatter?: (value: any) => MethodReturn<TSignature>) {`
yield IncIndent
yield `return this.mapReturnValue<MethodReturn<TSignature>>(await this.appClient.call(typedCallParams), returnValueFormatter)`
yield DecIndentAndCloseBlock
yield NewLine
yield* opMethods(ctx)
yield* clearState(ctx)
yield* noopMethods(ctx)
yield* getStateMethods(ctx)
yield* composeMethod(ctx)
yield DecIndentAndCloseBlock
}
function* opMethods(ctx: GeneratorContext): DocumentParts {
const { app, callConfig, name } = ctx
yield* jsDoc({
description: `Idempotently deploys the ${app.contract.name} smart contract.`,
params: {
params: 'The arguments for the contract calls and any additional parameters for the call',
},
returns: 'The deployment result',
})
yield `public deploy(params: ${name}DeployArgs & AppClientDeployCoreParams = {}): ReturnType<ApplicationClient['deploy']> {`
yield IncIndent
if (callConfig.createMethods.length) yield `const createArgs = params.createCall?.(${name}CallFactory.create)`
if (callConfig.updateMethods.length) yield `const updateArgs = params.updateCall?.(${name}CallFactory.update)`
if (callConfig.deleteMethods.length) yield `const deleteArgs = params.deleteCall?.(${name}CallFactory.delete)`
yield `return this.appClient.deploy({`
yield IncIndent
yield `...params,`
if (callConfig.updateMethods.length) yield 'updateArgs,'
if (callConfig.deleteMethods.length) yield 'deleteArgs,'
if (callConfig.createMethods.length) {
yield 'createArgs,'
yield `createOnCompleteAction: createArgs?.onCompleteAction,`
}
yield DecIndent
yield `})`
yield DecIndentAndCloseBlock
yield NewLine
yield* operationMethod(ctx, `Creates a new instance of the ${app.contract.name} smart contract`, callConfig.createMethods, 'create', true)
yield* operationMethod(
ctx,
`Updates an existing instance of the ${app.contract.name} smart contract`,
callConfig.updateMethods,
'update',
true,
)
yield* operationMethod(ctx, `Deletes an existing instance of the ${app.contract.name} smart contract`, callConfig.deleteMethods, 'delete')
yield* operationMethod(
ctx,
`Opts the user into an existing instance of the ${app.contract.name} smart contract`,
callConfig.optInMethods,
'optIn',
)
yield* operationMethod(
ctx,
`Makes a close out call to an existing instance of the ${app.contract.name} smart contract`,
callConfig.closeOutMethods,
'closeOut',
)
}
function* operationMethod(
{ app, methodSignatureToUniqueName, name }: GeneratorContext,
description: string,
methods: MethodList,
verb: 'create' | 'update' | 'optIn' | 'closeOut' | 'delete',
includeCompilation?: boolean,
): DocumentParts {
if (methods.length) {
yield* jsDoc(`Gets available ${verb} methods`)
yield `public get ${verb}() {`
yield IncIndent
yield `const $this = this`
yield `return {`
yield IncIndent
for (const methodSig of methods) {
const onComplete = verb === 'create' ? getCreateOnCompleteOptions(methodSig, app) : undefined
if (methodSig === BARE_CALL) {
yield* jsDoc({
description: `${description} using a bare call.`,
params: {
args: `The arguments for the bare call`,
},
returns: `The ${verb} result`,
})
yield `bare(args: BareCallArgs & AppClientCallCoreParams ${
includeCompilation ? '& AppClientCompilationParams ' : ''
}& CoreAppCallArgs${onComplete?.type ? ` & ${onComplete.type}` : ''}${
onComplete?.isOptional !== false ? ' = {}' : ''
}): Promise<AppCallTransactionResultOfType<undefined>> {`
yield* indent(`return $this.appClient.${verb}(args) as unknown as Promise<AppCallTransactionResultOfType<undefined>>`)
yield '},'
} else {
const uniqueName = methodSignatureToUniqueName[methodSig]
const method = app.contract.methods.find((m) => algokit.getABIMethodSignature(m) === methodSig)
yield* jsDoc({
description: `${description} using the ${methodSig} ABI method.`,
params: {
args: `The arguments for the smart contract call`,
params: `Any additional parameters for the call`,
},
returns: `The ${verb} result${method?.returns?.desc ? `: ${method.returns.desc}` : ''}`,
})
yield `async ${makeSafeMethodIdentifier(uniqueName)}(args: MethodArgs<'${methodSig}'>, params: AppClientCallCoreParams${
includeCompilation ? ' & AppClientCompilationParams' : ''
}${onComplete?.type ? ` & ${onComplete.type}` : ''}${
onComplete?.isOptional !== false ? ' = {}' : ''
}): Promise<AppCallTransactionResultOfType<MethodReturn<'${methodSig}'>>> {`
yield* indent(
`return $this.mapReturnValue(await $this.appClient.${verb}(${name}CallFactory.${verb}.${makeSafeMethodIdentifier(
uniqueName,
)}(args, params)))`,
)
yield '},'
}
}
yield DecIndentAndCloseBlock
yield DecIndentAndCloseBlock
yield NewLine
}
}
function* clearState({ app }: GeneratorContext): DocumentParts {
yield* jsDoc({
description: `Makes a clear_state call to an existing instance of the ${app.contract.name} smart contract.`,
params: {
args: `The arguments for the bare call`,
},
returns: `The clear_state result`,
})
yield `public clearState(args: BareCallArgs & AppClientCallCoreParams & CoreAppCallArgs = {}) {`
yield IncIndent
yield `return this.appClient.clearState(args)`
yield DecIndentAndCloseBlock
yield NewLine
}
function* noopMethods({ app, name, callConfig, methodSignatureToUniqueName }: GeneratorContext): DocumentParts {
for (const method of app.contract.methods) {
const methodSignature = algokit.getABIMethodSignature(method)
const methodName = makeSafeMethodIdentifier(methodSignatureToUniqueName[methodSignature])
// Skip methods which don't support a no_op call config
if (!callConfig.callMethods.includes(methodSignature)) continue
yield* jsDoc({
description: `Calls the ${algokit.getABIMethodSignature(method)} ABI method.`,
abiDescription: method.desc,
params: {
args: `The arguments for the contract call`,
params: `Any additional parameters for the call`,
},
returns: `The result of the call${method?.returns?.desc ? `: ${method.returns.desc}` : ''}`,
})
yield `public ${methodName}(args: MethodArgs<'${methodSignature}'>, params: AppClientCallCoreParams & CoreAppCallArgs = {}) {`
yield IncIndent
const outputTypeName = app.hints?.[methodSignature]?.structs?.output?.name
yield `return this.call(${name}CallFactory.${methodName}(args, params)${
outputTypeName === undefined ? '' : `, ${makeSafeTypeIdentifier(outputTypeName)}`
})`
yield DecIndent
yield '}'
yield NewLine
}
}
function* getStateMethods({ app, name }: GeneratorContext): DocumentParts {
const globalStateValues = app.schema.global?.declared && Object.values(app.schema.global?.declared)
const localStateValues = app.schema.local?.declared && Object.values(app.schema.local?.declared)
if (globalStateValues?.length || localStateValues?.length) {
yield* jsDoc({
description: 'Extracts a binary state value out of an AppState dictionary',
params: {
state: 'The state dictionary containing the state value',
key: 'The key of the state value',
},
returns: 'A BinaryState instance containing the state value, or undefined if the key was not found',
})
yield `private static getBinaryState(state: AppState, key: string): BinaryState | undefined {`
yield IncIndent
yield `const value = state[key]`
yield `if (!value) return undefined`
yield `if (!('valueRaw' in value))`
yield* indent(`throw new Error(\`Failed to parse state value for \${key}; received an int when expected a byte array\`)`)
yield `return {`
yield IncIndent
yield `asString(): string {`
yield* indent(`return value.value`)
yield `},`
yield `asByteArray(): Uint8Array {`
yield* indent(`return value.valueRaw`)
yield `}`
yield DecIndentAndCloseBlock
yield DecIndentAndCloseBlock
yield NewLine
yield* jsDoc({
description: 'Extracts a integer state value out of an AppState dictionary',
params: {
state: 'The state dictionary containing the state value',
key: 'The key of the state value',
},
returns: 'An IntegerState instance containing the state value, or undefined if the key was not found',
})
yield `private static getIntegerState(state: AppState, key: string): IntegerState | undefined {`
yield IncIndent
yield `const value = state[key]`
yield `if (!value) return undefined`
yield `if ('valueRaw' in value)`
yield* indent(`throw new Error(\`Failed to parse state value for \${key}; received a byte array when expected a number\`)`)
yield `return {`
yield IncIndent
yield `asBigInt() {`
yield* indent(`return typeof value.value === 'bigint' ? value.value : BigInt(value.value)`)
yield `},`
yield `asNumber(): number {`
yield* indent(`return typeof value.value === 'bigint' ? Number(value.value) : value.value`)
yield `},`
yield DecIndentAndCloseBlock
yield DecIndentAndCloseBlock
yield NewLine
}
if (globalStateValues?.length) {
yield* jsDoc(`Returns the smart contract's global state wrapped in a strongly typed accessor with options to format the stored value`)
yield `public async getGlobalState(): Promise<${name}['state']['global']> {`
yield IncIndent
yield `const state = await this.appClient.getGlobalState()`
yield `return {`
yield IncIndent
for (const stateValue of globalStateValues) {
yield `get ${stateValue.key}() {`
if (stateValue.type === 'uint64') {
yield* indent(`return ${name}Client.getIntegerState(state, '${stateValue.key}')`)
} else {
yield* indent(`return ${name}Client.getBinaryState(state, '${stateValue.key}')`)
}
yield '},'
}
yield DecIndentAndCloseBlock
yield DecIndentAndCloseBlock
yield NewLine
}
if (localStateValues?.length) {
yield* jsDoc({
description: `Returns the smart contract's local state wrapped in a strongly typed accessor with options to format the stored value`,
params: {
account: `The address of the account for which to read local state from`,
},
})
yield `public async getLocalState(account: string | SendTransactionFrom): Promise<${name}['state']['local']> {`
yield IncIndent
yield `const state = await this.appClient.getLocalState(account)`
yield `return {`
yield IncIndent
for (const stateValue of localStateValues) {
yield `get ${stateValue.key}() {`
if (stateValue.type === 'uint64') {
yield* indent(`return ${name}Client.getIntegerState(state, '${stateValue.key}')`)
} else {
yield* indent(`return ${name}Client.getBinaryState(state, '${stateValue.key}')`)
}
yield '},'
}
yield DecIndentAndCloseBlock
yield DecIndentAndCloseBlock
yield NewLine
}
}
| src/client/call-client.ts | algorandfoundation-algokit-client-generator-ts-2de43ed | [
{
"filename": "src/client/call-composer.ts",
"retrieved_chunk": " yield IncIndent\n yield `...result,`\n yield `returns: result.returns?.map((val, i) => resultMappers[i] !== undefined ? resultMappers[i]!(val.returnValue) : val.returnValue)`\n yield DecIndentAndCloseBlock\n yield DecIndentAndCloseBlock\n yield DecIndent\n yield `} as unknown as ${name}Composer`\n yield DecIndentAndCloseBlock\n}\nfunction* callComposerNoops({ app, callConfig, methodSignatureToUniqueName }: GeneratorContext): DocumentParts {",
"score": 54.56834750167829
},
{
"filename": "src/client/helpers/get-call-config-summary.ts",
"retrieved_chunk": " }\n if (hasCall(config.close_out)) {\n result.closeOutMethods.push(method)\n }\n}\nconst hasCall = (config: CallConfigValue | undefined) => {\n return config === 'CALL' || config === 'ALL'\n}\nconst hasCreate = (config: CallConfigValue | undefined) => {\n return config === 'CREATE' || config === 'ALL'",
"score": 27.959085984056404
},
{
"filename": "src/schema/load.ts",
"retrieved_chunk": " const file = JSON.parse(fs.readFileSync(appJsonPath, 'utf-8'))\n const result = validator.validate(file, appJsonSchema as unknown as Schema)\n if (!result.valid) boom(result.toString())\n return file as AlgoAppSpec\n}",
"score": 26.36147959200407
},
{
"filename": "src/output/writer.ts",
"retrieved_chunk": " get last() {\n return this._last\n },\n toString() {\n return this.result.join('')\n },\n }\n writeDocumentPartsTo(document, options, writer)\n return writer.toString()\n}",
"score": 24.688340558489887
},
{
"filename": "src/client/call-composer.ts",
"retrieved_chunk": " yield IncIndent\n yield 'await promiseChain'\n yield 'return atc'\n yield DecIndent\n yield '},'\n yield `async execute() {`\n yield IncIndent\n yield `await promiseChain`\n yield `const result = await algokit.sendAtomicTransactionComposer({ atc, sendParams: {} }, client.algod)`\n yield `return {`",
"score": 23.198146825362894
}
] | typescript | DecIndentAndCloseBlock
yield NewLine
yield* jsDoc({ |
import { GeneratorContext } from './generator-context'
import { DecIndent, DecIndentAndCloseBlock, DocumentParts, IncIndent, inline, jsDoc, NewLine } from '../output/writer'
import * as algokit from '@algorandfoundation/algokit-utils'
import { getEquivalentType } from './helpers/get-equivalent-type'
import { makeSafePropertyIdentifier, makeSafeTypeIdentifier, makeSafeVariableIdentifier } from '../util/sanitization'
export function* appTypes(ctx: GeneratorContext): DocumentParts {
const { app, methodSignatureToUniqueName, name } = ctx
yield* jsDoc(`Defines the types of available calls and state of the ${name} smart contract.`)
yield `export type ${name} = {`
yield IncIndent
yield* jsDoc('Maps method signatures / names to their argument and return types.')
yield 'methods:'
yield IncIndent
for (const method of app.contract.methods) {
const methodSig = algokit.getABIMethodSignature(method)
const uniqueName = methodSignatureToUniqueName[methodSig]
yield `& Record<'${methodSig}'${methodSig !== uniqueName ? ` | '${uniqueName}'` : ''}, {`
yield IncIndent
yield `argsObj: {`
yield IncIndent
const argsMeta = method.args.map((arg) => ({
...arg,
hasDefault: app.hints?.[methodSig]?.default_arguments?.[arg.name],
tsType: getEquivalentType(arg.type, 'input'),
}))
for (const arg of argsMeta) {
if (arg.desc) yield* jsDoc(arg.desc)
yield `${makeSafePropertyIdentifier(arg.name)}${arg.hasDefault ? '?' : ''}: ${arg.tsType}`
}
yield DecIndentAndCloseBlock
yield* inline(
`argsTuple: [`,
argsMeta
.map(
(arg) =>
`${makeSafeVariableIdentifier(arg.name)}: ${getEquivalentType(arg.type, 'input')}${arg.hasDefault ? ' | undefined' : ''}`,
)
.join(', '),
']',
)
const outputStruct = ctx.app.hints?.[methodSig]?.structs?.output
if (method.returns.desc) yield* jsDoc(method.returns.desc)
if (outputStruct) {
yield `returns: ${makeSafeTypeIdentifier(outputStruct.name)}`
} else {
yield `returns: ${getEquivalentType(method.returns.type ?? 'void', 'output')}`
}
yield DecIndent
yield '}>'
}
yield DecIndent
yield* appState(ctx)
yield DecIndentAndCloseBlock
yield* jsDoc('Defines the possible abi call signatures')
yield `export type ${name}Sig = keyof ${name}['methods']`
yield* jsDoc(
'Defines an object containing all relevant parameters for a single call to the contract. Where TSignature is undefined, a' +
' bare call is made',
)
yield `export type TypedCallParams<TSignature extends ${name}Sig | undefined> = {`
yield IncIndent
yield 'method: TSignature'
yield 'methodArgs: TSignature extends undefined ? undefined : Array<ABIAppCallArg | undefined>'
yield DecIndent
yield '} & AppClientCallCoreParams & CoreAppCallArgs'
yield* jsDoc('Defines the arguments required for a bare call')
yield `export type BareCallArgs = Omit<RawAppCallArgs, keyof CoreAppCallArgs>`
yield* structs(ctx)
yield* jsDoc(`Maps a method signature from the ${name} smart contract to the method's arguments in either tuple of struct form`)
yield `export type MethodArgs<TSignature extends ${name}Sig> = ${name}['methods'][TSignature]['argsObj' | 'argsTuple']`
yield* jsDoc(`Maps a method signature from the ${name} smart contract to the method's return type`)
yield `export type MethodReturn<TSignature extends ${name}Sig> = ${name}['methods'][TSignature]['returns']`
yield NewLine
}
function* structs({ app }: GeneratorContext): DocumentParts {
if (app.hints === undefined) return
for (const methodHint of Object.values(app.hints)) {
if (methodHint.structs === undefined) continue
for (const struct of Object.values(methodHint.structs)) {
yield* jsDoc(`Represents a ${struct.name} result as a struct`)
yield `export type ${makeSafeTypeIdentifier(struct.name)} = {`
yield IncIndent
for (const [key, type] of struct.elements) {
yield `${makeSafePropertyIdentifier(key)}: ${getEquivalentType(type, 'output')}`
}
yield DecIndentAndCloseBlock
yield* jsDoc(`Converts the tuple representation of a ${struct.name} to the struct representation`)
yield* inline(
`export function ${makeSafeTypeIdentifier(struct.name)}(`,
`[${struct.elements.map(([key]) => makeSafeVariableIdentifier(key)).join(', ')}]: `,
`[${struct.elements.map(([_, type]) => getEquivalentType(type, 'output')).join(', ')}] ) {`,
)
yield IncIndent
yield `return {`
yield IncIndent
for (const [key] of struct.elements) {
const prop = makeSafePropertyIdentifier(key)
const param = makeSafeVariableIdentifier(key)
yield `${prop}${prop !== param ? `: ${param}` : ''},`
}
yield DecIndentAndCloseBlock
yield DecIndentAndCloseBlock
}
}
}
function* appState({ app }: GeneratorContext): DocumentParts {
const hasLocal = app.schema.local?.declared && Object.keys(app.schema.local.declared).length
const hasGlobal = app.schema.global?.declared && Object.keys(app.schema.global.declared).length
if (hasLocal || hasGlobal) {
yield* jsDoc('Defines the shape of the global and local state of the application.')
yield 'state: {'
yield IncIndent
if (hasGlobal) {
yield 'global: {'
yield IncIndent
for (const prop of Object.values(app.schema.global!.declared!)) {
if ( | prop.descr) { |
yield* jsDoc(prop.descr)
}
yield `'${prop.key}'?: ${prop.type === 'uint64' ? 'IntegerState' : 'BinaryState'}`
}
yield DecIndentAndCloseBlock
}
if (hasLocal) {
yield 'local: {'
yield IncIndent
for (const prop of Object.values(app.schema.local!.declared!)) {
if (prop.descr) {
yield* jsDoc(prop.descr)
}
yield `'${prop.key}'?: ${prop.type === 'uint64' ? 'IntegerState' : 'BinaryState'}`
}
yield DecIndentAndCloseBlock
}
yield DecIndentAndCloseBlock
}
}
| src/client/app-types.ts | algorandfoundation-algokit-client-generator-ts-2de43ed | [
{
"filename": "src/client/call-client.ts",
"retrieved_chunk": " outputTypeName === undefined ? '' : `, ${makeSafeTypeIdentifier(outputTypeName)}`\n })`\n yield DecIndent\n yield '}'\n yield NewLine\n }\n}\nfunction* getStateMethods({ app, name }: GeneratorContext): DocumentParts {\n const globalStateValues = app.schema.global?.declared && Object.values(app.schema.global?.declared)\n const localStateValues = app.schema.local?.declared && Object.values(app.schema.local?.declared)",
"score": 51.041728202299794
},
{
"filename": "src/client/call-client.ts",
"retrieved_chunk": " yield NewLine\n }\n if (globalStateValues?.length) {\n yield* jsDoc(`Returns the smart contract's global state wrapped in a strongly typed accessor with options to format the stored value`)\n yield `public async getGlobalState(): Promise<${name}['state']['global']> {`\n yield IncIndent\n yield `const state = await this.appClient.getGlobalState()`\n yield `return {`\n yield IncIndent\n for (const stateValue of globalStateValues) {",
"score": 40.3268741341776
},
{
"filename": "src/schema/application.d.ts",
"retrieved_chunk": " source: \"abi-method\";\n data: ContractMethod;\n }\n | {\n /**\n * The default value should be fetched from global state\n */\n source: \"global-state\";\n /**\n * The key of the state variable",
"score": 31.120325091461805
},
{
"filename": "src/schema/application.d.ts",
"retrieved_chunk": " * Catch all for fixed length arrays and tuples\n */\n type: string;\n };\n}\n/**\n * The schema for global and local storage\n */\nexport interface SchemaSpec {\n global?: Schema;",
"score": 28.669568577116145
},
{
"filename": "src/client/call-client.ts",
"retrieved_chunk": " yield NewLine\n }\n if (localStateValues?.length) {\n yield* jsDoc({\n description: `Returns the smart contract's local state wrapped in a strongly typed accessor with options to format the stored value`,\n params: {\n account: `The address of the account for which to read local state from`,\n },\n })\n yield `public async getLocalState(account: string | SendTransactionFrom): Promise<${name}['state']['local']> {`",
"score": 28.316109160347764
}
] | typescript | prop.descr) { |
import { pascalCase } from 'change-case'
import { AlgoAppSpec, CallConfig, CallConfigValue } from '../../schema/application'
export const BARE_CALL = Symbol('bare')
export type MethodIdentifier = string | typeof BARE_CALL
export type MethodList = Array<MethodIdentifier>
export type CallConfigSummary = {
createMethods: MethodList
callMethods: MethodList
deleteMethods: MethodList
updateMethods: MethodList
optInMethods: MethodList
closeOutMethods: MethodList
}
export const getCallConfigSummary = (app: AlgoAppSpec) => {
const result: CallConfigSummary = {
createMethods: [],
callMethods: [],
deleteMethods: [],
updateMethods: [],
optInMethods: [],
closeOutMethods: [],
}
if (app.bare_call_config) {
addToConfig(result, BARE_CALL, app.bare_call_config)
}
if (app.hints) {
for (const [method, hints] of Object.entries(app.hints)) {
if (hints.call_config) {
addToConfig(result, method, hints.call_config)
}
}
}
return result
}
export const getCreateOnComplete = (app: AlgoAppSpec, method: MethodIdentifier) => {
const callConfig = method === BARE_CALL ? app.bare_call_config : app.hints?.[method]?.call_config
if (!callConfig) {
return ''
}
const hasNoOp = callConfig.no_op === 'ALL' || callConfig.no_op === 'CREATE'
return `{ onCompleteAction${hasNoOp ? '?' : ''}: ${getCreateOnCompleteTypes(callConfig)} }`
}
const | getCreateOnCompleteTypes = (config: CallConfig) => { |
return Object.keys(config)
.map((oc) => oc as keyof CallConfig)
.filter((oc) => config[oc] === 'ALL' || config[oc] === 'CREATE')
.map((oc) => `'${oc}' | OnApplicationComplete.${pascalCase(oc)}OC`)
.join(' | ')
}
const addToConfig = (result: CallConfigSummary, method: MethodIdentifier, config: CallConfig) => {
if (hasCall(config.no_op)) {
result.callMethods.push(method)
}
if (
hasCreate(config.no_op) ||
hasCreate(config.opt_in) ||
hasCreate(config.close_out) ||
hasCreate(config.update_application) ||
hasCreate(config.delete_application)
) {
result.createMethods.push(method)
}
if (hasCall(config.delete_application)) {
result.deleteMethods.push(method)
}
if (hasCall(config.update_application)) {
result.updateMethods.push(method)
}
if (hasCall(config.opt_in)) {
result.optInMethods.push(method)
}
if (hasCall(config.close_out)) {
result.closeOutMethods.push(method)
}
}
const hasCall = (config: CallConfigValue | undefined) => {
return config === 'CALL' || config === 'ALL'
}
const hasCreate = (config: CallConfigValue | undefined) => {
return config === 'CREATE' || config === 'ALL'
}
| src/client/helpers/get-call-config-summary.ts | algorandfoundation-algokit-client-generator-ts-2de43ed | [
{
"filename": "src/client/deploy-types.ts",
"retrieved_chunk": "import { DecIndent, DecIndentAndCloseBlock, DocumentParts, IncIndent, jsDoc, NewLine } from '../output/writer'\nimport { makeSafeTypeIdentifier } from '../util/sanitization'\nimport { BARE_CALL, MethodIdentifier } from './helpers/get-call-config-summary'\nimport { GeneratorContext } from './generator-context'\nimport { AlgoAppSpec, CallConfig } from '../schema/application'\nimport { OnCompleteCodeMap } from './utility-types'\nexport function getCreateOnCompleteOptions(method: MethodIdentifier, app: AlgoAppSpec) {\n const callConfig = method === BARE_CALL ? app.bare_call_config : app.hints?.[method]?.call_config\n const hasNoOp = callConfig?.no_op === 'ALL' || callConfig?.no_op === 'CREATE'\n const onCompleteType = callConfig",
"score": 66.42955005012924
},
{
"filename": "src/client/deploy-types.ts",
"retrieved_chunk": " ? `(${Object.entries(callConfig)\n .filter(([_, value]) => value === 'ALL' || value === 'CREATE')\n .map(([oc]) => OnCompleteCodeMap[oc as keyof CallConfig])\n .join(' | ')})`\n : {}\n return {\n type: onCompleteType,\n isOptional: hasNoOp,\n }\n}",
"score": 34.784450944699984
},
{
"filename": "src/client/call-client.ts",
"retrieved_chunk": "}\nfunction* noopMethods({ app, name, callConfig, methodSignatureToUniqueName }: GeneratorContext): DocumentParts {\n for (const method of app.contract.methods) {\n const methodSignature = algokit.getABIMethodSignature(method)\n const methodName = makeSafeMethodIdentifier(methodSignatureToUniqueName[methodSignature])\n // Skip methods which don't support a no_op call config\n if (!callConfig.callMethods.includes(methodSignature)) continue\n yield* jsDoc({\n description: `Calls the ${algokit.getABIMethodSignature(method)} ABI method.`,\n abiDescription: method.desc,",
"score": 30.189498570299058
},
{
"filename": "src/client/call-composer.ts",
"retrieved_chunk": " for (const method of app.contract.methods) {\n const methodSignature = algokit.getABIMethodSignature(method)\n const methodName = makeSafeMethodIdentifier(methodSignatureToUniqueName[methodSignature])\n // Skip methods which don't support a no_op call config\n if (!callConfig.callMethods.includes(methodSignature)) continue\n yield `${methodName}(args: MethodArgs<'${methodSignature}'>, params?: AppClientCallCoreParams & CoreAppCallArgs) {`\n yield IncIndent\n yield `promiseChain = promiseChain.then(() => client.${methodName}(args, {...params, sendParams: {...params?.sendParams, skipSending: true, atc}}))`\n const outputTypeName = app.hints?.[methodSignature]?.structs?.output?.name\n yield `resultMappers.push(${outputTypeName ?? 'undefined'})`",
"score": 24.073902900059302
},
{
"filename": "src/client/deploy-types.ts",
"retrieved_chunk": "export function* deployTypes({ app, callConfig }: GeneratorContext): DocumentParts {\n const name = makeSafeTypeIdentifier(app.contract.name)\n if (callConfig.createMethods.length > 0) {\n yield* jsDoc(`A factory for available 'create' calls`)\n yield `export type ${name}CreateCalls = (typeof ${name}CallFactory)['create']`\n yield* jsDoc('Defines supported create methods for this smart contract')\n yield `export type ${name}CreateCallParams =`\n yield IncIndent\n for (const method of callConfig.createMethods) {\n const onComplete = getCreateOnCompleteOptions(method, app)",
"score": 22.892774150949272
}
] | typescript | getCreateOnCompleteTypes = (config: CallConfig) => { |
import { DecIndent, DecIndentAndCloseBlock, DocumentParts, IncIndent, jsDoc, NewLine } from '../output/writer'
import { makeSafeTypeIdentifier } from '../util/sanitization'
import { BARE_CALL, MethodIdentifier } from './helpers/get-call-config-summary'
import { GeneratorContext } from './generator-context'
import { AlgoAppSpec, CallConfig } from '../schema/application'
import { OnCompleteCodeMap } from './utility-types'
export function getCreateOnCompleteOptions(method: MethodIdentifier, app: AlgoAppSpec) {
const callConfig = method === BARE_CALL ? app.bare_call_config : app.hints?.[method]?.call_config
const hasNoOp = callConfig?.no_op === 'ALL' || callConfig?.no_op === 'CREATE'
const onCompleteType = callConfig
? `(${Object.entries(callConfig)
.filter(([_, value]) => value === 'ALL' || value === 'CREATE')
.map(([oc]) => OnCompleteCodeMap[oc as keyof CallConfig])
.join(' | ')})`
: {}
return {
type: onCompleteType,
isOptional: hasNoOp,
}
}
export function* deployTypes({ app, callConfig }: GeneratorContext): DocumentParts {
const name = makeSafeTypeIdentifier(app.contract.name)
if (callConfig.createMethods.length > 0) {
yield* jsDoc(`A factory for available 'create' calls`)
yield `export type ${name}CreateCalls = (typeof ${name}CallFactory)['create']`
yield* jsDoc('Defines supported create methods for this smart contract')
yield `export type ${name}CreateCallParams =`
yield IncIndent
for (const method of callConfig.createMethods) {
const onComplete = getCreateOnCompleteOptions(method, app)
if (method === BARE_CALL) {
yield `| (TypedCallParams<undefined> & ${onComplete.type})`
} else {
yield `| (TypedCallParams<'${method}'> & ${onComplete.type})`
}
}
| yield DecIndent
} |
if (callConfig.updateMethods.length > 0) {
yield* jsDoc(`A factory for available 'update' calls`)
yield `export type ${name}UpdateCalls = (typeof ${name}CallFactory)['update']`
yield* jsDoc('Defines supported update methods for this smart contract')
yield `export type ${name}UpdateCallParams =`
yield IncIndent
for (const method of callConfig.updateMethods) {
if (method === BARE_CALL) {
yield `| TypedCallParams<undefined>`
} else {
yield `| TypedCallParams<'${method}'>`
}
}
yield DecIndent
}
if (callConfig.deleteMethods.length > 0) {
yield* jsDoc(`A factory for available 'delete' calls`)
yield `export type ${name}DeleteCalls = (typeof ${name}CallFactory)['delete']`
yield* jsDoc('Defines supported delete methods for this smart contract')
yield `export type ${name}DeleteCallParams =`
yield IncIndent
for (const method of callConfig.deleteMethods) {
if (method === BARE_CALL) {
yield `| TypedCallParams<undefined>`
} else {
yield `| TypedCallParams<'${method}'>`
}
}
yield DecIndent
}
yield* jsDoc('Defines arguments required for the deploy method.')
yield `export type ${name}DeployArgs = {`
yield IncIndent
yield `deployTimeParams?: TealTemplateParams`
if (callConfig.createMethods.length) {
yield* jsDoc('A delegate which takes a create call factory and returns the create call params for this smart contract')
yield `createCall?: (callFactory: ${name}CreateCalls) => ${name}CreateCallParams`
}
if (callConfig.updateMethods.length) {
yield* jsDoc('A delegate which takes a update call factory and returns the update call params for this smart contract')
yield `updateCall?: (callFactory: ${name}UpdateCalls) => ${name}UpdateCallParams`
}
if (callConfig.deleteMethods.length) {
yield* jsDoc('A delegate which takes a delete call factory and returns the delete call params for this smart contract')
yield `deleteCall?: (callFactory: ${name}DeleteCalls) => ${name}DeleteCallParams`
}
yield DecIndentAndCloseBlock
yield NewLine
}
| src/client/deploy-types.ts | algorandfoundation-algokit-client-generator-ts-2de43ed | [
{
"filename": "src/client/call-factory.ts",
"retrieved_chunk": " includeCompilation ? ' & AppClientCompilationParams' : ''\n }${onComplete?.type ? ` & ${onComplete.type}` : ''}${onComplete?.isOptional !== false ? ' = {}' : ''}`,\n })\n } else {\n const method = app.contract.methods.find((m) => algokit.getABIMethodSignature(m) === methodSig)!\n const uniqueName = methodSignatureToUniqueName[methodSig]\n yield* jsDoc({\n description: `${description} using the ${methodSig} ABI method`,\n params: {\n args: `Any args for the contract call`,",
"score": 29.910893031515155
},
{
"filename": "src/client/call-composer.ts",
"retrieved_chunk": " if (methods.length) {\n yield `get ${verb}() {`\n yield IncIndent\n yield `const $this = this`\n yield `return {`\n yield IncIndent\n for (const methodSig of methods) {\n const onComplete = verb === 'create' ? getCreateOnCompleteOptions(methodSig, app) : undefined\n if (methodSig === BARE_CALL) {\n yield `bare(args${onComplete?.isOptional !== false ? '?' : ''}: BareCallArgs & AppClientCallCoreParams ${",
"score": 26.938930455944387
},
{
"filename": "src/client/call-composer.ts",
"retrieved_chunk": " includeCompilation ? '& AppClientCompilationParams ' : ''\n }& CoreAppCallArgs${onComplete?.type ? ` & ${onComplete.type}` : ''}) {`\n yield IncIndent\n yield `promiseChain = promiseChain.then(() => client.${verb}.bare({...args, sendParams: {...args?.sendParams, skipSending: true, atc}}))`\n yield `resultMappers.push(undefined)`\n yield `return $this`\n yield DecIndent\n yield '},'\n } else {\n const uniqueName = methodSignatureToUniqueName[methodSig]",
"score": 25.0118555482871
},
{
"filename": "src/client/call-client.ts",
"retrieved_chunk": " })\n yield `bare(args: BareCallArgs & AppClientCallCoreParams ${\n includeCompilation ? '& AppClientCompilationParams ' : ''\n }& CoreAppCallArgs${onComplete?.type ? ` & ${onComplete.type}` : ''}${\n onComplete?.isOptional !== false ? ' = {}' : ''\n }): Promise<AppCallTransactionResultOfType<undefined>> {`\n yield* indent(`return $this.appClient.${verb}(args) as unknown as Promise<AppCallTransactionResultOfType<undefined>>`)\n yield '},'\n } else {\n const uniqueName = methodSignatureToUniqueName[methodSig]",
"score": 24.887860153123928
},
{
"filename": "src/client/app-types.ts",
"retrieved_chunk": " const outputStruct = ctx.app.hints?.[methodSig]?.structs?.output\n if (method.returns.desc) yield* jsDoc(method.returns.desc)\n if (outputStruct) {\n yield `returns: ${makeSafeTypeIdentifier(outputStruct.name)}`\n } else {\n yield `returns: ${getEquivalentType(method.returns.type ?? 'void', 'output')}`\n }\n yield DecIndent\n yield '}>'\n }",
"score": 24.473737363431198
}
] | typescript | yield DecIndent
} |
import { DecIndent, DecIndentAndCloseBlock, DocumentParts, IncIndent } from '../output/writer'
import { GeneratorContext } from './generator-context'
import * as algokit from '@algorandfoundation/algokit-utils'
import { makeSafeMethodIdentifier } from '../util/sanitization'
import { BARE_CALL, MethodList } from './helpers/get-call-config-summary'
import { getCreateOnCompleteOptions } from './deploy-types'
export function* composeMethod(ctx: GeneratorContext): DocumentParts {
const { name, callConfig } = ctx
yield `public compose(): ${name}Composer {`
yield IncIndent
yield `const client = this`
yield `const atc = new AtomicTransactionComposer()`
yield `let promiseChain:Promise<unknown> = Promise.resolve()`
yield `const resultMappers: Array<undefined | ((x: any) => any)> = []`
yield `return {`
yield IncIndent
yield* callComposerNoops(ctx)
yield* callComposerOperationMethods(ctx, callConfig.updateMethods, 'update', true)
yield* callComposerOperationMethods(ctx, callConfig.deleteMethods, 'delete')
yield* callComposerOperationMethods(ctx, callConfig.optInMethods, 'optIn')
yield* callComposerOperationMethods(ctx, callConfig.closeOutMethods, 'closeOut')
yield* callComposerClearState()
yield `addTransaction(txn: TransactionWithSigner | TransactionToSign | Transaction | Promise<SendTransactionResult>, defaultSender?: SendTransactionFrom) {`
yield IncIndent
yield 'promiseChain = promiseChain.then(async () => atc.addTransaction(await algokit.getTransactionWithSigner(txn, defaultSender ??' +
' client.sender)))'
yield 'return this'
yield DecIndent
yield '},'
yield `async atc() {`
yield IncIndent
yield 'await promiseChain'
yield 'return atc'
yield DecIndent
yield '},'
yield `async execute() {`
yield IncIndent
yield `await promiseChain`
yield `const result = await algokit.sendAtomicTransactionComposer({ atc, sendParams: {} }, client.algod)`
yield `return {`
yield IncIndent
yield `...result,`
yield `returns: result.returns?.map((val, i) => resultMappers[i] !== undefined ? resultMappers[i]!(val.returnValue) : val.returnValue)`
yield DecIndentAndCloseBlock
yield DecIndentAndCloseBlock
yield DecIndent
yield `} as unknown as ${name}Composer`
yield DecIndentAndCloseBlock
}
function* callComposerNoops | ({ app, callConfig, methodSignatureToUniqueName }: GeneratorContext): DocumentParts { |
for (const method of app.contract.methods) {
const methodSignature = algokit.getABIMethodSignature(method)
const methodName = makeSafeMethodIdentifier(methodSignatureToUniqueName[methodSignature])
// Skip methods which don't support a no_op call config
if (!callConfig.callMethods.includes(methodSignature)) continue
yield `${methodName}(args: MethodArgs<'${methodSignature}'>, params?: AppClientCallCoreParams & CoreAppCallArgs) {`
yield IncIndent
yield `promiseChain = promiseChain.then(() => client.${methodName}(args, {...params, sendParams: {...params?.sendParams, skipSending: true, atc}}))`
const outputTypeName = app.hints?.[methodSignature]?.structs?.output?.name
yield `resultMappers.push(${outputTypeName ?? 'undefined'})`
yield `return this`
yield DecIndent
yield '},'
}
}
function* callComposerClearState(): DocumentParts {
yield `clearState(args?: BareCallArgs & AppClientCallCoreParams & CoreAppCallArgs) {`
yield IncIndent
yield `promiseChain = promiseChain.then(() => client.clearState({...args, sendParams: {...args?.sendParams, skipSending: true, atc}}))`
yield `resultMappers.push(undefined)`
yield `return this`
yield DecIndent
yield '},'
}
function* callComposerOperationMethods(
{ app, methodSignatureToUniqueName }: GeneratorContext,
methods: MethodList,
verb: 'create' | 'update' | 'optIn' | 'closeOut' | 'delete',
includeCompilation?: boolean,
): DocumentParts {
if (methods.length) {
yield `get ${verb}() {`
yield IncIndent
yield `const $this = this`
yield `return {`
yield IncIndent
for (const methodSig of methods) {
const onComplete = verb === 'create' ? getCreateOnCompleteOptions(methodSig, app) : undefined
if (methodSig === BARE_CALL) {
yield `bare(args${onComplete?.isOptional !== false ? '?' : ''}: BareCallArgs & AppClientCallCoreParams ${
includeCompilation ? '& AppClientCompilationParams ' : ''
}& CoreAppCallArgs${onComplete?.type ? ` & ${onComplete.type}` : ''}) {`
yield IncIndent
yield `promiseChain = promiseChain.then(() => client.${verb}.bare({...args, sendParams: {...args?.sendParams, skipSending: true, atc}}))`
yield `resultMappers.push(undefined)`
yield `return $this`
yield DecIndent
yield '},'
} else {
const uniqueName = methodSignatureToUniqueName[methodSig]
const methodName = makeSafeMethodIdentifier(uniqueName)
yield `${methodName}(args: MethodArgs<'${methodSig}'>, params${
onComplete?.isOptional !== false ? '?' : ''
}: AppClientCallCoreParams${includeCompilation ? ' & AppClientCompilationParams' : ''}${
onComplete?.type ? ` & ${onComplete.type}` : ''
}) {`
yield IncIndent
yield `promiseChain = promiseChain.then(() => client.${verb}.${methodName}(args, {...params, sendParams: {...params?.sendParams, skipSending: true, atc}}))`
const outputTypeName = app.hints?.[methodSig]?.structs?.output?.name
yield `resultMappers.push(${outputTypeName ?? 'undefined'})`
yield `return $this`
yield DecIndent
yield '},'
}
}
yield DecIndentAndCloseBlock
yield DecIndent
yield '},'
}
}
| src/client/call-composer.ts | algorandfoundation-algokit-client-generator-ts-2de43ed | [
{
"filename": "src/client/call-client.ts",
"retrieved_chunk": " yield `const returnValue = result.return?.returnValue !== undefined && returnValueFormatter !== undefined`\n yield IncIndent\n yield `? returnValueFormatter(result.return.returnValue)`\n yield `: result.return?.returnValue as TReturn | undefined`\n yield `return { ...result, return: returnValue }`\n yield DecIndent\n yield DecIndentAndCloseBlock\n yield NewLine\n yield* jsDoc({\n description: 'Calls the ABI method with the matching signature using an onCompletion code of NO_OP',",
"score": 48.04392933426492
},
{
"filename": "src/output/writer.ts",
"retrieved_chunk": " writeDocumentPartsTo(document, options, writer)\n}\nexport function writeDocumentPartsToString(document: DocumentParts, options: WriteOptions = {}) {\n const writer = {\n result: [] as string[],\n _last: '',\n write(val: string) {\n this._last = val\n this.result.push(val)\n },",
"score": 34.0454357275433
},
{
"filename": "src/client/call-client.ts",
"retrieved_chunk": " yield NewLine\n yield* opMethods(ctx)\n yield* clearState(ctx)\n yield* noopMethods(ctx)\n yield* getStateMethods(ctx)\n yield* composeMethod(ctx)\n yield DecIndentAndCloseBlock\n}\nfunction* opMethods(ctx: GeneratorContext): DocumentParts {\n const { app, callConfig, name } = ctx",
"score": 27.56880118664373
},
{
"filename": "src/client/call-client.ts",
"retrieved_chunk": " }\n }\n yield DecIndentAndCloseBlock\n yield DecIndentAndCloseBlock\n yield NewLine\n }\n}\nfunction* clearState({ app }: GeneratorContext): DocumentParts {\n yield* jsDoc({\n description: `Makes a clear_state call to an existing instance of the ${app.contract.name} smart contract.`,",
"score": 26.61626616416315
},
{
"filename": "src/client/call-client.ts",
"retrieved_chunk": " params: {\n args: `The arguments for the bare call`,\n },\n returns: `The clear_state result`,\n })\n yield `public clearState(args: BareCallArgs & AppClientCallCoreParams & CoreAppCallArgs = {}) {`\n yield IncIndent\n yield `return this.appClient.clearState(args)`\n yield DecIndentAndCloseBlock\n yield NewLine",
"score": 25.41952902494044
}
] | typescript | ({ app, callConfig, methodSignatureToUniqueName }: GeneratorContext): DocumentParts { |
import { pascalCase } from 'change-case'
import { AlgoAppSpec, CallConfig, CallConfigValue } from '../../schema/application'
export const BARE_CALL = Symbol('bare')
export type MethodIdentifier = string | typeof BARE_CALL
export type MethodList = Array<MethodIdentifier>
export type CallConfigSummary = {
createMethods: MethodList
callMethods: MethodList
deleteMethods: MethodList
updateMethods: MethodList
optInMethods: MethodList
closeOutMethods: MethodList
}
export const getCallConfigSummary = (app: AlgoAppSpec) => {
const result: CallConfigSummary = {
createMethods: [],
callMethods: [],
deleteMethods: [],
updateMethods: [],
optInMethods: [],
closeOutMethods: [],
}
if (app.bare_call_config) {
addToConfig(result, BARE_CALL, app.bare_call_config)
}
if (app.hints) {
for (const [method, hints] of Object.entries(app.hints)) {
if (hints.call_config) {
addToConfig(result, method, hints.call_config)
}
}
}
return result
}
export const getCreateOnComplete = (app: AlgoAppSpec, method: MethodIdentifier) => {
const callConfig = method === BARE_CALL ? app.bare_call_config : app.hints?.[method]?.call_config
if (!callConfig) {
return ''
}
const hasNoOp = callConfig.no_op === 'ALL' || callConfig.no_op === 'CREATE'
return `{ onCompleteAction${hasNoOp ? '?' : ''}: ${getCreateOnCompleteTypes(callConfig)} }`
}
const getCreateOnCompleteTypes = (config: CallConfig) => {
return Object.keys(config)
.map((oc) => oc as keyof CallConfig)
.filter((oc) => config[oc] === 'ALL' || config[oc] === 'CREATE')
.map((oc) => | `'${oc}' | OnApplicationComplete.${pascalCase(oc)}OC`)
.join(' | ')
} |
const addToConfig = (result: CallConfigSummary, method: MethodIdentifier, config: CallConfig) => {
if (hasCall(config.no_op)) {
result.callMethods.push(method)
}
if (
hasCreate(config.no_op) ||
hasCreate(config.opt_in) ||
hasCreate(config.close_out) ||
hasCreate(config.update_application) ||
hasCreate(config.delete_application)
) {
result.createMethods.push(method)
}
if (hasCall(config.delete_application)) {
result.deleteMethods.push(method)
}
if (hasCall(config.update_application)) {
result.updateMethods.push(method)
}
if (hasCall(config.opt_in)) {
result.optInMethods.push(method)
}
if (hasCall(config.close_out)) {
result.closeOutMethods.push(method)
}
}
const hasCall = (config: CallConfigValue | undefined) => {
return config === 'CALL' || config === 'ALL'
}
const hasCreate = (config: CallConfigValue | undefined) => {
return config === 'CREATE' || config === 'ALL'
}
| src/client/helpers/get-call-config-summary.ts | algorandfoundation-algokit-client-generator-ts-2de43ed | [
{
"filename": "src/client/deploy-types.ts",
"retrieved_chunk": " ? `(${Object.entries(callConfig)\n .filter(([_, value]) => value === 'ALL' || value === 'CREATE')\n .map(([oc]) => OnCompleteCodeMap[oc as keyof CallConfig])\n .join(' | ')})`\n : {}\n return {\n type: onCompleteType,\n isOptional: hasNoOp,\n }\n}",
"score": 114.37782005451552
},
{
"filename": "src/client/deploy-types.ts",
"retrieved_chunk": "import { DecIndent, DecIndentAndCloseBlock, DocumentParts, IncIndent, jsDoc, NewLine } from '../output/writer'\nimport { makeSafeTypeIdentifier } from '../util/sanitization'\nimport { BARE_CALL, MethodIdentifier } from './helpers/get-call-config-summary'\nimport { GeneratorContext } from './generator-context'\nimport { AlgoAppSpec, CallConfig } from '../schema/application'\nimport { OnCompleteCodeMap } from './utility-types'\nexport function getCreateOnCompleteOptions(method: MethodIdentifier, app: AlgoAppSpec) {\n const callConfig = method === BARE_CALL ? app.bare_call_config : app.hints?.[method]?.call_config\n const hasNoOp = callConfig?.no_op === 'ALL' || callConfig?.no_op === 'CREATE'\n const onCompleteType = callConfig",
"score": 24.516370939133193
},
{
"filename": "src/client/generator-context.ts",
"retrieved_chunk": "import { AlgoAppSpec } from '../schema/application'\nimport { CallConfigSummary, getCallConfigSummary } from './helpers/get-call-config-summary'\nimport { makeSafeTypeIdentifier } from '../util/sanitization'\nimport * as algokit from '@algorandfoundation/algokit-utils'\nexport type GeneratorContext = {\n app: AlgoAppSpec\n name: string\n callConfig: CallConfigSummary\n methodSignatureToUniqueName: Record<string, string>\n}",
"score": 14.264953656164835
},
{
"filename": "src/client/helpers/get-equivalent-type.ts",
"retrieved_chunk": " }\n if (abiType instanceof ABITupleType) {\n return `[${abiType.childTypes.map((c) => abiTypeToTs(c, ioType)).join(', ')}]`\n }\n if (abiType instanceof ABIByteType) {\n return 'number'\n }\n if (abiType instanceof ABIStringType) {\n return 'string'\n }",
"score": 13.726596840148826
},
{
"filename": "src/client/call-composer.ts",
"retrieved_chunk": "import { DecIndent, DecIndentAndCloseBlock, DocumentParts, IncIndent } from '../output/writer'\nimport { GeneratorContext } from './generator-context'\nimport * as algokit from '@algorandfoundation/algokit-utils'\nimport { makeSafeMethodIdentifier } from '../util/sanitization'\nimport { BARE_CALL, MethodList } from './helpers/get-call-config-summary'\nimport { getCreateOnCompleteOptions } from './deploy-types'\nexport function* composeMethod(ctx: GeneratorContext): DocumentParts {\n const { name, callConfig } = ctx\n yield `public compose(): ${name}Composer {`\n yield IncIndent",
"score": 12.14335233472548
}
] | typescript | `'${oc}' | OnApplicationComplete.${pascalCase(oc)}OC`)
.join(' | ')
} |
import { pascalCase } from 'change-case'
import { AlgoAppSpec, CallConfig, CallConfigValue } from '../../schema/application'
export const BARE_CALL = Symbol('bare')
export type MethodIdentifier = string | typeof BARE_CALL
export type MethodList = Array<MethodIdentifier>
export type CallConfigSummary = {
createMethods: MethodList
callMethods: MethodList
deleteMethods: MethodList
updateMethods: MethodList
optInMethods: MethodList
closeOutMethods: MethodList
}
export const getCallConfigSummary = (app: AlgoAppSpec) => {
const result: CallConfigSummary = {
createMethods: [],
callMethods: [],
deleteMethods: [],
updateMethods: [],
optInMethods: [],
closeOutMethods: [],
}
if (app.bare_call_config) {
addToConfig(result, BARE_CALL, app.bare_call_config)
}
if (app.hints) {
for (const [method, hints] of Object.entries(app.hints)) {
if (hints.call_config) {
addToConfig(result, method, hints.call_config)
}
}
}
return result
}
export const getCreateOnComplete = (app: AlgoAppSpec, method: MethodIdentifier) => {
const callConfig = method === BARE_CALL ? app.bare_call_config : app.hints?.[method]?.call_config
if (!callConfig) {
return ''
}
const hasNoOp = callConfig.no_op === 'ALL' || callConfig.no_op === 'CREATE'
return `{ onCompleteAction${hasNoOp ? '?' : ''}: ${getCreateOnCompleteTypes(callConfig)} }`
}
const getCreateOnCompleteTypes = (config: CallConfig) => {
return Object.keys(config)
.map((oc) => oc as keyof CallConfig)
.filter((oc) => config[oc] === 'ALL' || config[oc] === 'CREATE')
.map((oc) => ` | '${oc}' | OnApplicationComplete.${pascalCase(oc)}OC`)
.join(' | ')
} |
const addToConfig = (result: CallConfigSummary, method: MethodIdentifier, config: CallConfig) => {
if (hasCall(config.no_op)) {
result.callMethods.push(method)
}
if (
hasCreate(config.no_op) ||
hasCreate(config.opt_in) ||
hasCreate(config.close_out) ||
hasCreate(config.update_application) ||
hasCreate(config.delete_application)
) {
result.createMethods.push(method)
}
if (hasCall(config.delete_application)) {
result.deleteMethods.push(method)
}
if (hasCall(config.update_application)) {
result.updateMethods.push(method)
}
if (hasCall(config.opt_in)) {
result.optInMethods.push(method)
}
if (hasCall(config.close_out)) {
result.closeOutMethods.push(method)
}
}
const hasCall = (config: CallConfigValue | undefined) => {
return config === 'CALL' || config === 'ALL'
}
const hasCreate = (config: CallConfigValue | undefined) => {
return config === 'CREATE' || config === 'ALL'
}
| src/client/helpers/get-call-config-summary.ts | algorandfoundation-algokit-client-generator-ts-2de43ed | [
{
"filename": "src/client/deploy-types.ts",
"retrieved_chunk": " ? `(${Object.entries(callConfig)\n .filter(([_, value]) => value === 'ALL' || value === 'CREATE')\n .map(([oc]) => OnCompleteCodeMap[oc as keyof CallConfig])\n .join(' | ')})`\n : {}\n return {\n type: onCompleteType,\n isOptional: hasNoOp,\n }\n}",
"score": 114.37782005451552
},
{
"filename": "src/client/deploy-types.ts",
"retrieved_chunk": "import { DecIndent, DecIndentAndCloseBlock, DocumentParts, IncIndent, jsDoc, NewLine } from '../output/writer'\nimport { makeSafeTypeIdentifier } from '../util/sanitization'\nimport { BARE_CALL, MethodIdentifier } from './helpers/get-call-config-summary'\nimport { GeneratorContext } from './generator-context'\nimport { AlgoAppSpec, CallConfig } from '../schema/application'\nimport { OnCompleteCodeMap } from './utility-types'\nexport function getCreateOnCompleteOptions(method: MethodIdentifier, app: AlgoAppSpec) {\n const callConfig = method === BARE_CALL ? app.bare_call_config : app.hints?.[method]?.call_config\n const hasNoOp = callConfig?.no_op === 'ALL' || callConfig?.no_op === 'CREATE'\n const onCompleteType = callConfig",
"score": 24.516370939133193
},
{
"filename": "src/client/generator-context.ts",
"retrieved_chunk": "import { AlgoAppSpec } from '../schema/application'\nimport { CallConfigSummary, getCallConfigSummary } from './helpers/get-call-config-summary'\nimport { makeSafeTypeIdentifier } from '../util/sanitization'\nimport * as algokit from '@algorandfoundation/algokit-utils'\nexport type GeneratorContext = {\n app: AlgoAppSpec\n name: string\n callConfig: CallConfigSummary\n methodSignatureToUniqueName: Record<string, string>\n}",
"score": 14.264953656164835
},
{
"filename": "src/client/helpers/get-equivalent-type.ts",
"retrieved_chunk": " }\n if (abiType instanceof ABITupleType) {\n return `[${abiType.childTypes.map((c) => abiTypeToTs(c, ioType)).join(', ')}]`\n }\n if (abiType instanceof ABIByteType) {\n return 'number'\n }\n if (abiType instanceof ABIStringType) {\n return 'string'\n }",
"score": 13.726596840148826
},
{
"filename": "src/client/call-composer.ts",
"retrieved_chunk": "import { DecIndent, DecIndentAndCloseBlock, DocumentParts, IncIndent } from '../output/writer'\nimport { GeneratorContext } from './generator-context'\nimport * as algokit from '@algorandfoundation/algokit-utils'\nimport { makeSafeMethodIdentifier } from '../util/sanitization'\nimport { BARE_CALL, MethodList } from './helpers/get-call-config-summary'\nimport { getCreateOnCompleteOptions } from './deploy-types'\nexport function* composeMethod(ctx: GeneratorContext): DocumentParts {\n const { name, callConfig } = ctx\n yield `public compose(): ${name}Composer {`\n yield IncIndent",
"score": 12.14335233472548
}
] | typescript | '${oc}' | OnApplicationComplete.${pascalCase(oc)}OC`)
.join(' | ')
} |
import { pascalCase } from 'change-case'
import { AlgoAppSpec, CallConfig, CallConfigValue } from '../../schema/application'
export const BARE_CALL = Symbol('bare')
export type MethodIdentifier = string | typeof BARE_CALL
export type MethodList = Array<MethodIdentifier>
export type CallConfigSummary = {
createMethods: MethodList
callMethods: MethodList
deleteMethods: MethodList
updateMethods: MethodList
optInMethods: MethodList
closeOutMethods: MethodList
}
export const getCallConfigSummary = (app: AlgoAppSpec) => {
const result: CallConfigSummary = {
createMethods: [],
callMethods: [],
deleteMethods: [],
updateMethods: [],
optInMethods: [],
closeOutMethods: [],
}
if (app.bare_call_config) {
addToConfig(result, BARE_CALL, app.bare_call_config)
}
if (app.hints) {
for (const [method, hints] of Object.entries(app.hints)) {
if (hints.call_config) {
addToConfig(result, method, hints.call_config)
}
}
}
return result
}
export const getCreateOnComplete = (app: AlgoAppSpec, method: MethodIdentifier) => {
const callConfig = method === BARE_CALL ? app.bare_call_config : app.hints?.[method]?.call_config
if (!callConfig) {
return ''
}
const hasNoOp = callConfig.no_op === 'ALL' || callConfig.no_op === 'CREATE'
return `{ onCompleteAction${hasNoOp ? '?' : ''}: ${getCreateOnCompleteTypes(callConfig)} }`
}
const getCreateOnCompleteTypes = (config: CallConfig) => {
return Object.keys(config)
.map((oc) => oc as keyof CallConfig)
.filter((oc) => config[oc] === 'ALL' || config[oc] === 'CREATE')
.map((oc) => `'${oc}' | OnApplicationComplete.${pascalCase(oc)}OC`)
.join(' | ')
}
const addToConfig = (result: CallConfigSummary, method: MethodIdentifier, config: CallConfig) => {
if (hasCall(config.no_op)) {
result.callMethods.push(method)
}
if (
hasCreate(config.no_op) ||
hasCreate(config.opt_in) ||
hasCreate(config.close_out) ||
hasCreate(config.update_application) ||
hasCreate(config.delete_application)
) {
result.createMethods.push(method)
}
if (hasCall(config.delete_application)) {
result.deleteMethods.push(method)
}
if (hasCall(config.update_application)) {
result.updateMethods.push(method)
}
if (hasCall(config.opt_in)) {
result.optInMethods.push(method)
}
if (hasCall(config.close_out)) {
result.closeOutMethods.push(method)
}
}
| const hasCall = (config: CallConfigValue | undefined) => { |
return config === 'CALL' || config === 'ALL'
}
const hasCreate = (config: CallConfigValue | undefined) => {
return config === 'CREATE' || config === 'ALL'
}
| src/client/helpers/get-call-config-summary.ts | algorandfoundation-algokit-client-generator-ts-2de43ed | [
{
"filename": "src/output/writer.ts",
"retrieved_chunk": " writeDocumentPartsTo(document, options, writer)\n}\nexport function writeDocumentPartsToString(document: DocumentParts, options: WriteOptions = {}) {\n const writer = {\n result: [] as string[],\n _last: '',\n write(val: string) {\n this._last = val\n this.result.push(val)\n },",
"score": 21.297701692258695
},
{
"filename": "src/client/call-composer.ts",
"retrieved_chunk": " for (const method of app.contract.methods) {\n const methodSignature = algokit.getABIMethodSignature(method)\n const methodName = makeSafeMethodIdentifier(methodSignatureToUniqueName[methodSignature])\n // Skip methods which don't support a no_op call config\n if (!callConfig.callMethods.includes(methodSignature)) continue\n yield `${methodName}(args: MethodArgs<'${methodSignature}'>, params?: AppClientCallCoreParams & CoreAppCallArgs) {`\n yield IncIndent\n yield `promiseChain = promiseChain.then(() => client.${methodName}(args, {...params, sendParams: {...params?.sendParams, skipSending: true, atc}}))`\n const outputTypeName = app.hints?.[methodSignature]?.structs?.output?.name\n yield `resultMappers.push(${outputTypeName ?? 'undefined'})`",
"score": 20.180736756281284
},
{
"filename": "src/schema/application.d.ts",
"retrieved_chunk": " name: string;\n}\nexport interface CallConfig {\n no_op?: CallConfigValue;\n opt_in?: CallConfigValue;\n close_out?: CallConfigValue;\n update_application?: CallConfigValue;\n delete_application?: CallConfigValue;\n}\nexport interface AppSources {",
"score": 18.89623712973225
},
{
"filename": "src/client/call-client.ts",
"retrieved_chunk": " yield `const returnValue = result.return?.returnValue !== undefined && returnValueFormatter !== undefined`\n yield IncIndent\n yield `? returnValueFormatter(result.return.returnValue)`\n yield `: result.return?.returnValue as TReturn | undefined`\n yield `return { ...result, return: returnValue }`\n yield DecIndent\n yield DecIndentAndCloseBlock\n yield NewLine\n yield* jsDoc({\n description: 'Calls the ABI method with the matching signature using an onCompletion code of NO_OP',",
"score": 17.58800556136033
},
{
"filename": "src/client/call-client.ts",
"retrieved_chunk": "}\nfunction* noopMethods({ app, name, callConfig, methodSignatureToUniqueName }: GeneratorContext): DocumentParts {\n for (const method of app.contract.methods) {\n const methodSignature = algokit.getABIMethodSignature(method)\n const methodName = makeSafeMethodIdentifier(methodSignatureToUniqueName[methodSignature])\n // Skip methods which don't support a no_op call config\n if (!callConfig.callMethods.includes(methodSignature)) continue\n yield* jsDoc({\n description: `Calls the ${algokit.getABIMethodSignature(method)} ABI method.`,\n abiDescription: method.desc,",
"score": 16.773832350260648
}
] | typescript | const hasCall = (config: CallConfigValue | undefined) => { |
import { DecIndent, DecIndentAndCloseBlock, DocumentParts, IncIndent } from '../output/writer'
import { GeneratorContext } from './generator-context'
import * as algokit from '@algorandfoundation/algokit-utils'
import { makeSafeMethodIdentifier } from '../util/sanitization'
import { BARE_CALL, MethodList } from './helpers/get-call-config-summary'
import { getCreateOnCompleteOptions } from './deploy-types'
export function* composeMethod(ctx: GeneratorContext): DocumentParts {
const { name, callConfig } = ctx
yield `public compose(): ${name}Composer {`
yield IncIndent
yield `const client = this`
yield `const atc = new AtomicTransactionComposer()`
yield `let promiseChain:Promise<unknown> = Promise.resolve()`
yield `const resultMappers: Array<undefined | ((x: any) => any)> = []`
yield `return {`
yield IncIndent
yield* callComposerNoops(ctx)
yield* callComposerOperationMethods(ctx, callConfig.updateMethods, 'update', true)
yield* callComposerOperationMethods(ctx, callConfig.deleteMethods, 'delete')
yield* callComposerOperationMethods(ctx, callConfig.optInMethods, 'optIn')
yield* callComposerOperationMethods(ctx, callConfig.closeOutMethods, 'closeOut')
yield* callComposerClearState()
yield `addTransaction(txn: TransactionWithSigner | TransactionToSign | Transaction | Promise<SendTransactionResult>, defaultSender?: SendTransactionFrom) {`
yield IncIndent
yield 'promiseChain = promiseChain.then(async () => atc.addTransaction(await algokit.getTransactionWithSigner(txn, defaultSender ??' +
' client.sender)))'
yield 'return this'
yield DecIndent
yield '},'
yield `async atc() {`
yield IncIndent
yield 'await promiseChain'
yield 'return atc'
yield DecIndent
yield '},'
yield `async execute() {`
yield IncIndent
yield `await promiseChain`
yield `const result = await algokit.sendAtomicTransactionComposer({ atc, sendParams: {} }, client.algod)`
yield `return {`
yield IncIndent
yield `...result,`
yield `returns: result.returns?.map((val, i) => resultMappers[i] !== undefined ? resultMappers[i]!(val.returnValue) : val.returnValue)`
yield DecIndentAndCloseBlock
yield DecIndentAndCloseBlock
yield DecIndent
yield `} as unknown as ${name}Composer`
yield DecIndentAndCloseBlock
}
| function* callComposerNoops({ app, callConfig, methodSignatureToUniqueName }: GeneratorContext): DocumentParts { |
for (const method of app.contract.methods) {
const methodSignature = algokit.getABIMethodSignature(method)
const methodName = makeSafeMethodIdentifier(methodSignatureToUniqueName[methodSignature])
// Skip methods which don't support a no_op call config
if (!callConfig.callMethods.includes(methodSignature)) continue
yield `${methodName}(args: MethodArgs<'${methodSignature}'>, params?: AppClientCallCoreParams & CoreAppCallArgs) {`
yield IncIndent
yield `promiseChain = promiseChain.then(() => client.${methodName}(args, {...params, sendParams: {...params?.sendParams, skipSending: true, atc}}))`
const outputTypeName = app.hints?.[methodSignature]?.structs?.output?.name
yield `resultMappers.push(${outputTypeName ?? 'undefined'})`
yield `return this`
yield DecIndent
yield '},'
}
}
function* callComposerClearState(): DocumentParts {
yield `clearState(args?: BareCallArgs & AppClientCallCoreParams & CoreAppCallArgs) {`
yield IncIndent
yield `promiseChain = promiseChain.then(() => client.clearState({...args, sendParams: {...args?.sendParams, skipSending: true, atc}}))`
yield `resultMappers.push(undefined)`
yield `return this`
yield DecIndent
yield '},'
}
function* callComposerOperationMethods(
{ app, methodSignatureToUniqueName }: GeneratorContext,
methods: MethodList,
verb: 'create' | 'update' | 'optIn' | 'closeOut' | 'delete',
includeCompilation?: boolean,
): DocumentParts {
if (methods.length) {
yield `get ${verb}() {`
yield IncIndent
yield `const $this = this`
yield `return {`
yield IncIndent
for (const methodSig of methods) {
const onComplete = verb === 'create' ? getCreateOnCompleteOptions(methodSig, app) : undefined
if (methodSig === BARE_CALL) {
yield `bare(args${onComplete?.isOptional !== false ? '?' : ''}: BareCallArgs & AppClientCallCoreParams ${
includeCompilation ? '& AppClientCompilationParams ' : ''
}& CoreAppCallArgs${onComplete?.type ? ` & ${onComplete.type}` : ''}) {`
yield IncIndent
yield `promiseChain = promiseChain.then(() => client.${verb}.bare({...args, sendParams: {...args?.sendParams, skipSending: true, atc}}))`
yield `resultMappers.push(undefined)`
yield `return $this`
yield DecIndent
yield '},'
} else {
const uniqueName = methodSignatureToUniqueName[methodSig]
const methodName = makeSafeMethodIdentifier(uniqueName)
yield `${methodName}(args: MethodArgs<'${methodSig}'>, params${
onComplete?.isOptional !== false ? '?' : ''
}: AppClientCallCoreParams${includeCompilation ? ' & AppClientCompilationParams' : ''}${
onComplete?.type ? ` & ${onComplete.type}` : ''
}) {`
yield IncIndent
yield `promiseChain = promiseChain.then(() => client.${verb}.${methodName}(args, {...params, sendParams: {...params?.sendParams, skipSending: true, atc}}))`
const outputTypeName = app.hints?.[methodSig]?.structs?.output?.name
yield `resultMappers.push(${outputTypeName ?? 'undefined'})`
yield `return $this`
yield DecIndent
yield '},'
}
}
yield DecIndentAndCloseBlock
yield DecIndent
yield '},'
}
}
| src/client/call-composer.ts | algorandfoundation-algokit-client-generator-ts-2de43ed | [
{
"filename": "src/client/call-client.ts",
"retrieved_chunk": " yield `const returnValue = result.return?.returnValue !== undefined && returnValueFormatter !== undefined`\n yield IncIndent\n yield `? returnValueFormatter(result.return.returnValue)`\n yield `: result.return?.returnValue as TReturn | undefined`\n yield `return { ...result, return: returnValue }`\n yield DecIndent\n yield DecIndentAndCloseBlock\n yield NewLine\n yield* jsDoc({\n description: 'Calls the ABI method with the matching signature using an onCompletion code of NO_OP',",
"score": 50.8889284767618
},
{
"filename": "src/output/writer.ts",
"retrieved_chunk": " writeDocumentPartsTo(document, options, writer)\n}\nexport function writeDocumentPartsToString(document: DocumentParts, options: WriteOptions = {}) {\n const writer = {\n result: [] as string[],\n _last: '',\n write(val: string) {\n this._last = val\n this.result.push(val)\n },",
"score": 34.0454357275433
},
{
"filename": "src/client/call-client.ts",
"retrieved_chunk": " yield NewLine\n yield* opMethods(ctx)\n yield* clearState(ctx)\n yield* noopMethods(ctx)\n yield* getStateMethods(ctx)\n yield* composeMethod(ctx)\n yield DecIndentAndCloseBlock\n}\nfunction* opMethods(ctx: GeneratorContext): DocumentParts {\n const { app, callConfig, name } = ctx",
"score": 29.604966794874283
},
{
"filename": "src/client/call-client.ts",
"retrieved_chunk": " }\n }\n yield DecIndentAndCloseBlock\n yield DecIndentAndCloseBlock\n yield NewLine\n }\n}\nfunction* clearState({ app }: GeneratorContext): DocumentParts {\n yield* jsDoc({\n description: `Makes a clear_state call to an existing instance of the ${app.contract.name} smart contract.`,",
"score": 28.442950226914412
},
{
"filename": "src/client/call-client.ts",
"retrieved_chunk": " params: {\n args: `The arguments for the bare call`,\n },\n returns: `The clear_state result`,\n })\n yield `public clearState(args: BareCallArgs & AppClientCallCoreParams & CoreAppCallArgs = {}) {`\n yield IncIndent\n yield `return this.appClient.clearState(args)`\n yield DecIndentAndCloseBlock\n yield NewLine",
"score": 28.41541419417329
}
] | typescript | function* callComposerNoops({ app, callConfig, methodSignatureToUniqueName }: GeneratorContext): DocumentParts { |
import * as algokit from '@algorandfoundation/algokit-utils'
import { DecIndent, DecIndentAndCloseBlock, DocumentParts, IncIndent, indent, inline, jsDoc, NewLine } from '../output/writer'
import { makeSafeMethodIdentifier, makeSafeTypeIdentifier } from '../util/sanitization'
import { BARE_CALL, MethodList } from './helpers/get-call-config-summary'
import { GeneratorContext } from './generator-context'
import { getCreateOnCompleteOptions } from './deploy-types'
import { composeMethod } from './call-composer'
export function* callClient(ctx: GeneratorContext): DocumentParts {
const { app, name } = ctx
yield* jsDoc(`A client to make calls to the ${app.contract.name} smart contract`)
yield `export class ${makeSafeTypeIdentifier(app.contract.name)}Client {`
yield IncIndent
yield* jsDoc(`The underlying \`ApplicationClient\` for when you want to have more flexibility`)
yield 'public readonly appClient: ApplicationClient'
yield NewLine
yield `private readonly sender: SendTransactionFrom | undefined`
yield NewLine
yield* jsDoc({
description: `Creates a new instance of \`${makeSafeTypeIdentifier(app.contract.name)}Client\``,
params: {
appDetails: 'appDetails The details to identify the app to deploy',
algod: 'An algod client instance',
},
})
yield `constructor(appDetails: AppDetails, private algod: Algodv2) {`
yield IncIndent
yield `this.sender = appDetails.sender`
yield 'this.appClient = algokit.getAppClient({'
yield* indent('...appDetails,', 'app: APP_SPEC')
yield '}, algod)'
yield DecIndent
yield '}'
yield NewLine
yield* jsDoc({
description: 'Checks for decode errors on the AppCallTransactionResult and maps the return value to the specified generic type',
params: {
result: 'The AppCallTransactionResult to be mapped',
returnValueFormatter: 'An optional delegate to format the return value if required',
},
returns: 'The smart contract response with an updated return value',
})
yield* inline(
`protected mapReturnValue<TReturn>`,
`(result: AppCallTransactionResult, returnValueFormatter?: (value: any) => TReturn): `,
`AppCallTransactionResultOfType<TReturn> {`,
)
yield IncIndent
yield `if(result.return?.decodeError) {`
yield* indent(`throw result.return.decodeError`)
yield `}`
yield `const returnValue = result.return?.returnValue !== undefined && returnValueFormatter !== undefined`
yield IncIndent
yield `? returnValueFormatter(result.return.returnValue)`
yield `: result.return?.returnValue as TReturn | undefined`
yield `return { ...result, return: returnValue }`
yield DecIndent
yield DecIndentAndCloseBlock
yield NewLine
yield* jsDoc({
description: 'Calls the ABI method with the matching signature using an onCompletion code of NO_OP',
params: {
typedCallParams: 'An object containing the method signature, args, and any other relevant parameters',
returnValueFormatter: 'An optional delegate which when provided will be used to map non-undefined return values to the target type',
},
returns: 'The result of the smart contract call',
})
yield `public async call<TSignature extends keyof ${name}['methods']>(typedCallParams: TypedCallParams<TSignature>, returnValueFormatter?: (value: any) => MethodReturn<TSignature>) {`
yield IncIndent
yield `return this.mapReturnValue<MethodReturn<TSignature>>(await this.appClient.call(typedCallParams), returnValueFormatter)`
yield DecIndentAndCloseBlock
yield NewLine
yield* opMethods(ctx)
yield* clearState(ctx)
yield* noopMethods(ctx)
yield* getStateMethods(ctx)
| yield* composeMethod(ctx)
yield DecIndentAndCloseBlock
} |
function* opMethods(ctx: GeneratorContext): DocumentParts {
const { app, callConfig, name } = ctx
yield* jsDoc({
description: `Idempotently deploys the ${app.contract.name} smart contract.`,
params: {
params: 'The arguments for the contract calls and any additional parameters for the call',
},
returns: 'The deployment result',
})
yield `public deploy(params: ${name}DeployArgs & AppClientDeployCoreParams = {}): ReturnType<ApplicationClient['deploy']> {`
yield IncIndent
if (callConfig.createMethods.length) yield `const createArgs = params.createCall?.(${name}CallFactory.create)`
if (callConfig.updateMethods.length) yield `const updateArgs = params.updateCall?.(${name}CallFactory.update)`
if (callConfig.deleteMethods.length) yield `const deleteArgs = params.deleteCall?.(${name}CallFactory.delete)`
yield `return this.appClient.deploy({`
yield IncIndent
yield `...params,`
if (callConfig.updateMethods.length) yield 'updateArgs,'
if (callConfig.deleteMethods.length) yield 'deleteArgs,'
if (callConfig.createMethods.length) {
yield 'createArgs,'
yield `createOnCompleteAction: createArgs?.onCompleteAction,`
}
yield DecIndent
yield `})`
yield DecIndentAndCloseBlock
yield NewLine
yield* operationMethod(ctx, `Creates a new instance of the ${app.contract.name} smart contract`, callConfig.createMethods, 'create', true)
yield* operationMethod(
ctx,
`Updates an existing instance of the ${app.contract.name} smart contract`,
callConfig.updateMethods,
'update',
true,
)
yield* operationMethod(ctx, `Deletes an existing instance of the ${app.contract.name} smart contract`, callConfig.deleteMethods, 'delete')
yield* operationMethod(
ctx,
`Opts the user into an existing instance of the ${app.contract.name} smart contract`,
callConfig.optInMethods,
'optIn',
)
yield* operationMethod(
ctx,
`Makes a close out call to an existing instance of the ${app.contract.name} smart contract`,
callConfig.closeOutMethods,
'closeOut',
)
}
function* operationMethod(
{ app, methodSignatureToUniqueName, name }: GeneratorContext,
description: string,
methods: MethodList,
verb: 'create' | 'update' | 'optIn' | 'closeOut' | 'delete',
includeCompilation?: boolean,
): DocumentParts {
if (methods.length) {
yield* jsDoc(`Gets available ${verb} methods`)
yield `public get ${verb}() {`
yield IncIndent
yield `const $this = this`
yield `return {`
yield IncIndent
for (const methodSig of methods) {
const onComplete = verb === 'create' ? getCreateOnCompleteOptions(methodSig, app) : undefined
if (methodSig === BARE_CALL) {
yield* jsDoc({
description: `${description} using a bare call.`,
params: {
args: `The arguments for the bare call`,
},
returns: `The ${verb} result`,
})
yield `bare(args: BareCallArgs & AppClientCallCoreParams ${
includeCompilation ? '& AppClientCompilationParams ' : ''
}& CoreAppCallArgs${onComplete?.type ? ` & ${onComplete.type}` : ''}${
onComplete?.isOptional !== false ? ' = {}' : ''
}): Promise<AppCallTransactionResultOfType<undefined>> {`
yield* indent(`return $this.appClient.${verb}(args) as unknown as Promise<AppCallTransactionResultOfType<undefined>>`)
yield '},'
} else {
const uniqueName = methodSignatureToUniqueName[methodSig]
const method = app.contract.methods.find((m) => algokit.getABIMethodSignature(m) === methodSig)
yield* jsDoc({
description: `${description} using the ${methodSig} ABI method.`,
params: {
args: `The arguments for the smart contract call`,
params: `Any additional parameters for the call`,
},
returns: `The ${verb} result${method?.returns?.desc ? `: ${method.returns.desc}` : ''}`,
})
yield `async ${makeSafeMethodIdentifier(uniqueName)}(args: MethodArgs<'${methodSig}'>, params: AppClientCallCoreParams${
includeCompilation ? ' & AppClientCompilationParams' : ''
}${onComplete?.type ? ` & ${onComplete.type}` : ''}${
onComplete?.isOptional !== false ? ' = {}' : ''
}): Promise<AppCallTransactionResultOfType<MethodReturn<'${methodSig}'>>> {`
yield* indent(
`return $this.mapReturnValue(await $this.appClient.${verb}(${name}CallFactory.${verb}.${makeSafeMethodIdentifier(
uniqueName,
)}(args, params)))`,
)
yield '},'
}
}
yield DecIndentAndCloseBlock
yield DecIndentAndCloseBlock
yield NewLine
}
}
function* clearState({ app }: GeneratorContext): DocumentParts {
yield* jsDoc({
description: `Makes a clear_state call to an existing instance of the ${app.contract.name} smart contract.`,
params: {
args: `The arguments for the bare call`,
},
returns: `The clear_state result`,
})
yield `public clearState(args: BareCallArgs & AppClientCallCoreParams & CoreAppCallArgs = {}) {`
yield IncIndent
yield `return this.appClient.clearState(args)`
yield DecIndentAndCloseBlock
yield NewLine
}
function* noopMethods({ app, name, callConfig, methodSignatureToUniqueName }: GeneratorContext): DocumentParts {
for (const method of app.contract.methods) {
const methodSignature = algokit.getABIMethodSignature(method)
const methodName = makeSafeMethodIdentifier(methodSignatureToUniqueName[methodSignature])
// Skip methods which don't support a no_op call config
if (!callConfig.callMethods.includes(methodSignature)) continue
yield* jsDoc({
description: `Calls the ${algokit.getABIMethodSignature(method)} ABI method.`,
abiDescription: method.desc,
params: {
args: `The arguments for the contract call`,
params: `Any additional parameters for the call`,
},
returns: `The result of the call${method?.returns?.desc ? `: ${method.returns.desc}` : ''}`,
})
yield `public ${methodName}(args: MethodArgs<'${methodSignature}'>, params: AppClientCallCoreParams & CoreAppCallArgs = {}) {`
yield IncIndent
const outputTypeName = app.hints?.[methodSignature]?.structs?.output?.name
yield `return this.call(${name}CallFactory.${methodName}(args, params)${
outputTypeName === undefined ? '' : `, ${makeSafeTypeIdentifier(outputTypeName)}`
})`
yield DecIndent
yield '}'
yield NewLine
}
}
function* getStateMethods({ app, name }: GeneratorContext): DocumentParts {
const globalStateValues = app.schema.global?.declared && Object.values(app.schema.global?.declared)
const localStateValues = app.schema.local?.declared && Object.values(app.schema.local?.declared)
if (globalStateValues?.length || localStateValues?.length) {
yield* jsDoc({
description: 'Extracts a binary state value out of an AppState dictionary',
params: {
state: 'The state dictionary containing the state value',
key: 'The key of the state value',
},
returns: 'A BinaryState instance containing the state value, or undefined if the key was not found',
})
yield `private static getBinaryState(state: AppState, key: string): BinaryState | undefined {`
yield IncIndent
yield `const value = state[key]`
yield `if (!value) return undefined`
yield `if (!('valueRaw' in value))`
yield* indent(`throw new Error(\`Failed to parse state value for \${key}; received an int when expected a byte array\`)`)
yield `return {`
yield IncIndent
yield `asString(): string {`
yield* indent(`return value.value`)
yield `},`
yield `asByteArray(): Uint8Array {`
yield* indent(`return value.valueRaw`)
yield `}`
yield DecIndentAndCloseBlock
yield DecIndentAndCloseBlock
yield NewLine
yield* jsDoc({
description: 'Extracts a integer state value out of an AppState dictionary',
params: {
state: 'The state dictionary containing the state value',
key: 'The key of the state value',
},
returns: 'An IntegerState instance containing the state value, or undefined if the key was not found',
})
yield `private static getIntegerState(state: AppState, key: string): IntegerState | undefined {`
yield IncIndent
yield `const value = state[key]`
yield `if (!value) return undefined`
yield `if ('valueRaw' in value)`
yield* indent(`throw new Error(\`Failed to parse state value for \${key}; received a byte array when expected a number\`)`)
yield `return {`
yield IncIndent
yield `asBigInt() {`
yield* indent(`return typeof value.value === 'bigint' ? value.value : BigInt(value.value)`)
yield `},`
yield `asNumber(): number {`
yield* indent(`return typeof value.value === 'bigint' ? Number(value.value) : value.value`)
yield `},`
yield DecIndentAndCloseBlock
yield DecIndentAndCloseBlock
yield NewLine
}
if (globalStateValues?.length) {
yield* jsDoc(`Returns the smart contract's global state wrapped in a strongly typed accessor with options to format the stored value`)
yield `public async getGlobalState(): Promise<${name}['state']['global']> {`
yield IncIndent
yield `const state = await this.appClient.getGlobalState()`
yield `return {`
yield IncIndent
for (const stateValue of globalStateValues) {
yield `get ${stateValue.key}() {`
if (stateValue.type === 'uint64') {
yield* indent(`return ${name}Client.getIntegerState(state, '${stateValue.key}')`)
} else {
yield* indent(`return ${name}Client.getBinaryState(state, '${stateValue.key}')`)
}
yield '},'
}
yield DecIndentAndCloseBlock
yield DecIndentAndCloseBlock
yield NewLine
}
if (localStateValues?.length) {
yield* jsDoc({
description: `Returns the smart contract's local state wrapped in a strongly typed accessor with options to format the stored value`,
params: {
account: `The address of the account for which to read local state from`,
},
})
yield `public async getLocalState(account: string | SendTransactionFrom): Promise<${name}['state']['local']> {`
yield IncIndent
yield `const state = await this.appClient.getLocalState(account)`
yield `return {`
yield IncIndent
for (const stateValue of localStateValues) {
yield `get ${stateValue.key}() {`
if (stateValue.type === 'uint64') {
yield* indent(`return ${name}Client.getIntegerState(state, '${stateValue.key}')`)
} else {
yield* indent(`return ${name}Client.getBinaryState(state, '${stateValue.key}')`)
}
yield '},'
}
yield DecIndentAndCloseBlock
yield DecIndentAndCloseBlock
yield NewLine
}
}
| src/client/call-client.ts | algorandfoundation-algokit-client-generator-ts-2de43ed | [
{
"filename": "src/client/call-factory.ts",
"retrieved_chunk": " yield IncIndent\n yield* opMethods(ctx)\n for (const method of ctx.app.contract.methods) {\n yield* callFactoryMethod(ctx, method)\n }\n yield DecIndent\n yield '}'\n}\nfunction* opMethods(ctx: GeneratorContext): DocumentParts {\n const { app, callConfig } = ctx",
"score": 25.79906213045578
},
{
"filename": "src/client/generate.ts",
"retrieved_chunk": " yield NewLine\n yield* utilityTypes()\n yield NewLine\n yield* appTypes(ctx)\n yield* deployTypes(ctx)\n yield NewLine\n // Write a call factory\n yield* callFactory(ctx)\n yield NewLine\n // Write a client",
"score": 22.67783448863696
},
{
"filename": "src/client/call-composer.ts",
"retrieved_chunk": " yield `const client = this`\n yield `const atc = new AtomicTransactionComposer()`\n yield `let promiseChain:Promise<unknown> = Promise.resolve()`\n yield `const resultMappers: Array<undefined | ((x: any) => any)> = []`\n yield `return {`\n yield IncIndent\n yield* callComposerNoops(ctx)\n yield* callComposerOperationMethods(ctx, callConfig.updateMethods, 'update', true)\n yield* callComposerOperationMethods(ctx, callConfig.deleteMethods, 'delete')\n yield* callComposerOperationMethods(ctx, callConfig.optInMethods, 'optIn')",
"score": 20.562158282037412
},
{
"filename": "src/client/call-composer.ts",
"retrieved_chunk": "import { DecIndent, DecIndentAndCloseBlock, DocumentParts, IncIndent } from '../output/writer'\nimport { GeneratorContext } from './generator-context'\nimport * as algokit from '@algorandfoundation/algokit-utils'\nimport { makeSafeMethodIdentifier } from '../util/sanitization'\nimport { BARE_CALL, MethodList } from './helpers/get-call-config-summary'\nimport { getCreateOnCompleteOptions } from './deploy-types'\nexport function* composeMethod(ctx: GeneratorContext): DocumentParts {\n const { name, callConfig } = ctx\n yield `public compose(): ${name}Composer {`\n yield IncIndent",
"score": 18.670171152525572
},
{
"filename": "src/client/generate.ts",
"retrieved_chunk": " yield* callClient(ctx)\n yield* callComposerType(ctx)\n}",
"score": 18.571013507431477
}
] | typescript | yield* composeMethod(ctx)
yield DecIndentAndCloseBlock
} |
import * as algokit from '@algorandfoundation/algokit-utils'
import { DecIndent, DecIndentAndCloseBlock, DocumentParts, IncIndent, indent, inline, jsDoc, NewLine } from '../output/writer'
import { makeSafeMethodIdentifier, makeSafeTypeIdentifier } from '../util/sanitization'
import { BARE_CALL, MethodList } from './helpers/get-call-config-summary'
import { GeneratorContext } from './generator-context'
import { getCreateOnCompleteOptions } from './deploy-types'
import { composeMethod } from './call-composer'
export function* callClient(ctx: GeneratorContext): DocumentParts {
const { app, name } = ctx
yield* jsDoc(`A client to make calls to the ${app.contract.name} smart contract`)
yield `export class ${makeSafeTypeIdentifier(app.contract.name)}Client {`
yield IncIndent
yield* jsDoc(`The underlying \`ApplicationClient\` for when you want to have more flexibility`)
yield 'public readonly appClient: ApplicationClient'
yield NewLine
yield `private readonly sender: SendTransactionFrom | undefined`
yield NewLine
yield* jsDoc({
description: `Creates a new instance of \`${makeSafeTypeIdentifier(app.contract.name)}Client\``,
params: {
appDetails: 'appDetails The details to identify the app to deploy',
algod: 'An algod client instance',
},
})
yield `constructor(appDetails: AppDetails, private algod: Algodv2) {`
yield IncIndent
yield `this.sender = appDetails.sender`
yield 'this.appClient = algokit.getAppClient({'
yield* indent('...appDetails,', 'app: APP_SPEC')
yield '}, algod)'
yield DecIndent
yield '}'
yield NewLine
yield* jsDoc({
description: 'Checks for decode errors on the AppCallTransactionResult and maps the return value to the specified generic type',
params: {
result: 'The AppCallTransactionResult to be mapped',
returnValueFormatter: 'An optional delegate to format the return value if required',
},
returns: 'The smart contract response with an updated return value',
})
yield* inline(
`protected mapReturnValue<TReturn>`,
`(result: AppCallTransactionResult, returnValueFormatter?: (value: any) => TReturn): `,
`AppCallTransactionResultOfType<TReturn> {`,
)
yield IncIndent
yield `if(result.return?.decodeError) {`
yield* indent(`throw result.return.decodeError`)
yield `}`
yield `const returnValue = result.return?.returnValue !== undefined && returnValueFormatter !== undefined`
yield IncIndent
yield `? returnValueFormatter(result.return.returnValue)`
yield `: result.return?.returnValue as TReturn | undefined`
yield `return { ...result, return: returnValue }`
yield DecIndent
yield DecIndentAndCloseBlock
yield NewLine
yield* jsDoc({
description: 'Calls the ABI method with the matching signature using an onCompletion code of NO_OP',
params: {
typedCallParams: 'An object containing the method signature, args, and any other relevant parameters',
returnValueFormatter: 'An optional delegate which when provided will be used to map non-undefined return values to the target type',
},
returns: 'The result of the smart contract call',
})
yield `public async call<TSignature extends keyof ${name}['methods']>(typedCallParams: TypedCallParams<TSignature>, returnValueFormatter?: (value: any) => MethodReturn<TSignature>) {`
yield IncIndent
yield `return this.mapReturnValue<MethodReturn<TSignature>>(await this.appClient.call(typedCallParams), returnValueFormatter)`
yield DecIndentAndCloseBlock
yield NewLine
yield* opMethods(ctx)
yield* clearState(ctx)
yield* noopMethods(ctx)
yield* getStateMethods(ctx)
yield* composeMethod(ctx)
yield DecIndentAndCloseBlock
}
function* opMethods(ctx: GeneratorContext): DocumentParts {
const { app, callConfig, name } = ctx
yield* jsDoc({
description: `Idempotently deploys the ${app.contract.name} smart contract.`,
params: {
params: 'The arguments for the contract calls and any additional parameters for the call',
},
returns: 'The deployment result',
})
yield `public deploy(params: ${name}DeployArgs & AppClientDeployCoreParams = {}): ReturnType<ApplicationClient['deploy']> {`
yield IncIndent
if (callConfig.createMethods.length) yield `const createArgs = params.createCall?.(${name}CallFactory.create)`
if (callConfig.updateMethods.length) yield `const updateArgs = params.updateCall?.(${name}CallFactory.update)`
if (callConfig.deleteMethods.length) yield `const deleteArgs = params.deleteCall?.(${name}CallFactory.delete)`
yield `return this.appClient.deploy({`
yield IncIndent
yield `...params,`
if (callConfig.updateMethods.length) yield 'updateArgs,'
if (callConfig.deleteMethods.length) yield 'deleteArgs,'
if (callConfig.createMethods.length) {
yield 'createArgs,'
yield `createOnCompleteAction: createArgs?.onCompleteAction,`
}
yield DecIndent
yield `})`
yield DecIndentAndCloseBlock
yield NewLine
yield* operationMethod(ctx, `Creates a new instance of the ${app.contract.name} smart contract`, callConfig.createMethods, 'create', true)
yield* operationMethod(
ctx,
`Updates an existing instance of the ${app.contract.name} smart contract`,
callConfig.updateMethods,
'update',
true,
)
yield* operationMethod(ctx, `Deletes an existing instance of the ${app.contract.name} smart contract`, callConfig.deleteMethods, 'delete')
yield* operationMethod(
ctx,
`Opts the user into an existing instance of the ${app.contract.name} smart contract`,
callConfig.optInMethods,
'optIn',
)
yield* operationMethod(
ctx,
`Makes a close out call to an existing instance of the ${app.contract.name} smart contract`,
callConfig.closeOutMethods,
'closeOut',
)
}
function* operationMethod(
{ app, methodSignatureToUniqueName, name }: GeneratorContext,
description: string,
methods: MethodList,
verb: 'create' | 'update' | 'optIn' | 'closeOut' | 'delete',
includeCompilation?: boolean,
): DocumentParts {
if (methods.length) {
yield* jsDoc(`Gets available ${verb} methods`)
yield `public get ${verb}() {`
yield IncIndent
yield `const $this = this`
yield `return {`
yield IncIndent
for (const methodSig of methods) {
const onComplete = verb === 'create' ? getCreateOnCompleteOptions(methodSig, app) : undefined
if (methodSig === BARE_CALL) {
yield* jsDoc({
description: `${description} using a bare call.`,
params: {
args: `The arguments for the bare call`,
},
returns: `The ${verb} result`,
})
yield `bare(args: BareCallArgs & AppClientCallCoreParams ${
includeCompilation ? '& AppClientCompilationParams ' : ''
}& CoreAppCallArgs${onComplete?.type ? ` & ${onComplete.type}` : ''}${
onComplete?.isOptional !== false ? ' = {}' : ''
}): Promise<AppCallTransactionResultOfType<undefined>> {`
yield* indent(`return $this.appClient.${verb}(args) as unknown as Promise<AppCallTransactionResultOfType<undefined>>`)
yield '},'
} else {
const uniqueName = methodSignatureToUniqueName[methodSig]
const method = app.contract.methods.find((m) => algokit.getABIMethodSignature(m) === methodSig)
yield* jsDoc({
description: `${description} using the ${methodSig} ABI method.`,
params: {
args: `The arguments for the smart contract call`,
params: `Any additional parameters for the call`,
},
returns: `The ${verb} result${method?.returns?.desc ? `: ${method.returns.desc}` : ''}`,
})
yield ` | async ${makeSafeMethodIdentifier(uniqueName)}(args: MethodArgs<'${methodSig}'>, params: AppClientCallCoreParams${ |
includeCompilation ? ' & AppClientCompilationParams' : ''
}${onComplete?.type ? ` & ${onComplete.type}` : ''}${
onComplete?.isOptional !== false ? ' = {}' : ''
}): Promise<AppCallTransactionResultOfType<MethodReturn<'${methodSig}'>>> {`
yield* indent(
`return $this.mapReturnValue(await $this.appClient.${verb}(${name}CallFactory.${verb}.${makeSafeMethodIdentifier(
uniqueName,
)}(args, params)))`,
)
yield '},'
}
}
yield DecIndentAndCloseBlock
yield DecIndentAndCloseBlock
yield NewLine
}
}
function* clearState({ app }: GeneratorContext): DocumentParts {
yield* jsDoc({
description: `Makes a clear_state call to an existing instance of the ${app.contract.name} smart contract.`,
params: {
args: `The arguments for the bare call`,
},
returns: `The clear_state result`,
})
yield `public clearState(args: BareCallArgs & AppClientCallCoreParams & CoreAppCallArgs = {}) {`
yield IncIndent
yield `return this.appClient.clearState(args)`
yield DecIndentAndCloseBlock
yield NewLine
}
function* noopMethods({ app, name, callConfig, methodSignatureToUniqueName }: GeneratorContext): DocumentParts {
for (const method of app.contract.methods) {
const methodSignature = algokit.getABIMethodSignature(method)
const methodName = makeSafeMethodIdentifier(methodSignatureToUniqueName[methodSignature])
// Skip methods which don't support a no_op call config
if (!callConfig.callMethods.includes(methodSignature)) continue
yield* jsDoc({
description: `Calls the ${algokit.getABIMethodSignature(method)} ABI method.`,
abiDescription: method.desc,
params: {
args: `The arguments for the contract call`,
params: `Any additional parameters for the call`,
},
returns: `The result of the call${method?.returns?.desc ? `: ${method.returns.desc}` : ''}`,
})
yield `public ${methodName}(args: MethodArgs<'${methodSignature}'>, params: AppClientCallCoreParams & CoreAppCallArgs = {}) {`
yield IncIndent
const outputTypeName = app.hints?.[methodSignature]?.structs?.output?.name
yield `return this.call(${name}CallFactory.${methodName}(args, params)${
outputTypeName === undefined ? '' : `, ${makeSafeTypeIdentifier(outputTypeName)}`
})`
yield DecIndent
yield '}'
yield NewLine
}
}
function* getStateMethods({ app, name }: GeneratorContext): DocumentParts {
const globalStateValues = app.schema.global?.declared && Object.values(app.schema.global?.declared)
const localStateValues = app.schema.local?.declared && Object.values(app.schema.local?.declared)
if (globalStateValues?.length || localStateValues?.length) {
yield* jsDoc({
description: 'Extracts a binary state value out of an AppState dictionary',
params: {
state: 'The state dictionary containing the state value',
key: 'The key of the state value',
},
returns: 'A BinaryState instance containing the state value, or undefined if the key was not found',
})
yield `private static getBinaryState(state: AppState, key: string): BinaryState | undefined {`
yield IncIndent
yield `const value = state[key]`
yield `if (!value) return undefined`
yield `if (!('valueRaw' in value))`
yield* indent(`throw new Error(\`Failed to parse state value for \${key}; received an int when expected a byte array\`)`)
yield `return {`
yield IncIndent
yield `asString(): string {`
yield* indent(`return value.value`)
yield `},`
yield `asByteArray(): Uint8Array {`
yield* indent(`return value.valueRaw`)
yield `}`
yield DecIndentAndCloseBlock
yield DecIndentAndCloseBlock
yield NewLine
yield* jsDoc({
description: 'Extracts a integer state value out of an AppState dictionary',
params: {
state: 'The state dictionary containing the state value',
key: 'The key of the state value',
},
returns: 'An IntegerState instance containing the state value, or undefined if the key was not found',
})
yield `private static getIntegerState(state: AppState, key: string): IntegerState | undefined {`
yield IncIndent
yield `const value = state[key]`
yield `if (!value) return undefined`
yield `if ('valueRaw' in value)`
yield* indent(`throw new Error(\`Failed to parse state value for \${key}; received a byte array when expected a number\`)`)
yield `return {`
yield IncIndent
yield `asBigInt() {`
yield* indent(`return typeof value.value === 'bigint' ? value.value : BigInt(value.value)`)
yield `},`
yield `asNumber(): number {`
yield* indent(`return typeof value.value === 'bigint' ? Number(value.value) : value.value`)
yield `},`
yield DecIndentAndCloseBlock
yield DecIndentAndCloseBlock
yield NewLine
}
if (globalStateValues?.length) {
yield* jsDoc(`Returns the smart contract's global state wrapped in a strongly typed accessor with options to format the stored value`)
yield `public async getGlobalState(): Promise<${name}['state']['global']> {`
yield IncIndent
yield `const state = await this.appClient.getGlobalState()`
yield `return {`
yield IncIndent
for (const stateValue of globalStateValues) {
yield `get ${stateValue.key}() {`
if (stateValue.type === 'uint64') {
yield* indent(`return ${name}Client.getIntegerState(state, '${stateValue.key}')`)
} else {
yield* indent(`return ${name}Client.getBinaryState(state, '${stateValue.key}')`)
}
yield '},'
}
yield DecIndentAndCloseBlock
yield DecIndentAndCloseBlock
yield NewLine
}
if (localStateValues?.length) {
yield* jsDoc({
description: `Returns the smart contract's local state wrapped in a strongly typed accessor with options to format the stored value`,
params: {
account: `The address of the account for which to read local state from`,
},
})
yield `public async getLocalState(account: string | SendTransactionFrom): Promise<${name}['state']['local']> {`
yield IncIndent
yield `const state = await this.appClient.getLocalState(account)`
yield `return {`
yield IncIndent
for (const stateValue of localStateValues) {
yield `get ${stateValue.key}() {`
if (stateValue.type === 'uint64') {
yield* indent(`return ${name}Client.getIntegerState(state, '${stateValue.key}')`)
} else {
yield* indent(`return ${name}Client.getBinaryState(state, '${stateValue.key}')`)
}
yield '},'
}
yield DecIndentAndCloseBlock
yield DecIndentAndCloseBlock
yield NewLine
}
}
| src/client/call-client.ts | algorandfoundation-algokit-client-generator-ts-2de43ed | [
{
"filename": "src/client/call-composer-types.ts",
"retrieved_chunk": " yield* jsDoc({\n description: `${description} using the ${methodSig} ABI method.`,\n params: {\n args: `The arguments for the smart contract call`,\n params: `Any additional parameters for the call`,\n },\n returns: `The typed transaction composer so you can fluently chain multiple calls or call execute to execute all queued up transactions`,\n })\n yield `${makeSafeMethodIdentifier(uniqueName)}(args: MethodArgs<'${methodSig}'>, params${\n onComplete?.isOptional !== false ? '?' : ''",
"score": 70.86859206511491
},
{
"filename": "src/client/call-composer-types.ts",
"retrieved_chunk": " if (!callConfig.callMethods.includes(methodSignature)) continue\n yield* jsDoc({\n description: `Calls the ${algokit.getABIMethodSignature(method)} ABI method.`,\n abiDescription: method.desc,\n params: {\n args: `The arguments for the contract call`,\n params: `Any additional parameters for the call`,\n },\n returns: `The typed transaction composer so you can fluently chain multiple calls or call execute to execute all queued up transactions`,\n })",
"score": 57.43495690444499
},
{
"filename": "src/client/call-factory.ts",
"retrieved_chunk": " params: `Any additional parameters for the call`,\n },\n returns: `A TypedCallParams object for the call`,\n })\n yield* factoryMethod({\n isNested: true,\n name: makeSafeMethodIdentifier(uniqueName),\n signature: methodSig,\n args: method.args,\n paramTypes: `AppClientCallCoreParams & CoreAppCallArgs${includeCompilation ? ' & AppClientCompilationParams' : ''}${",
"score": 54.96842048484193
},
{
"filename": "src/client/call-factory.ts",
"retrieved_chunk": "function* callFactoryMethod({ methodSignatureToUniqueName, callConfig }: GeneratorContext, method: ContractMethod) {\n const methodSignature = algokit.getABIMethodSignature(method)\n if (!callConfig.callMethods.includes(methodSignature)) return\n yield* jsDoc({\n description: `Constructs a no op call for the ${methodSignature} ABI method`,\n abiDescription: method.desc,\n params: {\n args: `Any args for the contract call`,\n params: `Any additional parameters for the call`,\n },",
"score": 51.15840091976782
},
{
"filename": "src/client/call-factory.ts",
"retrieved_chunk": " includeCompilation ? ' & AppClientCompilationParams' : ''\n }${onComplete?.type ? ` & ${onComplete.type}` : ''}${onComplete?.isOptional !== false ? ' = {}' : ''}`,\n })\n } else {\n const method = app.contract.methods.find((m) => algokit.getABIMethodSignature(m) === methodSig)!\n const uniqueName = methodSignatureToUniqueName[methodSig]\n yield* jsDoc({\n description: `${description} using the ${methodSig} ABI method`,\n params: {\n args: `Any args for the contract call`,",
"score": 49.61215821691211
}
] | typescript | async ${makeSafeMethodIdentifier(uniqueName)}(args: MethodArgs<'${methodSig}'>, params: AppClientCallCoreParams${ |
import { Request, Response, Router } from "express";
const router = Router();
import routes from "./routes";
import { rateLimit } from "express-rate-limit";
const resetPasswordLimiter = rateLimit({
windowMs: 60 * 60, // 1 hour
max: 5, // 5 requests
standardHeaders: true,
legacyHeaders: false,
message: {
"message": "Too many requests, try again later.",
"code": "RATE_LIMITED"
}
})
router.get("/", async (req: Request, res: Response) => {
routes.index(req, res);
})
router.get("/account", async (req: Request, res: Response) => {
routes.account.index(req, res);
})
router.get("/account/change-password", async (req: Request, res: Response) => {
routes.account["change-password"](req, res);
})
router.get("/account/reset-password", async (req: Request, res: Response) => {
routes.account["reset-password"](req, res);
})
router.post("/api/auth/forgot-password", async (req: Request, res: Response) => {
routes.api.auth["forgot-password"](req, res);
})
router.post("/api/auth/login", async (req: Request, res: Response) => {
routes.api.auth.login(req, res);
})
router.delete("/api/posts", async (req: Request, res: Response) => {
routes.api.posts(req, res);
})
router.get("/api/posts", async (req: Request, res: Response) => {
routes.api.posts(req, res);
})
router.patch("/api/posts", async (req: Request, res: Response) => {
routes.api.posts(req, res);
})
router.put("/api/posts", async (req: Request, res: Response) => {
routes.api.posts(req, res);
})
router.patch("/api/user/password", async (req: Request, res: Response) => {
routes.api.user.password(req, res);
})
router.put("/api/user/password", resetPasswordLimiter, async (req: Request, res: Response) => {
routes.api.user.password(req, res);
})
router.get("/api/users", async (req: Request, res: Response) => {
routes.api.users(req, res);
})
router.get("/auth/forgot-password", async (req: Request, res: Response) => {
routes.auth["forgot-password"](req, res);
})
router.get("/auth/login", async (req: Request, res: Response) => {
routes.auth.login(req, res);
})
router.get("/auth/logout", async (req: Request, res: Response) => {
routes.auth.logout(req, res);
})
router.get("/author/:username", async (req: Request, res: Response) => {
| routes.author(req, res); |
})
router.get("/authors", async (req: Request, res: Response) => {
routes.authors(req, res);
})
router.get("/dashboard", async (req: Request, res: Response) => {
routes.dashboard(req, res);
})
router.get("/post/create", async (req: Request, res: Response) => {
routes.post.create(req, res);
})
router.get("/post/delete/:id", async (req: Request, res: Response) => {
routes.post.delete(req, res);
})
router.get("/post/edit/:id", async (req: Request, res: Response) => {
routes.post.edit(req, res);
})
router.get("/post/:id", async (req: Request, res: Response) => {
routes.post.index(req, res);
})
router.get("*", async (req: Request, res: Response) => {
routes[404](req, res);
})
export default router;
| src/util/router.ts | wdhdev-blog-171008f | [
{
"filename": "src/util/routes.ts",
"retrieved_chunk": " password: require(\"../endpoints/api/user/password\")\n },\n users: apiUsers\n },\n auth: {\n \"forgot-password\": require(\"../endpoints/auth/forgot-password\"),\n login: require(\"../endpoints/auth/login\"),\n logout: require(\"../endpoints/auth/logout\")\n },\n author: author,",
"score": 34.69853881016332
},
{
"filename": "src/endpoints/dashboard.ts",
"retrieved_chunk": "import { Request, Response } from \"express\";\nimport gravatar from \"gravatar-url\";\nimport Post from \"../models/Post\";\nexport default async (req: Request & any, res: Response) => {\n if(!req.session.loggedIn) return res.status(401).redirect(\"/auth/login\");\n res.status(200).render(\"dashboard\", {\n avatar: gravatar(req.session.email),\n firstName: req.session.firstName,\n username: req.session.username,\n posts: (await Post.find({ author: req.session.username })).reverse()",
"score": 23.98324853737359
},
{
"filename": "src/util/routes.ts",
"retrieved_chunk": " index: require(\"../endpoints/account\"),\n \"reset-password\": require(\"../endpoints/account/reset-password\")\n },\n api: {\n auth: {\n \"forgot-password\": require(\"../endpoints/api/auth/forgot-password\"),\n login: require(\"../endpoints/api/auth/login\")\n },\n posts: require(\"../endpoints/api/posts\"),\n user: {",
"score": 22.892043462309434
},
{
"filename": "src/endpoints/author.ts",
"retrieved_chunk": "import { Request, Response } from \"express\";\nimport gravatar from \"gravatar-url\";\nimport moment from \"moment\";\nimport Post from \"../models/Post\";\nimport User from \"../models/User\";\nexport default async (req: Request, res: Response) => {\n if(!await User.findOne({ username: req.params.username })) return res.status(404).render(\"errors/404\");\n const user = await User.findOne({ username: req.params.username });\n res.status(200).render(\"author\", {\n author: {",
"score": 15.494086495051546
},
{
"filename": "src/endpoints/404.ts",
"retrieved_chunk": "import { Request, Response } from \"express\";\nexport default async (req: Request, res: Response) => {\n res.status(404).render(\"errors/404\");\n}",
"score": 15.11094683900077
}
] | typescript | routes.author(req, res); |
import { HTMLElement, parse } from "node-html-parser"
import { addSegment } from "../segments"
import { parseTimestamp, TimestampFormatter } from "../timestamp"
import { Segment } from "../types"
/**
* Regular expression to detect `<html>` tag
*/
const PATTERN_HTML_TAG = /^< *html.*?>/i
/**
* Regular expression to detect transcript data where `<time>` is followed by `<p>`
*/
const PATTERN_HTML_TIME_P = /(?<time><time>\d[\d:.,]*?<\/time>)[ \t\r\n]*?(?<body><p>.*?<\/p>)/i
/**
* Regular expression to detect transcript data where `<p>` is followed by `<time>`
*/
const PATTERN_HTML_P_TIME = /(?<body><p>.*?<\/p>)[ \t\r\n]*?(?<time><time>\d[\d:.,]*?<\/time>)/i
type HTMLSegmentPart = {
cite: string
time: string
text: string
}
/**
* Determines if the value of data is a valid HTML transcript format
*
* @param data The transcript data
* @returns True: data is valid HTML transcript format
*/
export const isHTML = (data: string): boolean => {
return (
data.startsWith("<!--") ||
PATTERN_HTML_TAG.test(data) ||
PATTERN_HTML_TIME_P.test(data) ||
PATTERN_HTML_P_TIME.test(data)
)
}
/**
* Updates HTML Segment parts if expected HTML segment
*
* @param element HTML segment to check
* @param segmentPart Current segment parts
* @returns Updated HTML Segment part and segment data for next segment (if fields encountered)
*/
const updateSegmentPartFromElement = (
element: HTMLElement,
segmentPart: HTMLSegmentPart
): {
current: HTMLSegmentPart
next: HTMLSegmentPart
} => {
const currentSegmentPart = segmentPart
const nextSegmentPart: HTMLSegmentPart = {
cite: "",
time: "",
text: "",
}
if (element.tagName === "CITE") {
if (currentSegmentPart.cite === "") {
currentSegmentPart.cite = element.innerHTML
} else {
nextSegmentPart.cite = element.innerHTML
}
} else if (element.tagName === "TIME") {
if (currentSegmentPart.time === "") {
currentSegmentPart.time = element.innerHTML
} else {
nextSegmentPart.time = element.innerHTML
}
} else if (element.tagName === "P") {
if (currentSegmentPart.text === "") {
currentSegmentPart.text = element.innerHTML
} else {
nextSegmentPart.text = element.innerHTML
}
}
return { current: currentSegmentPart, next: nextSegmentPart }
}
/**
* Create Segment from HTML segment parts
*
* @param segmentPart HTML segment data
* @param lastSpeaker Name of last speaker. Will be used if no speaker found in `segmentLines`
* @returns Created segment
*/
const createSegmentFromSegmentPart = (segmentPart: HTMLSegmentPart, lastSpeaker: string): Segment => {
const calculatedSpeaker = segmentPart.cite ? segmentPart.cite : lastSpeaker
| const startTime = parseTimestamp(segmentPart.time)
return { |
startTime,
startTimeFormatted: TimestampFormatter.format(startTime),
endTime: 0,
endTimeFormatted: TimestampFormatter.format(0),
speaker: calculatedSpeaker.replace(":", "").trimEnd(),
body: segmentPart.text,
}
}
/**
* Parse HTML data and create {@link Segment} for each segment data found in data
*
* @param elements HTML elements containing transcript data
* @returns Segments created from HTML data
*/
const getSegmentsFromHTMLElements = (elements: Array<HTMLElement>): Array<Segment> => {
let outSegments: Array<Segment> = []
let lastSpeaker = ""
let segmentPart: HTMLSegmentPart = {
cite: "",
time: "",
text: "",
}
let nextSegmentPart: HTMLSegmentPart = {
cite: "",
time: "",
text: "",
}
elements.forEach((element, count) => {
const segmentParts = updateSegmentPartFromElement(element, segmentPart)
segmentPart = segmentParts.current
nextSegmentPart = segmentParts.next
if (
count === elements.length - 1 ||
Object.keys(nextSegmentPart).filter((x) => nextSegmentPart[x] === "").length !== 3
) {
// time is required
if (segmentPart.time === "") {
console.warn(`Segment ${count} does not contain time information, ignoring`)
} else {
const segment = createSegmentFromSegmentPart(segmentPart, lastSpeaker)
lastSpeaker = segment.speaker
// update endTime of previous Segment
const totalSegments = outSegments.length
if (totalSegments > 0) {
outSegments[totalSegments - 1].endTime = segment.startTime
outSegments[totalSegments - 1].endTimeFormatted = TimestampFormatter.format(
outSegments[totalSegments - 1].endTime
)
}
outSegments = addSegment(segment, outSegments)
}
// clear
segmentPart = nextSegmentPart
nextSegmentPart = {
cite: "",
time: "",
text: "",
}
}
})
return outSegments
}
/**
* Parse HTML data to an Array of {@link Segment}
*
* @param data The transcript data
* @returns An array of Segments from the parsed data
* @throws {TypeError} When `data` is not valid HTML format
*/
export const parseHTML = (data: string): Array<Segment> => {
const dataTrimmed = data.trim()
if (!isHTML(dataTrimmed)) {
throw new TypeError(`Data is not valid HTML format`)
}
const html = parse(data)
let root: HTMLElement
const htmlElements = html.getElementsByTagName("html")
if (htmlElements.length === 0) {
root = html
} else {
const htmlElement = htmlElements[0]
const bodyElements = htmlElement.getElementsByTagName("body")
if (bodyElements.length > 0) {
// eslint-disable-next-line prefer-destructuring
root = bodyElements[0]
} else {
root = htmlElement
}
}
return getSegmentsFromHTMLElements(root.childNodes as Array<HTMLElement>)
}
| src/formats/html.ts | stevencrader-transcriptator-75faa70 | [
{
"filename": "src/formats/srt.ts",
"retrieved_chunk": "}\n/**\n * Create Segment from lines containing an SRT segment/cue\n *\n * @param segmentLines Lines containing SRT data\n * @param lastSpeaker Name of last speaker. Will be used if no speaker found in `segmentLines`\n * @returns Created segment\n */\nconst createSegmentFromSRTLines = (segmentLines: Array<string>, lastSpeaker: string): Segment => {\n const srtSegment = parseSRTSegment(segmentLines)",
"score": 49.02247594864464
},
{
"filename": "src/formats/srt.ts",
"retrieved_chunk": " const calculatedSpeaker = srtSegment.speaker ? srtSegment.speaker : lastSpeaker\n return {\n startTime: srtSegment.startTime,\n startTimeFormatted: TimestampFormatter.format(srtSegment.startTime),\n endTime: srtSegment.endTime,\n endTimeFormatted: TimestampFormatter.format(srtSegment.endTime),\n speaker: calculatedSpeaker,\n body: srtSegment.body,\n }\n}",
"score": 17.821030903286694
},
{
"filename": "src/segments.ts",
"retrieved_chunk": " *\n * @param newSegment segment before any rules options to it\n * @param priorSegment prior parsed segment\n * @param lastSpeaker last speaker name.\n * Used when speaker in segment has been removed via {@link Options.speakerChange} rule\n * @returns the updated segment info\n */\nconst doCombineWithPrior = (newSegment: Segment, priorSegment: Segment, lastSpeaker: string): CombineResult => {\n const {\n combineEqualTimes,",
"score": 17.806485782996806
},
{
"filename": "src/segments.ts",
"retrieved_chunk": " *\n * @param newSegment segment before any rules options to it\n * @param lastSpeaker last speaker name.\n * Used when speaker in segment has been removed via {@link Options.speakerChange} rule\n * @returns the updated segment info\n */\nconst doCombineNoPrior = (newSegment: Segment, lastSpeaker: string): CombineResult => {\n const { speakerChange } = Options\n let result: CombineResult = {\n segment: newSegment,",
"score": 16.761740749600172
},
{
"filename": "src/segments.ts",
"retrieved_chunk": " * Apply any options to the current segment\n *\n * @param newSegment segment before any rules options to it\n * @param priorSegment prior parsed segment. For the first segment, this shall be undefined.\n * @param lastSpeaker last speaker name.\n * Used when speaker in segment has been removed via {@link Options.speakerChange} rule\n * @returns the updated segment info\n */\nconst applyOptions = (newSegment: Segment, priorSegment: Segment, lastSpeaker: string = undefined): CombineResult => {\n if (!Options.optionsSet()) {",
"score": 16.68518524406809
}
] | typescript | const startTime = parseTimestamp(segmentPart.time)
return { |
import { HTMLElement, parse } from "node-html-parser"
import { addSegment } from "../segments"
import { parseTimestamp, TimestampFormatter } from "../timestamp"
import { Segment } from "../types"
/**
* Regular expression to detect `<html>` tag
*/
const PATTERN_HTML_TAG = /^< *html.*?>/i
/**
* Regular expression to detect transcript data where `<time>` is followed by `<p>`
*/
const PATTERN_HTML_TIME_P = /(?<time><time>\d[\d:.,]*?<\/time>)[ \t\r\n]*?(?<body><p>.*?<\/p>)/i
/**
* Regular expression to detect transcript data where `<p>` is followed by `<time>`
*/
const PATTERN_HTML_P_TIME = /(?<body><p>.*?<\/p>)[ \t\r\n]*?(?<time><time>\d[\d:.,]*?<\/time>)/i
type HTMLSegmentPart = {
cite: string
time: string
text: string
}
/**
* Determines if the value of data is a valid HTML transcript format
*
* @param data The transcript data
* @returns True: data is valid HTML transcript format
*/
export const isHTML = (data: string): boolean => {
return (
data.startsWith("<!--") ||
PATTERN_HTML_TAG.test(data) ||
PATTERN_HTML_TIME_P.test(data) ||
PATTERN_HTML_P_TIME.test(data)
)
}
/**
* Updates HTML Segment parts if expected HTML segment
*
* @param element HTML segment to check
* @param segmentPart Current segment parts
* @returns Updated HTML Segment part and segment data for next segment (if fields encountered)
*/
const updateSegmentPartFromElement = (
element: HTMLElement,
segmentPart: HTMLSegmentPart
): {
current: HTMLSegmentPart
next: HTMLSegmentPart
} => {
const currentSegmentPart = segmentPart
const nextSegmentPart: HTMLSegmentPart = {
cite: "",
time: "",
text: "",
}
if (element.tagName === "CITE") {
if (currentSegmentPart.cite === "") {
currentSegmentPart.cite = element.innerHTML
} else {
nextSegmentPart.cite = element.innerHTML
}
} else if (element.tagName === "TIME") {
if (currentSegmentPart.time === "") {
currentSegmentPart.time = element.innerHTML
} else {
nextSegmentPart.time = element.innerHTML
}
} else if (element.tagName === "P") {
if (currentSegmentPart.text === "") {
currentSegmentPart.text = element.innerHTML
} else {
nextSegmentPart.text = element.innerHTML
}
}
return { current: currentSegmentPart, next: nextSegmentPart }
}
/**
* Create Segment from HTML segment parts
*
* @param segmentPart HTML segment data
* @param lastSpeaker Name of last speaker. Will be used if no speaker found in `segmentLines`
* @returns Created segment
*/
const createSegmentFromSegmentPart = (segmentPart: HTMLSegmentPart, lastSpeaker: string): Segment => {
const calculatedSpeaker = segmentPart.cite ? segmentPart.cite : lastSpeaker
const startTime = parseTimestamp(segmentPart.time)
return {
startTime,
startTimeFormatted: TimestampFormatter.format(startTime),
endTime: 0,
endTimeFormatted: TimestampFormatter.format(0),
speaker: calculatedSpeaker.replace(":", "").trimEnd(),
body: segmentPart.text,
}
}
/**
* Parse HTML data and create {@link Segment} for each segment data found in data
*
* @param elements HTML elements containing transcript data
* @returns Segments created from HTML data
*/
const getSegmentsFromHTMLElements = (elements: Array<HTMLElement>): Array<Segment> => {
let outSegments: Array<Segment> = []
let lastSpeaker = ""
let segmentPart: HTMLSegmentPart = {
cite: "",
time: "",
text: "",
}
let nextSegmentPart: HTMLSegmentPart = {
cite: "",
time: "",
text: "",
}
elements.forEach((element, count) => {
const segmentParts = updateSegmentPartFromElement(element, segmentPart)
segmentPart = segmentParts.current
nextSegmentPart = segmentParts.next
if (
count === elements.length - 1 ||
Object.keys(nextSegmentPart).filter((x) => nextSegmentPart[x] === "").length !== 3
) {
// time is required
if (segmentPart.time === "") {
console.warn(`Segment ${count} does not contain time information, ignoring`)
} else {
const segment = createSegmentFromSegmentPart(segmentPart, lastSpeaker)
lastSpeaker = segment.speaker
// update endTime of previous Segment
const totalSegments = outSegments.length
if (totalSegments > 0) {
outSegments[totalSegments - 1].endTime = segment.startTime
outSegments[totalSegments - 1].endTimeFormatted = TimestampFormatter.format(
outSegments[totalSegments - 1].endTime
)
}
| outSegments = addSegment(segment, outSegments)
} |
// clear
segmentPart = nextSegmentPart
nextSegmentPart = {
cite: "",
time: "",
text: "",
}
}
})
return outSegments
}
/**
* Parse HTML data to an Array of {@link Segment}
*
* @param data The transcript data
* @returns An array of Segments from the parsed data
* @throws {TypeError} When `data` is not valid HTML format
*/
export const parseHTML = (data: string): Array<Segment> => {
const dataTrimmed = data.trim()
if (!isHTML(dataTrimmed)) {
throw new TypeError(`Data is not valid HTML format`)
}
const html = parse(data)
let root: HTMLElement
const htmlElements = html.getElementsByTagName("html")
if (htmlElements.length === 0) {
root = html
} else {
const htmlElement = htmlElements[0]
const bodyElements = htmlElement.getElementsByTagName("body")
if (bodyElements.length > 0) {
// eslint-disable-next-line prefer-destructuring
root = bodyElements[0]
} else {
root = htmlElement
}
}
return getSegmentsFromHTMLElements(root.childNodes as Array<HTMLElement>)
}
| src/formats/html.ts | stevencrader-transcriptator-75faa70 | [
{
"filename": "src/formats/json.ts",
"retrieved_chunk": "const parseDictSegmentsJSON = (data: JSONTranscript): Array<Segment> => {\n let outSegments: Array<Segment> = []\n data.segments.forEach((segment) => {\n outSegments = addSegment(\n {\n startTime: segment.startTime,\n startTimeFormatted: TimestampFormatter.format(segment.startTime),\n endTime: segment.endTime,\n endTimeFormatted: TimestampFormatter.format(segment.endTime),\n speaker: segment.speaker,",
"score": 40.79948138881606
},
{
"filename": "src/formats/srt.ts",
"retrieved_chunk": " segmentLines = [] // clear buffer\n } else {\n segmentLines.push(line)\n }\n })\n // handle data when trailing line not included\n if (segmentLines.length !== 0) {\n try {\n outSegments = addSegment(createSegmentFromSRTLines(segmentLines, lastSpeaker), outSegments)\n lastSpeaker = outSegments[outSegments.length - 1].speaker",
"score": 36.08299706362216
},
{
"filename": "src/segments.ts",
"retrieved_chunk": " let lastSpeaker: string\n if (speakerChange) {\n lastSpeaker = getLastSpeaker(priorSegment, outSegments)\n }\n const newSegmentInfo = applyOptions(newSegment, priorSegment, lastSpeaker)\n if (newSegmentInfo.replace && outSegments.length > 0) {\n outSegments[outSegments.length - 1] = newSegmentInfo.segment\n } else {\n outSegments.push(newSegmentInfo.segment)\n }",
"score": 35.32321940153589
},
{
"filename": "src/formats/srt.ts",
"retrieved_chunk": " // handle consecutive multiple blank lines\n if (segmentLines.length !== 0) {\n try {\n outSegments = addSegment(createSegmentFromSRTLines(segmentLines, lastSpeaker), outSegments)\n lastSpeaker = outSegments[outSegments.length - 1].speaker\n } catch (e) {\n console.error(`Error parsing SRT segment lines (source line ${count}): ${e}`)\n console.error(segmentLines)\n }\n }",
"score": 34.486813650401636
},
{
"filename": "src/segments.ts",
"retrieved_chunk": " *\n * @param newSegment segment to add or replace\n * @param priorSegments array of all previous segments\n * @returns updated array of segments with new segment added or last segment updated (per options)\n */\nexport const addSegment = (newSegment: Segment, priorSegments: Array<Segment>): Array<Segment> => {\n const { speakerChange } = Options\n const outSegments = priorSegments || []\n const priorSegment = outSegments.length > 0 ? outSegments[outSegments.length - 1] : undefined\n // don't worry about identifying the last speaker if speaker is not being removed by speakerChange",
"score": 32.29476361985712
}
] | typescript | outSegments = addSegment(segment, outSegments)
} |
import { addSegment } from "../segments"
import { parseSpeaker } from "../speaker"
import { TimestampFormatter } from "../timestamp"
import { Segment } from "../types"
/**
* Define a segment/cue used in the JSONTranscript format
*/
export type JSONSegment = {
/**
* Time (in seconds) when segment starts
*/
startTime: number
/**
* Time (in seconds) when segment ends
*/
endTime: number
/**
* Name of speaker for `body`
*/
speaker?: string
/**
* Text of transcript for segment
*/
body: string
}
/**
* Define the JSON transcript format
*/
export type JSONTranscript = {
/**
* Version of file format
*/
version: string
/**
* Segment data
*/
segments: Array<JSONSegment>
}
/**
* Define the JSON transcript Segment format
*/
export type SubtitleSegment = {
/**
* Time (in milliseconds) when segment starts
*/
start: number
/**
* Time (in milliseconds) when segment ends
*/
end: number
/**
* Text of transcript for segment
*/
text: string
}
/**
* Determines if the value of data is a valid JSON transcript format
*
* @param data The transcript data
* @returns True: data is valid JSON transcript format
*/
export const isJSON = (data: string): boolean => {
return (data.startsWith("{") && data.endsWith("}")) || (data.startsWith("[") && data.endsWith("]"))
}
/**
* Parse JSON data where segments are in the `segments` Array and in the {@link JSONSegment} format
*
* @param data Parsed JSON data
* @returns An array of Segments from the parsed data
*/
const parseDictSegmentsJSON = (data | : JSONTranscript): Array<Segment> => { |
let outSegments: Array<Segment> = []
data.segments.forEach((segment) => {
outSegments = addSegment(
{
startTime: segment.startTime,
startTimeFormatted: TimestampFormatter.format(segment.startTime),
endTime: segment.endTime,
endTimeFormatted: TimestampFormatter.format(segment.endTime),
speaker: segment.speaker,
body: segment.body,
},
outSegments
)
})
return outSegments
}
/**
* Parse JSON data where top level item is a dict/object
*
* @param data The transcript data
* @returns An array of Segments from the parsed data
* @throws {TypeError} When JSON data does not match one of the valid formats
*/
const parseDictJSON = (data: object): Array<Segment> => {
let outSegments: Array<Segment> = []
if (Object.keys(data).length === 0) {
return outSegments
}
if ("segments" in data) {
outSegments = parseDictSegmentsJSON(data as JSONTranscript)
} else {
throw new TypeError(`Unknown JSON dict transcript format`)
}
return outSegments
}
/**
* Convert {@link SubtitleSegment} to the {@link Segment} format used here
*
* @param data Segment parsed from JSON data
* @returns Segment representing `data`.
* Returns {@link undefined} when data does not match {@link SubtitleSegment} format.
*/
const getSegmentFromSubtitle = (data: SubtitleSegment): Segment => {
if ("start" in data && "end" in data && "text" in data) {
const { speaker, message } = parseSpeaker(data.text)
const startTime = data.start / 1000
const endTime = data.end / 1000
const segment: Segment = {
startTime,
startTimeFormatted: TimestampFormatter.format(startTime),
endTime,
endTimeFormatted: TimestampFormatter.format(endTime),
speaker,
body: message,
}
if (Number.isNaN(segment.startTime)) {
console.warn(`Computed start time is NaN: ${segment.startTime}`)
return undefined
}
if (Number.isNaN(segment.endTime)) {
console.warn(`Computed end time is NaN: ${segment.endTime}`)
return undefined
}
return segment
}
return undefined
}
/**
* Parse JSON data where items in data are in the {@link SubtitleSegment} format
*
* @param data Parsed JSON data
* @returns An array of Segments from the parsed data
* @throws {TypeError} When item in `data` does not match the {@link SubtitleSegment} format
*/
const parseListJSONSubtitle = (data: Array<SubtitleSegment>): Array<Segment> => {
let outSegments: Array<Segment> = []
let lastSpeaker = ""
data.forEach((subtitle, count) => {
const subtitleSegment = getSegmentFromSubtitle(subtitle)
if (subtitleSegment !== undefined) {
lastSpeaker = subtitleSegment.speaker ? subtitleSegment.speaker : lastSpeaker
subtitleSegment.speaker = lastSpeaker
outSegments = addSegment(subtitleSegment, outSegments)
} else {
throw new TypeError(`Unable to parse segment for item ${count}`)
}
})
return outSegments
}
/**
* Parse JSON data where top level item is an Array
*
* @param data The transcript data
* @returns An array of Segments from the parsed data
* @throws {TypeError} When JSON data does not match one of the valid formats
*/
const parseListJSON = (data: Array<unknown>): Array<Segment> => {
let outSegments: Array<Segment> = []
if (data.length === 0) {
return outSegments
}
const subtitleSegment = getSegmentFromSubtitle(data[0] as SubtitleSegment)
if (subtitleSegment !== undefined) {
outSegments = parseListJSONSubtitle(data as Array<SubtitleSegment>)
} else {
throw new TypeError(`Unknown JSON list transcript format`)
}
return outSegments
}
/**
* Parse JSON data to an Array of {@link Segment}
*
* @param data The transcript data
* @returns An array of Segments from the parsed data
* @throws {TypeError} When `data` is not valid JSON format
*/
export const parseJSON = (data: string): Array<Segment> => {
const dataTrimmed = data.trim()
let outSegments: Array<Segment> = []
if (!isJSON(dataTrimmed)) {
throw new TypeError(`Data is not valid JSON format`)
}
let parsed: object | Array<unknown>
try {
parsed = JSON.parse(data)
} catch (e) {
throw new TypeError(`Data is not valid JSON: ${e}`)
}
if (parsed.constructor === Object) {
outSegments = parseDictJSON(parsed)
} else if (parsed.constructor === Array) {
outSegments = parseListJSON(parsed)
}
return outSegments
}
| src/formats/json.ts | stevencrader-transcriptator-75faa70 | [
{
"filename": "src/formats/vtt.ts",
"retrieved_chunk": " * @returns True: data is valid VTT transcript format\n */\nexport const isVTT = (data: string): boolean => {\n return data.startsWith(\"WEBVTT\")\n}\n/**\n * Parse VTT data to an Array of {@link Segment}\n *\n * @param data The transcript data\n * @returns An array of Segments from the parsed data",
"score": 56.380977711447876
},
{
"filename": "src/formats/srt.ts",
"retrieved_chunk": " return false\n }\n}\n/**\n * Parse SRT data to an Array of {@link Segment}\n *\n * @param data The transcript data\n * @returns An array of Segments from the parsed data\n * @throws {TypeError} When `data` is not valid SRT format\n */",
"score": 49.91308205424407
},
{
"filename": "src/formats/html.ts",
"retrieved_chunk": " * Parse HTML data to an Array of {@link Segment}\n *\n * @param data The transcript data\n * @returns An array of Segments from the parsed data\n * @throws {TypeError} When `data` is not valid HTML format\n */\nexport const parseHTML = (data: string): Array<Segment> => {\n const dataTrimmed = data.trim()\n if (!isHTML(dataTrimmed)) {\n throw new TypeError(`Data is not valid HTML format`)",
"score": 45.68982263130665
},
{
"filename": "src/index.ts",
"retrieved_chunk": "}\n/**\n * Convert the data to an Array of {@link Segment}\n *\n * @param data The transcript data\n * @param transcriptFormat The format of the data.\n * @returns An Array of Segment objects from the parsed data\n * @throws {TypeError} When `transcriptFormat` is unknown\n */\nexport const convertFile = (data: string, transcriptFormat: TranscriptFormat = undefined): Array<Segment> => {",
"score": 42.181499320445425
},
{
"filename": "src/formats/html.ts",
"retrieved_chunk": "}\n/**\n * Determines if the value of data is a valid HTML transcript format\n *\n * @param data The transcript data\n * @returns True: data is valid HTML transcript format\n */\nexport const isHTML = (data: string): boolean => {\n return (\n data.startsWith(\"<!--\") ||",
"score": 37.308854303052584
}
] | typescript | : JSONTranscript): Array<Segment> => { |
import { addSegment } from "../segments"
import { parseSpeaker } from "../speaker"
import { TimestampFormatter } from "../timestamp"
import { Segment } from "../types"
/**
* Define a segment/cue used in the JSONTranscript format
*/
export type JSONSegment = {
/**
* Time (in seconds) when segment starts
*/
startTime: number
/**
* Time (in seconds) when segment ends
*/
endTime: number
/**
* Name of speaker for `body`
*/
speaker?: string
/**
* Text of transcript for segment
*/
body: string
}
/**
* Define the JSON transcript format
*/
export type JSONTranscript = {
/**
* Version of file format
*/
version: string
/**
* Segment data
*/
segments: Array<JSONSegment>
}
/**
* Define the JSON transcript Segment format
*/
export type SubtitleSegment = {
/**
* Time (in milliseconds) when segment starts
*/
start: number
/**
* Time (in milliseconds) when segment ends
*/
end: number
/**
* Text of transcript for segment
*/
text: string
}
/**
* Determines if the value of data is a valid JSON transcript format
*
* @param data The transcript data
* @returns True: data is valid JSON transcript format
*/
export const isJSON = (data: string): boolean => {
return (data.startsWith("{") && data.endsWith("}")) || (data.startsWith("[") && data.endsWith("]"))
}
/**
* Parse JSON data where segments are in the `segments` Array and in the {@link JSONSegment} format
*
* @param data Parsed JSON data
* @returns An array of Segments from the parsed data
*/
const parseDictSegmentsJSON = (data: JSONTranscript): Array<Segment> => {
let outSegments: Array<Segment> = []
data.segments.forEach((segment) => {
| outSegments = addSegment(
{ |
startTime: segment.startTime,
startTimeFormatted: TimestampFormatter.format(segment.startTime),
endTime: segment.endTime,
endTimeFormatted: TimestampFormatter.format(segment.endTime),
speaker: segment.speaker,
body: segment.body,
},
outSegments
)
})
return outSegments
}
/**
* Parse JSON data where top level item is a dict/object
*
* @param data The transcript data
* @returns An array of Segments from the parsed data
* @throws {TypeError} When JSON data does not match one of the valid formats
*/
const parseDictJSON = (data: object): Array<Segment> => {
let outSegments: Array<Segment> = []
if (Object.keys(data).length === 0) {
return outSegments
}
if ("segments" in data) {
outSegments = parseDictSegmentsJSON(data as JSONTranscript)
} else {
throw new TypeError(`Unknown JSON dict transcript format`)
}
return outSegments
}
/**
* Convert {@link SubtitleSegment} to the {@link Segment} format used here
*
* @param data Segment parsed from JSON data
* @returns Segment representing `data`.
* Returns {@link undefined} when data does not match {@link SubtitleSegment} format.
*/
const getSegmentFromSubtitle = (data: SubtitleSegment): Segment => {
if ("start" in data && "end" in data && "text" in data) {
const { speaker, message } = parseSpeaker(data.text)
const startTime = data.start / 1000
const endTime = data.end / 1000
const segment: Segment = {
startTime,
startTimeFormatted: TimestampFormatter.format(startTime),
endTime,
endTimeFormatted: TimestampFormatter.format(endTime),
speaker,
body: message,
}
if (Number.isNaN(segment.startTime)) {
console.warn(`Computed start time is NaN: ${segment.startTime}`)
return undefined
}
if (Number.isNaN(segment.endTime)) {
console.warn(`Computed end time is NaN: ${segment.endTime}`)
return undefined
}
return segment
}
return undefined
}
/**
* Parse JSON data where items in data are in the {@link SubtitleSegment} format
*
* @param data Parsed JSON data
* @returns An array of Segments from the parsed data
* @throws {TypeError} When item in `data` does not match the {@link SubtitleSegment} format
*/
const parseListJSONSubtitle = (data: Array<SubtitleSegment>): Array<Segment> => {
let outSegments: Array<Segment> = []
let lastSpeaker = ""
data.forEach((subtitle, count) => {
const subtitleSegment = getSegmentFromSubtitle(subtitle)
if (subtitleSegment !== undefined) {
lastSpeaker = subtitleSegment.speaker ? subtitleSegment.speaker : lastSpeaker
subtitleSegment.speaker = lastSpeaker
outSegments = addSegment(subtitleSegment, outSegments)
} else {
throw new TypeError(`Unable to parse segment for item ${count}`)
}
})
return outSegments
}
/**
* Parse JSON data where top level item is an Array
*
* @param data The transcript data
* @returns An array of Segments from the parsed data
* @throws {TypeError} When JSON data does not match one of the valid formats
*/
const parseListJSON = (data: Array<unknown>): Array<Segment> => {
let outSegments: Array<Segment> = []
if (data.length === 0) {
return outSegments
}
const subtitleSegment = getSegmentFromSubtitle(data[0] as SubtitleSegment)
if (subtitleSegment !== undefined) {
outSegments = parseListJSONSubtitle(data as Array<SubtitleSegment>)
} else {
throw new TypeError(`Unknown JSON list transcript format`)
}
return outSegments
}
/**
* Parse JSON data to an Array of {@link Segment}
*
* @param data The transcript data
* @returns An array of Segments from the parsed data
* @throws {TypeError} When `data` is not valid JSON format
*/
export const parseJSON = (data: string): Array<Segment> => {
const dataTrimmed = data.trim()
let outSegments: Array<Segment> = []
if (!isJSON(dataTrimmed)) {
throw new TypeError(`Data is not valid JSON format`)
}
let parsed: object | Array<unknown>
try {
parsed = JSON.parse(data)
} catch (e) {
throw new TypeError(`Data is not valid JSON: ${e}`)
}
if (parsed.constructor === Object) {
outSegments = parseDictJSON(parsed)
} else if (parsed.constructor === Array) {
outSegments = parseListJSON(parsed)
}
return outSegments
}
| src/formats/json.ts | stevencrader-transcriptator-75faa70 | [
{
"filename": "src/formats/srt.ts",
"retrieved_chunk": " return false\n }\n}\n/**\n * Parse SRT data to an Array of {@link Segment}\n *\n * @param data The transcript data\n * @returns An array of Segments from the parsed data\n * @throws {TypeError} When `data` is not valid SRT format\n */",
"score": 45.17157998070407
},
{
"filename": "src/formats/vtt.ts",
"retrieved_chunk": " * @returns True: data is valid VTT transcript format\n */\nexport const isVTT = (data: string): boolean => {\n return data.startsWith(\"WEBVTT\")\n}\n/**\n * Parse VTT data to an Array of {@link Segment}\n *\n * @param data The transcript data\n * @returns An array of Segments from the parsed data",
"score": 43.899566949102784
},
{
"filename": "src/formats/html.ts",
"retrieved_chunk": " * Parse HTML data to an Array of {@link Segment}\n *\n * @param data The transcript data\n * @returns An array of Segments from the parsed data\n * @throws {TypeError} When `data` is not valid HTML format\n */\nexport const parseHTML = (data: string): Array<Segment> => {\n const dataTrimmed = data.trim()\n if (!isHTML(dataTrimmed)) {\n throw new TypeError(`Data is not valid HTML format`)",
"score": 42.290976048488616
},
{
"filename": "src/index.ts",
"retrieved_chunk": "}\n/**\n * Convert the data to an Array of {@link Segment}\n *\n * @param data The transcript data\n * @param transcriptFormat The format of the data.\n * @returns An Array of Segment objects from the parsed data\n * @throws {TypeError} When `transcriptFormat` is unknown\n */\nexport const convertFile = (data: string, transcriptFormat: TranscriptFormat = undefined): Array<Segment> => {",
"score": 39.74556434824153
},
{
"filename": "src/index.ts",
"retrieved_chunk": " const format = transcriptFormat ?? determineFormat(data)\n const normalizedData = data.trimStart()\n let outSegments: Array<Segment> = []\n switch (format) {\n case TranscriptFormat.HTML:\n outSegments = parseHTML(normalizedData)\n break\n case TranscriptFormat.JSON:\n outSegments = parseJSON(normalizedData)\n break",
"score": 38.59111362602873
}
] | typescript | outSegments = addSegment(
{ |
import { isHTML, parseHTML } from "./formats/html"
import { isJSON, parseJSON } from "./formats/json"
import { isSRT, parseSRT } from "./formats/srt"
import { isVTT, parseVTT } from "./formats/vtt"
import { Segment, TranscriptFormat } from "./types"
export { Segment, TranscriptFormat } from "./types"
export { TimestampFormatter, FormatterCallback } from "./timestamp"
export { Options, IOptions } from "./options"
/**
* Determines the format of transcript by inspecting the data
*
* @param data The transcript data
* @returns The determined transcript format
* @throws {TypeError} Cannot determine format of data or error parsing data
*/
export const determineFormat = (data: string): TranscriptFormat => {
const normalizedData = data.trim()
if (isVTT(normalizedData)) {
return TranscriptFormat.VTT
}
if (isJSON(normalizedData)) {
return TranscriptFormat.JSON
}
if (isHTML(normalizedData)) {
return TranscriptFormat.HTML
}
if (isSRT(normalizedData)) {
return TranscriptFormat.SRT
}
throw new TypeError(`Cannot determine format for data`)
}
/**
* Convert the data to an Array of {@link Segment}
*
* @param data The transcript data
* @param transcriptFormat The format of the data.
* @returns An Array of Segment objects from the parsed data
* @throws {TypeError} When `transcriptFormat` is unknown
*/
| export const convertFile = (data: string, transcriptFormat: TranscriptFormat = undefined): Array<Segment> => { |
const format = transcriptFormat ?? determineFormat(data)
const normalizedData = data.trimStart()
let outSegments: Array<Segment> = []
switch (format) {
case TranscriptFormat.HTML:
outSegments = parseHTML(normalizedData)
break
case TranscriptFormat.JSON:
outSegments = parseJSON(normalizedData)
break
case TranscriptFormat.SRT:
outSegments = parseSRT(normalizedData)
break
case TranscriptFormat.VTT:
outSegments = parseVTT(normalizedData)
break
default:
throw new TypeError(`Unknown transcript format: ${format}`)
}
return outSegments
}
| src/index.ts | stevencrader-transcriptator-75faa70 | [
{
"filename": "src/formats/json.ts",
"retrieved_chunk": "/**\n * Parse JSON data to an Array of {@link Segment}\n *\n * @param data The transcript data\n * @returns An array of Segments from the parsed data\n * @throws {TypeError} When `data` is not valid JSON format\n */\nexport const parseJSON = (data: string): Array<Segment> => {\n const dataTrimmed = data.trim()\n let outSegments: Array<Segment> = []",
"score": 53.74010724828037
},
{
"filename": "src/formats/srt.ts",
"retrieved_chunk": " return false\n }\n}\n/**\n * Parse SRT data to an Array of {@link Segment}\n *\n * @param data The transcript data\n * @returns An array of Segments from the parsed data\n * @throws {TypeError} When `data` is not valid SRT format\n */",
"score": 52.22478539921524
},
{
"filename": "src/formats/json.ts",
"retrieved_chunk": "/**\n * Parse JSON data where top level item is an Array\n *\n * @param data The transcript data\n * @returns An array of Segments from the parsed data\n * @throws {TypeError} When JSON data does not match one of the valid formats\n */\nconst parseListJSON = (data: Array<unknown>): Array<Segment> => {\n let outSegments: Array<Segment> = []\n if (data.length === 0) {",
"score": 50.98957290598465
},
{
"filename": "src/formats/html.ts",
"retrieved_chunk": " * Parse HTML data to an Array of {@link Segment}\n *\n * @param data The transcript data\n * @returns An array of Segments from the parsed data\n * @throws {TypeError} When `data` is not valid HTML format\n */\nexport const parseHTML = (data: string): Array<Segment> => {\n const dataTrimmed = data.trim()\n if (!isHTML(dataTrimmed)) {\n throw new TypeError(`Data is not valid HTML format`)",
"score": 50.22142081103664
},
{
"filename": "src/formats/vtt.ts",
"retrieved_chunk": " * @returns True: data is valid VTT transcript format\n */\nexport const isVTT = (data: string): boolean => {\n return data.startsWith(\"WEBVTT\")\n}\n/**\n * Parse VTT data to an Array of {@link Segment}\n *\n * @param data The transcript data\n * @returns An array of Segments from the parsed data",
"score": 46.25518042648515
}
] | typescript | export const convertFile = (data: string, transcriptFormat: TranscriptFormat = undefined): Array<Segment> => { |
import { ContractMethod } from '../schema/application'
import { DecIndent, DecIndentAndCloseBlock, DocumentParts, IncIndent, jsDoc, NewLine } from '../output/writer'
import { isSafeVariableIdentifier, makeSafeMethodIdentifier, makeSafePropertyIdentifier } from '../util/sanitization'
import * as algokit from '@algorandfoundation/algokit-utils'
import { GeneratorContext } from './generator-context'
import { BARE_CALL, MethodList } from './helpers/get-call-config-summary'
import { getCreateOnCompleteOptions } from './deploy-types'
export function* callFactory(ctx: GeneratorContext): DocumentParts {
yield* jsDoc('Exposes methods for constructing all available smart contract calls')
yield `export abstract class ${ctx.name}CallFactory {`
yield IncIndent
yield* opMethods(ctx)
for (const method of ctx.app.contract.methods) {
yield* callFactoryMethod(ctx, method)
}
yield DecIndent
yield '}'
}
function* opMethods(ctx: GeneratorContext): DocumentParts {
const { app, callConfig } = ctx
yield* operationMethod(
ctx,
`Constructs a create call for the ${app.contract.name} smart contract`,
callConfig.createMethods,
'create',
true,
)
yield* operationMethod(
ctx,
`Constructs an update call for the ${app.contract.name} smart contract`,
callConfig.updateMethods,
'update',
true,
)
yield* operationMethod(ctx, `Constructs a delete call for the ${app.contract.name} smart contract`, callConfig.deleteMethods, 'delete')
yield* operationMethod(ctx, `Constructs an opt in call for the ${app.contract.name} smart contract`, callConfig.optInMethods, 'optIn')
yield* operationMethod(
ctx,
`Constructs a close out call for the ${app.contract.name} smart contract`,
callConfig.closeOutMethods,
'closeOut',
)
}
function* operationMethod(
{ app, methodSignatureToUniqueName }: GeneratorContext,
description: string,
methods: MethodList,
verb: 'create' | 'update' | 'optIn' | 'closeOut' | 'delete',
includeCompilation?: boolean,
): DocumentParts {
if (methods.length) {
yield* jsDoc(`Gets available ${verb} call factories`)
yield `static get ${verb}() {`
yield IncIndent
yield `return {`
yield IncIndent
for (const methodSig of methods) {
const onComplete = verb === 'create' ? getCreateOnCompleteOptions(methodSig, app) : undefined
if (methodSig === BARE_CALL) {
yield* jsDoc({
description: `${description} using a bare call`,
params: {
params: `Any parameters for the call`,
},
returns: `A TypedCallParams object for the call`,
})
yield* factoryMethod({
isNested: true,
name: 'bare',
paramTypes: `BareCallArgs & AppClientCallCoreParams & CoreAppCallArgs${
includeCompilation ? ' & AppClientCompilationParams' : ''
}${onComplete?.type ? ` & ${onComplete.type}` : ''}${onComplete?.isOptional !== false ? ' = {}' : ''}`,
})
} else {
const method = app.contract.methods.find((m) => algokit.getABIMethodSignature(m) === methodSig)!
const uniqueName = methodSignatureToUniqueName[methodSig]
yield* jsDoc({
description: `${description} using the ${methodSig} ABI method`,
params: {
args: `Any args for the contract call`,
params: `Any additional parameters for the call`,
},
returns: `A TypedCallParams object for the call`,
})
yield* factoryMethod({
isNested: true,
name: | makeSafeMethodIdentifier(uniqueName),
signature: methodSig,
args: method.args,
paramTypes: `AppClientCallCoreParams & CoreAppCallArgs${includeCompilation ? ' & AppClientCompilationParams' : ''}${ |
onComplete?.type ? ` & ${onComplete.type}` : ''
}${onComplete?.isOptional !== false ? ' = {}' : ''}`,
})
}
}
yield DecIndentAndCloseBlock
yield DecIndentAndCloseBlock
yield NewLine
}
}
function* callFactoryMethod({ methodSignatureToUniqueName, callConfig }: GeneratorContext, method: ContractMethod) {
const methodSignature = algokit.getABIMethodSignature(method)
if (!callConfig.callMethods.includes(methodSignature)) return
yield* jsDoc({
description: `Constructs a no op call for the ${methodSignature} ABI method`,
abiDescription: method.desc,
params: {
args: `Any args for the contract call`,
params: `Any additional parameters for the call`,
},
returns: `A TypedCallParams object for the call`,
})
yield* factoryMethod({
isNested: false,
name: makeSafeMethodIdentifier(methodSignatureToUniqueName[methodSignature]),
signature: methodSignature,
args: method.args,
paramTypes: 'AppClientCallCoreParams & CoreAppCallArgs',
})
}
function* factoryMethod({
isNested,
name,
signature,
args,
paramTypes,
}:
| {
isNested: boolean
name?: string
signature?: undefined
args?: undefined
paramTypes: string
}
| {
isNested: boolean
name?: string
signature: string
args: Array<{ name: string }>
paramTypes: string
}) {
yield `${isNested ? '' : 'static '}${name}(${signature === undefined ? '' : `args: MethodArgs<'${signature}'>, `}params: ${paramTypes}) {`
yield IncIndent
yield `return {`
yield IncIndent
if (signature) {
yield `method: '${signature}' as const,`
yield `methodArgs: Array.isArray(args) ? args : [${args
.map((a) => (isSafeVariableIdentifier(a.name) ? `args.${a.name}` : `args['${makeSafePropertyIdentifier(a.name)}']`))
.join(', ')}],`
} else {
yield `method: undefined,`
yield `methodArgs: undefined,`
}
yield '...params,'
yield DecIndent
yield '}'
yield DecIndent
yield `}${isNested ? ',' : ''}`
}
| src/client/call-factory.ts | algorandfoundation-algokit-client-generator-ts-2de43ed | [
{
"filename": "src/client/call-client.ts",
"retrieved_chunk": " const method = app.contract.methods.find((m) => algokit.getABIMethodSignature(m) === methodSig)\n yield* jsDoc({\n description: `${description} using the ${methodSig} ABI method.`,\n params: {\n args: `The arguments for the smart contract call`,\n params: `Any additional parameters for the call`,\n },\n returns: `The ${verb} result${method?.returns?.desc ? `: ${method.returns.desc}` : ''}`,\n })\n yield `async ${makeSafeMethodIdentifier(uniqueName)}(args: MethodArgs<'${methodSig}'>, params: AppClientCallCoreParams${",
"score": 24.37006403257143
},
{
"filename": "src/client/call-composer.ts",
"retrieved_chunk": " const methodName = makeSafeMethodIdentifier(uniqueName)\n yield `${methodName}(args: MethodArgs<'${methodSig}'>, params${\n onComplete?.isOptional !== false ? '?' : ''\n }: AppClientCallCoreParams${includeCompilation ? ' & AppClientCompilationParams' : ''}${\n onComplete?.type ? ` & ${onComplete.type}` : ''\n }) {`\n yield IncIndent\n yield `promiseChain = promiseChain.then(() => client.${verb}.${methodName}(args, {...params, sendParams: {...params?.sendParams, skipSending: true, atc}}))`\n const outputTypeName = app.hints?.[methodSig]?.structs?.output?.name\n yield `resultMappers.push(${outputTypeName ?? 'undefined'})`",
"score": 23.672510735095827
},
{
"filename": "src/client/call-composer-types.ts",
"retrieved_chunk": " params: {\n args: `The arguments for the bare call`,\n },\n returns: `The typed transaction composer so you can fluently chain multiple calls or call execute to execute all queued up transactions`,\n })\n yield `bare(args${onComplete?.isOptional !== false ? '?' : ''}: BareCallArgs & AppClientCallCoreParams ${\n includeCompilation ? '& AppClientCompilationParams ' : ''\n }& CoreAppCallArgs${onComplete?.type ? ` & ${onComplete.type}` : ''}): ${name}Composer<[...TReturns, undefined]>`\n } else {\n const uniqueName = methodSignatureToUniqueName[methodSig]",
"score": 23.66936306302491
},
{
"filename": "src/client/call-composer.ts",
"retrieved_chunk": " includeCompilation ? '& AppClientCompilationParams ' : ''\n }& CoreAppCallArgs${onComplete?.type ? ` & ${onComplete.type}` : ''}) {`\n yield IncIndent\n yield `promiseChain = promiseChain.then(() => client.${verb}.bare({...args, sendParams: {...args?.sendParams, skipSending: true, atc}}))`\n yield `resultMappers.push(undefined)`\n yield `return $this`\n yield DecIndent\n yield '},'\n } else {\n const uniqueName = methodSignatureToUniqueName[methodSig]",
"score": 22.933503652541365
},
{
"filename": "src/client/call-client.ts",
"retrieved_chunk": " })\n yield `bare(args: BareCallArgs & AppClientCallCoreParams ${\n includeCompilation ? '& AppClientCompilationParams ' : ''\n }& CoreAppCallArgs${onComplete?.type ? ` & ${onComplete.type}` : ''}${\n onComplete?.isOptional !== false ? ' = {}' : ''\n }): Promise<AppCallTransactionResultOfType<undefined>> {`\n yield* indent(`return $this.appClient.${verb}(args) as unknown as Promise<AppCallTransactionResultOfType<undefined>>`)\n yield '},'\n } else {\n const uniqueName = methodSignatureToUniqueName[methodSig]",
"score": 22.402946008957578
}
] | typescript | makeSafeMethodIdentifier(uniqueName),
signature: methodSig,
args: method.args,
paramTypes: `AppClientCallCoreParams & CoreAppCallArgs${includeCompilation ? ' & AppClientCompilationParams' : ''}${ |
import { addSegment } from "../segments"
import { parseSpeaker } from "../speaker"
import { parseTimestamp, TimestampFormatter } from "../timestamp"
import { PATTERN_LINE_SEPARATOR, Segment } from "../types"
/**
* Define a segment/cue parsed from SRT file
*/
export type SRTSegment = {
/**
* Cue number
*/
index: number
/**
* Time (in seconds) when segment starts
*/
startTime: number
/**
* Time (in seconds) when segment ends
*/
endTime: number
/**
* Name of speaker for `body`
*/
speaker: string
/**
* Text of transcript for segment
*/
body: string
}
/**
* Parse lines looking for data to be SRT format
*
* @param lines Lines containing SRT data
* @returns Parsed segment
* @throws {Error} When no non-empty strings in `lines`
* @throws {Error} When the minimum required number of lines is not received
* @throws {Error} When segment lines does not start with a number
* @throws {Error} When second segment line does not follow the timestamp format
*/
export const parseSRTSegment = (lines: Array<string>): SRTSegment => {
do {
if (lines.length === 0) {
throw new Error("SRT segment lines empty")
} else if (lines[0].trim() === "") {
lines.shift()
} else {
break
}
} while (lines.length > 0)
if (lines.length < 3) {
throw new Error(`SRT requires at least 3 lines, ${lines.length} received`)
}
const index = parseInt(lines[0], 10)
if (!index) {
throw new Error(`First line of SRT segment is not a number`)
}
const timestampLine = lines[1]
if (!timestampLine.includes("-->")) {
throw new Error(`SRT timestamp line does not include --> separator`)
}
const timestampParts = timestampLine.split("-->")
if (timestampParts.length !== 2) {
throw new Error(`SRT timestamp line contains more than 2 --> separators`)
}
const startTime = parseTimestamp(timestampParts[0].trim())
const endTime = parseTimestamp(timestampParts[1].trim())
let bodyLines = lines.slice(2)
const emptyLineIndex = bodyLines.findIndex((v) => v.trim() === "")
if (emptyLineIndex > 0) {
bodyLines = bodyLines.slice(0, emptyLineIndex)
}
const { speaker, message } = parseSpeaker(bodyLines.shift())
bodyLines = [message].concat(bodyLines)
return {
startTime,
endTime,
speaker,
body: bodyLines.join("\n"),
index,
}
}
/**
* Create Segment from lines containing an SRT segment/cue
*
* @param segmentLines Lines containing SRT data
* @param lastSpeaker Name of last speaker. Will be used if no speaker found in `segmentLines`
* @returns Created segment
*/
const createSegmentFromSRTLines = (segmentLines: Array<string>, lastSpeaker: string): Segment => {
const srtSegment = parseSRTSegment(segmentLines)
const calculatedSpeaker = srtSegment.speaker ? srtSegment.speaker : lastSpeaker
return {
startTime: srtSegment.startTime,
startTimeFormatted: TimestampFormatter.format(srtSegment.startTime),
endTime: srtSegment.endTime,
endTimeFormatted: TimestampFormatter.format(srtSegment.endTime),
speaker: calculatedSpeaker,
body: srtSegment.body,
}
}
/**
* Determines if the value of data is a valid SRT transcript format
*
* @param data The transcript data
* @returns True: data is valid SRT transcript format
*/
export const isSRT = (data: string): boolean => {
try {
return parseSRTSegment( | data.split(PATTERN_LINE_SEPARATOR).slice(0, 20)) !== undefined
} catch (e) { |
return false
}
}
/**
* Parse SRT data to an Array of {@link Segment}
*
* @param data The transcript data
* @returns An array of Segments from the parsed data
* @throws {TypeError} When `data` is not valid SRT format
*/
export const parseSRT = (data: string): Array<Segment> => {
if (!isSRT(data)) {
throw new TypeError(`Data is not valid SRT format`)
}
let outSegments: Array<Segment> = []
let lastSpeaker = ""
let segmentLines = []
data.split(PATTERN_LINE_SEPARATOR).forEach((line, count) => {
// separator line found, handle previous data
if (line.trim() === "") {
// handle consecutive multiple blank lines
if (segmentLines.length !== 0) {
try {
outSegments = addSegment(createSegmentFromSRTLines(segmentLines, lastSpeaker), outSegments)
lastSpeaker = outSegments[outSegments.length - 1].speaker
} catch (e) {
console.error(`Error parsing SRT segment lines (source line ${count}): ${e}`)
console.error(segmentLines)
}
}
segmentLines = [] // clear buffer
} else {
segmentLines.push(line)
}
})
// handle data when trailing line not included
if (segmentLines.length !== 0) {
try {
outSegments = addSegment(createSegmentFromSRTLines(segmentLines, lastSpeaker), outSegments)
lastSpeaker = outSegments[outSegments.length - 1].speaker
} catch (e) {
console.error(`Error parsing final SRT segment lines: ${e}`)
console.error(segmentLines)
}
}
return outSegments
}
| src/formats/srt.ts | stevencrader-transcriptator-75faa70 | [
{
"filename": "src/formats/html.ts",
"retrieved_chunk": "}\n/**\n * Determines if the value of data is a valid HTML transcript format\n *\n * @param data The transcript data\n * @returns True: data is valid HTML transcript format\n */\nexport const isHTML = (data: string): boolean => {\n return (\n data.startsWith(\"<!--\") ||",
"score": 53.34521996273871
},
{
"filename": "src/formats/json.ts",
"retrieved_chunk": " /**\n * Text of transcript for segment\n */\n text: string\n}\n/**\n * Determines if the value of data is a valid JSON transcript format\n *\n * @param data The transcript data\n * @returns True: data is valid JSON transcript format",
"score": 49.54776870718494
},
{
"filename": "src/formats/vtt.ts",
"retrieved_chunk": " * @returns True: data is valid VTT transcript format\n */\nexport const isVTT = (data: string): boolean => {\n return data.startsWith(\"WEBVTT\")\n}\n/**\n * Parse VTT data to an Array of {@link Segment}\n *\n * @param data The transcript data\n * @returns An array of Segments from the parsed data",
"score": 39.4543057660767
},
{
"filename": "src/formats/vtt.ts",
"retrieved_chunk": "import { Segment } from \"../types\"\nimport { parseSRT } from \"./srt\"\n/**\n * Required header for WebVTT/VTT files\n */\nconst WEBVTT_HEADER = \"WEBVTT\"\n/**\n * Determines if the value of data is a valid VTT transcript format\n *\n * @param data The transcript data",
"score": 36.7582535554829
},
{
"filename": "src/formats/json.ts",
"retrieved_chunk": " if (!isJSON(dataTrimmed)) {\n throw new TypeError(`Data is not valid JSON format`)\n }\n let parsed: object | Array<unknown>\n try {\n parsed = JSON.parse(data)\n } catch (e) {\n throw new TypeError(`Data is not valid JSON: ${e}`)\n }\n if (parsed.constructor === Object) {",
"score": 31.886325913751055
}
] | typescript | data.split(PATTERN_LINE_SEPARATOR).slice(0, 20)) !== undefined
} catch (e) { |
import { Options } from "./options"
import { TimestampFormatter } from "./timestamp"
import { DEFAULT_COMBINE_SEGMENTS_LENGTH, Segment } from "./types"
/**
* Regular Expression for detecting punctuation that should not be prefixed with a space
*/
const PATTERN_PUNCTUATIONS = /^ *[.,?!}\]>) *$]/
/**
* Regular Expression for detecting space characters at the end of a string
*/
const PATTERN_TRAILING_SPACE = /^ *$/
/**
* Remove any trailing space characters from data
*
* @param data text to trim
* @returns text with any trailing space character removed
*/
const trimEndSpace = (data: string): string => {
return data.replace(PATTERN_TRAILING_SPACE, "")
}
/**
* Append `addition` to `body` with the character(s) specified.
*
* If `addition` matches the {@link PATTERN_PUNCTUATIONS} pattern, no character is added before the additional data.
*
* @param body Current body text
* @param addition Additional text to add to `body`
* @param separator Character(s) to use to separate data. If undefined, uses `\n`.
* @returns Combined data
*/
const joinBody = (body: string, addition: string, separator: string = undefined): string => {
if (body) {
let separatorToUse = separator || "\n"
if (PATTERN_PUNCTUATIONS.exec(addition)) {
separatorToUse = ""
}
return `${trimEndSpace(body)}${separatorToUse}${trimEndSpace(addition)}`
}
return trimEndSpace(addition)
}
/**
* Combine one or more {@link Segment}
*
* @param segments Array of Segment objects to combine
* @param bodySeparator Character(s) to use to separate body data. If undefined, uses `\n`.
* @returns Combined segment where:
*
* - `startTime`: from first segment
* - `startTimeFormatted`: from first segment
* - `endTime`: from last segment
* - `endTimeFormatted`: from last segment
* - `speaker`: from first segment
* - `body`: combination of all segments
*/
const joinSegments = (segments: | Array<Segment>, bodySeparator: string = undefined): Segment => { |
const newSegment = { ...segments[0] }
segments.slice(1).forEach((segment) => {
newSegment.endTime = segment.endTime
newSegment.endTimeFormatted = TimestampFormatter.format(segment.endTime)
newSegment.body = joinBody(newSegment.body, segment.body, bodySeparator)
})
return newSegment
}
/**
* Type returned from combine functions
*/
type CombineResult = {
/**
* The updated segment with any changes applied
*/
segment: Segment
/**
* If true, the {@link segment} contains a {@link Segment} that should replace the prior segment instead of
* appending a new segment
*/
replace: boolean
/**
* Indicates if the combine rule was applied
*/
combined: boolean
}
/**
* Checks if the new and prior segments have the same speaker.
*
* If so, combines segments where:
* - `startTime`: from priorSegment
* - `startTimeFormatted`: from priorSegment
* - `endTime`: from newSegment
* - `endTimeFormatted`: from newSegment
* - `speaker`: from priorSegment
* - `body`: body of priorSegment with body of newSegment separated with space
*
* @param newSegment segment being created
* @param priorSegment prior parsed segment
* @param lastSpeaker last speaker name.
* Used when speaker in segment has been removed via {@link Options.speakerChange} rule
* @returns result of combination.
* If segments were combined, {@link CombineResult.replace} and {@link CombineResult.combined} set to true.
*/
const doCombineSpeaker = (newSegment: Segment, priorSegment: Segment, lastSpeaker: string): CombineResult => {
if (newSegment.speaker === priorSegment.speaker || newSegment.speaker === lastSpeaker) {
return {
segment: joinSegments([priorSegment, newSegment], " "),
replace: true,
combined: true,
}
}
return {
segment: newSegment,
replace: false,
combined: false,
}
}
/**
* Checks if the new and prior segments have the same speaker and combining body results in new body shorter than
* max length
*
* If so, combines segments where:
* - `startTime`: from priorSegment
* - `startTimeFormatted`: from priorSegment
* - `endTime`: from newSegment
* - `endTimeFormatted`: from newSegment
* - `speaker`: from priorSegment
* - `body`: body of priorSegment with body of newSegment separated with space
*
* @param newSegment segment being created
* @param priorSegment prior parsed segment
* @param maxLength maximum allowed length of combined body. If undefined, uses {@link DEFAULT_COMBINE_SEGMENTS_LENGTH}
* @param lastSpeaker last speaker name.
* Used when speaker in segment has been removed via {@link Options.speakerChange} rule
* @returns result of combination.
* If segments were combined, {@link CombineResult.replace} and {@link CombineResult.combined} set to true.
*/
const doCombineSegments = (
newSegment: Segment,
priorSegment: Segment,
maxLength: number,
lastSpeaker: string
): CombineResult => {
if (priorSegment === undefined) {
return {
segment: newSegment,
replace: false,
combined: false,
}
}
const combineSegmentsLength = maxLength || DEFAULT_COMBINE_SEGMENTS_LENGTH
if (
(newSegment.speaker === priorSegment.speaker || newSegment.speaker === lastSpeaker) &&
joinBody(priorSegment.body, newSegment.body, " ").length <= combineSegmentsLength
) {
return {
segment: joinSegments([priorSegment, newSegment], " "),
replace: true,
combined: true,
}
}
return {
segment: newSegment,
replace: false,
combined: false,
}
}
/**
* Checks if the new and prior segments have the same speaker, startTime and endTime.
*
* If so, combines segments where:
* - `startTime`: from priorSegment
* - `startTimeFormatted`: from priorSegment
* - `endTime`: from newSegment
* - `endTimeFormatted`: from newSegment
* - `speaker`: from priorSegment
* - `body`: body of priorSegment with body of newSegment separated with value of separator argument
*
* @param newSegment segment being created
* @param priorSegment prior parsed segment
* @param separator string to use to combine body values. If undefined, uses "\n"
* @param lastSpeaker last speaker name.
* Used when speaker in segment has been removed via {@link Options.speakerChange} rule
* @returns result of combination.
* If segments were combined, {@link CombineResult.replace} and {@link CombineResult.combined} set to true.
*/
const doCombineEqualTimes = (
newSegment: Segment,
priorSegment: Segment,
separator: string,
lastSpeaker: string
): CombineResult => {
const combineEqualTimesSeparator = separator || "\n"
if (
newSegment.startTime === priorSegment.startTime &&
newSegment.endTime === priorSegment.endTime &&
(newSegment.speaker === priorSegment.speaker || newSegment.speaker === lastSpeaker)
) {
return {
segment: joinSegments([priorSegment, newSegment], combineEqualTimesSeparator),
replace: true,
combined: true,
}
}
return {
segment: newSegment,
replace: false,
combined: false,
}
}
/**
* Checks if the new and prior segments have the same speaker. If so, sets the speaker value to undefined
*
* If so, combines segments where:
* - `startTime`: from priorSegment
* - `startTimeFormatted`: from priorSegment
* - `endTime`: from newSegment
* - `endTimeFormatted`: from newSegment
* - `speaker`: from newSegment if different from priorSegment else undefined
* - `body`: body of priorSegment with body of newSegment separated with space
*
* @param newSegment segment being created
* @param priorSegment prior parsed segment. For the first segment, this shall be undefined.
* @param lastSpeaker last speaker name.
* Used when speaker in segment has been removed via {@link Options.speakerChange} rule
* @returns result of combination.
* If segments were combined, {@link CombineResult.replace} set to false and {@link CombineResult.combined} set to true.
*/
const doSpeakerChange = (newSegment: Segment, priorSegment: Segment, lastSpeaker: string): CombineResult => {
const result: CombineResult = {
segment: newSegment,
replace: false,
combined: false,
}
if (priorSegment === undefined) {
if (newSegment.speaker === lastSpeaker) {
const segment: Segment = { ...newSegment }
segment.speaker = undefined
return {
segment,
replace: false,
combined: true,
}
}
return result
}
if (newSegment.speaker === undefined) {
return result
}
if (
newSegment.speaker === "" ||
newSegment.speaker === priorSegment.speaker ||
newSegment.speaker === lastSpeaker
) {
const segment: Segment = { ...newSegment }
segment.speaker = undefined
return {
segment,
replace: false,
combined: true,
}
}
return result
}
/**
* Determine how {@link Options.speakerChange is applied based an past options being applied}
*
* @param currentResult current result object from any prior options
* @param priorSegment prior parsed segment
* @param lastSpeaker last speaker name.
* @returns result of combination.
* If segments were combined, {@link CombineResult.replace} set to false and {@link CombineResult.combined} set to true.
*/
const applyOptionsAndDoSpeakerChange = (
currentResult: CombineResult,
priorSegment: Segment,
lastSpeaker: string
): CombineResult => {
const { combineSegments, combineEqualTimes } = Options
let result = currentResult
if (combineSegments && currentResult.combined && currentResult.replace) {
result = doSpeakerChange(currentResult.segment, undefined, undefined)
} else if (combineEqualTimes) {
if (result.combined && result.replace) {
result = doSpeakerChange(currentResult.segment, undefined, undefined)
} else {
result = doSpeakerChange(currentResult.segment, priorSegment, lastSpeaker)
}
} else {
result = doSpeakerChange(currentResult.segment, priorSegment, lastSpeaker)
}
if (result) {
result = {
segment: result.segment,
replace: currentResult.replace || result.replace,
combined: currentResult.combined || result.combined,
}
}
return result
}
/**
* Apply convert rules when no prior segment exits.
*
* NOTE: not all rules applicable when no prior segment
*
* @param newSegment segment before any rules options to it
* @param lastSpeaker last speaker name.
* Used when speaker in segment has been removed via {@link Options.speakerChange} rule
* @returns the updated segment info
*/
const doCombineNoPrior = (newSegment: Segment, lastSpeaker: string): CombineResult => {
const { speakerChange } = Options
let result: CombineResult = {
segment: newSegment,
replace: false,
combined: false,
}
if (speakerChange) {
result = doSpeakerChange(result.segment, undefined, lastSpeaker)
}
return result
}
/**
* Apply convert rules when prior segment exits.
*
* @param newSegment segment before any rules options to it
* @param priorSegment prior parsed segment
* @param lastSpeaker last speaker name.
* Used when speaker in segment has been removed via {@link Options.speakerChange} rule
* @returns the updated segment info
*/
const doCombineWithPrior = (newSegment: Segment, priorSegment: Segment, lastSpeaker: string): CombineResult => {
const {
combineEqualTimes,
combineEqualTimesSeparator,
combineSegments,
combineSegmentsLength,
combineSpeaker,
speakerChange,
} = Options
let result: CombineResult = {
segment: { ...newSegment },
replace: false,
combined: false,
}
let combinedSpeaker = false
if (combineSpeaker) {
result = doCombineSpeaker(result.segment, priorSegment, lastSpeaker)
combinedSpeaker = result.combined
}
if (!combinedSpeaker && combineEqualTimes) {
result = doCombineEqualTimes(result.segment, priorSegment, combineEqualTimesSeparator, lastSpeaker)
}
if (!combinedSpeaker && combineSegments) {
let combineResult
if (combineEqualTimes && result.combined) {
combineResult = doCombineSegments(result.segment, undefined, combineSegmentsLength, lastSpeaker)
} else {
combineResult = doCombineSegments(result.segment, priorSegment, combineSegmentsLength, lastSpeaker)
}
if (combineResult) {
result = {
segment: combineResult.segment,
replace: result.replace || combineResult.replace,
combined: result.combined || combineResult.combined,
}
}
}
if (speakerChange) {
result = applyOptionsAndDoSpeakerChange(result, priorSegment, lastSpeaker)
}
return result
}
/**
* Apply any options to the current segment
*
* @param newSegment segment before any rules options to it
* @param priorSegment prior parsed segment. For the first segment, this shall be undefined.
* @param lastSpeaker last speaker name.
* Used when speaker in segment has been removed via {@link Options.speakerChange} rule
* @returns the updated segment info
*/
const applyOptions = (newSegment: Segment, priorSegment: Segment, lastSpeaker: string = undefined): CombineResult => {
if (!Options.optionsSet()) {
return {
segment: newSegment,
replace: false,
combined: false,
}
}
let result: CombineResult
// if no prior segment, limited additional checking
if (priorSegment === undefined) {
result = doCombineNoPrior(newSegment, lastSpeaker)
} else {
result = doCombineWithPrior(newSegment, priorSegment, lastSpeaker)
}
return result
}
/**
* Get the last speaker name from the previously parsed segments
*
* @param priorSegment prior parsed segment
* @param priorSegments array of all previous segments
* @returns the name of the last speaker
*/
const getLastSpeaker = (priorSegment: Segment, priorSegments: Array<Segment>): string => {
let lastSpeaker
if (priorSegment) {
lastSpeaker = priorSegment.speaker
}
if (lastSpeaker === undefined && priorSegments.length > 0) {
lastSpeaker = priorSegments[0].speaker
for (let i = priorSegments.length - 1; i > 0; i--) {
if (priorSegments[i].speaker !== undefined) {
lastSpeaker = priorSegments[i].speaker
break
}
}
}
return lastSpeaker
}
/**
* Helper for adding segment to or updating last segment in array of segments
*
* @param newSegment segment to add or replace
* @param priorSegments array of all previous segments
* @returns updated array of segments with new segment added or last segment updated (per options)
*/
export const addSegment = (newSegment: Segment, priorSegments: Array<Segment>): Array<Segment> => {
const { speakerChange } = Options
const outSegments = priorSegments || []
const priorSegment = outSegments.length > 0 ? outSegments[outSegments.length - 1] : undefined
// don't worry about identifying the last speaker if speaker is not being removed by speakerChange
let lastSpeaker: string
if (speakerChange) {
lastSpeaker = getLastSpeaker(priorSegment, outSegments)
}
const newSegmentInfo = applyOptions(newSegment, priorSegment, lastSpeaker)
if (newSegmentInfo.replace && outSegments.length > 0) {
outSegments[outSegments.length - 1] = newSegmentInfo.segment
} else {
outSegments.push(newSegmentInfo.segment)
}
return outSegments
}
| src/segments.ts | stevencrader-transcriptator-75faa70 | [
{
"filename": "src/formats/json.ts",
"retrieved_chunk": "const parseDictSegmentsJSON = (data: JSONTranscript): Array<Segment> => {\n let outSegments: Array<Segment> = []\n data.segments.forEach((segment) => {\n outSegments = addSegment(\n {\n startTime: segment.startTime,\n startTimeFormatted: TimestampFormatter.format(segment.startTime),\n endTime: segment.endTime,\n endTimeFormatted: TimestampFormatter.format(segment.endTime),\n speaker: segment.speaker,",
"score": 29.887941823471294
},
{
"filename": "src/formats/json.ts",
"retrieved_chunk": "import { addSegment } from \"../segments\"\nimport { parseSpeaker } from \"../speaker\"\nimport { TimestampFormatter } from \"../timestamp\"\nimport { Segment } from \"../types\"\n/**\n * Define a segment/cue used in the JSONTranscript format\n */\nexport type JSONSegment = {\n /**\n * Time (in seconds) when segment starts",
"score": 23.70659332824911
},
{
"filename": "src/formats/json.ts",
"retrieved_chunk": " startTimeFormatted: TimestampFormatter.format(startTime),\n endTime,\n endTimeFormatted: TimestampFormatter.format(endTime),\n speaker,\n body: message,\n }\n if (Number.isNaN(segment.startTime)) {\n console.warn(`Computed start time is NaN: ${segment.startTime}`)\n return undefined\n }",
"score": 23.70526904096872
},
{
"filename": "src/formats/srt.ts",
"retrieved_chunk": "import { addSegment } from \"../segments\"\nimport { parseSpeaker } from \"../speaker\"\nimport { parseTimestamp, TimestampFormatter } from \"../timestamp\"\nimport { PATTERN_LINE_SEPARATOR, Segment } from \"../types\"\n/**\n * Define a segment/cue parsed from SRT file\n */\nexport type SRTSegment = {\n /**\n * Cue number",
"score": 23.224089560454395
},
{
"filename": "src/formats/srt.ts",
"retrieved_chunk": "}\n/**\n * Create Segment from lines containing an SRT segment/cue\n *\n * @param segmentLines Lines containing SRT data\n * @param lastSpeaker Name of last speaker. Will be used if no speaker found in `segmentLines`\n * @returns Created segment\n */\nconst createSegmentFromSRTLines = (segmentLines: Array<string>, lastSpeaker: string): Segment => {\n const srtSegment = parseSRTSegment(segmentLines)",
"score": 22.241542025327718
}
] | typescript | Array<Segment>, bodySeparator: string = undefined): Segment => { |
import { Options } from "./options"
import { TimestampFormatter } from "./timestamp"
import { DEFAULT_COMBINE_SEGMENTS_LENGTH, Segment } from "./types"
/**
* Regular Expression for detecting punctuation that should not be prefixed with a space
*/
const PATTERN_PUNCTUATIONS = /^ *[.,?!}\]>) *$]/
/**
* Regular Expression for detecting space characters at the end of a string
*/
const PATTERN_TRAILING_SPACE = /^ *$/
/**
* Remove any trailing space characters from data
*
* @param data text to trim
* @returns text with any trailing space character removed
*/
const trimEndSpace = (data: string): string => {
return data.replace(PATTERN_TRAILING_SPACE, "")
}
/**
* Append `addition` to `body` with the character(s) specified.
*
* If `addition` matches the {@link PATTERN_PUNCTUATIONS} pattern, no character is added before the additional data.
*
* @param body Current body text
* @param addition Additional text to add to `body`
* @param separator Character(s) to use to separate data. If undefined, uses `\n`.
* @returns Combined data
*/
const joinBody = (body: string, addition: string, separator: string = undefined): string => {
if (body) {
let separatorToUse = separator || "\n"
if (PATTERN_PUNCTUATIONS.exec(addition)) {
separatorToUse = ""
}
return `${trimEndSpace(body)}${separatorToUse}${trimEndSpace(addition)}`
}
return trimEndSpace(addition)
}
/**
* Combine one or more {@link Segment}
*
* @param segments Array of Segment objects to combine
* @param bodySeparator Character(s) to use to separate body data. If undefined, uses `\n`.
* @returns Combined segment where:
*
* - `startTime`: from first segment
* - `startTimeFormatted`: from first segment
* - `endTime`: from last segment
* - `endTimeFormatted`: from last segment
* - `speaker`: from first segment
* - `body`: combination of all segments
*/
const joinSegments = (segments: Array<Segment>, bodySeparator: string = undefined): Segment => {
const newSegment = { ...segments[0] }
segments.slice(1).forEach((segment) => {
newSegment.endTime = segment.endTime
newSegment.endTimeFormatted | = TimestampFormatter.format(segment.endTime)
newSegment.body = joinBody(newSegment.body, segment.body, bodySeparator)
})
return newSegment
} |
/**
* Type returned from combine functions
*/
type CombineResult = {
/**
* The updated segment with any changes applied
*/
segment: Segment
/**
* If true, the {@link segment} contains a {@link Segment} that should replace the prior segment instead of
* appending a new segment
*/
replace: boolean
/**
* Indicates if the combine rule was applied
*/
combined: boolean
}
/**
* Checks if the new and prior segments have the same speaker.
*
* If so, combines segments where:
* - `startTime`: from priorSegment
* - `startTimeFormatted`: from priorSegment
* - `endTime`: from newSegment
* - `endTimeFormatted`: from newSegment
* - `speaker`: from priorSegment
* - `body`: body of priorSegment with body of newSegment separated with space
*
* @param newSegment segment being created
* @param priorSegment prior parsed segment
* @param lastSpeaker last speaker name.
* Used when speaker in segment has been removed via {@link Options.speakerChange} rule
* @returns result of combination.
* If segments were combined, {@link CombineResult.replace} and {@link CombineResult.combined} set to true.
*/
const doCombineSpeaker = (newSegment: Segment, priorSegment: Segment, lastSpeaker: string): CombineResult => {
if (newSegment.speaker === priorSegment.speaker || newSegment.speaker === lastSpeaker) {
return {
segment: joinSegments([priorSegment, newSegment], " "),
replace: true,
combined: true,
}
}
return {
segment: newSegment,
replace: false,
combined: false,
}
}
/**
* Checks if the new and prior segments have the same speaker and combining body results in new body shorter than
* max length
*
* If so, combines segments where:
* - `startTime`: from priorSegment
* - `startTimeFormatted`: from priorSegment
* - `endTime`: from newSegment
* - `endTimeFormatted`: from newSegment
* - `speaker`: from priorSegment
* - `body`: body of priorSegment with body of newSegment separated with space
*
* @param newSegment segment being created
* @param priorSegment prior parsed segment
* @param maxLength maximum allowed length of combined body. If undefined, uses {@link DEFAULT_COMBINE_SEGMENTS_LENGTH}
* @param lastSpeaker last speaker name.
* Used when speaker in segment has been removed via {@link Options.speakerChange} rule
* @returns result of combination.
* If segments were combined, {@link CombineResult.replace} and {@link CombineResult.combined} set to true.
*/
const doCombineSegments = (
newSegment: Segment,
priorSegment: Segment,
maxLength: number,
lastSpeaker: string
): CombineResult => {
if (priorSegment === undefined) {
return {
segment: newSegment,
replace: false,
combined: false,
}
}
const combineSegmentsLength = maxLength || DEFAULT_COMBINE_SEGMENTS_LENGTH
if (
(newSegment.speaker === priorSegment.speaker || newSegment.speaker === lastSpeaker) &&
joinBody(priorSegment.body, newSegment.body, " ").length <= combineSegmentsLength
) {
return {
segment: joinSegments([priorSegment, newSegment], " "),
replace: true,
combined: true,
}
}
return {
segment: newSegment,
replace: false,
combined: false,
}
}
/**
* Checks if the new and prior segments have the same speaker, startTime and endTime.
*
* If so, combines segments where:
* - `startTime`: from priorSegment
* - `startTimeFormatted`: from priorSegment
* - `endTime`: from newSegment
* - `endTimeFormatted`: from newSegment
* - `speaker`: from priorSegment
* - `body`: body of priorSegment with body of newSegment separated with value of separator argument
*
* @param newSegment segment being created
* @param priorSegment prior parsed segment
* @param separator string to use to combine body values. If undefined, uses "\n"
* @param lastSpeaker last speaker name.
* Used when speaker in segment has been removed via {@link Options.speakerChange} rule
* @returns result of combination.
* If segments were combined, {@link CombineResult.replace} and {@link CombineResult.combined} set to true.
*/
const doCombineEqualTimes = (
newSegment: Segment,
priorSegment: Segment,
separator: string,
lastSpeaker: string
): CombineResult => {
const combineEqualTimesSeparator = separator || "\n"
if (
newSegment.startTime === priorSegment.startTime &&
newSegment.endTime === priorSegment.endTime &&
(newSegment.speaker === priorSegment.speaker || newSegment.speaker === lastSpeaker)
) {
return {
segment: joinSegments([priorSegment, newSegment], combineEqualTimesSeparator),
replace: true,
combined: true,
}
}
return {
segment: newSegment,
replace: false,
combined: false,
}
}
/**
* Checks if the new and prior segments have the same speaker. If so, sets the speaker value to undefined
*
* If so, combines segments where:
* - `startTime`: from priorSegment
* - `startTimeFormatted`: from priorSegment
* - `endTime`: from newSegment
* - `endTimeFormatted`: from newSegment
* - `speaker`: from newSegment if different from priorSegment else undefined
* - `body`: body of priorSegment with body of newSegment separated with space
*
* @param newSegment segment being created
* @param priorSegment prior parsed segment. For the first segment, this shall be undefined.
* @param lastSpeaker last speaker name.
* Used when speaker in segment has been removed via {@link Options.speakerChange} rule
* @returns result of combination.
* If segments were combined, {@link CombineResult.replace} set to false and {@link CombineResult.combined} set to true.
*/
const doSpeakerChange = (newSegment: Segment, priorSegment: Segment, lastSpeaker: string): CombineResult => {
const result: CombineResult = {
segment: newSegment,
replace: false,
combined: false,
}
if (priorSegment === undefined) {
if (newSegment.speaker === lastSpeaker) {
const segment: Segment = { ...newSegment }
segment.speaker = undefined
return {
segment,
replace: false,
combined: true,
}
}
return result
}
if (newSegment.speaker === undefined) {
return result
}
if (
newSegment.speaker === "" ||
newSegment.speaker === priorSegment.speaker ||
newSegment.speaker === lastSpeaker
) {
const segment: Segment = { ...newSegment }
segment.speaker = undefined
return {
segment,
replace: false,
combined: true,
}
}
return result
}
/**
* Determine how {@link Options.speakerChange is applied based an past options being applied}
*
* @param currentResult current result object from any prior options
* @param priorSegment prior parsed segment
* @param lastSpeaker last speaker name.
* @returns result of combination.
* If segments were combined, {@link CombineResult.replace} set to false and {@link CombineResult.combined} set to true.
*/
const applyOptionsAndDoSpeakerChange = (
currentResult: CombineResult,
priorSegment: Segment,
lastSpeaker: string
): CombineResult => {
const { combineSegments, combineEqualTimes } = Options
let result = currentResult
if (combineSegments && currentResult.combined && currentResult.replace) {
result = doSpeakerChange(currentResult.segment, undefined, undefined)
} else if (combineEqualTimes) {
if (result.combined && result.replace) {
result = doSpeakerChange(currentResult.segment, undefined, undefined)
} else {
result = doSpeakerChange(currentResult.segment, priorSegment, lastSpeaker)
}
} else {
result = doSpeakerChange(currentResult.segment, priorSegment, lastSpeaker)
}
if (result) {
result = {
segment: result.segment,
replace: currentResult.replace || result.replace,
combined: currentResult.combined || result.combined,
}
}
return result
}
/**
* Apply convert rules when no prior segment exits.
*
* NOTE: not all rules applicable when no prior segment
*
* @param newSegment segment before any rules options to it
* @param lastSpeaker last speaker name.
* Used when speaker in segment has been removed via {@link Options.speakerChange} rule
* @returns the updated segment info
*/
const doCombineNoPrior = (newSegment: Segment, lastSpeaker: string): CombineResult => {
const { speakerChange } = Options
let result: CombineResult = {
segment: newSegment,
replace: false,
combined: false,
}
if (speakerChange) {
result = doSpeakerChange(result.segment, undefined, lastSpeaker)
}
return result
}
/**
* Apply convert rules when prior segment exits.
*
* @param newSegment segment before any rules options to it
* @param priorSegment prior parsed segment
* @param lastSpeaker last speaker name.
* Used when speaker in segment has been removed via {@link Options.speakerChange} rule
* @returns the updated segment info
*/
const doCombineWithPrior = (newSegment: Segment, priorSegment: Segment, lastSpeaker: string): CombineResult => {
const {
combineEqualTimes,
combineEqualTimesSeparator,
combineSegments,
combineSegmentsLength,
combineSpeaker,
speakerChange,
} = Options
let result: CombineResult = {
segment: { ...newSegment },
replace: false,
combined: false,
}
let combinedSpeaker = false
if (combineSpeaker) {
result = doCombineSpeaker(result.segment, priorSegment, lastSpeaker)
combinedSpeaker = result.combined
}
if (!combinedSpeaker && combineEqualTimes) {
result = doCombineEqualTimes(result.segment, priorSegment, combineEqualTimesSeparator, lastSpeaker)
}
if (!combinedSpeaker && combineSegments) {
let combineResult
if (combineEqualTimes && result.combined) {
combineResult = doCombineSegments(result.segment, undefined, combineSegmentsLength, lastSpeaker)
} else {
combineResult = doCombineSegments(result.segment, priorSegment, combineSegmentsLength, lastSpeaker)
}
if (combineResult) {
result = {
segment: combineResult.segment,
replace: result.replace || combineResult.replace,
combined: result.combined || combineResult.combined,
}
}
}
if (speakerChange) {
result = applyOptionsAndDoSpeakerChange(result, priorSegment, lastSpeaker)
}
return result
}
/**
* Apply any options to the current segment
*
* @param newSegment segment before any rules options to it
* @param priorSegment prior parsed segment. For the first segment, this shall be undefined.
* @param lastSpeaker last speaker name.
* Used when speaker in segment has been removed via {@link Options.speakerChange} rule
* @returns the updated segment info
*/
const applyOptions = (newSegment: Segment, priorSegment: Segment, lastSpeaker: string = undefined): CombineResult => {
if (!Options.optionsSet()) {
return {
segment: newSegment,
replace: false,
combined: false,
}
}
let result: CombineResult
// if no prior segment, limited additional checking
if (priorSegment === undefined) {
result = doCombineNoPrior(newSegment, lastSpeaker)
} else {
result = doCombineWithPrior(newSegment, priorSegment, lastSpeaker)
}
return result
}
/**
* Get the last speaker name from the previously parsed segments
*
* @param priorSegment prior parsed segment
* @param priorSegments array of all previous segments
* @returns the name of the last speaker
*/
const getLastSpeaker = (priorSegment: Segment, priorSegments: Array<Segment>): string => {
let lastSpeaker
if (priorSegment) {
lastSpeaker = priorSegment.speaker
}
if (lastSpeaker === undefined && priorSegments.length > 0) {
lastSpeaker = priorSegments[0].speaker
for (let i = priorSegments.length - 1; i > 0; i--) {
if (priorSegments[i].speaker !== undefined) {
lastSpeaker = priorSegments[i].speaker
break
}
}
}
return lastSpeaker
}
/**
* Helper for adding segment to or updating last segment in array of segments
*
* @param newSegment segment to add or replace
* @param priorSegments array of all previous segments
* @returns updated array of segments with new segment added or last segment updated (per options)
*/
export const addSegment = (newSegment: Segment, priorSegments: Array<Segment>): Array<Segment> => {
const { speakerChange } = Options
const outSegments = priorSegments || []
const priorSegment = outSegments.length > 0 ? outSegments[outSegments.length - 1] : undefined
// don't worry about identifying the last speaker if speaker is not being removed by speakerChange
let lastSpeaker: string
if (speakerChange) {
lastSpeaker = getLastSpeaker(priorSegment, outSegments)
}
const newSegmentInfo = applyOptions(newSegment, priorSegment, lastSpeaker)
if (newSegmentInfo.replace && outSegments.length > 0) {
outSegments[outSegments.length - 1] = newSegmentInfo.segment
} else {
outSegments.push(newSegmentInfo.segment)
}
return outSegments
}
| src/segments.ts | stevencrader-transcriptator-75faa70 | [
{
"filename": "src/formats/json.ts",
"retrieved_chunk": "const parseDictSegmentsJSON = (data: JSONTranscript): Array<Segment> => {\n let outSegments: Array<Segment> = []\n data.segments.forEach((segment) => {\n outSegments = addSegment(\n {\n startTime: segment.startTime,\n startTimeFormatted: TimestampFormatter.format(segment.startTime),\n endTime: segment.endTime,\n endTimeFormatted: TimestampFormatter.format(segment.endTime),\n speaker: segment.speaker,",
"score": 35.402499039371065
},
{
"filename": "src/formats/json.ts",
"retrieved_chunk": " startTimeFormatted: TimestampFormatter.format(startTime),\n endTime,\n endTimeFormatted: TimestampFormatter.format(endTime),\n speaker,\n body: message,\n }\n if (Number.isNaN(segment.startTime)) {\n console.warn(`Computed start time is NaN: ${segment.startTime}`)\n return undefined\n }",
"score": 28.487159857687036
},
{
"filename": "src/formats/html.ts",
"retrieved_chunk": " if (totalSegments > 0) {\n outSegments[totalSegments - 1].endTime = segment.startTime\n outSegments[totalSegments - 1].endTimeFormatted = TimestampFormatter.format(\n outSegments[totalSegments - 1].endTime\n )\n }\n outSegments = addSegment(segment, outSegments)\n }\n // clear\n segmentPart = nextSegmentPart",
"score": 25.928014922448074
},
{
"filename": "src/formats/srt.ts",
"retrieved_chunk": " const calculatedSpeaker = srtSegment.speaker ? srtSegment.speaker : lastSpeaker\n return {\n startTime: srtSegment.startTime,\n startTimeFormatted: TimestampFormatter.format(srtSegment.startTime),\n endTime: srtSegment.endTime,\n endTimeFormatted: TimestampFormatter.format(srtSegment.endTime),\n speaker: calculatedSpeaker,\n body: srtSegment.body,\n }\n}",
"score": 25.080656335637464
},
{
"filename": "src/types.ts",
"retrieved_chunk": " endTime: number\n /**\n * Time when segment ends formatted as a string in the format HH:mm:SS.fff\n */\n endTimeFormatted: string\n /**\n * Name of speaker for `body`\n */\n speaker?: string\n /**",
"score": 19.841918914616585
}
] | typescript | = TimestampFormatter.format(segment.endTime)
newSegment.body = joinBody(newSegment.body, segment.body, bodySeparator)
})
return newSegment
} |
import { isHTML, parseHTML } from "./formats/html"
import { isJSON, parseJSON } from "./formats/json"
import { isSRT, parseSRT } from "./formats/srt"
import { isVTT, parseVTT } from "./formats/vtt"
import { Segment, TranscriptFormat } from "./types"
export { Segment, TranscriptFormat } from "./types"
export { TimestampFormatter, FormatterCallback } from "./timestamp"
export { Options, IOptions } from "./options"
/**
* Determines the format of transcript by inspecting the data
*
* @param data The transcript data
* @returns The determined transcript format
* @throws {TypeError} Cannot determine format of data or error parsing data
*/
export const determineFormat = (data: string): TranscriptFormat => {
const normalizedData = data.trim()
if (isVTT(normalizedData)) {
return TranscriptFormat.VTT
}
if (isJSON(normalizedData)) {
return TranscriptFormat.JSON
}
if (isHTML(normalizedData)) {
return TranscriptFormat.HTML
}
if (isSRT(normalizedData)) {
return TranscriptFormat.SRT
}
throw new TypeError(`Cannot determine format for data`)
}
/**
* Convert the data to an Array of {@link Segment}
*
* @param data The transcript data
* @param transcriptFormat The format of the data.
* @returns An Array of Segment objects from the parsed data
* @throws {TypeError} When `transcriptFormat` is unknown
*/
export const convertFile = (data: string, transcriptFormat: TranscriptFormat = undefined): Array<Segment> => {
const format = transcriptFormat ?? determineFormat(data)
const normalizedData = data.trimStart()
let outSegments: Array<Segment> = []
switch (format) {
case TranscriptFormat.HTML:
outSegments = parseHTML(normalizedData)
break
case TranscriptFormat.JSON:
outSegments = parseJSON(normalizedData)
break
case TranscriptFormat.SRT:
outSegments = parseSRT(normalizedData)
break
case TranscriptFormat.VTT:
| outSegments = parseVTT(normalizedData)
break
default:
throw new TypeError(`Unknown transcript format: ${format}`)
} |
return outSegments
}
| src/index.ts | stevencrader-transcriptator-75faa70 | [
{
"filename": "src/options.ts",
"retrieved_chunk": " case \"combineSpeaker\":\n verifyType(name, \"boolean\", value)\n this.combineSpeaker = <boolean>value\n break\n case \"speakerChange\":\n verifyType(name, \"boolean\", value)\n this.speakerChange = <boolean>value\n break\n default:\n break",
"score": 28.792076204972062
},
{
"filename": "src/options.ts",
"retrieved_chunk": " actual = this.combineSegments\n break\n case \"combineSegmentsLength\":\n actual = this.combineSegmentsLength\n break\n case \"combineSpeaker\":\n actual = this.combineSpeaker\n break\n case \"speakerChange\":\n actual = this.speakerChange",
"score": 27.51226067175024
},
{
"filename": "src/options.ts",
"retrieved_chunk": " public getOptionByName = (name: string): boolean | string | number => {\n let actual\n switch (name) {\n case \"combineEqualTimes\":\n actual = this.combineEqualTimes\n break\n case \"combineEqualTimesSeparator\":\n actual = this.combineEqualTimesSeparator\n break\n case \"combineSegments\":",
"score": 24.762056057726976
},
{
"filename": "src/options.ts",
"retrieved_chunk": " this.combineEqualTimesSeparator = <string>value\n break\n case \"combineSegments\":\n verifyType(name, \"boolean\", value)\n this.combineSegments = <boolean>value\n break\n case \"combineSegmentsLength\":\n verifyType(name, \"number\", value)\n this.combineSegmentsLength = <number>value\n break",
"score": 24.74511511028429
},
{
"filename": "src/formats/vtt.ts",
"retrieved_chunk": " * @throws {TypeError} When `data` is not valid VTT format\n */\nexport const parseVTT = (data: string): Array<Segment> => {\n if (!isVTT(data)) {\n throw new TypeError(`Data is not valid VTT format`)\n }\n // format is similar enough to SRT to be parsed by the same parser\n // Remove WEBVTT header first\n return parseSRT(data.substring(WEBVTT_HEADER.length).trimStart())\n}",
"score": 22.040460267511147
}
] | typescript | outSegments = parseVTT(normalizedData)
break
default:
throw new TypeError(`Unknown transcript format: ${format}`)
} |
import { addSegment } from "../segments"
import { parseSpeaker } from "../speaker"
import { parseTimestamp, TimestampFormatter } from "../timestamp"
import { PATTERN_LINE_SEPARATOR, Segment } from "../types"
/**
* Define a segment/cue parsed from SRT file
*/
export type SRTSegment = {
/**
* Cue number
*/
index: number
/**
* Time (in seconds) when segment starts
*/
startTime: number
/**
* Time (in seconds) when segment ends
*/
endTime: number
/**
* Name of speaker for `body`
*/
speaker: string
/**
* Text of transcript for segment
*/
body: string
}
/**
* Parse lines looking for data to be SRT format
*
* @param lines Lines containing SRT data
* @returns Parsed segment
* @throws {Error} When no non-empty strings in `lines`
* @throws {Error} When the minimum required number of lines is not received
* @throws {Error} When segment lines does not start with a number
* @throws {Error} When second segment line does not follow the timestamp format
*/
export const parseSRTSegment = (lines: Array<string>): SRTSegment => {
do {
if (lines.length === 0) {
throw new Error("SRT segment lines empty")
} else if (lines[0].trim() === "") {
lines.shift()
} else {
break
}
} while (lines.length > 0)
if (lines.length < 3) {
throw new Error(`SRT requires at least 3 lines, ${lines.length} received`)
}
const index = parseInt(lines[0], 10)
if (!index) {
throw new Error(`First line of SRT segment is not a number`)
}
const timestampLine = lines[1]
if (!timestampLine.includes("-->")) {
throw new Error(`SRT timestamp line does not include --> separator`)
}
const timestampParts = timestampLine.split("-->")
if (timestampParts.length !== 2) {
throw new Error(`SRT timestamp line contains more than 2 --> separators`)
}
const startTime = parseTimestamp(timestampParts[0].trim())
const endTime = parseTimestamp(timestampParts[1].trim())
let bodyLines = lines.slice(2)
const emptyLineIndex = bodyLines.findIndex((v) => v.trim() === "")
if (emptyLineIndex > 0) {
bodyLines = bodyLines.slice(0, emptyLineIndex)
}
const { | speaker, message } = parseSpeaker(bodyLines.shift())
bodyLines = [message].concat(bodyLines)
return { |
startTime,
endTime,
speaker,
body: bodyLines.join("\n"),
index,
}
}
/**
* Create Segment from lines containing an SRT segment/cue
*
* @param segmentLines Lines containing SRT data
* @param lastSpeaker Name of last speaker. Will be used if no speaker found in `segmentLines`
* @returns Created segment
*/
const createSegmentFromSRTLines = (segmentLines: Array<string>, lastSpeaker: string): Segment => {
const srtSegment = parseSRTSegment(segmentLines)
const calculatedSpeaker = srtSegment.speaker ? srtSegment.speaker : lastSpeaker
return {
startTime: srtSegment.startTime,
startTimeFormatted: TimestampFormatter.format(srtSegment.startTime),
endTime: srtSegment.endTime,
endTimeFormatted: TimestampFormatter.format(srtSegment.endTime),
speaker: calculatedSpeaker,
body: srtSegment.body,
}
}
/**
* Determines if the value of data is a valid SRT transcript format
*
* @param data The transcript data
* @returns True: data is valid SRT transcript format
*/
export const isSRT = (data: string): boolean => {
try {
return parseSRTSegment(data.split(PATTERN_LINE_SEPARATOR).slice(0, 20)) !== undefined
} catch (e) {
return false
}
}
/**
* Parse SRT data to an Array of {@link Segment}
*
* @param data The transcript data
* @returns An array of Segments from the parsed data
* @throws {TypeError} When `data` is not valid SRT format
*/
export const parseSRT = (data: string): Array<Segment> => {
if (!isSRT(data)) {
throw new TypeError(`Data is not valid SRT format`)
}
let outSegments: Array<Segment> = []
let lastSpeaker = ""
let segmentLines = []
data.split(PATTERN_LINE_SEPARATOR).forEach((line, count) => {
// separator line found, handle previous data
if (line.trim() === "") {
// handle consecutive multiple blank lines
if (segmentLines.length !== 0) {
try {
outSegments = addSegment(createSegmentFromSRTLines(segmentLines, lastSpeaker), outSegments)
lastSpeaker = outSegments[outSegments.length - 1].speaker
} catch (e) {
console.error(`Error parsing SRT segment lines (source line ${count}): ${e}`)
console.error(segmentLines)
}
}
segmentLines = [] // clear buffer
} else {
segmentLines.push(line)
}
})
// handle data when trailing line not included
if (segmentLines.length !== 0) {
try {
outSegments = addSegment(createSegmentFromSRTLines(segmentLines, lastSpeaker), outSegments)
lastSpeaker = outSegments[outSegments.length - 1].speaker
} catch (e) {
console.error(`Error parsing final SRT segment lines: ${e}`)
console.error(segmentLines)
}
}
return outSegments
}
| src/formats/srt.ts | stevencrader-transcriptator-75faa70 | [
{
"filename": "src/speaker.ts",
"retrieved_chunk": " * @returns The speaker (if found) and the remaining string\n */\nexport const parseSpeaker = (data: string): { speaker: string; message: string } => {\n let speaker = \"\"\n let message = data\n const speakerMatch = PATTERN_SPEAKER.exec(data)\n if (speakerMatch !== null) {\n speaker = speakerMatch.groups.speaker\n message = speakerMatch.groups.body\n }",
"score": 19.7293727336246
},
{
"filename": "src/segments.ts",
"retrieved_chunk": " * - `endTimeFormatted`: from last segment\n * - `speaker`: from first segment\n * - `body`: combination of all segments\n */\nconst joinSegments = (segments: Array<Segment>, bodySeparator: string = undefined): Segment => {\n const newSegment = { ...segments[0] }\n segments.slice(1).forEach((segment) => {\n newSegment.endTime = segment.endTime\n newSegment.endTimeFormatted = TimestampFormatter.format(segment.endTime)\n newSegment.body = joinBody(newSegment.body, segment.body, bodySeparator)",
"score": 18.102044434088175
},
{
"filename": "src/timestamp.ts",
"retrieved_chunk": " timestamp = parseInt(splits[0], 10) * 60 * 60 + parseInt(splits[1], 10) * 60 + parseInt(splits[2], 10)\n } else if (splitLength === 2) {\n timestamp = parseInt(splits[0], 10) * 60 + parseInt(splits[1], 10)\n } else if (splitLength === 1) {\n timestamp = parseInt(splits[0], 10)\n }\n let ms = parseInt(match.groups.ms, 10)\n if (Number.isNaN(ms)) {\n ms = 0\n } else if (ms !== 0) {",
"score": 16.848916386655713
},
{
"filename": "src/speaker.ts",
"retrieved_chunk": " return { speaker, message }\n}",
"score": 13.907893895857681
},
{
"filename": "src/timestamp.ts",
"retrieved_chunk": " }\n const match = PATTERN_TIMESTAMP.exec(value.trim())\n if (match === null) {\n throw new TypeError(`Not enough separator fields in timestamp string`)\n }\n const { time } = match.groups\n const splits = time.split(\":\")\n const splitLength = splits.length\n let timestamp = 0\n if (splitLength === 3) {",
"score": 13.778623388345359
}
] | typescript | speaker, message } = parseSpeaker(bodyLines.shift())
bodyLines = [message].concat(bodyLines)
return { |
import { addSegment } from "../segments"
import { parseSpeaker } from "../speaker"
import { TimestampFormatter } from "../timestamp"
import { Segment } from "../types"
/**
* Define a segment/cue used in the JSONTranscript format
*/
export type JSONSegment = {
/**
* Time (in seconds) when segment starts
*/
startTime: number
/**
* Time (in seconds) when segment ends
*/
endTime: number
/**
* Name of speaker for `body`
*/
speaker?: string
/**
* Text of transcript for segment
*/
body: string
}
/**
* Define the JSON transcript format
*/
export type JSONTranscript = {
/**
* Version of file format
*/
version: string
/**
* Segment data
*/
segments: Array<JSONSegment>
}
/**
* Define the JSON transcript Segment format
*/
export type SubtitleSegment = {
/**
* Time (in milliseconds) when segment starts
*/
start: number
/**
* Time (in milliseconds) when segment ends
*/
end: number
/**
* Text of transcript for segment
*/
text: string
}
/**
* Determines if the value of data is a valid JSON transcript format
*
* @param data The transcript data
* @returns True: data is valid JSON transcript format
*/
export const isJSON = (data: string): boolean => {
return (data.startsWith("{") && data.endsWith("}")) || (data.startsWith("[") && data.endsWith("]"))
}
/**
* Parse JSON data where segments are in the `segments` Array and in the {@link JSONSegment} format
*
* @param data Parsed JSON data
* @returns An array of Segments from the parsed data
*/
const parseDictSegmentsJSON = (data: JSONTranscript): Array<Segment> => {
let outSegments: Array<Segment> = []
data.segments.forEach((segment) => {
outSegments = addSegment(
{
startTime: segment.startTime,
startTimeFormatted: TimestampFormatter.format(segment.startTime),
endTime: segment.endTime,
endTimeFormatted: TimestampFormatter.format(segment.endTime),
speaker: segment.speaker,
body: segment.body,
},
outSegments
)
})
return outSegments
}
/**
* Parse JSON data where top level item is a dict/object
*
* @param data The transcript data
* @returns An array of Segments from the parsed data
* @throws {TypeError} When JSON data does not match one of the valid formats
*/
const parseDictJSON = (data: object): Array<Segment> => {
let outSegments: Array<Segment> = []
if (Object.keys(data).length === 0) {
return outSegments
}
if ("segments" in data) {
outSegments = parseDictSegmentsJSON(data as JSONTranscript)
} else {
throw new TypeError(`Unknown JSON dict transcript format`)
}
return outSegments
}
/**
* Convert {@link SubtitleSegment} to the {@link Segment} format used here
*
* @param data Segment parsed from JSON data
* @returns Segment representing `data`.
* Returns {@link undefined} when data does not match {@link SubtitleSegment} format.
*/
const getSegmentFromSubtitle = (data: SubtitleSegment): Segment => {
if ("start" in data && "end" in data && "text" in data) {
const { speaker, message } = parseSpeaker(data.text)
const startTime = data.start / 1000
const endTime = data.end / 1000
const segment: Segment = {
startTime,
startTimeFormatted: TimestampFormatter.format(startTime),
endTime,
endTimeFormatted: TimestampFormatter.format(endTime),
speaker,
body: message,
}
| if (Number.isNaN(segment.startTime)) { |
console.warn(`Computed start time is NaN: ${segment.startTime}`)
return undefined
}
if (Number.isNaN(segment.endTime)) {
console.warn(`Computed end time is NaN: ${segment.endTime}`)
return undefined
}
return segment
}
return undefined
}
/**
* Parse JSON data where items in data are in the {@link SubtitleSegment} format
*
* @param data Parsed JSON data
* @returns An array of Segments from the parsed data
* @throws {TypeError} When item in `data` does not match the {@link SubtitleSegment} format
*/
const parseListJSONSubtitle = (data: Array<SubtitleSegment>): Array<Segment> => {
let outSegments: Array<Segment> = []
let lastSpeaker = ""
data.forEach((subtitle, count) => {
const subtitleSegment = getSegmentFromSubtitle(subtitle)
if (subtitleSegment !== undefined) {
lastSpeaker = subtitleSegment.speaker ? subtitleSegment.speaker : lastSpeaker
subtitleSegment.speaker = lastSpeaker
outSegments = addSegment(subtitleSegment, outSegments)
} else {
throw new TypeError(`Unable to parse segment for item ${count}`)
}
})
return outSegments
}
/**
* Parse JSON data where top level item is an Array
*
* @param data The transcript data
* @returns An array of Segments from the parsed data
* @throws {TypeError} When JSON data does not match one of the valid formats
*/
const parseListJSON = (data: Array<unknown>): Array<Segment> => {
let outSegments: Array<Segment> = []
if (data.length === 0) {
return outSegments
}
const subtitleSegment = getSegmentFromSubtitle(data[0] as SubtitleSegment)
if (subtitleSegment !== undefined) {
outSegments = parseListJSONSubtitle(data as Array<SubtitleSegment>)
} else {
throw new TypeError(`Unknown JSON list transcript format`)
}
return outSegments
}
/**
* Parse JSON data to an Array of {@link Segment}
*
* @param data The transcript data
* @returns An array of Segments from the parsed data
* @throws {TypeError} When `data` is not valid JSON format
*/
export const parseJSON = (data: string): Array<Segment> => {
const dataTrimmed = data.trim()
let outSegments: Array<Segment> = []
if (!isJSON(dataTrimmed)) {
throw new TypeError(`Data is not valid JSON format`)
}
let parsed: object | Array<unknown>
try {
parsed = JSON.parse(data)
} catch (e) {
throw new TypeError(`Data is not valid JSON: ${e}`)
}
if (parsed.constructor === Object) {
outSegments = parseDictJSON(parsed)
} else if (parsed.constructor === Array) {
outSegments = parseListJSON(parsed)
}
return outSegments
}
| src/formats/json.ts | stevencrader-transcriptator-75faa70 | [
{
"filename": "src/formats/srt.ts",
"retrieved_chunk": " const calculatedSpeaker = srtSegment.speaker ? srtSegment.speaker : lastSpeaker\n return {\n startTime: srtSegment.startTime,\n startTimeFormatted: TimestampFormatter.format(srtSegment.startTime),\n endTime: srtSegment.endTime,\n endTimeFormatted: TimestampFormatter.format(srtSegment.endTime),\n speaker: calculatedSpeaker,\n body: srtSegment.body,\n }\n}",
"score": 41.63961798562262
},
{
"filename": "src/formats/html.ts",
"retrieved_chunk": " if (totalSegments > 0) {\n outSegments[totalSegments - 1].endTime = segment.startTime\n outSegments[totalSegments - 1].endTimeFormatted = TimestampFormatter.format(\n outSegments[totalSegments - 1].endTime\n )\n }\n outSegments = addSegment(segment, outSegments)\n }\n // clear\n segmentPart = nextSegmentPart",
"score": 28.41762403281177
},
{
"filename": "src/formats/html.ts",
"retrieved_chunk": " * @param lastSpeaker Name of last speaker. Will be used if no speaker found in `segmentLines`\n * @returns Created segment\n */\nconst createSegmentFromSegmentPart = (segmentPart: HTMLSegmentPart, lastSpeaker: string): Segment => {\n const calculatedSpeaker = segmentPart.cite ? segmentPart.cite : lastSpeaker\n const startTime = parseTimestamp(segmentPart.time)\n return {\n startTime,\n startTimeFormatted: TimestampFormatter.format(startTime),\n endTime: 0,",
"score": 26.812150675580043
},
{
"filename": "src/formats/srt.ts",
"retrieved_chunk": " }\n const { speaker, message } = parseSpeaker(bodyLines.shift())\n bodyLines = [message].concat(bodyLines)\n return {\n startTime,\n endTime,\n speaker,\n body: bodyLines.join(\"\\n\"),\n index,\n }",
"score": 24.54479777009283
},
{
"filename": "src/segments.ts",
"retrieved_chunk": " * - `endTimeFormatted`: from last segment\n * - `speaker`: from first segment\n * - `body`: combination of all segments\n */\nconst joinSegments = (segments: Array<Segment>, bodySeparator: string = undefined): Segment => {\n const newSegment = { ...segments[0] }\n segments.slice(1).forEach((segment) => {\n newSegment.endTime = segment.endTime\n newSegment.endTimeFormatted = TimestampFormatter.format(segment.endTime)\n newSegment.body = joinBody(newSegment.body, segment.body, bodySeparator)",
"score": 24.49985072315055
}
] | typescript | if (Number.isNaN(segment.startTime)) { |
import { addSegment } from "../segments"
import { parseSpeaker } from "../speaker"
import { parseTimestamp, TimestampFormatter } from "../timestamp"
import { PATTERN_LINE_SEPARATOR, Segment } from "../types"
/**
* Define a segment/cue parsed from SRT file
*/
export type SRTSegment = {
/**
* Cue number
*/
index: number
/**
* Time (in seconds) when segment starts
*/
startTime: number
/**
* Time (in seconds) when segment ends
*/
endTime: number
/**
* Name of speaker for `body`
*/
speaker: string
/**
* Text of transcript for segment
*/
body: string
}
/**
* Parse lines looking for data to be SRT format
*
* @param lines Lines containing SRT data
* @returns Parsed segment
* @throws {Error} When no non-empty strings in `lines`
* @throws {Error} When the minimum required number of lines is not received
* @throws {Error} When segment lines does not start with a number
* @throws {Error} When second segment line does not follow the timestamp format
*/
export const parseSRTSegment = (lines: Array<string>): SRTSegment => {
do {
if (lines.length === 0) {
throw new Error("SRT segment lines empty")
} else if (lines[0].trim() === "") {
lines.shift()
} else {
break
}
} while (lines.length > 0)
if (lines.length < 3) {
throw new Error(`SRT requires at least 3 lines, ${lines.length} received`)
}
const index = parseInt(lines[0], 10)
if (!index) {
throw new Error(`First line of SRT segment is not a number`)
}
const timestampLine = lines[1]
if (!timestampLine.includes("-->")) {
throw new Error(`SRT timestamp line does not include --> separator`)
}
const timestampParts = timestampLine.split("-->")
if (timestampParts.length !== 2) {
throw new Error(`SRT timestamp line contains more than 2 --> separators`)
}
const startTime = parseTimestamp(timestampParts[0].trim())
const endTime = parseTimestamp(timestampParts[1].trim())
let bodyLines = lines.slice(2)
const emptyLineIndex = bodyLines.findIndex((v) => v.trim() === "")
if (emptyLineIndex > 0) {
bodyLines = bodyLines.slice(0, emptyLineIndex)
}
const { speaker, message } = | parseSpeaker(bodyLines.shift())
bodyLines = [message].concat(bodyLines)
return { |
startTime,
endTime,
speaker,
body: bodyLines.join("\n"),
index,
}
}
/**
* Create Segment from lines containing an SRT segment/cue
*
* @param segmentLines Lines containing SRT data
* @param lastSpeaker Name of last speaker. Will be used if no speaker found in `segmentLines`
* @returns Created segment
*/
const createSegmentFromSRTLines = (segmentLines: Array<string>, lastSpeaker: string): Segment => {
const srtSegment = parseSRTSegment(segmentLines)
const calculatedSpeaker = srtSegment.speaker ? srtSegment.speaker : lastSpeaker
return {
startTime: srtSegment.startTime,
startTimeFormatted: TimestampFormatter.format(srtSegment.startTime),
endTime: srtSegment.endTime,
endTimeFormatted: TimestampFormatter.format(srtSegment.endTime),
speaker: calculatedSpeaker,
body: srtSegment.body,
}
}
/**
* Determines if the value of data is a valid SRT transcript format
*
* @param data The transcript data
* @returns True: data is valid SRT transcript format
*/
export const isSRT = (data: string): boolean => {
try {
return parseSRTSegment(data.split(PATTERN_LINE_SEPARATOR).slice(0, 20)) !== undefined
} catch (e) {
return false
}
}
/**
* Parse SRT data to an Array of {@link Segment}
*
* @param data The transcript data
* @returns An array of Segments from the parsed data
* @throws {TypeError} When `data` is not valid SRT format
*/
export const parseSRT = (data: string): Array<Segment> => {
if (!isSRT(data)) {
throw new TypeError(`Data is not valid SRT format`)
}
let outSegments: Array<Segment> = []
let lastSpeaker = ""
let segmentLines = []
data.split(PATTERN_LINE_SEPARATOR).forEach((line, count) => {
// separator line found, handle previous data
if (line.trim() === "") {
// handle consecutive multiple blank lines
if (segmentLines.length !== 0) {
try {
outSegments = addSegment(createSegmentFromSRTLines(segmentLines, lastSpeaker), outSegments)
lastSpeaker = outSegments[outSegments.length - 1].speaker
} catch (e) {
console.error(`Error parsing SRT segment lines (source line ${count}): ${e}`)
console.error(segmentLines)
}
}
segmentLines = [] // clear buffer
} else {
segmentLines.push(line)
}
})
// handle data when trailing line not included
if (segmentLines.length !== 0) {
try {
outSegments = addSegment(createSegmentFromSRTLines(segmentLines, lastSpeaker), outSegments)
lastSpeaker = outSegments[outSegments.length - 1].speaker
} catch (e) {
console.error(`Error parsing final SRT segment lines: ${e}`)
console.error(segmentLines)
}
}
return outSegments
}
| src/formats/srt.ts | stevencrader-transcriptator-75faa70 | [
{
"filename": "src/speaker.ts",
"retrieved_chunk": " * @returns The speaker (if found) and the remaining string\n */\nexport const parseSpeaker = (data: string): { speaker: string; message: string } => {\n let speaker = \"\"\n let message = data\n const speakerMatch = PATTERN_SPEAKER.exec(data)\n if (speakerMatch !== null) {\n speaker = speakerMatch.groups.speaker\n message = speakerMatch.groups.body\n }",
"score": 19.7293727336246
},
{
"filename": "src/segments.ts",
"retrieved_chunk": " * - `endTimeFormatted`: from last segment\n * - `speaker`: from first segment\n * - `body`: combination of all segments\n */\nconst joinSegments = (segments: Array<Segment>, bodySeparator: string = undefined): Segment => {\n const newSegment = { ...segments[0] }\n segments.slice(1).forEach((segment) => {\n newSegment.endTime = segment.endTime\n newSegment.endTimeFormatted = TimestampFormatter.format(segment.endTime)\n newSegment.body = joinBody(newSegment.body, segment.body, bodySeparator)",
"score": 18.102044434088175
},
{
"filename": "src/timestamp.ts",
"retrieved_chunk": " timestamp = parseInt(splits[0], 10) * 60 * 60 + parseInt(splits[1], 10) * 60 + parseInt(splits[2], 10)\n } else if (splitLength === 2) {\n timestamp = parseInt(splits[0], 10) * 60 + parseInt(splits[1], 10)\n } else if (splitLength === 1) {\n timestamp = parseInt(splits[0], 10)\n }\n let ms = parseInt(match.groups.ms, 10)\n if (Number.isNaN(ms)) {\n ms = 0\n } else if (ms !== 0) {",
"score": 16.848916386655713
},
{
"filename": "src/speaker.ts",
"retrieved_chunk": " return { speaker, message }\n}",
"score": 13.907893895857681
},
{
"filename": "src/timestamp.ts",
"retrieved_chunk": " }\n const match = PATTERN_TIMESTAMP.exec(value.trim())\n if (match === null) {\n throw new TypeError(`Not enough separator fields in timestamp string`)\n }\n const { time } = match.groups\n const splits = time.split(\":\")\n const splitLength = splits.length\n let timestamp = 0\n if (splitLength === 3) {",
"score": 13.778623388345359
}
] | typescript | parseSpeaker(bodyLines.shift())
bodyLines = [message].concat(bodyLines)
return { |
import { pascalCase } from 'change-case'
import { AlgoAppSpec, CallConfig, CallConfigValue } from '../../schema/application'
export const BARE_CALL = Symbol('bare')
export type MethodIdentifier = string | typeof BARE_CALL
export type MethodList = Array<MethodIdentifier>
export type CallConfigSummary = {
createMethods: MethodList
callMethods: MethodList
deleteMethods: MethodList
updateMethods: MethodList
optInMethods: MethodList
closeOutMethods: MethodList
}
export const getCallConfigSummary = (app: AlgoAppSpec) => {
const result: CallConfigSummary = {
createMethods: [],
callMethods: [],
deleteMethods: [],
updateMethods: [],
optInMethods: [],
closeOutMethods: [],
}
if (app.bare_call_config) {
addToConfig(result, BARE_CALL, app.bare_call_config)
}
if (app.hints) {
for (const [method, hints] of Object.entries(app.hints)) {
if (hints.call_config) {
addToConfig(result, method, hints.call_config)
}
}
}
return result
}
export const getCreateOnComplete = (app: AlgoAppSpec, method: MethodIdentifier) => {
const callConfig = method === BARE_CALL ? app.bare_call_config : app.hints?.[method]?.call_config
if (!callConfig) {
return ''
}
const hasNoOp = callConfig.no_op === 'ALL' || callConfig.no_op === 'CREATE'
return `{ onCompleteAction${hasNoOp ? '?' : ''}: ${getCreateOnCompleteTypes(callConfig)} }`
}
const getCreateOnCompleteTypes = (config: CallConfig) => {
return Object.keys(config)
.map((oc) => oc as keyof CallConfig)
.filter((oc) => config[oc] === 'ALL' || config[oc] === 'CREATE')
.map | ((oc) => `'${oc}' | OnApplicationComplete.${pascalCase(oc)}OC`)
.join(' | ')
} |
const addToConfig = (result: CallConfigSummary, method: MethodIdentifier, config: CallConfig) => {
if (hasCall(config.no_op)) {
result.callMethods.push(method)
}
if (
hasCreate(config.no_op) ||
hasCreate(config.opt_in) ||
hasCreate(config.close_out) ||
hasCreate(config.update_application) ||
hasCreate(config.delete_application)
) {
result.createMethods.push(method)
}
if (hasCall(config.delete_application)) {
result.deleteMethods.push(method)
}
if (hasCall(config.update_application)) {
result.updateMethods.push(method)
}
if (hasCall(config.opt_in)) {
result.optInMethods.push(method)
}
if (hasCall(config.close_out)) {
result.closeOutMethods.push(method)
}
}
const hasCall = (config: CallConfigValue | undefined) => {
return config === 'CALL' || config === 'ALL'
}
const hasCreate = (config: CallConfigValue | undefined) => {
return config === 'CREATE' || config === 'ALL'
}
| src/client/helpers/get-call-config-summary.ts | algorandfoundation-algokit-client-generator-ts-2de43ed | [
{
"filename": "src/client/deploy-types.ts",
"retrieved_chunk": " ? `(${Object.entries(callConfig)\n .filter(([_, value]) => value === 'ALL' || value === 'CREATE')\n .map(([oc]) => OnCompleteCodeMap[oc as keyof CallConfig])\n .join(' | ')})`\n : {}\n return {\n type: onCompleteType,\n isOptional: hasNoOp,\n }\n}",
"score": 114.37782005451552
},
{
"filename": "src/client/deploy-types.ts",
"retrieved_chunk": "import { DecIndent, DecIndentAndCloseBlock, DocumentParts, IncIndent, jsDoc, NewLine } from '../output/writer'\nimport { makeSafeTypeIdentifier } from '../util/sanitization'\nimport { BARE_CALL, MethodIdentifier } from './helpers/get-call-config-summary'\nimport { GeneratorContext } from './generator-context'\nimport { AlgoAppSpec, CallConfig } from '../schema/application'\nimport { OnCompleteCodeMap } from './utility-types'\nexport function getCreateOnCompleteOptions(method: MethodIdentifier, app: AlgoAppSpec) {\n const callConfig = method === BARE_CALL ? app.bare_call_config : app.hints?.[method]?.call_config\n const hasNoOp = callConfig?.no_op === 'ALL' || callConfig?.no_op === 'CREATE'\n const onCompleteType = callConfig",
"score": 24.516370939133193
},
{
"filename": "src/client/generator-context.ts",
"retrieved_chunk": "import { AlgoAppSpec } from '../schema/application'\nimport { CallConfigSummary, getCallConfigSummary } from './helpers/get-call-config-summary'\nimport { makeSafeTypeIdentifier } from '../util/sanitization'\nimport * as algokit from '@algorandfoundation/algokit-utils'\nexport type GeneratorContext = {\n app: AlgoAppSpec\n name: string\n callConfig: CallConfigSummary\n methodSignatureToUniqueName: Record<string, string>\n}",
"score": 14.264953656164835
},
{
"filename": "src/client/helpers/get-equivalent-type.ts",
"retrieved_chunk": " }\n if (abiType instanceof ABITupleType) {\n return `[${abiType.childTypes.map((c) => abiTypeToTs(c, ioType)).join(', ')}]`\n }\n if (abiType instanceof ABIByteType) {\n return 'number'\n }\n if (abiType instanceof ABIStringType) {\n return 'string'\n }",
"score": 13.726596840148826
},
{
"filename": "src/client/call-composer.ts",
"retrieved_chunk": "import { DecIndent, DecIndentAndCloseBlock, DocumentParts, IncIndent } from '../output/writer'\nimport { GeneratorContext } from './generator-context'\nimport * as algokit from '@algorandfoundation/algokit-utils'\nimport { makeSafeMethodIdentifier } from '../util/sanitization'\nimport { BARE_CALL, MethodList } from './helpers/get-call-config-summary'\nimport { getCreateOnCompleteOptions } from './deploy-types'\nexport function* composeMethod(ctx: GeneratorContext): DocumentParts {\n const { name, callConfig } = ctx\n yield `public compose(): ${name}Composer {`\n yield IncIndent",
"score": 12.14335233472548
}
] | typescript | ((oc) => `'${oc}' | OnApplicationComplete.${pascalCase(oc)}OC`)
.join(' | ')
} |
import { addSegment } from "../segments"
import { parseSpeaker } from "../speaker"
import { TimestampFormatter } from "../timestamp"
import { Segment } from "../types"
/**
* Define a segment/cue used in the JSONTranscript format
*/
export type JSONSegment = {
/**
* Time (in seconds) when segment starts
*/
startTime: number
/**
* Time (in seconds) when segment ends
*/
endTime: number
/**
* Name of speaker for `body`
*/
speaker?: string
/**
* Text of transcript for segment
*/
body: string
}
/**
* Define the JSON transcript format
*/
export type JSONTranscript = {
/**
* Version of file format
*/
version: string
/**
* Segment data
*/
segments: Array<JSONSegment>
}
/**
* Define the JSON transcript Segment format
*/
export type SubtitleSegment = {
/**
* Time (in milliseconds) when segment starts
*/
start: number
/**
* Time (in milliseconds) when segment ends
*/
end: number
/**
* Text of transcript for segment
*/
text: string
}
/**
* Determines if the value of data is a valid JSON transcript format
*
* @param data The transcript data
* @returns True: data is valid JSON transcript format
*/
export const isJSON = (data: string): boolean => {
return (data.startsWith("{") && data.endsWith("}")) || (data.startsWith("[") && data.endsWith("]"))
}
/**
* Parse JSON data where segments are in the `segments` Array and in the {@link JSONSegment} format
*
* @param data Parsed JSON data
* @returns An array of Segments from the parsed data
*/
const parseDictSegmentsJSON = (data: JSONTranscript): Array<Segment> => {
let outSegments: Array<Segment> = []
data.segments.forEach((segment) => {
outSegments = addSegment(
{
startTime: segment.startTime,
startTimeFormatted: TimestampFormatter.format(segment.startTime),
endTime: segment.endTime,
endTimeFormatted: TimestampFormatter.format(segment.endTime),
speaker: segment.speaker,
body: segment.body,
},
outSegments
)
})
return outSegments
}
/**
* Parse JSON data where top level item is a dict/object
*
* @param data The transcript data
* @returns An array of Segments from the parsed data
* @throws {TypeError} When JSON data does not match one of the valid formats
*/
const parseDictJSON = (data: object): Array<Segment> => {
let outSegments: Array<Segment> = []
if (Object.keys(data).length === 0) {
return outSegments
}
if ("segments" in data) {
outSegments = parseDictSegmentsJSON(data as JSONTranscript)
} else {
throw new TypeError(`Unknown JSON dict transcript format`)
}
return outSegments
}
/**
* Convert {@link SubtitleSegment} to the {@link Segment} format used here
*
* @param data Segment parsed from JSON data
* @returns Segment representing `data`.
* Returns {@link undefined} when data does not match {@link SubtitleSegment} format.
*/
const getSegmentFromSubtitle = (data: SubtitleSegment): Segment => {
if ("start" in data && "end" in data && "text" in data) {
const { speaker, message } = parseSpeaker(data.text)
const startTime = data.start / 1000
const endTime = data.end / 1000
const segment: Segment = {
startTime,
startTimeFormatted: TimestampFormatter.format(startTime),
endTime,
endTimeFormatted: TimestampFormatter.format(endTime),
speaker,
body: message,
}
if (Number.isNaN(segment.startTime)) {
console.warn(`Computed start time is NaN: ${segment.startTime}`)
return undefined
}
if (Number.isNaN(segment.endTime)) {
console.warn(`Computed end time is NaN: ${segment.endTime}`)
return undefined
}
return segment
}
return undefined
}
/**
* Parse JSON data where items in data are in the {@link SubtitleSegment} format
*
* @param data Parsed JSON data
* @returns An array of Segments from the parsed data
* @throws {TypeError} When item in `data` does not match the {@link SubtitleSegment} format
*/
const parseListJSONSubtitle = (data: Array<SubtitleSegment>): Array<Segment> => {
let outSegments: Array<Segment> = []
let lastSpeaker = ""
data.forEach((subtitle, count) => {
const subtitleSegment = getSegmentFromSubtitle(subtitle)
if (subtitleSegment !== undefined) {
lastSpeaker = subtitleSegment | .speaker ? subtitleSegment.speaker : lastSpeaker
subtitleSegment.speaker = lastSpeaker
outSegments = addSegment(subtitleSegment, outSegments)
} else { |
throw new TypeError(`Unable to parse segment for item ${count}`)
}
})
return outSegments
}
/**
* Parse JSON data where top level item is an Array
*
* @param data The transcript data
* @returns An array of Segments from the parsed data
* @throws {TypeError} When JSON data does not match one of the valid formats
*/
const parseListJSON = (data: Array<unknown>): Array<Segment> => {
let outSegments: Array<Segment> = []
if (data.length === 0) {
return outSegments
}
const subtitleSegment = getSegmentFromSubtitle(data[0] as SubtitleSegment)
if (subtitleSegment !== undefined) {
outSegments = parseListJSONSubtitle(data as Array<SubtitleSegment>)
} else {
throw new TypeError(`Unknown JSON list transcript format`)
}
return outSegments
}
/**
* Parse JSON data to an Array of {@link Segment}
*
* @param data The transcript data
* @returns An array of Segments from the parsed data
* @throws {TypeError} When `data` is not valid JSON format
*/
export const parseJSON = (data: string): Array<Segment> => {
const dataTrimmed = data.trim()
let outSegments: Array<Segment> = []
if (!isJSON(dataTrimmed)) {
throw new TypeError(`Data is not valid JSON format`)
}
let parsed: object | Array<unknown>
try {
parsed = JSON.parse(data)
} catch (e) {
throw new TypeError(`Data is not valid JSON: ${e}`)
}
if (parsed.constructor === Object) {
outSegments = parseDictJSON(parsed)
} else if (parsed.constructor === Array) {
outSegments = parseListJSON(parsed)
}
return outSegments
}
| src/formats/json.ts | stevencrader-transcriptator-75faa70 | [
{
"filename": "src/formats/srt.ts",
"retrieved_chunk": "export const parseSRT = (data: string): Array<Segment> => {\n if (!isSRT(data)) {\n throw new TypeError(`Data is not valid SRT format`)\n }\n let outSegments: Array<Segment> = []\n let lastSpeaker = \"\"\n let segmentLines = []\n data.split(PATTERN_LINE_SEPARATOR).forEach((line, count) => {\n // separator line found, handle previous data\n if (line.trim() === \"\") {",
"score": 27.780254104816553
},
{
"filename": "src/formats/srt.ts",
"retrieved_chunk": " segmentLines = [] // clear buffer\n } else {\n segmentLines.push(line)\n }\n })\n // handle data when trailing line not included\n if (segmentLines.length !== 0) {\n try {\n outSegments = addSegment(createSegmentFromSRTLines(segmentLines, lastSpeaker), outSegments)\n lastSpeaker = outSegments[outSegments.length - 1].speaker",
"score": 26.87909549900082
},
{
"filename": "src/segments.ts",
"retrieved_chunk": " let lastSpeaker: string\n if (speakerChange) {\n lastSpeaker = getLastSpeaker(priorSegment, outSegments)\n }\n const newSegmentInfo = applyOptions(newSegment, priorSegment, lastSpeaker)\n if (newSegmentInfo.replace && outSegments.length > 0) {\n outSegments[outSegments.length - 1] = newSegmentInfo.segment\n } else {\n outSegments.push(newSegmentInfo.segment)\n }",
"score": 26.08036612363499
},
{
"filename": "src/formats/srt.ts",
"retrieved_chunk": " // handle consecutive multiple blank lines\n if (segmentLines.length !== 0) {\n try {\n outSegments = addSegment(createSegmentFromSRTLines(segmentLines, lastSpeaker), outSegments)\n lastSpeaker = outSegments[outSegments.length - 1].speaker\n } catch (e) {\n console.error(`Error parsing SRT segment lines (source line ${count}): ${e}`)\n console.error(segmentLines)\n }\n }",
"score": 25.376188188939334
},
{
"filename": "src/formats/html.ts",
"retrieved_chunk": " */\nconst getSegmentsFromHTMLElements = (elements: Array<HTMLElement>): Array<Segment> => {\n let outSegments: Array<Segment> = []\n let lastSpeaker = \"\"\n let segmentPart: HTMLSegmentPart = {\n cite: \"\",\n time: \"\",\n text: \"\",\n }\n let nextSegmentPart: HTMLSegmentPart = {",
"score": 25.19440686587994
}
] | typescript | .speaker ? subtitleSegment.speaker : lastSpeaker
subtitleSegment.speaker = lastSpeaker
outSegments = addSegment(subtitleSegment, outSegments)
} else { |
import { Options } from "./options"
import { TimestampFormatter } from "./timestamp"
import { DEFAULT_COMBINE_SEGMENTS_LENGTH, Segment } from "./types"
/**
* Regular Expression for detecting punctuation that should not be prefixed with a space
*/
const PATTERN_PUNCTUATIONS = /^ *[.,?!}\]>) *$]/
/**
* Regular Expression for detecting space characters at the end of a string
*/
const PATTERN_TRAILING_SPACE = /^ *$/
/**
* Remove any trailing space characters from data
*
* @param data text to trim
* @returns text with any trailing space character removed
*/
const trimEndSpace = (data: string): string => {
return data.replace(PATTERN_TRAILING_SPACE, "")
}
/**
* Append `addition` to `body` with the character(s) specified.
*
* If `addition` matches the {@link PATTERN_PUNCTUATIONS} pattern, no character is added before the additional data.
*
* @param body Current body text
* @param addition Additional text to add to `body`
* @param separator Character(s) to use to separate data. If undefined, uses `\n`.
* @returns Combined data
*/
const joinBody = (body: string, addition: string, separator: string = undefined): string => {
if (body) {
let separatorToUse = separator || "\n"
if (PATTERN_PUNCTUATIONS.exec(addition)) {
separatorToUse = ""
}
return `${trimEndSpace(body)}${separatorToUse}${trimEndSpace(addition)}`
}
return trimEndSpace(addition)
}
/**
* Combine one or more {@link Segment}
*
* @param segments Array of Segment objects to combine
* @param bodySeparator Character(s) to use to separate body data. If undefined, uses `\n`.
* @returns Combined segment where:
*
* - `startTime`: from first segment
* - `startTimeFormatted`: from first segment
* - `endTime`: from last segment
* - `endTimeFormatted`: from last segment
* - `speaker`: from first segment
* - `body`: combination of all segments
*/
const joinSegments = (segments: Array<Segment>, bodySeparator: string = undefined): Segment => {
const newSegment = { ...segments[0] }
segments.slice(1).forEach((segment) => {
newSegment.endTime = segment.endTime
newSegment.endTimeFormatted = TimestampFormatter.format(segment.endTime)
newSegment.body = joinBody(newSegment.body, segment.body, bodySeparator)
})
return newSegment
}
/**
* Type returned from combine functions
*/
type CombineResult = {
/**
* The updated segment with any changes applied
*/
segment: Segment
/**
* If true, the {@link segment} contains a {@link Segment} that should replace the prior segment instead of
* appending a new segment
*/
replace: boolean
/**
* Indicates if the combine rule was applied
*/
combined: boolean
}
/**
* Checks if the new and prior segments have the same speaker.
*
* If so, combines segments where:
* - `startTime`: from priorSegment
* - `startTimeFormatted`: from priorSegment
* - `endTime`: from newSegment
* - `endTimeFormatted`: from newSegment
* - `speaker`: from priorSegment
* - `body`: body of priorSegment with body of newSegment separated with space
*
* @param newSegment segment being created
* @param priorSegment prior parsed segment
* @param lastSpeaker last speaker name.
* Used when speaker in segment has been removed via {@link Options.speakerChange} rule
* @returns result of combination.
* If segments were combined, {@link CombineResult.replace} and {@link CombineResult.combined} set to true.
*/
const doCombineSpeaker = (newSegment: Segment, priorSegment: Segment, lastSpeaker: string): CombineResult => {
if (newSegment.speaker === priorSegment.speaker || newSegment.speaker === lastSpeaker) {
return {
segment: joinSegments([priorSegment, newSegment], " "),
replace: true,
combined: true,
}
}
return {
segment: newSegment,
replace: false,
combined: false,
}
}
/**
* Checks if the new and prior segments have the same speaker and combining body results in new body shorter than
* max length
*
* If so, combines segments where:
* - `startTime`: from priorSegment
* - `startTimeFormatted`: from priorSegment
* - `endTime`: from newSegment
* - `endTimeFormatted`: from newSegment
* - `speaker`: from priorSegment
* - `body`: body of priorSegment with body of newSegment separated with space
*
* @param newSegment segment being created
* @param priorSegment prior parsed segment
* @param maxLength maximum allowed length of combined body. If undefined, uses {@link DEFAULT_COMBINE_SEGMENTS_LENGTH}
* @param lastSpeaker last speaker name.
* Used when speaker in segment has been removed via {@link Options.speakerChange} rule
* @returns result of combination.
* If segments were combined, {@link CombineResult.replace} and {@link CombineResult.combined} set to true.
*/
const doCombineSegments = (
newSegment: Segment,
priorSegment: Segment,
maxLength: number,
lastSpeaker: string
): CombineResult => {
if (priorSegment === undefined) {
return {
segment: newSegment,
replace: false,
combined: false,
}
}
const combineSegmentsLength = maxLength || DEFAULT_COMBINE_SEGMENTS_LENGTH
if (
(newSegment.speaker === priorSegment.speaker || newSegment.speaker === lastSpeaker) &&
joinBody(priorSegment.body, newSegment.body, " ").length <= combineSegmentsLength
) {
return {
segment: joinSegments([priorSegment, newSegment], " "),
replace: true,
combined: true,
}
}
return {
segment: newSegment,
replace: false,
combined: false,
}
}
/**
* Checks if the new and prior segments have the same speaker, startTime and endTime.
*
* If so, combines segments where:
* - `startTime`: from priorSegment
* - `startTimeFormatted`: from priorSegment
* - `endTime`: from newSegment
* - `endTimeFormatted`: from newSegment
* - `speaker`: from priorSegment
* - `body`: body of priorSegment with body of newSegment separated with value of separator argument
*
* @param newSegment segment being created
* @param priorSegment prior parsed segment
* @param separator string to use to combine body values. If undefined, uses "\n"
* @param lastSpeaker last speaker name.
* Used when speaker in segment has been removed via {@link Options.speakerChange} rule
* @returns result of combination.
* If segments were combined, {@link CombineResult.replace} and {@link CombineResult.combined} set to true.
*/
const doCombineEqualTimes = (
newSegment: Segment,
priorSegment: Segment,
separator: string,
lastSpeaker: string
): CombineResult => {
const combineEqualTimesSeparator = separator || "\n"
if (
newSegment.startTime === priorSegment.startTime &&
newSegment.endTime === priorSegment.endTime &&
(newSegment.speaker === priorSegment.speaker || newSegment.speaker === lastSpeaker)
) {
return {
segment: joinSegments([priorSegment, newSegment], combineEqualTimesSeparator),
replace: true,
combined: true,
}
}
return {
segment: newSegment,
replace: false,
combined: false,
}
}
/**
* Checks if the new and prior segments have the same speaker. If so, sets the speaker value to undefined
*
* If so, combines segments where:
* - `startTime`: from priorSegment
* - `startTimeFormatted`: from priorSegment
* - `endTime`: from newSegment
* - `endTimeFormatted`: from newSegment
* - `speaker`: from newSegment if different from priorSegment else undefined
* - `body`: body of priorSegment with body of newSegment separated with space
*
* @param newSegment segment being created
* @param priorSegment prior parsed segment. For the first segment, this shall be undefined.
* @param lastSpeaker last speaker name.
* Used when speaker in segment has been removed via {@link Options.speakerChange} rule
* @returns result of combination.
* If segments were combined, {@link CombineResult.replace} set to false and {@link CombineResult.combined} set to true.
*/
const doSpeakerChange = (newSegment: Segment, priorSegment: Segment, lastSpeaker: string): CombineResult => {
const result: CombineResult = {
segment: newSegment,
replace: false,
combined: false,
}
if (priorSegment === undefined) {
if (newSegment.speaker === lastSpeaker) {
const segment: Segment = { ...newSegment }
segment.speaker = undefined
return {
segment,
replace: false,
combined: true,
}
}
return result
}
if (newSegment.speaker === undefined) {
return result
}
if (
newSegment.speaker === "" ||
newSegment.speaker === priorSegment.speaker ||
newSegment.speaker === lastSpeaker
) {
const segment: Segment = { ...newSegment }
segment.speaker = undefined
return {
segment,
replace: false,
combined: true,
}
}
return result
}
/**
* Determine how {@link Options.speakerChange is applied based an past options being applied}
*
* @param currentResult current result object from any prior options
* @param priorSegment prior parsed segment
* @param lastSpeaker last speaker name.
* @returns result of combination.
* If segments were combined, {@link CombineResult.replace} set to false and {@link CombineResult.combined} set to true.
*/
const applyOptionsAndDoSpeakerChange = (
currentResult: CombineResult,
priorSegment: Segment,
lastSpeaker: string
): CombineResult => {
const { combineSegments, combineEqualTimes | } = Options
let result = currentResult
if (combineSegments && currentResult.combined && currentResult.replace) { |
result = doSpeakerChange(currentResult.segment, undefined, undefined)
} else if (combineEqualTimes) {
if (result.combined && result.replace) {
result = doSpeakerChange(currentResult.segment, undefined, undefined)
} else {
result = doSpeakerChange(currentResult.segment, priorSegment, lastSpeaker)
}
} else {
result = doSpeakerChange(currentResult.segment, priorSegment, lastSpeaker)
}
if (result) {
result = {
segment: result.segment,
replace: currentResult.replace || result.replace,
combined: currentResult.combined || result.combined,
}
}
return result
}
/**
* Apply convert rules when no prior segment exits.
*
* NOTE: not all rules applicable when no prior segment
*
* @param newSegment segment before any rules options to it
* @param lastSpeaker last speaker name.
* Used when speaker in segment has been removed via {@link Options.speakerChange} rule
* @returns the updated segment info
*/
const doCombineNoPrior = (newSegment: Segment, lastSpeaker: string): CombineResult => {
const { speakerChange } = Options
let result: CombineResult = {
segment: newSegment,
replace: false,
combined: false,
}
if (speakerChange) {
result = doSpeakerChange(result.segment, undefined, lastSpeaker)
}
return result
}
/**
* Apply convert rules when prior segment exits.
*
* @param newSegment segment before any rules options to it
* @param priorSegment prior parsed segment
* @param lastSpeaker last speaker name.
* Used when speaker in segment has been removed via {@link Options.speakerChange} rule
* @returns the updated segment info
*/
const doCombineWithPrior = (newSegment: Segment, priorSegment: Segment, lastSpeaker: string): CombineResult => {
const {
combineEqualTimes,
combineEqualTimesSeparator,
combineSegments,
combineSegmentsLength,
combineSpeaker,
speakerChange,
} = Options
let result: CombineResult = {
segment: { ...newSegment },
replace: false,
combined: false,
}
let combinedSpeaker = false
if (combineSpeaker) {
result = doCombineSpeaker(result.segment, priorSegment, lastSpeaker)
combinedSpeaker = result.combined
}
if (!combinedSpeaker && combineEqualTimes) {
result = doCombineEqualTimes(result.segment, priorSegment, combineEqualTimesSeparator, lastSpeaker)
}
if (!combinedSpeaker && combineSegments) {
let combineResult
if (combineEqualTimes && result.combined) {
combineResult = doCombineSegments(result.segment, undefined, combineSegmentsLength, lastSpeaker)
} else {
combineResult = doCombineSegments(result.segment, priorSegment, combineSegmentsLength, lastSpeaker)
}
if (combineResult) {
result = {
segment: combineResult.segment,
replace: result.replace || combineResult.replace,
combined: result.combined || combineResult.combined,
}
}
}
if (speakerChange) {
result = applyOptionsAndDoSpeakerChange(result, priorSegment, lastSpeaker)
}
return result
}
/**
* Apply any options to the current segment
*
* @param newSegment segment before any rules options to it
* @param priorSegment prior parsed segment. For the first segment, this shall be undefined.
* @param lastSpeaker last speaker name.
* Used when speaker in segment has been removed via {@link Options.speakerChange} rule
* @returns the updated segment info
*/
const applyOptions = (newSegment: Segment, priorSegment: Segment, lastSpeaker: string = undefined): CombineResult => {
if (!Options.optionsSet()) {
return {
segment: newSegment,
replace: false,
combined: false,
}
}
let result: CombineResult
// if no prior segment, limited additional checking
if (priorSegment === undefined) {
result = doCombineNoPrior(newSegment, lastSpeaker)
} else {
result = doCombineWithPrior(newSegment, priorSegment, lastSpeaker)
}
return result
}
/**
* Get the last speaker name from the previously parsed segments
*
* @param priorSegment prior parsed segment
* @param priorSegments array of all previous segments
* @returns the name of the last speaker
*/
const getLastSpeaker = (priorSegment: Segment, priorSegments: Array<Segment>): string => {
let lastSpeaker
if (priorSegment) {
lastSpeaker = priorSegment.speaker
}
if (lastSpeaker === undefined && priorSegments.length > 0) {
lastSpeaker = priorSegments[0].speaker
for (let i = priorSegments.length - 1; i > 0; i--) {
if (priorSegments[i].speaker !== undefined) {
lastSpeaker = priorSegments[i].speaker
break
}
}
}
return lastSpeaker
}
/**
* Helper for adding segment to or updating last segment in array of segments
*
* @param newSegment segment to add or replace
* @param priorSegments array of all previous segments
* @returns updated array of segments with new segment added or last segment updated (per options)
*/
export const addSegment = (newSegment: Segment, priorSegments: Array<Segment>): Array<Segment> => {
const { speakerChange } = Options
const outSegments = priorSegments || []
const priorSegment = outSegments.length > 0 ? outSegments[outSegments.length - 1] : undefined
// don't worry about identifying the last speaker if speaker is not being removed by speakerChange
let lastSpeaker: string
if (speakerChange) {
lastSpeaker = getLastSpeaker(priorSegment, outSegments)
}
const newSegmentInfo = applyOptions(newSegment, priorSegment, lastSpeaker)
if (newSegmentInfo.replace && outSegments.length > 0) {
outSegments[outSegments.length - 1] = newSegmentInfo.segment
} else {
outSegments.push(newSegmentInfo.segment)
}
return outSegments
}
| src/segments.ts | stevencrader-transcriptator-75faa70 | [
{
"filename": "src/options.ts",
"retrieved_chunk": " public optionsSet = (): boolean => {\n const { combineEqualTimes, combineSegments, combineSpeaker, speakerChange } = this\n return combineEqualTimes || combineSegments || combineSpeaker || speakerChange\n }\n}\nexport const Options = new OptionsManager()",
"score": 14.824245555877376
},
{
"filename": "src/options.ts",
"retrieved_chunk": " public getOptionByName = (name: string): boolean | string | number => {\n let actual\n switch (name) {\n case \"combineEqualTimes\":\n actual = this.combineEqualTimes\n break\n case \"combineEqualTimesSeparator\":\n actual = this.combineEqualTimesSeparator\n break\n case \"combineSegments\":",
"score": 10.295578463957938
},
{
"filename": "src/types.ts",
"retrieved_chunk": " * Text of transcript for segment\n */\n body: string\n}\n/**\n * Default length to use when combining segments with {@link Options.combineSegments}\n */\nexport const DEFAULT_COMBINE_SEGMENTS_LENGTH = 32",
"score": 9.888552069267053
},
{
"filename": "src/formats/html.ts",
"retrieved_chunk": " */\nconst getSegmentsFromHTMLElements = (elements: Array<HTMLElement>): Array<Segment> => {\n let outSegments: Array<Segment> = []\n let lastSpeaker = \"\"\n let segmentPart: HTMLSegmentPart = {\n cite: \"\",\n time: \"\",\n text: \"\",\n }\n let nextSegmentPart: HTMLSegmentPart = {",
"score": 8.355253660289709
},
{
"filename": "src/options.ts",
"retrieved_chunk": " *\n * Note: If this is enabled, {@link combineEqualTimes} and {@link combineSegments} will not be applied.\n *\n * Warning: if the transcript does not contain speaker information, resulting segment will contain entire transcript text.\n */\n combineSpeaker?: boolean\n /**\n * Only include {@link Segment.speaker} when speaker changes\n *\n * May be used in combination with {@link combineSpeaker}, {@link combineEqualTimes}, or {@link combineSegments}",
"score": 7.710129835712542
}
] | typescript | } = Options
let result = currentResult
if (combineSegments && currentResult.combined && currentResult.replace) { |
import { addSegment } from "../segments"
import { parseSpeaker } from "../speaker"
import { TimestampFormatter } from "../timestamp"
import { Segment } from "../types"
/**
* Define a segment/cue used in the JSONTranscript format
*/
export type JSONSegment = {
/**
* Time (in seconds) when segment starts
*/
startTime: number
/**
* Time (in seconds) when segment ends
*/
endTime: number
/**
* Name of speaker for `body`
*/
speaker?: string
/**
* Text of transcript for segment
*/
body: string
}
/**
* Define the JSON transcript format
*/
export type JSONTranscript = {
/**
* Version of file format
*/
version: string
/**
* Segment data
*/
segments: Array<JSONSegment>
}
/**
* Define the JSON transcript Segment format
*/
export type SubtitleSegment = {
/**
* Time (in milliseconds) when segment starts
*/
start: number
/**
* Time (in milliseconds) when segment ends
*/
end: number
/**
* Text of transcript for segment
*/
text: string
}
/**
* Determines if the value of data is a valid JSON transcript format
*
* @param data The transcript data
* @returns True: data is valid JSON transcript format
*/
export const isJSON = (data: string): boolean => {
return (data.startsWith("{") && data.endsWith("}")) || (data.startsWith("[") && data.endsWith("]"))
}
/**
* Parse JSON data where segments are in the `segments` Array and in the {@link JSONSegment} format
*
* @param data Parsed JSON data
* @returns An array of Segments from the parsed data
*/
const parseDictSegmentsJSON = (data: JSONTranscript): Array<Segment> => {
let outSegments: Array<Segment> = []
data.segments.forEach((segment) => {
outSegments = addSegment(
{
startTime: segment.startTime,
startTimeFormatted: TimestampFormatter.format(segment.startTime),
endTime: segment.endTime,
endTimeFormatted: TimestampFormatter.format(segment.endTime),
speaker: segment.speaker,
body: segment.body,
},
outSegments
)
})
return outSegments
}
/**
* Parse JSON data where top level item is a dict/object
*
* @param data The transcript data
* @returns An array of Segments from the parsed data
* @throws {TypeError} When JSON data does not match one of the valid formats
*/
const parseDictJSON = (data: object): Array<Segment> => {
let outSegments: Array<Segment> = []
if (Object.keys(data).length === 0) {
return outSegments
}
if ("segments" in data) {
outSegments = parseDictSegmentsJSON(data as JSONTranscript)
} else {
throw new TypeError(`Unknown JSON dict transcript format`)
}
return outSegments
}
/**
* Convert {@link SubtitleSegment} to the {@link Segment} format used here
*
* @param data Segment parsed from JSON data
* @returns Segment representing `data`.
* Returns {@link undefined} when data does not match {@link SubtitleSegment} format.
*/
const getSegmentFromSubtitle = (data: SubtitleSegment): Segment => {
if ("start" in data && "end" in data && "text" in data) {
const { speaker, message } = parseSpeaker(data.text)
const startTime = data.start / 1000
const endTime = data.end / 1000
const segment: Segment = {
startTime,
startTimeFormatted: TimestampFormatter.format(startTime),
endTime,
endTimeFormatted: TimestampFormatter.format(endTime),
speaker,
body: message,
}
if (Number.isNaN(segment.startTime)) {
console.warn(`Computed start time is NaN: ${segment.startTime}`)
return undefined
}
| if (Number.isNaN(segment.endTime)) { |
console.warn(`Computed end time is NaN: ${segment.endTime}`)
return undefined
}
return segment
}
return undefined
}
/**
* Parse JSON data where items in data are in the {@link SubtitleSegment} format
*
* @param data Parsed JSON data
* @returns An array of Segments from the parsed data
* @throws {TypeError} When item in `data` does not match the {@link SubtitleSegment} format
*/
const parseListJSONSubtitle = (data: Array<SubtitleSegment>): Array<Segment> => {
let outSegments: Array<Segment> = []
let lastSpeaker = ""
data.forEach((subtitle, count) => {
const subtitleSegment = getSegmentFromSubtitle(subtitle)
if (subtitleSegment !== undefined) {
lastSpeaker = subtitleSegment.speaker ? subtitleSegment.speaker : lastSpeaker
subtitleSegment.speaker = lastSpeaker
outSegments = addSegment(subtitleSegment, outSegments)
} else {
throw new TypeError(`Unable to parse segment for item ${count}`)
}
})
return outSegments
}
/**
* Parse JSON data where top level item is an Array
*
* @param data The transcript data
* @returns An array of Segments from the parsed data
* @throws {TypeError} When JSON data does not match one of the valid formats
*/
const parseListJSON = (data: Array<unknown>): Array<Segment> => {
let outSegments: Array<Segment> = []
if (data.length === 0) {
return outSegments
}
const subtitleSegment = getSegmentFromSubtitle(data[0] as SubtitleSegment)
if (subtitleSegment !== undefined) {
outSegments = parseListJSONSubtitle(data as Array<SubtitleSegment>)
} else {
throw new TypeError(`Unknown JSON list transcript format`)
}
return outSegments
}
/**
* Parse JSON data to an Array of {@link Segment}
*
* @param data The transcript data
* @returns An array of Segments from the parsed data
* @throws {TypeError} When `data` is not valid JSON format
*/
export const parseJSON = (data: string): Array<Segment> => {
const dataTrimmed = data.trim()
let outSegments: Array<Segment> = []
if (!isJSON(dataTrimmed)) {
throw new TypeError(`Data is not valid JSON format`)
}
let parsed: object | Array<unknown>
try {
parsed = JSON.parse(data)
} catch (e) {
throw new TypeError(`Data is not valid JSON: ${e}`)
}
if (parsed.constructor === Object) {
outSegments = parseDictJSON(parsed)
} else if (parsed.constructor === Array) {
outSegments = parseListJSON(parsed)
}
return outSegments
}
| src/formats/json.ts | stevencrader-transcriptator-75faa70 | [
{
"filename": "src/formats/srt.ts",
"retrieved_chunk": " const calculatedSpeaker = srtSegment.speaker ? srtSegment.speaker : lastSpeaker\n return {\n startTime: srtSegment.startTime,\n startTimeFormatted: TimestampFormatter.format(srtSegment.startTime),\n endTime: srtSegment.endTime,\n endTimeFormatted: TimestampFormatter.format(srtSegment.endTime),\n speaker: calculatedSpeaker,\n body: srtSegment.body,\n }\n}",
"score": 29.594236666738603
},
{
"filename": "src/formats/html.ts",
"retrieved_chunk": " if (totalSegments > 0) {\n outSegments[totalSegments - 1].endTime = segment.startTime\n outSegments[totalSegments - 1].endTimeFormatted = TimestampFormatter.format(\n outSegments[totalSegments - 1].endTime\n )\n }\n outSegments = addSegment(segment, outSegments)\n }\n // clear\n segmentPart = nextSegmentPart",
"score": 22.589833295789784
},
{
"filename": "src/formats/srt.ts",
"retrieved_chunk": " }\n const { speaker, message } = parseSpeaker(bodyLines.shift())\n bodyLines = [message].concat(bodyLines)\n return {\n startTime,\n endTime,\n speaker,\n body: bodyLines.join(\"\\n\"),\n index,\n }",
"score": 22.12711935883298
},
{
"filename": "src/segments.ts",
"retrieved_chunk": " * - `endTimeFormatted`: from last segment\n * - `speaker`: from first segment\n * - `body`: combination of all segments\n */\nconst joinSegments = (segments: Array<Segment>, bodySeparator: string = undefined): Segment => {\n const newSegment = { ...segments[0] }\n segments.slice(1).forEach((segment) => {\n newSegment.endTime = segment.endTime\n newSegment.endTimeFormatted = TimestampFormatter.format(segment.endTime)\n newSegment.body = joinBody(newSegment.body, segment.body, bodySeparator)",
"score": 21.2643843916853
},
{
"filename": "src/formats/html.ts",
"retrieved_chunk": " * @param lastSpeaker Name of last speaker. Will be used if no speaker found in `segmentLines`\n * @returns Created segment\n */\nconst createSegmentFromSegmentPart = (segmentPart: HTMLSegmentPart, lastSpeaker: string): Segment => {\n const calculatedSpeaker = segmentPart.cite ? segmentPart.cite : lastSpeaker\n const startTime = parseTimestamp(segmentPart.time)\n return {\n startTime,\n startTimeFormatted: TimestampFormatter.format(startTime),\n endTime: 0,",
"score": 19.418581188800502
}
] | typescript | if (Number.isNaN(segment.endTime)) { |
import { Options } from "./options"
import { TimestampFormatter } from "./timestamp"
import { DEFAULT_COMBINE_SEGMENTS_LENGTH, Segment } from "./types"
/**
* Regular Expression for detecting punctuation that should not be prefixed with a space
*/
const PATTERN_PUNCTUATIONS = /^ *[.,?!}\]>) *$]/
/**
* Regular Expression for detecting space characters at the end of a string
*/
const PATTERN_TRAILING_SPACE = /^ *$/
/**
* Remove any trailing space characters from data
*
* @param data text to trim
* @returns text with any trailing space character removed
*/
const trimEndSpace = (data: string): string => {
return data.replace(PATTERN_TRAILING_SPACE, "")
}
/**
* Append `addition` to `body` with the character(s) specified.
*
* If `addition` matches the {@link PATTERN_PUNCTUATIONS} pattern, no character is added before the additional data.
*
* @param body Current body text
* @param addition Additional text to add to `body`
* @param separator Character(s) to use to separate data. If undefined, uses `\n`.
* @returns Combined data
*/
const joinBody = (body: string, addition: string, separator: string = undefined): string => {
if (body) {
let separatorToUse = separator || "\n"
if (PATTERN_PUNCTUATIONS.exec(addition)) {
separatorToUse = ""
}
return `${trimEndSpace(body)}${separatorToUse}${trimEndSpace(addition)}`
}
return trimEndSpace(addition)
}
/**
* Combine one or more {@link Segment}
*
* @param segments Array of Segment objects to combine
* @param bodySeparator Character(s) to use to separate body data. If undefined, uses `\n`.
* @returns Combined segment where:
*
* - `startTime`: from first segment
* - `startTimeFormatted`: from first segment
* - `endTime`: from last segment
* - `endTimeFormatted`: from last segment
* - `speaker`: from first segment
* - `body`: combination of all segments
*/
const joinSegments = (segments: Array<Segment>, bodySeparator: string = undefined): Segment => {
const newSegment = { ...segments[0] }
segments.slice(1).forEach((segment) => {
newSegment.endTime = segment.endTime
newSegment.endTimeFormatted = TimestampFormatter.format(segment.endTime)
newSegment.body = joinBody(newSegment.body, segment.body, bodySeparator)
})
return newSegment
}
/**
* Type returned from combine functions
*/
type CombineResult = {
/**
* The updated segment with any changes applied
*/
segment: Segment
/**
* If true, the {@link segment} contains a {@link Segment} that should replace the prior segment instead of
* appending a new segment
*/
replace: boolean
/**
* Indicates if the combine rule was applied
*/
combined: boolean
}
/**
* Checks if the new and prior segments have the same speaker.
*
* If so, combines segments where:
* - `startTime`: from priorSegment
* - `startTimeFormatted`: from priorSegment
* - `endTime`: from newSegment
* - `endTimeFormatted`: from newSegment
* - `speaker`: from priorSegment
* - `body`: body of priorSegment with body of newSegment separated with space
*
* @param newSegment segment being created
* @param priorSegment prior parsed segment
* @param lastSpeaker last speaker name.
* Used when speaker in segment has been removed via {@link Options.speakerChange} rule
* @returns result of combination.
* If segments were combined, {@link CombineResult.replace} and {@link CombineResult.combined} set to true.
*/
const doCombineSpeaker = (newSegment: Segment, priorSegment: Segment, lastSpeaker: string): CombineResult => {
if (newSegment.speaker === priorSegment.speaker || newSegment.speaker === lastSpeaker) {
return {
segment: joinSegments([priorSegment, newSegment], " "),
replace: true,
combined: true,
}
}
return {
segment: newSegment,
replace: false,
combined: false,
}
}
/**
* Checks if the new and prior segments have the same speaker and combining body results in new body shorter than
* max length
*
* If so, combines segments where:
* - `startTime`: from priorSegment
* - `startTimeFormatted`: from priorSegment
* - `endTime`: from newSegment
* - `endTimeFormatted`: from newSegment
* - `speaker`: from priorSegment
* - `body`: body of priorSegment with body of newSegment separated with space
*
* @param newSegment segment being created
* @param priorSegment prior parsed segment
* @param maxLength maximum allowed length of combined body. If undefined, uses {@link DEFAULT_COMBINE_SEGMENTS_LENGTH}
* @param lastSpeaker last speaker name.
* Used when speaker in segment has been removed via {@link Options.speakerChange} rule
* @returns result of combination.
* If segments were combined, {@link CombineResult.replace} and {@link CombineResult.combined} set to true.
*/
const doCombineSegments = (
newSegment: Segment,
priorSegment: Segment,
maxLength: number,
lastSpeaker: string
): CombineResult => {
if (priorSegment === undefined) {
return {
segment: newSegment,
replace: false,
combined: false,
}
}
const combineSegmentsLength = maxLength || DEFAULT_COMBINE_SEGMENTS_LENGTH
if (
(newSegment.speaker === priorSegment.speaker || newSegment.speaker === lastSpeaker) &&
joinBody(priorSegment.body, newSegment.body, " ").length <= combineSegmentsLength
) {
return {
segment: joinSegments([priorSegment, newSegment], " "),
replace: true,
combined: true,
}
}
return {
segment: newSegment,
replace: false,
combined: false,
}
}
/**
* Checks if the new and prior segments have the same speaker, startTime and endTime.
*
* If so, combines segments where:
* - `startTime`: from priorSegment
* - `startTimeFormatted`: from priorSegment
* - `endTime`: from newSegment
* - `endTimeFormatted`: from newSegment
* - `speaker`: from priorSegment
* - `body`: body of priorSegment with body of newSegment separated with value of separator argument
*
* @param newSegment segment being created
* @param priorSegment prior parsed segment
* @param separator string to use to combine body values. If undefined, uses "\n"
* @param lastSpeaker last speaker name.
* Used when speaker in segment has been removed via {@link Options.speakerChange} rule
* @returns result of combination.
* If segments were combined, {@link CombineResult.replace} and {@link CombineResult.combined} set to true.
*/
const doCombineEqualTimes = (
newSegment: Segment,
priorSegment: Segment,
separator: string,
lastSpeaker: string
): CombineResult => {
const combineEqualTimesSeparator = separator || "\n"
if (
newSegment.startTime === priorSegment.startTime &&
newSegment.endTime === priorSegment.endTime &&
(newSegment.speaker === priorSegment.speaker || newSegment.speaker === lastSpeaker)
) {
return {
segment: joinSegments([priorSegment, newSegment], combineEqualTimesSeparator),
replace: true,
combined: true,
}
}
return {
segment: newSegment,
replace: false,
combined: false,
}
}
/**
* Checks if the new and prior segments have the same speaker. If so, sets the speaker value to undefined
*
* If so, combines segments where:
* - `startTime`: from priorSegment
* - `startTimeFormatted`: from priorSegment
* - `endTime`: from newSegment
* - `endTimeFormatted`: from newSegment
* - `speaker`: from newSegment if different from priorSegment else undefined
* - `body`: body of priorSegment with body of newSegment separated with space
*
* @param newSegment segment being created
* @param priorSegment prior parsed segment. For the first segment, this shall be undefined.
* @param lastSpeaker last speaker name.
* Used when speaker in segment has been removed via {@link Options.speakerChange} rule
* @returns result of combination.
* If segments were combined, {@link CombineResult.replace} set to false and {@link CombineResult.combined} set to true.
*/
const doSpeakerChange = (newSegment: Segment, priorSegment: Segment, lastSpeaker: string): CombineResult => {
const result: CombineResult = {
segment: newSegment,
replace: false,
combined: false,
}
if (priorSegment === undefined) {
if (newSegment.speaker === lastSpeaker) {
const segment: Segment = { ...newSegment }
segment.speaker = undefined
return {
segment,
replace: false,
combined: true,
}
}
return result
}
if (newSegment.speaker === undefined) {
return result
}
if (
newSegment.speaker === "" ||
newSegment.speaker === priorSegment.speaker ||
newSegment.speaker === lastSpeaker
) {
const segment: Segment = { ...newSegment }
segment.speaker = undefined
return {
segment,
replace: false,
combined: true,
}
}
return result
}
/**
* Determine how {@link Options.speakerChange is applied based an past options being applied}
*
* @param currentResult current result object from any prior options
* @param priorSegment prior parsed segment
* @param lastSpeaker last speaker name.
* @returns result of combination.
* If segments were combined, {@link CombineResult.replace} set to false and {@link CombineResult.combined} set to true.
*/
const applyOptionsAndDoSpeakerChange = (
currentResult: CombineResult,
priorSegment: Segment,
lastSpeaker: string
): CombineResult => {
const { combineSegments, combineEqualTimes } = Options
let result = currentResult
if (combineSegments && currentResult.combined && currentResult.replace) {
result = doSpeakerChange(currentResult.segment, undefined, undefined)
} else if (combineEqualTimes) {
if (result.combined && result.replace) {
result = doSpeakerChange(currentResult.segment, undefined, undefined)
} else {
result = doSpeakerChange(currentResult.segment, priorSegment, lastSpeaker)
}
} else {
result = doSpeakerChange(currentResult.segment, priorSegment, lastSpeaker)
}
if (result) {
result = {
segment: result.segment,
replace: currentResult.replace || result.replace,
combined: currentResult.combined || result.combined,
}
}
return result
}
/**
* Apply convert rules when no prior segment exits.
*
* NOTE: not all rules applicable when no prior segment
*
* @param newSegment segment before any rules options to it
* @param lastSpeaker last speaker name.
* Used when speaker in segment has been removed via {@link Options.speakerChange} rule
* @returns the updated segment info
*/
const doCombineNoPrior = (newSegment: Segment, lastSpeaker: string): CombineResult => {
| const { speakerChange } = Options
let result: CombineResult = { |
segment: newSegment,
replace: false,
combined: false,
}
if (speakerChange) {
result = doSpeakerChange(result.segment, undefined, lastSpeaker)
}
return result
}
/**
* Apply convert rules when prior segment exits.
*
* @param newSegment segment before any rules options to it
* @param priorSegment prior parsed segment
* @param lastSpeaker last speaker name.
* Used when speaker in segment has been removed via {@link Options.speakerChange} rule
* @returns the updated segment info
*/
const doCombineWithPrior = (newSegment: Segment, priorSegment: Segment, lastSpeaker: string): CombineResult => {
const {
combineEqualTimes,
combineEqualTimesSeparator,
combineSegments,
combineSegmentsLength,
combineSpeaker,
speakerChange,
} = Options
let result: CombineResult = {
segment: { ...newSegment },
replace: false,
combined: false,
}
let combinedSpeaker = false
if (combineSpeaker) {
result = doCombineSpeaker(result.segment, priorSegment, lastSpeaker)
combinedSpeaker = result.combined
}
if (!combinedSpeaker && combineEqualTimes) {
result = doCombineEqualTimes(result.segment, priorSegment, combineEqualTimesSeparator, lastSpeaker)
}
if (!combinedSpeaker && combineSegments) {
let combineResult
if (combineEqualTimes && result.combined) {
combineResult = doCombineSegments(result.segment, undefined, combineSegmentsLength, lastSpeaker)
} else {
combineResult = doCombineSegments(result.segment, priorSegment, combineSegmentsLength, lastSpeaker)
}
if (combineResult) {
result = {
segment: combineResult.segment,
replace: result.replace || combineResult.replace,
combined: result.combined || combineResult.combined,
}
}
}
if (speakerChange) {
result = applyOptionsAndDoSpeakerChange(result, priorSegment, lastSpeaker)
}
return result
}
/**
* Apply any options to the current segment
*
* @param newSegment segment before any rules options to it
* @param priorSegment prior parsed segment. For the first segment, this shall be undefined.
* @param lastSpeaker last speaker name.
* Used when speaker in segment has been removed via {@link Options.speakerChange} rule
* @returns the updated segment info
*/
const applyOptions = (newSegment: Segment, priorSegment: Segment, lastSpeaker: string = undefined): CombineResult => {
if (!Options.optionsSet()) {
return {
segment: newSegment,
replace: false,
combined: false,
}
}
let result: CombineResult
// if no prior segment, limited additional checking
if (priorSegment === undefined) {
result = doCombineNoPrior(newSegment, lastSpeaker)
} else {
result = doCombineWithPrior(newSegment, priorSegment, lastSpeaker)
}
return result
}
/**
* Get the last speaker name from the previously parsed segments
*
* @param priorSegment prior parsed segment
* @param priorSegments array of all previous segments
* @returns the name of the last speaker
*/
const getLastSpeaker = (priorSegment: Segment, priorSegments: Array<Segment>): string => {
let lastSpeaker
if (priorSegment) {
lastSpeaker = priorSegment.speaker
}
if (lastSpeaker === undefined && priorSegments.length > 0) {
lastSpeaker = priorSegments[0].speaker
for (let i = priorSegments.length - 1; i > 0; i--) {
if (priorSegments[i].speaker !== undefined) {
lastSpeaker = priorSegments[i].speaker
break
}
}
}
return lastSpeaker
}
/**
* Helper for adding segment to or updating last segment in array of segments
*
* @param newSegment segment to add or replace
* @param priorSegments array of all previous segments
* @returns updated array of segments with new segment added or last segment updated (per options)
*/
export const addSegment = (newSegment: Segment, priorSegments: Array<Segment>): Array<Segment> => {
const { speakerChange } = Options
const outSegments = priorSegments || []
const priorSegment = outSegments.length > 0 ? outSegments[outSegments.length - 1] : undefined
// don't worry about identifying the last speaker if speaker is not being removed by speakerChange
let lastSpeaker: string
if (speakerChange) {
lastSpeaker = getLastSpeaker(priorSegment, outSegments)
}
const newSegmentInfo = applyOptions(newSegment, priorSegment, lastSpeaker)
if (newSegmentInfo.replace && outSegments.length > 0) {
outSegments[outSegments.length - 1] = newSegmentInfo.segment
} else {
outSegments.push(newSegmentInfo.segment)
}
return outSegments
}
| src/segments.ts | stevencrader-transcriptator-75faa70 | [
{
"filename": "src/formats/srt.ts",
"retrieved_chunk": "}\n/**\n * Create Segment from lines containing an SRT segment/cue\n *\n * @param segmentLines Lines containing SRT data\n * @param lastSpeaker Name of last speaker. Will be used if no speaker found in `segmentLines`\n * @returns Created segment\n */\nconst createSegmentFromSRTLines = (segmentLines: Array<string>, lastSpeaker: string): Segment => {\n const srtSegment = parseSRTSegment(segmentLines)",
"score": 24.997348710720885
},
{
"filename": "src/formats/html.ts",
"retrieved_chunk": " * @param lastSpeaker Name of last speaker. Will be used if no speaker found in `segmentLines`\n * @returns Created segment\n */\nconst createSegmentFromSegmentPart = (segmentPart: HTMLSegmentPart, lastSpeaker: string): Segment => {\n const calculatedSpeaker = segmentPart.cite ? segmentPart.cite : lastSpeaker\n const startTime = parseTimestamp(segmentPart.time)\n return {\n startTime,\n startTimeFormatted: TimestampFormatter.format(startTime),\n endTime: 0,",
"score": 23.52177368611998
},
{
"filename": "src/types.ts",
"retrieved_chunk": " * Text of transcript for segment\n */\n body: string\n}\n/**\n * Default length to use when combining segments with {@link Options.combineSegments}\n */\nexport const DEFAULT_COMBINE_SEGMENTS_LENGTH = 32",
"score": 20.126401237886093
},
{
"filename": "src/options.ts",
"retrieved_chunk": " *\n * Can be used with {@link speakerChange}. The {@link speakerChange} rule is applied last.\n *\n * Cannot be used with {@link combineSpeaker}\n */\n combineEqualTimes?: boolean\n /**\n * Character to use when {@link combineEqualTimes} is true.\n *\n * Default: `\\n`",
"score": 20.025955121024406
},
{
"filename": "src/options.ts",
"retrieved_chunk": " static _instance: OptionsManager\n /**\n * Combine segments if the {@link Segment.startTime}, {@link Segment.endTime}, and {@link Segment.speaker} match\n * between the current and prior segments\n *\n * Can be used with {@link combineSegments}. The {@link combineEqualTimes} rule is applied first.\n *\n * Can be used with {@link speakerChange}. The {@link speakerChange} rule is applied last.\n *\n * Cannot be used with {@link combineSpeaker}",
"score": 19.984216182463598
}
] | typescript | const { speakerChange } = Options
let result: CombineResult = { |
import { isHTML, parseHTML } from "./formats/html"
import { isJSON, parseJSON } from "./formats/json"
import { isSRT, parseSRT } from "./formats/srt"
import { isVTT, parseVTT } from "./formats/vtt"
import { Segment, TranscriptFormat } from "./types"
export { Segment, TranscriptFormat } from "./types"
export { TimestampFormatter, FormatterCallback } from "./timestamp"
export { Options, IOptions } from "./options"
/**
* Determines the format of transcript by inspecting the data
*
* @param data The transcript data
* @returns The determined transcript format
* @throws {TypeError} Cannot determine format of data or error parsing data
*/
export const determineFormat = (data: string): TranscriptFormat => {
const normalizedData = data.trim()
if (isVTT(normalizedData)) {
return TranscriptFormat.VTT
}
if (isJSON(normalizedData)) {
return TranscriptFormat.JSON
}
if (isHTML(normalizedData)) {
return TranscriptFormat.HTML
}
if (isSRT(normalizedData)) {
return TranscriptFormat.SRT
}
throw new TypeError(`Cannot determine format for data`)
}
/**
* Convert the data to an Array of {@link Segment}
*
* @param data The transcript data
* @param transcriptFormat The format of the data.
* @returns An Array of Segment objects from the parsed data
* @throws {TypeError} When `transcriptFormat` is unknown
*/
export const convertFile = (data: string, transcriptFormat: TranscriptFormat = undefined): Array<Segment> => {
const format = transcriptFormat ?? determineFormat(data)
const normalizedData = data.trimStart()
let outSegments: Array<Segment> = []
switch (format) {
case TranscriptFormat.HTML:
outSegments = parseHTML(normalizedData)
break
case TranscriptFormat.JSON:
outSegments = parseJSON(normalizedData)
break
case TranscriptFormat.SRT:
outSegments = parseSRT(normalizedData)
break
case TranscriptFormat.VTT:
outSegments | = parseVTT(normalizedData)
break
default:
throw new TypeError(`Unknown transcript format: ${format}`)
} |
return outSegments
}
| src/index.ts | stevencrader-transcriptator-75faa70 | [
{
"filename": "src/options.ts",
"retrieved_chunk": " case \"combineSpeaker\":\n verifyType(name, \"boolean\", value)\n this.combineSpeaker = <boolean>value\n break\n case \"speakerChange\":\n verifyType(name, \"boolean\", value)\n this.speakerChange = <boolean>value\n break\n default:\n break",
"score": 23.749238513623048
},
{
"filename": "src/options.ts",
"retrieved_chunk": " actual = this.combineSegments\n break\n case \"combineSegmentsLength\":\n actual = this.combineSegmentsLength\n break\n case \"combineSpeaker\":\n actual = this.combineSpeaker\n break\n case \"speakerChange\":\n actual = this.speakerChange",
"score": 22.34606100051368
},
{
"filename": "src/formats/vtt.ts",
"retrieved_chunk": " * @throws {TypeError} When `data` is not valid VTT format\n */\nexport const parseVTT = (data: string): Array<Segment> => {\n if (!isVTT(data)) {\n throw new TypeError(`Data is not valid VTT format`)\n }\n // format is similar enough to SRT to be parsed by the same parser\n // Remove WEBVTT header first\n return parseSRT(data.substring(WEBVTT_HEADER.length).trimStart())\n}",
"score": 22.040460267511147
},
{
"filename": "src/formats/json.ts",
"retrieved_chunk": " return outSegments\n }\n const subtitleSegment = getSegmentFromSubtitle(data[0] as SubtitleSegment)\n if (subtitleSegment !== undefined) {\n outSegments = parseListJSONSubtitle(data as Array<SubtitleSegment>)\n } else {\n throw new TypeError(`Unknown JSON list transcript format`)\n }\n return outSegments\n}",
"score": 21.436933227903978
},
{
"filename": "src/formats/json.ts",
"retrieved_chunk": " outSegments = parseDictSegmentsJSON(data as JSONTranscript)\n } else {\n throw new TypeError(`Unknown JSON dict transcript format`)\n }\n return outSegments\n}\n/**\n * Convert {@link SubtitleSegment} to the {@link Segment} format used here\n *\n * @param data Segment parsed from JSON data",
"score": 20.585616569957764
}
] | typescript | = parseVTT(normalizedData)
break
default:
throw new TypeError(`Unknown transcript format: ${format}`)
} |
import { Options } from "./options"
import { TimestampFormatter } from "./timestamp"
import { DEFAULT_COMBINE_SEGMENTS_LENGTH, Segment } from "./types"
/**
* Regular Expression for detecting punctuation that should not be prefixed with a space
*/
const PATTERN_PUNCTUATIONS = /^ *[.,?!}\]>) *$]/
/**
* Regular Expression for detecting space characters at the end of a string
*/
const PATTERN_TRAILING_SPACE = /^ *$/
/**
* Remove any trailing space characters from data
*
* @param data text to trim
* @returns text with any trailing space character removed
*/
const trimEndSpace = (data: string): string => {
return data.replace(PATTERN_TRAILING_SPACE, "")
}
/**
* Append `addition` to `body` with the character(s) specified.
*
* If `addition` matches the {@link PATTERN_PUNCTUATIONS} pattern, no character is added before the additional data.
*
* @param body Current body text
* @param addition Additional text to add to `body`
* @param separator Character(s) to use to separate data. If undefined, uses `\n`.
* @returns Combined data
*/
const joinBody = (body: string, addition: string, separator: string = undefined): string => {
if (body) {
let separatorToUse = separator || "\n"
if (PATTERN_PUNCTUATIONS.exec(addition)) {
separatorToUse = ""
}
return `${trimEndSpace(body)}${separatorToUse}${trimEndSpace(addition)}`
}
return trimEndSpace(addition)
}
/**
* Combine one or more {@link Segment}
*
* @param segments Array of Segment objects to combine
* @param bodySeparator Character(s) to use to separate body data. If undefined, uses `\n`.
* @returns Combined segment where:
*
* - `startTime`: from first segment
* - `startTimeFormatted`: from first segment
* - `endTime`: from last segment
* - `endTimeFormatted`: from last segment
* - `speaker`: from first segment
* - `body`: combination of all segments
*/
const joinSegments = | (segments: Array<Segment>, bodySeparator: string = undefined): Segment => { |
const newSegment = { ...segments[0] }
segments.slice(1).forEach((segment) => {
newSegment.endTime = segment.endTime
newSegment.endTimeFormatted = TimestampFormatter.format(segment.endTime)
newSegment.body = joinBody(newSegment.body, segment.body, bodySeparator)
})
return newSegment
}
/**
* Type returned from combine functions
*/
type CombineResult = {
/**
* The updated segment with any changes applied
*/
segment: Segment
/**
* If true, the {@link segment} contains a {@link Segment} that should replace the prior segment instead of
* appending a new segment
*/
replace: boolean
/**
* Indicates if the combine rule was applied
*/
combined: boolean
}
/**
* Checks if the new and prior segments have the same speaker.
*
* If so, combines segments where:
* - `startTime`: from priorSegment
* - `startTimeFormatted`: from priorSegment
* - `endTime`: from newSegment
* - `endTimeFormatted`: from newSegment
* - `speaker`: from priorSegment
* - `body`: body of priorSegment with body of newSegment separated with space
*
* @param newSegment segment being created
* @param priorSegment prior parsed segment
* @param lastSpeaker last speaker name.
* Used when speaker in segment has been removed via {@link Options.speakerChange} rule
* @returns result of combination.
* If segments were combined, {@link CombineResult.replace} and {@link CombineResult.combined} set to true.
*/
const doCombineSpeaker = (newSegment: Segment, priorSegment: Segment, lastSpeaker: string): CombineResult => {
if (newSegment.speaker === priorSegment.speaker || newSegment.speaker === lastSpeaker) {
return {
segment: joinSegments([priorSegment, newSegment], " "),
replace: true,
combined: true,
}
}
return {
segment: newSegment,
replace: false,
combined: false,
}
}
/**
* Checks if the new and prior segments have the same speaker and combining body results in new body shorter than
* max length
*
* If so, combines segments where:
* - `startTime`: from priorSegment
* - `startTimeFormatted`: from priorSegment
* - `endTime`: from newSegment
* - `endTimeFormatted`: from newSegment
* - `speaker`: from priorSegment
* - `body`: body of priorSegment with body of newSegment separated with space
*
* @param newSegment segment being created
* @param priorSegment prior parsed segment
* @param maxLength maximum allowed length of combined body. If undefined, uses {@link DEFAULT_COMBINE_SEGMENTS_LENGTH}
* @param lastSpeaker last speaker name.
* Used when speaker in segment has been removed via {@link Options.speakerChange} rule
* @returns result of combination.
* If segments were combined, {@link CombineResult.replace} and {@link CombineResult.combined} set to true.
*/
const doCombineSegments = (
newSegment: Segment,
priorSegment: Segment,
maxLength: number,
lastSpeaker: string
): CombineResult => {
if (priorSegment === undefined) {
return {
segment: newSegment,
replace: false,
combined: false,
}
}
const combineSegmentsLength = maxLength || DEFAULT_COMBINE_SEGMENTS_LENGTH
if (
(newSegment.speaker === priorSegment.speaker || newSegment.speaker === lastSpeaker) &&
joinBody(priorSegment.body, newSegment.body, " ").length <= combineSegmentsLength
) {
return {
segment: joinSegments([priorSegment, newSegment], " "),
replace: true,
combined: true,
}
}
return {
segment: newSegment,
replace: false,
combined: false,
}
}
/**
* Checks if the new and prior segments have the same speaker, startTime and endTime.
*
* If so, combines segments where:
* - `startTime`: from priorSegment
* - `startTimeFormatted`: from priorSegment
* - `endTime`: from newSegment
* - `endTimeFormatted`: from newSegment
* - `speaker`: from priorSegment
* - `body`: body of priorSegment with body of newSegment separated with value of separator argument
*
* @param newSegment segment being created
* @param priorSegment prior parsed segment
* @param separator string to use to combine body values. If undefined, uses "\n"
* @param lastSpeaker last speaker name.
* Used when speaker in segment has been removed via {@link Options.speakerChange} rule
* @returns result of combination.
* If segments were combined, {@link CombineResult.replace} and {@link CombineResult.combined} set to true.
*/
const doCombineEqualTimes = (
newSegment: Segment,
priorSegment: Segment,
separator: string,
lastSpeaker: string
): CombineResult => {
const combineEqualTimesSeparator = separator || "\n"
if (
newSegment.startTime === priorSegment.startTime &&
newSegment.endTime === priorSegment.endTime &&
(newSegment.speaker === priorSegment.speaker || newSegment.speaker === lastSpeaker)
) {
return {
segment: joinSegments([priorSegment, newSegment], combineEqualTimesSeparator),
replace: true,
combined: true,
}
}
return {
segment: newSegment,
replace: false,
combined: false,
}
}
/**
* Checks if the new and prior segments have the same speaker. If so, sets the speaker value to undefined
*
* If so, combines segments where:
* - `startTime`: from priorSegment
* - `startTimeFormatted`: from priorSegment
* - `endTime`: from newSegment
* - `endTimeFormatted`: from newSegment
* - `speaker`: from newSegment if different from priorSegment else undefined
* - `body`: body of priorSegment with body of newSegment separated with space
*
* @param newSegment segment being created
* @param priorSegment prior parsed segment. For the first segment, this shall be undefined.
* @param lastSpeaker last speaker name.
* Used when speaker in segment has been removed via {@link Options.speakerChange} rule
* @returns result of combination.
* If segments were combined, {@link CombineResult.replace} set to false and {@link CombineResult.combined} set to true.
*/
const doSpeakerChange = (newSegment: Segment, priorSegment: Segment, lastSpeaker: string): CombineResult => {
const result: CombineResult = {
segment: newSegment,
replace: false,
combined: false,
}
if (priorSegment === undefined) {
if (newSegment.speaker === lastSpeaker) {
const segment: Segment = { ...newSegment }
segment.speaker = undefined
return {
segment,
replace: false,
combined: true,
}
}
return result
}
if (newSegment.speaker === undefined) {
return result
}
if (
newSegment.speaker === "" ||
newSegment.speaker === priorSegment.speaker ||
newSegment.speaker === lastSpeaker
) {
const segment: Segment = { ...newSegment }
segment.speaker = undefined
return {
segment,
replace: false,
combined: true,
}
}
return result
}
/**
* Determine how {@link Options.speakerChange is applied based an past options being applied}
*
* @param currentResult current result object from any prior options
* @param priorSegment prior parsed segment
* @param lastSpeaker last speaker name.
* @returns result of combination.
* If segments were combined, {@link CombineResult.replace} set to false and {@link CombineResult.combined} set to true.
*/
const applyOptionsAndDoSpeakerChange = (
currentResult: CombineResult,
priorSegment: Segment,
lastSpeaker: string
): CombineResult => {
const { combineSegments, combineEqualTimes } = Options
let result = currentResult
if (combineSegments && currentResult.combined && currentResult.replace) {
result = doSpeakerChange(currentResult.segment, undefined, undefined)
} else if (combineEqualTimes) {
if (result.combined && result.replace) {
result = doSpeakerChange(currentResult.segment, undefined, undefined)
} else {
result = doSpeakerChange(currentResult.segment, priorSegment, lastSpeaker)
}
} else {
result = doSpeakerChange(currentResult.segment, priorSegment, lastSpeaker)
}
if (result) {
result = {
segment: result.segment,
replace: currentResult.replace || result.replace,
combined: currentResult.combined || result.combined,
}
}
return result
}
/**
* Apply convert rules when no prior segment exits.
*
* NOTE: not all rules applicable when no prior segment
*
* @param newSegment segment before any rules options to it
* @param lastSpeaker last speaker name.
* Used when speaker in segment has been removed via {@link Options.speakerChange} rule
* @returns the updated segment info
*/
const doCombineNoPrior = (newSegment: Segment, lastSpeaker: string): CombineResult => {
const { speakerChange } = Options
let result: CombineResult = {
segment: newSegment,
replace: false,
combined: false,
}
if (speakerChange) {
result = doSpeakerChange(result.segment, undefined, lastSpeaker)
}
return result
}
/**
* Apply convert rules when prior segment exits.
*
* @param newSegment segment before any rules options to it
* @param priorSegment prior parsed segment
* @param lastSpeaker last speaker name.
* Used when speaker in segment has been removed via {@link Options.speakerChange} rule
* @returns the updated segment info
*/
const doCombineWithPrior = (newSegment: Segment, priorSegment: Segment, lastSpeaker: string): CombineResult => {
const {
combineEqualTimes,
combineEqualTimesSeparator,
combineSegments,
combineSegmentsLength,
combineSpeaker,
speakerChange,
} = Options
let result: CombineResult = {
segment: { ...newSegment },
replace: false,
combined: false,
}
let combinedSpeaker = false
if (combineSpeaker) {
result = doCombineSpeaker(result.segment, priorSegment, lastSpeaker)
combinedSpeaker = result.combined
}
if (!combinedSpeaker && combineEqualTimes) {
result = doCombineEqualTimes(result.segment, priorSegment, combineEqualTimesSeparator, lastSpeaker)
}
if (!combinedSpeaker && combineSegments) {
let combineResult
if (combineEqualTimes && result.combined) {
combineResult = doCombineSegments(result.segment, undefined, combineSegmentsLength, lastSpeaker)
} else {
combineResult = doCombineSegments(result.segment, priorSegment, combineSegmentsLength, lastSpeaker)
}
if (combineResult) {
result = {
segment: combineResult.segment,
replace: result.replace || combineResult.replace,
combined: result.combined || combineResult.combined,
}
}
}
if (speakerChange) {
result = applyOptionsAndDoSpeakerChange(result, priorSegment, lastSpeaker)
}
return result
}
/**
* Apply any options to the current segment
*
* @param newSegment segment before any rules options to it
* @param priorSegment prior parsed segment. For the first segment, this shall be undefined.
* @param lastSpeaker last speaker name.
* Used when speaker in segment has been removed via {@link Options.speakerChange} rule
* @returns the updated segment info
*/
const applyOptions = (newSegment: Segment, priorSegment: Segment, lastSpeaker: string = undefined): CombineResult => {
if (!Options.optionsSet()) {
return {
segment: newSegment,
replace: false,
combined: false,
}
}
let result: CombineResult
// if no prior segment, limited additional checking
if (priorSegment === undefined) {
result = doCombineNoPrior(newSegment, lastSpeaker)
} else {
result = doCombineWithPrior(newSegment, priorSegment, lastSpeaker)
}
return result
}
/**
* Get the last speaker name from the previously parsed segments
*
* @param priorSegment prior parsed segment
* @param priorSegments array of all previous segments
* @returns the name of the last speaker
*/
const getLastSpeaker = (priorSegment: Segment, priorSegments: Array<Segment>): string => {
let lastSpeaker
if (priorSegment) {
lastSpeaker = priorSegment.speaker
}
if (lastSpeaker === undefined && priorSegments.length > 0) {
lastSpeaker = priorSegments[0].speaker
for (let i = priorSegments.length - 1; i > 0; i--) {
if (priorSegments[i].speaker !== undefined) {
lastSpeaker = priorSegments[i].speaker
break
}
}
}
return lastSpeaker
}
/**
* Helper for adding segment to or updating last segment in array of segments
*
* @param newSegment segment to add or replace
* @param priorSegments array of all previous segments
* @returns updated array of segments with new segment added or last segment updated (per options)
*/
export const addSegment = (newSegment: Segment, priorSegments: Array<Segment>): Array<Segment> => {
const { speakerChange } = Options
const outSegments = priorSegments || []
const priorSegment = outSegments.length > 0 ? outSegments[outSegments.length - 1] : undefined
// don't worry about identifying the last speaker if speaker is not being removed by speakerChange
let lastSpeaker: string
if (speakerChange) {
lastSpeaker = getLastSpeaker(priorSegment, outSegments)
}
const newSegmentInfo = applyOptions(newSegment, priorSegment, lastSpeaker)
if (newSegmentInfo.replace && outSegments.length > 0) {
outSegments[outSegments.length - 1] = newSegmentInfo.segment
} else {
outSegments.push(newSegmentInfo.segment)
}
return outSegments
}
| src/segments.ts | stevencrader-transcriptator-75faa70 | [
{
"filename": "src/formats/json.ts",
"retrieved_chunk": "const parseDictSegmentsJSON = (data: JSONTranscript): Array<Segment> => {\n let outSegments: Array<Segment> = []\n data.segments.forEach((segment) => {\n outSegments = addSegment(\n {\n startTime: segment.startTime,\n startTimeFormatted: TimestampFormatter.format(segment.startTime),\n endTime: segment.endTime,\n endTimeFormatted: TimestampFormatter.format(segment.endTime),\n speaker: segment.speaker,",
"score": 29.887941823471294
},
{
"filename": "src/formats/json.ts",
"retrieved_chunk": "import { addSegment } from \"../segments\"\nimport { parseSpeaker } from \"../speaker\"\nimport { TimestampFormatter } from \"../timestamp\"\nimport { Segment } from \"../types\"\n/**\n * Define a segment/cue used in the JSONTranscript format\n */\nexport type JSONSegment = {\n /**\n * Time (in seconds) when segment starts",
"score": 23.70659332824911
},
{
"filename": "src/formats/json.ts",
"retrieved_chunk": " startTimeFormatted: TimestampFormatter.format(startTime),\n endTime,\n endTimeFormatted: TimestampFormatter.format(endTime),\n speaker,\n body: message,\n }\n if (Number.isNaN(segment.startTime)) {\n console.warn(`Computed start time is NaN: ${segment.startTime}`)\n return undefined\n }",
"score": 23.70526904096872
},
{
"filename": "src/formats/srt.ts",
"retrieved_chunk": "import { addSegment } from \"../segments\"\nimport { parseSpeaker } from \"../speaker\"\nimport { parseTimestamp, TimestampFormatter } from \"../timestamp\"\nimport { PATTERN_LINE_SEPARATOR, Segment } from \"../types\"\n/**\n * Define a segment/cue parsed from SRT file\n */\nexport type SRTSegment = {\n /**\n * Cue number",
"score": 23.224089560454395
},
{
"filename": "src/formats/srt.ts",
"retrieved_chunk": "}\n/**\n * Create Segment from lines containing an SRT segment/cue\n *\n * @param segmentLines Lines containing SRT data\n * @param lastSpeaker Name of last speaker. Will be used if no speaker found in `segmentLines`\n * @returns Created segment\n */\nconst createSegmentFromSRTLines = (segmentLines: Array<string>, lastSpeaker: string): Segment => {\n const srtSegment = parseSRTSegment(segmentLines)",
"score": 22.241542025327718
}
] | typescript | (segments: Array<Segment>, bodySeparator: string = undefined): Segment => { |
import { Options } from "./options"
import { TimestampFormatter } from "./timestamp"
import { DEFAULT_COMBINE_SEGMENTS_LENGTH, Segment } from "./types"
/**
* Regular Expression for detecting punctuation that should not be prefixed with a space
*/
const PATTERN_PUNCTUATIONS = /^ *[.,?!}\]>) *$]/
/**
* Regular Expression for detecting space characters at the end of a string
*/
const PATTERN_TRAILING_SPACE = /^ *$/
/**
* Remove any trailing space characters from data
*
* @param data text to trim
* @returns text with any trailing space character removed
*/
const trimEndSpace = (data: string): string => {
return data.replace(PATTERN_TRAILING_SPACE, "")
}
/**
* Append `addition` to `body` with the character(s) specified.
*
* If `addition` matches the {@link PATTERN_PUNCTUATIONS} pattern, no character is added before the additional data.
*
* @param body Current body text
* @param addition Additional text to add to `body`
* @param separator Character(s) to use to separate data. If undefined, uses `\n`.
* @returns Combined data
*/
const joinBody = (body: string, addition: string, separator: string = undefined): string => {
if (body) {
let separatorToUse = separator || "\n"
if (PATTERN_PUNCTUATIONS.exec(addition)) {
separatorToUse = ""
}
return `${trimEndSpace(body)}${separatorToUse}${trimEndSpace(addition)}`
}
return trimEndSpace(addition)
}
/**
* Combine one or more {@link Segment}
*
* @param segments Array of Segment objects to combine
* @param bodySeparator Character(s) to use to separate body data. If undefined, uses `\n`.
* @returns Combined segment where:
*
* - `startTime`: from first segment
* - `startTimeFormatted`: from first segment
* - `endTime`: from last segment
* - `endTimeFormatted`: from last segment
* - `speaker`: from first segment
* - `body`: combination of all segments
*/
const joinSegments = (segments: Array<Segment>, bodySeparator: string = undefined): Segment => {
const newSegment = { ...segments[0] }
segments.slice(1).forEach((segment) => {
newSegment.endTime = segment.endTime
newSegment.endTimeFormatted = TimestampFormatter.format(segment.endTime)
newSegment.body = joinBody(newSegment.body, segment.body, bodySeparator)
})
return newSegment
}
/**
* Type returned from combine functions
*/
type CombineResult = {
/**
* The updated segment with any changes applied
*/
segment: Segment
/**
* If true, the {@link segment} contains a {@link Segment} that should replace the prior segment instead of
* appending a new segment
*/
replace: boolean
/**
* Indicates if the combine rule was applied
*/
combined: boolean
}
/**
* Checks if the new and prior segments have the same speaker.
*
* If so, combines segments where:
* - `startTime`: from priorSegment
* - `startTimeFormatted`: from priorSegment
* - `endTime`: from newSegment
* - `endTimeFormatted`: from newSegment
* - `speaker`: from priorSegment
* - `body`: body of priorSegment with body of newSegment separated with space
*
* @param newSegment segment being created
* @param priorSegment prior parsed segment
* @param lastSpeaker last speaker name.
* Used when speaker in segment has been removed via {@link Options.speakerChange} rule
* @returns result of combination.
* If segments were combined, {@link CombineResult.replace} and {@link CombineResult.combined} set to true.
*/
const doCombineSpeaker = (newSegment: Segment, priorSegment: Segment, lastSpeaker: string): CombineResult => {
if (newSegment.speaker === priorSegment.speaker || newSegment.speaker === lastSpeaker) {
return {
segment: joinSegments([priorSegment, newSegment], " "),
replace: true,
combined: true,
}
}
return {
segment: newSegment,
replace: false,
combined: false,
}
}
/**
* Checks if the new and prior segments have the same speaker and combining body results in new body shorter than
* max length
*
* If so, combines segments where:
* - `startTime`: from priorSegment
* - `startTimeFormatted`: from priorSegment
* - `endTime`: from newSegment
* - `endTimeFormatted`: from newSegment
* - `speaker`: from priorSegment
* - `body`: body of priorSegment with body of newSegment separated with space
*
* @param newSegment segment being created
* @param priorSegment prior parsed segment
* @param maxLength maximum allowed length of combined body. If undefined, uses {@link DEFAULT_COMBINE_SEGMENTS_LENGTH}
* @param lastSpeaker last speaker name.
* Used when speaker in segment has been removed via {@link Options.speakerChange} rule
* @returns result of combination.
* If segments were combined, {@link CombineResult.replace} and {@link CombineResult.combined} set to true.
*/
const doCombineSegments = (
newSegment: Segment,
priorSegment: Segment,
maxLength: number,
lastSpeaker: string
): CombineResult => {
if (priorSegment === undefined) {
return {
segment: newSegment,
replace: false,
combined: false,
}
}
const combineSegmentsLength = maxLength || DEFAULT_COMBINE_SEGMENTS_LENGTH
if (
(newSegment.speaker === priorSegment.speaker || newSegment.speaker === lastSpeaker) &&
joinBody(priorSegment.body, newSegment.body, " ").length <= combineSegmentsLength
) {
return {
segment: joinSegments([priorSegment, newSegment], " "),
replace: true,
combined: true,
}
}
return {
segment: newSegment,
replace: false,
combined: false,
}
}
/**
* Checks if the new and prior segments have the same speaker, startTime and endTime.
*
* If so, combines segments where:
* - `startTime`: from priorSegment
* - `startTimeFormatted`: from priorSegment
* - `endTime`: from newSegment
* - `endTimeFormatted`: from newSegment
* - `speaker`: from priorSegment
* - `body`: body of priorSegment with body of newSegment separated with value of separator argument
*
* @param newSegment segment being created
* @param priorSegment prior parsed segment
* @param separator string to use to combine body values. If undefined, uses "\n"
* @param lastSpeaker last speaker name.
* Used when speaker in segment has been removed via {@link Options.speakerChange} rule
* @returns result of combination.
* If segments were combined, {@link CombineResult.replace} and {@link CombineResult.combined} set to true.
*/
const doCombineEqualTimes = (
newSegment: Segment,
priorSegment: Segment,
separator: string,
lastSpeaker: string
): CombineResult => {
const combineEqualTimesSeparator = separator || "\n"
if (
newSegment.startTime === priorSegment.startTime &&
newSegment.endTime === priorSegment.endTime &&
(newSegment.speaker === priorSegment.speaker || newSegment.speaker === lastSpeaker)
) {
return {
segment: joinSegments([priorSegment, newSegment], combineEqualTimesSeparator),
replace: true,
combined: true,
}
}
return {
segment: newSegment,
replace: false,
combined: false,
}
}
/**
* Checks if the new and prior segments have the same speaker. If so, sets the speaker value to undefined
*
* If so, combines segments where:
* - `startTime`: from priorSegment
* - `startTimeFormatted`: from priorSegment
* - `endTime`: from newSegment
* - `endTimeFormatted`: from newSegment
* - `speaker`: from newSegment if different from priorSegment else undefined
* - `body`: body of priorSegment with body of newSegment separated with space
*
* @param newSegment segment being created
* @param priorSegment prior parsed segment. For the first segment, this shall be undefined.
* @param lastSpeaker last speaker name.
* Used when speaker in segment has been removed via {@link Options.speakerChange} rule
* @returns result of combination.
* If segments were combined, {@link CombineResult.replace} set to false and {@link CombineResult.combined} set to true.
*/
const doSpeakerChange = (newSegment: Segment, priorSegment: Segment, lastSpeaker: string): CombineResult => {
const result: CombineResult = {
segment: newSegment,
replace: false,
combined: false,
}
if (priorSegment === undefined) {
if (newSegment.speaker === lastSpeaker) {
const segment: Segment = { ...newSegment }
segment.speaker = undefined
return {
segment,
replace: false,
combined: true,
}
}
return result
}
if (newSegment.speaker === undefined) {
return result
}
if (
newSegment.speaker === "" ||
newSegment.speaker === priorSegment.speaker ||
newSegment.speaker === lastSpeaker
) {
const segment: Segment = { ...newSegment }
segment.speaker = undefined
return {
segment,
replace: false,
combined: true,
}
}
return result
}
/**
* Determine how {@link Options.speakerChange is applied based an past options being applied}
*
* @param currentResult current result object from any prior options
* @param priorSegment prior parsed segment
* @param lastSpeaker last speaker name.
* @returns result of combination.
* If segments were combined, {@link CombineResult.replace} set to false and {@link CombineResult.combined} set to true.
*/
const applyOptionsAndDoSpeakerChange = (
currentResult: CombineResult,
priorSegment: Segment,
lastSpeaker: string
): CombineResult => {
| const { combineSegments, combineEqualTimes } = Options
let result = currentResult
if (combineSegments && currentResult.combined && currentResult.replace) { |
result = doSpeakerChange(currentResult.segment, undefined, undefined)
} else if (combineEqualTimes) {
if (result.combined && result.replace) {
result = doSpeakerChange(currentResult.segment, undefined, undefined)
} else {
result = doSpeakerChange(currentResult.segment, priorSegment, lastSpeaker)
}
} else {
result = doSpeakerChange(currentResult.segment, priorSegment, lastSpeaker)
}
if (result) {
result = {
segment: result.segment,
replace: currentResult.replace || result.replace,
combined: currentResult.combined || result.combined,
}
}
return result
}
/**
* Apply convert rules when no prior segment exits.
*
* NOTE: not all rules applicable when no prior segment
*
* @param newSegment segment before any rules options to it
* @param lastSpeaker last speaker name.
* Used when speaker in segment has been removed via {@link Options.speakerChange} rule
* @returns the updated segment info
*/
const doCombineNoPrior = (newSegment: Segment, lastSpeaker: string): CombineResult => {
const { speakerChange } = Options
let result: CombineResult = {
segment: newSegment,
replace: false,
combined: false,
}
if (speakerChange) {
result = doSpeakerChange(result.segment, undefined, lastSpeaker)
}
return result
}
/**
* Apply convert rules when prior segment exits.
*
* @param newSegment segment before any rules options to it
* @param priorSegment prior parsed segment
* @param lastSpeaker last speaker name.
* Used when speaker in segment has been removed via {@link Options.speakerChange} rule
* @returns the updated segment info
*/
const doCombineWithPrior = (newSegment: Segment, priorSegment: Segment, lastSpeaker: string): CombineResult => {
const {
combineEqualTimes,
combineEqualTimesSeparator,
combineSegments,
combineSegmentsLength,
combineSpeaker,
speakerChange,
} = Options
let result: CombineResult = {
segment: { ...newSegment },
replace: false,
combined: false,
}
let combinedSpeaker = false
if (combineSpeaker) {
result = doCombineSpeaker(result.segment, priorSegment, lastSpeaker)
combinedSpeaker = result.combined
}
if (!combinedSpeaker && combineEqualTimes) {
result = doCombineEqualTimes(result.segment, priorSegment, combineEqualTimesSeparator, lastSpeaker)
}
if (!combinedSpeaker && combineSegments) {
let combineResult
if (combineEqualTimes && result.combined) {
combineResult = doCombineSegments(result.segment, undefined, combineSegmentsLength, lastSpeaker)
} else {
combineResult = doCombineSegments(result.segment, priorSegment, combineSegmentsLength, lastSpeaker)
}
if (combineResult) {
result = {
segment: combineResult.segment,
replace: result.replace || combineResult.replace,
combined: result.combined || combineResult.combined,
}
}
}
if (speakerChange) {
result = applyOptionsAndDoSpeakerChange(result, priorSegment, lastSpeaker)
}
return result
}
/**
* Apply any options to the current segment
*
* @param newSegment segment before any rules options to it
* @param priorSegment prior parsed segment. For the first segment, this shall be undefined.
* @param lastSpeaker last speaker name.
* Used when speaker in segment has been removed via {@link Options.speakerChange} rule
* @returns the updated segment info
*/
const applyOptions = (newSegment: Segment, priorSegment: Segment, lastSpeaker: string = undefined): CombineResult => {
if (!Options.optionsSet()) {
return {
segment: newSegment,
replace: false,
combined: false,
}
}
let result: CombineResult
// if no prior segment, limited additional checking
if (priorSegment === undefined) {
result = doCombineNoPrior(newSegment, lastSpeaker)
} else {
result = doCombineWithPrior(newSegment, priorSegment, lastSpeaker)
}
return result
}
/**
* Get the last speaker name from the previously parsed segments
*
* @param priorSegment prior parsed segment
* @param priorSegments array of all previous segments
* @returns the name of the last speaker
*/
const getLastSpeaker = (priorSegment: Segment, priorSegments: Array<Segment>): string => {
let lastSpeaker
if (priorSegment) {
lastSpeaker = priorSegment.speaker
}
if (lastSpeaker === undefined && priorSegments.length > 0) {
lastSpeaker = priorSegments[0].speaker
for (let i = priorSegments.length - 1; i > 0; i--) {
if (priorSegments[i].speaker !== undefined) {
lastSpeaker = priorSegments[i].speaker
break
}
}
}
return lastSpeaker
}
/**
* Helper for adding segment to or updating last segment in array of segments
*
* @param newSegment segment to add or replace
* @param priorSegments array of all previous segments
* @returns updated array of segments with new segment added or last segment updated (per options)
*/
export const addSegment = (newSegment: Segment, priorSegments: Array<Segment>): Array<Segment> => {
const { speakerChange } = Options
const outSegments = priorSegments || []
const priorSegment = outSegments.length > 0 ? outSegments[outSegments.length - 1] : undefined
// don't worry about identifying the last speaker if speaker is not being removed by speakerChange
let lastSpeaker: string
if (speakerChange) {
lastSpeaker = getLastSpeaker(priorSegment, outSegments)
}
const newSegmentInfo = applyOptions(newSegment, priorSegment, lastSpeaker)
if (newSegmentInfo.replace && outSegments.length > 0) {
outSegments[outSegments.length - 1] = newSegmentInfo.segment
} else {
outSegments.push(newSegmentInfo.segment)
}
return outSegments
}
| src/segments.ts | stevencrader-transcriptator-75faa70 | [
{
"filename": "src/options.ts",
"retrieved_chunk": " */\n public combineEqualTimes = false\n /**\n * Character to use when {@link combineEqualTimes} is true.\n */\n public combineEqualTimesSeparator = \"\\n\"\n /**\n * Combine segments where speaker is the same and concatenated `body` fits in the {@link combineSegmentsLength}\n *\n * Can be used with {@link combineEqualTimes}. The {@link combineSegments} rule is applied first.",
"score": 19.997155452151517
},
{
"filename": "src/types.ts",
"retrieved_chunk": " * Text of transcript for segment\n */\n body: string\n}\n/**\n * Default length to use when combining segments with {@link Options.combineSegments}\n */\nexport const DEFAULT_COMBINE_SEGMENTS_LENGTH = 32",
"score": 16.680473630654646
},
{
"filename": "src/options.ts",
"retrieved_chunk": " /**\n * Combine consecutive segments from the same speaker.\n *\n * Note: If this is enabled, {@link combineEqualTimes} and {@link combineSegments} will not be applied.\n *\n * Warning: if the transcript does not contain speaker information, resulting segment will contain entire transcript text.\n */\n public combineSpeaker = false\n /**\n * Only include {@link Segment.speaker} when speaker changes",
"score": 16.54027390775514
},
{
"filename": "src/options.ts",
"retrieved_chunk": " */\n combineSegments?: boolean\n /**\n * Max length of body text to use when {@link combineSegments} is true\n *\n * Default: See {@link DEFAULT_COMBINE_SEGMENTS_LENGTH}\n */\n combineSegmentsLength?: number\n /**\n * Combine consecutive segments from the same speaker.",
"score": 15.786987766761643
},
{
"filename": "src/options.ts",
"retrieved_chunk": " *\n * @param options the options to set\n * @param setDefault true: set all values to the default before setting values specified by `options`\n */\n public setOptions = (options: IOptions, setDefault = true): void => {\n if (setDefault) {\n this.restoreDefaultSettings()\n }\n if (options === undefined) {\n return",
"score": 15.373637034849617
}
] | typescript | const { combineSegments, combineEqualTimes } = Options
let result = currentResult
if (combineSegments && currentResult.combined && currentResult.replace) { |
import { pascalCase } from 'change-case'
import { AlgoAppSpec, CallConfig, CallConfigValue } from '../../schema/application'
export const BARE_CALL = Symbol('bare')
export type MethodIdentifier = string | typeof BARE_CALL
export type MethodList = Array<MethodIdentifier>
export type CallConfigSummary = {
createMethods: MethodList
callMethods: MethodList
deleteMethods: MethodList
updateMethods: MethodList
optInMethods: MethodList
closeOutMethods: MethodList
}
export const getCallConfigSummary = (app: AlgoAppSpec) => {
const result: CallConfigSummary = {
createMethods: [],
callMethods: [],
deleteMethods: [],
updateMethods: [],
optInMethods: [],
closeOutMethods: [],
}
if (app.bare_call_config) {
addToConfig(result, BARE_CALL, app.bare_call_config)
}
if (app.hints) {
for (const [method, hints] of Object.entries(app.hints)) {
if (hints.call_config) {
addToConfig(result, method, hints.call_config)
}
}
}
return result
}
export const getCreateOnComplete = (app: AlgoAppSpec, method: MethodIdentifier) => {
const callConfig = method === BARE_CALL ? app.bare_call_config : app.hints?.[method]?.call_config
if (!callConfig) {
return ''
}
const hasNoOp = callConfig.no_op === 'ALL' || callConfig.no_op === 'CREATE'
return `{ onCompleteAction${hasNoOp ? '?' : ''}: ${getCreateOnCompleteTypes(callConfig)} }`
}
const getCreateOnCompleteTypes = (config: CallConfig) => {
return Object.keys(config)
.map((oc) => oc as keyof CallConfig)
.filter((oc) => config[oc] === 'ALL' || config[oc] === 'CREATE')
| .map((oc) => `'${oc}' | OnApplicationComplete.${pascalCase(oc)}OC`)
.join(' | ')
} |
const addToConfig = (result: CallConfigSummary, method: MethodIdentifier, config: CallConfig) => {
if (hasCall(config.no_op)) {
result.callMethods.push(method)
}
if (
hasCreate(config.no_op) ||
hasCreate(config.opt_in) ||
hasCreate(config.close_out) ||
hasCreate(config.update_application) ||
hasCreate(config.delete_application)
) {
result.createMethods.push(method)
}
if (hasCall(config.delete_application)) {
result.deleteMethods.push(method)
}
if (hasCall(config.update_application)) {
result.updateMethods.push(method)
}
if (hasCall(config.opt_in)) {
result.optInMethods.push(method)
}
if (hasCall(config.close_out)) {
result.closeOutMethods.push(method)
}
}
const hasCall = (config: CallConfigValue | undefined) => {
return config === 'CALL' || config === 'ALL'
}
const hasCreate = (config: CallConfigValue | undefined) => {
return config === 'CREATE' || config === 'ALL'
}
| src/client/helpers/get-call-config-summary.ts | algorandfoundation-algokit-client-generator-ts-2de43ed | [
{
"filename": "src/client/deploy-types.ts",
"retrieved_chunk": " ? `(${Object.entries(callConfig)\n .filter(([_, value]) => value === 'ALL' || value === 'CREATE')\n .map(([oc]) => OnCompleteCodeMap[oc as keyof CallConfig])\n .join(' | ')})`\n : {}\n return {\n type: onCompleteType,\n isOptional: hasNoOp,\n }\n}",
"score": 132.20583887921072
},
{
"filename": "src/client/deploy-types.ts",
"retrieved_chunk": "import { DecIndent, DecIndentAndCloseBlock, DocumentParts, IncIndent, jsDoc, NewLine } from '../output/writer'\nimport { makeSafeTypeIdentifier } from '../util/sanitization'\nimport { BARE_CALL, MethodIdentifier } from './helpers/get-call-config-summary'\nimport { GeneratorContext } from './generator-context'\nimport { AlgoAppSpec, CallConfig } from '../schema/application'\nimport { OnCompleteCodeMap } from './utility-types'\nexport function getCreateOnCompleteOptions(method: MethodIdentifier, app: AlgoAppSpec) {\n const callConfig = method === BARE_CALL ? app.bare_call_config : app.hints?.[method]?.call_config\n const hasNoOp = callConfig?.no_op === 'ALL' || callConfig?.no_op === 'CREATE'\n const onCompleteType = callConfig",
"score": 45.016134482011246
},
{
"filename": "src/client/call-client.ts",
"retrieved_chunk": "}\nfunction* noopMethods({ app, name, callConfig, methodSignatureToUniqueName }: GeneratorContext): DocumentParts {\n for (const method of app.contract.methods) {\n const methodSignature = algokit.getABIMethodSignature(method)\n const methodName = makeSafeMethodIdentifier(methodSignatureToUniqueName[methodSignature])\n // Skip methods which don't support a no_op call config\n if (!callConfig.callMethods.includes(methodSignature)) continue\n yield* jsDoc({\n description: `Calls the ${algokit.getABIMethodSignature(method)} ABI method.`,\n abiDescription: method.desc,",
"score": 20.608941428941854
},
{
"filename": "src/schema/application.d.ts",
"retrieved_chunk": " */\n data: string | number;\n };\nexport type CallConfigValue = \"NEVER\" | \"CALL\" | \"CREATE\" | \"ALL\";\nexport interface AlgoAppSpec {\n hints?: {\n [k: string]: Hint;\n };\n source: AppSources;\n contract: AbiContract;",
"score": 19.175186114271852
},
{
"filename": "src/client/utility-types.ts",
"retrieved_chunk": "import { DecIndentAndCloseBlock, DocumentParts, IncIndent, jsDoc } from '../output/writer'\nexport function* utilityTypes(): DocumentParts {\n yield* jsDoc(`Defines an onCompletionAction of 'no_op'`)\n yield `export type OnCompleteNoOp = { onCompleteAction?: 'no_op' | OnApplicationComplete.NoOpOC }`\n yield* jsDoc(`Defines an onCompletionAction of 'opt_in'`)\n yield `export type OnCompleteOptIn = { onCompleteAction: 'opt_in' | OnApplicationComplete.OptInOC }`\n yield* jsDoc(`Defines an onCompletionAction of 'close_out'`)\n yield `export type OnCompleteCloseOut = { onCompleteAction: 'close_out' | OnApplicationComplete.CloseOutOC }`\n yield* jsDoc(`Defines an onCompletionAction of 'delete_application'`)\n yield `export type OnCompleteDelApp = { onCompleteAction: 'delete_application' | OnApplicationComplete.DeleteApplicationOC }`",
"score": 18.505701434494156
}
] | typescript | .map((oc) => `'${oc}' | OnApplicationComplete.${pascalCase(oc)}OC`)
.join(' | ')
} |
import { addSegment } from "../segments"
import { parseSpeaker } from "../speaker"
import { parseTimestamp, TimestampFormatter } from "../timestamp"
import { PATTERN_LINE_SEPARATOR, Segment } from "../types"
/**
* Define a segment/cue parsed from SRT file
*/
export type SRTSegment = {
/**
* Cue number
*/
index: number
/**
* Time (in seconds) when segment starts
*/
startTime: number
/**
* Time (in seconds) when segment ends
*/
endTime: number
/**
* Name of speaker for `body`
*/
speaker: string
/**
* Text of transcript for segment
*/
body: string
}
/**
* Parse lines looking for data to be SRT format
*
* @param lines Lines containing SRT data
* @returns Parsed segment
* @throws {Error} When no non-empty strings in `lines`
* @throws {Error} When the minimum required number of lines is not received
* @throws {Error} When segment lines does not start with a number
* @throws {Error} When second segment line does not follow the timestamp format
*/
export const parseSRTSegment = (lines: Array<string>): SRTSegment => {
do {
if (lines.length === 0) {
throw new Error("SRT segment lines empty")
} else if (lines[0].trim() === "") {
lines.shift()
} else {
break
}
} while (lines.length > 0)
if (lines.length < 3) {
throw new Error(`SRT requires at least 3 lines, ${lines.length} received`)
}
const index = parseInt(lines[0], 10)
if (!index) {
throw new Error(`First line of SRT segment is not a number`)
}
const timestampLine = lines[1]
if (!timestampLine.includes("-->")) {
throw new Error(`SRT timestamp line does not include --> separator`)
}
const timestampParts = timestampLine.split("-->")
if (timestampParts.length !== 2) {
throw new Error(`SRT timestamp line contains more than 2 --> separators`)
}
const startTime = parseTimestamp(timestampParts[0].trim())
const endTime = parseTimestamp(timestampParts[1].trim())
let bodyLines = lines.slice(2)
const emptyLineIndex = bodyLines.findIndex((v) => v.trim() === "")
if (emptyLineIndex > 0) {
bodyLines = bodyLines.slice(0, emptyLineIndex)
}
const { speaker, message } = parseSpeaker(bodyLines.shift())
bodyLines = [message].concat(bodyLines)
return {
startTime,
endTime,
speaker,
body: bodyLines.join("\n"),
index,
}
}
/**
* Create Segment from lines containing an SRT segment/cue
*
* @param segmentLines Lines containing SRT data
* @param lastSpeaker Name of last speaker. Will be used if no speaker found in `segmentLines`
* @returns Created segment
*/
const createSegmentFromSRTLines = (segmentLines: Array<string>, lastSpeaker: string): Segment => {
const srtSegment = parseSRTSegment(segmentLines)
const calculatedSpeaker = srtSegment.speaker ? srtSegment.speaker : lastSpeaker
return {
startTime: srtSegment.startTime,
startTimeFormatted: TimestampFormatter.format(srtSegment.startTime),
endTime: srtSegment.endTime,
endTimeFormatted: TimestampFormatter.format(srtSegment.endTime),
speaker: calculatedSpeaker,
body: srtSegment.body,
}
}
/**
* Determines if the value of data is a valid SRT transcript format
*
* @param data The transcript data
* @returns True: data is valid SRT transcript format
*/
export const isSRT = (data: string): boolean => {
try {
return parseSRTSegment(data | .split(PATTERN_LINE_SEPARATOR).slice(0, 20)) !== undefined
} catch (e) { |
return false
}
}
/**
* Parse SRT data to an Array of {@link Segment}
*
* @param data The transcript data
* @returns An array of Segments from the parsed data
* @throws {TypeError} When `data` is not valid SRT format
*/
export const parseSRT = (data: string): Array<Segment> => {
if (!isSRT(data)) {
throw new TypeError(`Data is not valid SRT format`)
}
let outSegments: Array<Segment> = []
let lastSpeaker = ""
let segmentLines = []
data.split(PATTERN_LINE_SEPARATOR).forEach((line, count) => {
// separator line found, handle previous data
if (line.trim() === "") {
// handle consecutive multiple blank lines
if (segmentLines.length !== 0) {
try {
outSegments = addSegment(createSegmentFromSRTLines(segmentLines, lastSpeaker), outSegments)
lastSpeaker = outSegments[outSegments.length - 1].speaker
} catch (e) {
console.error(`Error parsing SRT segment lines (source line ${count}): ${e}`)
console.error(segmentLines)
}
}
segmentLines = [] // clear buffer
} else {
segmentLines.push(line)
}
})
// handle data when trailing line not included
if (segmentLines.length !== 0) {
try {
outSegments = addSegment(createSegmentFromSRTLines(segmentLines, lastSpeaker), outSegments)
lastSpeaker = outSegments[outSegments.length - 1].speaker
} catch (e) {
console.error(`Error parsing final SRT segment lines: ${e}`)
console.error(segmentLines)
}
}
return outSegments
}
| src/formats/srt.ts | stevencrader-transcriptator-75faa70 | [
{
"filename": "src/formats/html.ts",
"retrieved_chunk": "}\n/**\n * Determines if the value of data is a valid HTML transcript format\n *\n * @param data The transcript data\n * @returns True: data is valid HTML transcript format\n */\nexport const isHTML = (data: string): boolean => {\n return (\n data.startsWith(\"<!--\") ||",
"score": 53.34521996273871
},
{
"filename": "src/formats/json.ts",
"retrieved_chunk": " /**\n * Text of transcript for segment\n */\n text: string\n}\n/**\n * Determines if the value of data is a valid JSON transcript format\n *\n * @param data The transcript data\n * @returns True: data is valid JSON transcript format",
"score": 49.54776870718494
},
{
"filename": "src/formats/vtt.ts",
"retrieved_chunk": " * @returns True: data is valid VTT transcript format\n */\nexport const isVTT = (data: string): boolean => {\n return data.startsWith(\"WEBVTT\")\n}\n/**\n * Parse VTT data to an Array of {@link Segment}\n *\n * @param data The transcript data\n * @returns An array of Segments from the parsed data",
"score": 39.4543057660767
},
{
"filename": "src/formats/vtt.ts",
"retrieved_chunk": "import { Segment } from \"../types\"\nimport { parseSRT } from \"./srt\"\n/**\n * Required header for WebVTT/VTT files\n */\nconst WEBVTT_HEADER = \"WEBVTT\"\n/**\n * Determines if the value of data is a valid VTT transcript format\n *\n * @param data The transcript data",
"score": 36.7582535554829
},
{
"filename": "src/formats/json.ts",
"retrieved_chunk": " if (!isJSON(dataTrimmed)) {\n throw new TypeError(`Data is not valid JSON format`)\n }\n let parsed: object | Array<unknown>\n try {\n parsed = JSON.parse(data)\n } catch (e) {\n throw new TypeError(`Data is not valid JSON: ${e}`)\n }\n if (parsed.constructor === Object) {",
"score": 31.886325913751055
}
] | typescript | .split(PATTERN_LINE_SEPARATOR).slice(0, 20)) !== undefined
} catch (e) { |
import { Options } from "./options"
import { TimestampFormatter } from "./timestamp"
import { DEFAULT_COMBINE_SEGMENTS_LENGTH, Segment } from "./types"
/**
* Regular Expression for detecting punctuation that should not be prefixed with a space
*/
const PATTERN_PUNCTUATIONS = /^ *[.,?!}\]>) *$]/
/**
* Regular Expression for detecting space characters at the end of a string
*/
const PATTERN_TRAILING_SPACE = /^ *$/
/**
* Remove any trailing space characters from data
*
* @param data text to trim
* @returns text with any trailing space character removed
*/
const trimEndSpace = (data: string): string => {
return data.replace(PATTERN_TRAILING_SPACE, "")
}
/**
* Append `addition` to `body` with the character(s) specified.
*
* If `addition` matches the {@link PATTERN_PUNCTUATIONS} pattern, no character is added before the additional data.
*
* @param body Current body text
* @param addition Additional text to add to `body`
* @param separator Character(s) to use to separate data. If undefined, uses `\n`.
* @returns Combined data
*/
const joinBody = (body: string, addition: string, separator: string = undefined): string => {
if (body) {
let separatorToUse = separator || "\n"
if (PATTERN_PUNCTUATIONS.exec(addition)) {
separatorToUse = ""
}
return `${trimEndSpace(body)}${separatorToUse}${trimEndSpace(addition)}`
}
return trimEndSpace(addition)
}
/**
* Combine one or more {@link Segment}
*
* @param segments Array of Segment objects to combine
* @param bodySeparator Character(s) to use to separate body data. If undefined, uses `\n`.
* @returns Combined segment where:
*
* - `startTime`: from first segment
* - `startTimeFormatted`: from first segment
* - `endTime`: from last segment
* - `endTimeFormatted`: from last segment
* - `speaker`: from first segment
* - `body`: combination of all segments
*/
const joinSegments = (segments: Array<Segment>, bodySeparator: string = undefined): Segment => {
const newSegment = { ...segments[0] }
segments.slice(1).forEach((segment) => {
newSegment.endTime = segment.endTime
newSegment.endTimeFormatted = TimestampFormatter.format(segment.endTime)
newSegment.body = joinBody(newSegment.body, segment.body, bodySeparator)
})
return newSegment
}
/**
* Type returned from combine functions
*/
type CombineResult = {
/**
* The updated segment with any changes applied
*/
segment: Segment
/**
* If true, the {@link segment} contains a {@link Segment} that should replace the prior segment instead of
* appending a new segment
*/
replace: boolean
/**
* Indicates if the combine rule was applied
*/
combined: boolean
}
/**
* Checks if the new and prior segments have the same speaker.
*
* If so, combines segments where:
* - `startTime`: from priorSegment
* - `startTimeFormatted`: from priorSegment
* - `endTime`: from newSegment
* - `endTimeFormatted`: from newSegment
* - `speaker`: from priorSegment
* - `body`: body of priorSegment with body of newSegment separated with space
*
* @param newSegment segment being created
* @param priorSegment prior parsed segment
* @param lastSpeaker last speaker name.
* Used when speaker in segment has been removed via {@link Options.speakerChange} rule
* @returns result of combination.
* If segments were combined, {@link CombineResult.replace} and {@link CombineResult.combined} set to true.
*/
const doCombineSpeaker = (newSegment: Segment, priorSegment: Segment, lastSpeaker: string): CombineResult => {
if (newSegment.speaker === priorSegment.speaker || newSegment.speaker === lastSpeaker) {
return {
segment: joinSegments([priorSegment, newSegment], " "),
replace: true,
combined: true,
}
}
return {
segment: newSegment,
replace: false,
combined: false,
}
}
/**
* Checks if the new and prior segments have the same speaker and combining body results in new body shorter than
* max length
*
* If so, combines segments where:
* - `startTime`: from priorSegment
* - `startTimeFormatted`: from priorSegment
* - `endTime`: from newSegment
* - `endTimeFormatted`: from newSegment
* - `speaker`: from priorSegment
* - `body`: body of priorSegment with body of newSegment separated with space
*
* @param newSegment segment being created
* @param priorSegment prior parsed segment
* @param maxLength maximum allowed length of combined body. If undefined, uses {@link DEFAULT_COMBINE_SEGMENTS_LENGTH}
* @param lastSpeaker last speaker name.
* Used when speaker in segment has been removed via {@link Options.speakerChange} rule
* @returns result of combination.
* If segments were combined, {@link CombineResult.replace} and {@link CombineResult.combined} set to true.
*/
const doCombineSegments = (
newSegment: Segment,
priorSegment: Segment,
maxLength: number,
lastSpeaker: string
): CombineResult => {
if (priorSegment === undefined) {
return {
segment: newSegment,
replace: false,
combined: false,
}
}
const combineSegmentsLength = maxLength || DEFAULT_COMBINE_SEGMENTS_LENGTH
if (
(newSegment.speaker === priorSegment.speaker || newSegment.speaker === lastSpeaker) &&
joinBody(priorSegment.body, newSegment.body, " ").length <= combineSegmentsLength
) {
return {
segment: joinSegments([priorSegment, newSegment], " "),
replace: true,
combined: true,
}
}
return {
segment: newSegment,
replace: false,
combined: false,
}
}
/**
* Checks if the new and prior segments have the same speaker, startTime and endTime.
*
* If so, combines segments where:
* - `startTime`: from priorSegment
* - `startTimeFormatted`: from priorSegment
* - `endTime`: from newSegment
* - `endTimeFormatted`: from newSegment
* - `speaker`: from priorSegment
* - `body`: body of priorSegment with body of newSegment separated with value of separator argument
*
* @param newSegment segment being created
* @param priorSegment prior parsed segment
* @param separator string to use to combine body values. If undefined, uses "\n"
* @param lastSpeaker last speaker name.
* Used when speaker in segment has been removed via {@link Options.speakerChange} rule
* @returns result of combination.
* If segments were combined, {@link CombineResult.replace} and {@link CombineResult.combined} set to true.
*/
const doCombineEqualTimes = (
newSegment: Segment,
priorSegment: Segment,
separator: string,
lastSpeaker: string
): CombineResult => {
const combineEqualTimesSeparator = separator || "\n"
if (
newSegment.startTime === priorSegment.startTime &&
newSegment.endTime === priorSegment.endTime &&
(newSegment.speaker === priorSegment.speaker || newSegment.speaker === lastSpeaker)
) {
return {
segment: joinSegments([priorSegment, newSegment], combineEqualTimesSeparator),
replace: true,
combined: true,
}
}
return {
segment: newSegment,
replace: false,
combined: false,
}
}
/**
* Checks if the new and prior segments have the same speaker. If so, sets the speaker value to undefined
*
* If so, combines segments where:
* - `startTime`: from priorSegment
* - `startTimeFormatted`: from priorSegment
* - `endTime`: from newSegment
* - `endTimeFormatted`: from newSegment
* - `speaker`: from newSegment if different from priorSegment else undefined
* - `body`: body of priorSegment with body of newSegment separated with space
*
* @param newSegment segment being created
* @param priorSegment prior parsed segment. For the first segment, this shall be undefined.
* @param lastSpeaker last speaker name.
* Used when speaker in segment has been removed via {@link Options.speakerChange} rule
* @returns result of combination.
* If segments were combined, {@link CombineResult.replace} set to false and {@link CombineResult.combined} set to true.
*/
const doSpeakerChange = (newSegment: Segment, priorSegment: Segment, lastSpeaker: string): CombineResult => {
const result: CombineResult = {
segment: newSegment,
replace: false,
combined: false,
}
if (priorSegment === undefined) {
if (newSegment.speaker === lastSpeaker) {
const segment: Segment = { ...newSegment }
segment.speaker = undefined
return {
segment,
replace: false,
combined: true,
}
}
return result
}
if (newSegment.speaker === undefined) {
return result
}
if (
newSegment.speaker === "" ||
newSegment.speaker === priorSegment.speaker ||
newSegment.speaker === lastSpeaker
) {
const segment: Segment = { ...newSegment }
segment.speaker = undefined
return {
segment,
replace: false,
combined: true,
}
}
return result
}
/**
* Determine how {@link Options.speakerChange is applied based an past options being applied}
*
* @param currentResult current result object from any prior options
* @param priorSegment prior parsed segment
* @param lastSpeaker last speaker name.
* @returns result of combination.
* If segments were combined, {@link CombineResult.replace} set to false and {@link CombineResult.combined} set to true.
*/
const applyOptionsAndDoSpeakerChange = (
currentResult: CombineResult,
priorSegment: Segment,
lastSpeaker: string
): CombineResult => {
const { combineSegments, combineEqualTimes } = Options
let result = currentResult
if (combineSegments && currentResult.combined && currentResult.replace) {
result = doSpeakerChange(currentResult.segment, undefined, undefined)
} else if (combineEqualTimes) {
if (result.combined && result.replace) {
result = doSpeakerChange(currentResult.segment, undefined, undefined)
} else {
result = doSpeakerChange(currentResult.segment, priorSegment, lastSpeaker)
}
} else {
result = doSpeakerChange(currentResult.segment, priorSegment, lastSpeaker)
}
if (result) {
result = {
segment: result.segment,
replace: currentResult.replace || result.replace,
combined: currentResult.combined || result.combined,
}
}
return result
}
/**
* Apply convert rules when no prior segment exits.
*
* NOTE: not all rules applicable when no prior segment
*
* @param newSegment segment before any rules options to it
* @param lastSpeaker last speaker name.
* Used when speaker in segment has been removed via {@link Options.speakerChange} rule
* @returns the updated segment info
*/
const doCombineNoPrior = (newSegment: Segment, lastSpeaker: string): CombineResult => {
const { speakerChange } = Options
let result: CombineResult = {
segment: newSegment,
replace: false,
combined: false,
}
if (speakerChange) {
result = doSpeakerChange(result.segment, undefined, lastSpeaker)
}
return result
}
/**
* Apply convert rules when prior segment exits.
*
* @param newSegment segment before any rules options to it
* @param priorSegment prior parsed segment
* @param lastSpeaker last speaker name.
* Used when speaker in segment has been removed via {@link Options.speakerChange} rule
* @returns the updated segment info
*/
const doCombineWithPrior = (newSegment: Segment, priorSegment: Segment, lastSpeaker: string): CombineResult => {
const {
combineEqualTimes,
combineEqualTimesSeparator,
combineSegments,
combineSegmentsLength,
combineSpeaker,
speakerChange,
} = Options
let result: CombineResult = {
segment: { ...newSegment },
replace: false,
combined: false,
}
let combinedSpeaker = false
if (combineSpeaker) {
result = doCombineSpeaker(result.segment, priorSegment, lastSpeaker)
combinedSpeaker = result.combined
}
if (!combinedSpeaker && combineEqualTimes) {
result = doCombineEqualTimes(result.segment, priorSegment, combineEqualTimesSeparator, lastSpeaker)
}
if (!combinedSpeaker && combineSegments) {
let combineResult
if (combineEqualTimes && result.combined) {
combineResult = doCombineSegments(result.segment, undefined, combineSegmentsLength, lastSpeaker)
} else {
combineResult = doCombineSegments(result.segment, priorSegment, combineSegmentsLength, lastSpeaker)
}
if (combineResult) {
result = {
segment: combineResult.segment,
replace: result.replace || combineResult.replace,
combined: result.combined || combineResult.combined,
}
}
}
if (speakerChange) {
result = applyOptionsAndDoSpeakerChange(result, priorSegment, lastSpeaker)
}
return result
}
/**
* Apply any options to the current segment
*
* @param newSegment segment before any rules options to it
* @param priorSegment prior parsed segment. For the first segment, this shall be undefined.
* @param lastSpeaker last speaker name.
* Used when speaker in segment has been removed via {@link Options.speakerChange} rule
* @returns the updated segment info
*/
const applyOptions = (newSegment: Segment, priorSegment: Segment, lastSpeaker: string = undefined): CombineResult => {
| if (!Options.optionsSet()) { |
return {
segment: newSegment,
replace: false,
combined: false,
}
}
let result: CombineResult
// if no prior segment, limited additional checking
if (priorSegment === undefined) {
result = doCombineNoPrior(newSegment, lastSpeaker)
} else {
result = doCombineWithPrior(newSegment, priorSegment, lastSpeaker)
}
return result
}
/**
* Get the last speaker name from the previously parsed segments
*
* @param priorSegment prior parsed segment
* @param priorSegments array of all previous segments
* @returns the name of the last speaker
*/
const getLastSpeaker = (priorSegment: Segment, priorSegments: Array<Segment>): string => {
let lastSpeaker
if (priorSegment) {
lastSpeaker = priorSegment.speaker
}
if (lastSpeaker === undefined && priorSegments.length > 0) {
lastSpeaker = priorSegments[0].speaker
for (let i = priorSegments.length - 1; i > 0; i--) {
if (priorSegments[i].speaker !== undefined) {
lastSpeaker = priorSegments[i].speaker
break
}
}
}
return lastSpeaker
}
/**
* Helper for adding segment to or updating last segment in array of segments
*
* @param newSegment segment to add or replace
* @param priorSegments array of all previous segments
* @returns updated array of segments with new segment added or last segment updated (per options)
*/
export const addSegment = (newSegment: Segment, priorSegments: Array<Segment>): Array<Segment> => {
const { speakerChange } = Options
const outSegments = priorSegments || []
const priorSegment = outSegments.length > 0 ? outSegments[outSegments.length - 1] : undefined
// don't worry about identifying the last speaker if speaker is not being removed by speakerChange
let lastSpeaker: string
if (speakerChange) {
lastSpeaker = getLastSpeaker(priorSegment, outSegments)
}
const newSegmentInfo = applyOptions(newSegment, priorSegment, lastSpeaker)
if (newSegmentInfo.replace && outSegments.length > 0) {
outSegments[outSegments.length - 1] = newSegmentInfo.segment
} else {
outSegments.push(newSegmentInfo.segment)
}
return outSegments
}
| src/segments.ts | stevencrader-transcriptator-75faa70 | [
{
"filename": "src/options.ts",
"retrieved_chunk": " *\n * @param options the options to set\n * @param setDefault true: set all values to the default before setting values specified by `options`\n */\n public setOptions = (options: IOptions, setDefault = true): void => {\n if (setDefault) {\n this.restoreDefaultSettings()\n }\n if (options === undefined) {\n return",
"score": 28.953109405686206
},
{
"filename": "src/formats/srt.ts",
"retrieved_chunk": "}\n/**\n * Create Segment from lines containing an SRT segment/cue\n *\n * @param segmentLines Lines containing SRT data\n * @param lastSpeaker Name of last speaker. Will be used if no speaker found in `segmentLines`\n * @returns Created segment\n */\nconst createSegmentFromSRTLines = (segmentLines: Array<string>, lastSpeaker: string): Segment => {\n const srtSegment = parseSRTSegment(segmentLines)",
"score": 28.044707168979052
},
{
"filename": "src/options.ts",
"retrieved_chunk": " static _instance: OptionsManager\n /**\n * Combine segments if the {@link Segment.startTime}, {@link Segment.endTime}, and {@link Segment.speaker} match\n * between the current and prior segments\n *\n * Can be used with {@link combineSegments}. The {@link combineEqualTimes} rule is applied first.\n *\n * Can be used with {@link speakerChange}. The {@link speakerChange} rule is applied last.\n *\n * Cannot be used with {@link combineSpeaker}",
"score": 25.810211721343297
},
{
"filename": "src/formats/html.ts",
"retrieved_chunk": " * @param lastSpeaker Name of last speaker. Will be used if no speaker found in `segmentLines`\n * @returns Created segment\n */\nconst createSegmentFromSegmentPart = (segmentPart: HTMLSegmentPart, lastSpeaker: string): Segment => {\n const calculatedSpeaker = segmentPart.cite ? segmentPart.cite : lastSpeaker\n const startTime = parseTimestamp(segmentPart.time)\n return {\n startTime,\n startTimeFormatted: TimestampFormatter.format(startTime),\n endTime: 0,",
"score": 25.056459596404316
},
{
"filename": "src/formats/json.ts",
"retrieved_chunk": " if (subtitleSegment !== undefined) {\n lastSpeaker = subtitleSegment.speaker ? subtitleSegment.speaker : lastSpeaker\n subtitleSegment.speaker = lastSpeaker\n outSegments = addSegment(subtitleSegment, outSegments)\n } else {\n throw new TypeError(`Unable to parse segment for item ${count}`)\n }\n })\n return outSegments\n}",
"score": 23.27482868008126
}
] | typescript | if (!Options.optionsSet()) { |
import { Options } from "./options"
import { TimestampFormatter } from "./timestamp"
import { DEFAULT_COMBINE_SEGMENTS_LENGTH, Segment } from "./types"
/**
* Regular Expression for detecting punctuation that should not be prefixed with a space
*/
const PATTERN_PUNCTUATIONS = /^ *[.,?!}\]>) *$]/
/**
* Regular Expression for detecting space characters at the end of a string
*/
const PATTERN_TRAILING_SPACE = /^ *$/
/**
* Remove any trailing space characters from data
*
* @param data text to trim
* @returns text with any trailing space character removed
*/
const trimEndSpace = (data: string): string => {
return data.replace(PATTERN_TRAILING_SPACE, "")
}
/**
* Append `addition` to `body` with the character(s) specified.
*
* If `addition` matches the {@link PATTERN_PUNCTUATIONS} pattern, no character is added before the additional data.
*
* @param body Current body text
* @param addition Additional text to add to `body`
* @param separator Character(s) to use to separate data. If undefined, uses `\n`.
* @returns Combined data
*/
const joinBody = (body: string, addition: string, separator: string = undefined): string => {
if (body) {
let separatorToUse = separator || "\n"
if (PATTERN_PUNCTUATIONS.exec(addition)) {
separatorToUse = ""
}
return `${trimEndSpace(body)}${separatorToUse}${trimEndSpace(addition)}`
}
return trimEndSpace(addition)
}
/**
* Combine one or more {@link Segment}
*
* @param segments Array of Segment objects to combine
* @param bodySeparator Character(s) to use to separate body data. If undefined, uses `\n`.
* @returns Combined segment where:
*
* - `startTime`: from first segment
* - `startTimeFormatted`: from first segment
* - `endTime`: from last segment
* - `endTimeFormatted`: from last segment
* - `speaker`: from first segment
* - `body`: combination of all segments
*/
const joinSegments = (segments: Array<Segment>, bodySeparator: string = undefined): Segment => {
const newSegment = { ...segments[0] }
segments.slice(1).forEach((segment) => {
newSegment.endTime = segment.endTime
newSegment.endTimeFormatted = TimestampFormatter.format(segment.endTime)
newSegment.body = joinBody(newSegment.body, segment.body, bodySeparator)
})
return newSegment
}
/**
* Type returned from combine functions
*/
type CombineResult = {
/**
* The updated segment with any changes applied
*/
segment: Segment
/**
* If true, the {@link segment} contains a {@link Segment} that should replace the prior segment instead of
* appending a new segment
*/
replace: boolean
/**
* Indicates if the combine rule was applied
*/
combined: boolean
}
/**
* Checks if the new and prior segments have the same speaker.
*
* If so, combines segments where:
* - `startTime`: from priorSegment
* - `startTimeFormatted`: from priorSegment
* - `endTime`: from newSegment
* - `endTimeFormatted`: from newSegment
* - `speaker`: from priorSegment
* - `body`: body of priorSegment with body of newSegment separated with space
*
* @param newSegment segment being created
* @param priorSegment prior parsed segment
* @param lastSpeaker last speaker name.
* Used when speaker in segment has been removed via {@link Options.speakerChange} rule
* @returns result of combination.
* If segments were combined, {@link CombineResult.replace} and {@link CombineResult.combined} set to true.
*/
const doCombineSpeaker = (newSegment: Segment, priorSegment: Segment, lastSpeaker: string): CombineResult => {
if (newSegment.speaker === priorSegment.speaker || newSegment.speaker === lastSpeaker) {
return {
segment: joinSegments([priorSegment, newSegment], " "),
replace: true,
combined: true,
}
}
return {
segment: newSegment,
replace: false,
combined: false,
}
}
/**
* Checks if the new and prior segments have the same speaker and combining body results in new body shorter than
* max length
*
* If so, combines segments where:
* - `startTime`: from priorSegment
* - `startTimeFormatted`: from priorSegment
* - `endTime`: from newSegment
* - `endTimeFormatted`: from newSegment
* - `speaker`: from priorSegment
* - `body`: body of priorSegment with body of newSegment separated with space
*
* @param newSegment segment being created
* @param priorSegment prior parsed segment
* @param maxLength maximum allowed length of combined body. If undefined, uses {@link DEFAULT_COMBINE_SEGMENTS_LENGTH}
* @param lastSpeaker last speaker name.
* Used when speaker in segment has been removed via {@link Options.speakerChange} rule
* @returns result of combination.
* If segments were combined, {@link CombineResult.replace} and {@link CombineResult.combined} set to true.
*/
const doCombineSegments = (
newSegment: Segment,
priorSegment: Segment,
maxLength: number,
lastSpeaker: string
): CombineResult => {
if (priorSegment === undefined) {
return {
segment: newSegment,
replace: false,
combined: false,
}
}
const combineSegmentsLength = maxLength || DEFAULT_COMBINE_SEGMENTS_LENGTH
if (
(newSegment.speaker === priorSegment.speaker || newSegment.speaker === lastSpeaker) &&
joinBody(priorSegment.body, newSegment.body, " ").length <= combineSegmentsLength
) {
return {
segment: joinSegments([priorSegment, newSegment], " "),
replace: true,
combined: true,
}
}
return {
segment: newSegment,
replace: false,
combined: false,
}
}
/**
* Checks if the new and prior segments have the same speaker, startTime and endTime.
*
* If so, combines segments where:
* - `startTime`: from priorSegment
* - `startTimeFormatted`: from priorSegment
* - `endTime`: from newSegment
* - `endTimeFormatted`: from newSegment
* - `speaker`: from priorSegment
* - `body`: body of priorSegment with body of newSegment separated with value of separator argument
*
* @param newSegment segment being created
* @param priorSegment prior parsed segment
* @param separator string to use to combine body values. If undefined, uses "\n"
* @param lastSpeaker last speaker name.
* Used when speaker in segment has been removed via {@link Options.speakerChange} rule
* @returns result of combination.
* If segments were combined, {@link CombineResult.replace} and {@link CombineResult.combined} set to true.
*/
const doCombineEqualTimes = (
newSegment: Segment,
priorSegment: Segment,
separator: string,
lastSpeaker: string
): CombineResult => {
const combineEqualTimesSeparator = separator || "\n"
if (
newSegment.startTime === priorSegment.startTime &&
newSegment.endTime === priorSegment.endTime &&
(newSegment.speaker === priorSegment.speaker || newSegment.speaker === lastSpeaker)
) {
return {
segment: joinSegments([priorSegment, newSegment], combineEqualTimesSeparator),
replace: true,
combined: true,
}
}
return {
segment: newSegment,
replace: false,
combined: false,
}
}
/**
* Checks if the new and prior segments have the same speaker. If so, sets the speaker value to undefined
*
* If so, combines segments where:
* - `startTime`: from priorSegment
* - `startTimeFormatted`: from priorSegment
* - `endTime`: from newSegment
* - `endTimeFormatted`: from newSegment
* - `speaker`: from newSegment if different from priorSegment else undefined
* - `body`: body of priorSegment with body of newSegment separated with space
*
* @param newSegment segment being created
* @param priorSegment prior parsed segment. For the first segment, this shall be undefined.
* @param lastSpeaker last speaker name.
* Used when speaker in segment has been removed via {@link Options.speakerChange} rule
* @returns result of combination.
* If segments were combined, {@link CombineResult.replace} set to false and {@link CombineResult.combined} set to true.
*/
const doSpeakerChange = (newSegment: Segment, priorSegment: Segment, lastSpeaker: string): CombineResult => {
const result: CombineResult = {
segment: newSegment,
replace: false,
combined: false,
}
if (priorSegment === undefined) {
if (newSegment.speaker === lastSpeaker) {
const segment: Segment = { ...newSegment }
segment.speaker = undefined
return {
segment,
replace: false,
combined: true,
}
}
return result
}
if (newSegment.speaker === undefined) {
return result
}
if (
newSegment.speaker === "" ||
newSegment.speaker === priorSegment.speaker ||
newSegment.speaker === lastSpeaker
) {
const segment: Segment = { ...newSegment }
segment.speaker = undefined
return {
segment,
replace: false,
combined: true,
}
}
return result
}
/**
* Determine how {@link Options.speakerChange is applied based an past options being applied}
*
* @param currentResult current result object from any prior options
* @param priorSegment prior parsed segment
* @param lastSpeaker last speaker name.
* @returns result of combination.
* If segments were combined, {@link CombineResult.replace} set to false and {@link CombineResult.combined} set to true.
*/
const applyOptionsAndDoSpeakerChange = (
currentResult: CombineResult,
priorSegment: Segment,
lastSpeaker: string
): CombineResult => {
const | { combineSegments, combineEqualTimes } = Options
let result = currentResult
if (combineSegments && currentResult.combined && currentResult.replace) { |
result = doSpeakerChange(currentResult.segment, undefined, undefined)
} else if (combineEqualTimes) {
if (result.combined && result.replace) {
result = doSpeakerChange(currentResult.segment, undefined, undefined)
} else {
result = doSpeakerChange(currentResult.segment, priorSegment, lastSpeaker)
}
} else {
result = doSpeakerChange(currentResult.segment, priorSegment, lastSpeaker)
}
if (result) {
result = {
segment: result.segment,
replace: currentResult.replace || result.replace,
combined: currentResult.combined || result.combined,
}
}
return result
}
/**
* Apply convert rules when no prior segment exits.
*
* NOTE: not all rules applicable when no prior segment
*
* @param newSegment segment before any rules options to it
* @param lastSpeaker last speaker name.
* Used when speaker in segment has been removed via {@link Options.speakerChange} rule
* @returns the updated segment info
*/
const doCombineNoPrior = (newSegment: Segment, lastSpeaker: string): CombineResult => {
const { speakerChange } = Options
let result: CombineResult = {
segment: newSegment,
replace: false,
combined: false,
}
if (speakerChange) {
result = doSpeakerChange(result.segment, undefined, lastSpeaker)
}
return result
}
/**
* Apply convert rules when prior segment exits.
*
* @param newSegment segment before any rules options to it
* @param priorSegment prior parsed segment
* @param lastSpeaker last speaker name.
* Used when speaker in segment has been removed via {@link Options.speakerChange} rule
* @returns the updated segment info
*/
const doCombineWithPrior = (newSegment: Segment, priorSegment: Segment, lastSpeaker: string): CombineResult => {
const {
combineEqualTimes,
combineEqualTimesSeparator,
combineSegments,
combineSegmentsLength,
combineSpeaker,
speakerChange,
} = Options
let result: CombineResult = {
segment: { ...newSegment },
replace: false,
combined: false,
}
let combinedSpeaker = false
if (combineSpeaker) {
result = doCombineSpeaker(result.segment, priorSegment, lastSpeaker)
combinedSpeaker = result.combined
}
if (!combinedSpeaker && combineEqualTimes) {
result = doCombineEqualTimes(result.segment, priorSegment, combineEqualTimesSeparator, lastSpeaker)
}
if (!combinedSpeaker && combineSegments) {
let combineResult
if (combineEqualTimes && result.combined) {
combineResult = doCombineSegments(result.segment, undefined, combineSegmentsLength, lastSpeaker)
} else {
combineResult = doCombineSegments(result.segment, priorSegment, combineSegmentsLength, lastSpeaker)
}
if (combineResult) {
result = {
segment: combineResult.segment,
replace: result.replace || combineResult.replace,
combined: result.combined || combineResult.combined,
}
}
}
if (speakerChange) {
result = applyOptionsAndDoSpeakerChange(result, priorSegment, lastSpeaker)
}
return result
}
/**
* Apply any options to the current segment
*
* @param newSegment segment before any rules options to it
* @param priorSegment prior parsed segment. For the first segment, this shall be undefined.
* @param lastSpeaker last speaker name.
* Used when speaker in segment has been removed via {@link Options.speakerChange} rule
* @returns the updated segment info
*/
const applyOptions = (newSegment: Segment, priorSegment: Segment, lastSpeaker: string = undefined): CombineResult => {
if (!Options.optionsSet()) {
return {
segment: newSegment,
replace: false,
combined: false,
}
}
let result: CombineResult
// if no prior segment, limited additional checking
if (priorSegment === undefined) {
result = doCombineNoPrior(newSegment, lastSpeaker)
} else {
result = doCombineWithPrior(newSegment, priorSegment, lastSpeaker)
}
return result
}
/**
* Get the last speaker name from the previously parsed segments
*
* @param priorSegment prior parsed segment
* @param priorSegments array of all previous segments
* @returns the name of the last speaker
*/
const getLastSpeaker = (priorSegment: Segment, priorSegments: Array<Segment>): string => {
let lastSpeaker
if (priorSegment) {
lastSpeaker = priorSegment.speaker
}
if (lastSpeaker === undefined && priorSegments.length > 0) {
lastSpeaker = priorSegments[0].speaker
for (let i = priorSegments.length - 1; i > 0; i--) {
if (priorSegments[i].speaker !== undefined) {
lastSpeaker = priorSegments[i].speaker
break
}
}
}
return lastSpeaker
}
/**
* Helper for adding segment to or updating last segment in array of segments
*
* @param newSegment segment to add or replace
* @param priorSegments array of all previous segments
* @returns updated array of segments with new segment added or last segment updated (per options)
*/
export const addSegment = (newSegment: Segment, priorSegments: Array<Segment>): Array<Segment> => {
const { speakerChange } = Options
const outSegments = priorSegments || []
const priorSegment = outSegments.length > 0 ? outSegments[outSegments.length - 1] : undefined
// don't worry about identifying the last speaker if speaker is not being removed by speakerChange
let lastSpeaker: string
if (speakerChange) {
lastSpeaker = getLastSpeaker(priorSegment, outSegments)
}
const newSegmentInfo = applyOptions(newSegment, priorSegment, lastSpeaker)
if (newSegmentInfo.replace && outSegments.length > 0) {
outSegments[outSegments.length - 1] = newSegmentInfo.segment
} else {
outSegments.push(newSegmentInfo.segment)
}
return outSegments
}
| src/segments.ts | stevencrader-transcriptator-75faa70 | [
{
"filename": "src/options.ts",
"retrieved_chunk": " public optionsSet = (): boolean => {\n const { combineEqualTimes, combineSegments, combineSpeaker, speakerChange } = this\n return combineEqualTimes || combineSegments || combineSpeaker || speakerChange\n }\n}\nexport const Options = new OptionsManager()",
"score": 14.824245555877376
},
{
"filename": "src/options.ts",
"retrieved_chunk": " public getOptionByName = (name: string): boolean | string | number => {\n let actual\n switch (name) {\n case \"combineEqualTimes\":\n actual = this.combineEqualTimes\n break\n case \"combineEqualTimesSeparator\":\n actual = this.combineEqualTimesSeparator\n break\n case \"combineSegments\":",
"score": 10.295578463957938
},
{
"filename": "src/types.ts",
"retrieved_chunk": " * Text of transcript for segment\n */\n body: string\n}\n/**\n * Default length to use when combining segments with {@link Options.combineSegments}\n */\nexport const DEFAULT_COMBINE_SEGMENTS_LENGTH = 32",
"score": 9.888552069267053
},
{
"filename": "src/formats/html.ts",
"retrieved_chunk": " */\nconst getSegmentsFromHTMLElements = (elements: Array<HTMLElement>): Array<Segment> => {\n let outSegments: Array<Segment> = []\n let lastSpeaker = \"\"\n let segmentPart: HTMLSegmentPart = {\n cite: \"\",\n time: \"\",\n text: \"\",\n }\n let nextSegmentPart: HTMLSegmentPart = {",
"score": 8.355253660289709
},
{
"filename": "src/options.ts",
"retrieved_chunk": " *\n * Note: If this is enabled, {@link combineEqualTimes} and {@link combineSegments} will not be applied.\n *\n * Warning: if the transcript does not contain speaker information, resulting segment will contain entire transcript text.\n */\n combineSpeaker?: boolean\n /**\n * Only include {@link Segment.speaker} when speaker changes\n *\n * May be used in combination with {@link combineSpeaker}, {@link combineEqualTimes}, or {@link combineSegments}",
"score": 7.710129835712542
}
] | typescript | { combineSegments, combineEqualTimes } = Options
let result = currentResult
if (combineSegments && currentResult.combined && currentResult.replace) { |
import { pascalCase } from 'change-case'
import { AlgoAppSpec, CallConfig, CallConfigValue } from '../../schema/application'
export const BARE_CALL = Symbol('bare')
export type MethodIdentifier = string | typeof BARE_CALL
export type MethodList = Array<MethodIdentifier>
export type CallConfigSummary = {
createMethods: MethodList
callMethods: MethodList
deleteMethods: MethodList
updateMethods: MethodList
optInMethods: MethodList
closeOutMethods: MethodList
}
export const getCallConfigSummary = (app: AlgoAppSpec) => {
const result: CallConfigSummary = {
createMethods: [],
callMethods: [],
deleteMethods: [],
updateMethods: [],
optInMethods: [],
closeOutMethods: [],
}
if (app.bare_call_config) {
addToConfig(result, BARE_CALL, app.bare_call_config)
}
if (app.hints) {
for (const [method, hints] of Object.entries(app.hints)) {
if (hints.call_config) {
addToConfig(result, method, hints.call_config)
}
}
}
return result
}
export const getCreateOnComplete = (app: AlgoAppSpec, method: MethodIdentifier) => {
const callConfig = method === BARE_CALL ? app.bare_call_config : app.hints?.[method]?.call_config
if (!callConfig) {
return ''
}
const hasNoOp = callConfig.no_op === 'ALL' || callConfig.no_op === 'CREATE'
return `{ onCompleteAction${hasNoOp ? '?' : ''}: ${getCreateOnCompleteTypes(callConfig)} }`
}
const getCreateOnCompleteTypes = | (config: CallConfig) => { |
return Object.keys(config)
.map((oc) => oc as keyof CallConfig)
.filter((oc) => config[oc] === 'ALL' || config[oc] === 'CREATE')
.map((oc) => `'${oc}' | OnApplicationComplete.${pascalCase(oc)}OC`)
.join(' | ')
}
const addToConfig = (result: CallConfigSummary, method: MethodIdentifier, config: CallConfig) => {
if (hasCall(config.no_op)) {
result.callMethods.push(method)
}
if (
hasCreate(config.no_op) ||
hasCreate(config.opt_in) ||
hasCreate(config.close_out) ||
hasCreate(config.update_application) ||
hasCreate(config.delete_application)
) {
result.createMethods.push(method)
}
if (hasCall(config.delete_application)) {
result.deleteMethods.push(method)
}
if (hasCall(config.update_application)) {
result.updateMethods.push(method)
}
if (hasCall(config.opt_in)) {
result.optInMethods.push(method)
}
if (hasCall(config.close_out)) {
result.closeOutMethods.push(method)
}
}
const hasCall = (config: CallConfigValue | undefined) => {
return config === 'CALL' || config === 'ALL'
}
const hasCreate = (config: CallConfigValue | undefined) => {
return config === 'CREATE' || config === 'ALL'
}
| src/client/helpers/get-call-config-summary.ts | algorandfoundation-algokit-client-generator-ts-2de43ed | [
{
"filename": "src/client/deploy-types.ts",
"retrieved_chunk": "import { DecIndent, DecIndentAndCloseBlock, DocumentParts, IncIndent, jsDoc, NewLine } from '../output/writer'\nimport { makeSafeTypeIdentifier } from '../util/sanitization'\nimport { BARE_CALL, MethodIdentifier } from './helpers/get-call-config-summary'\nimport { GeneratorContext } from './generator-context'\nimport { AlgoAppSpec, CallConfig } from '../schema/application'\nimport { OnCompleteCodeMap } from './utility-types'\nexport function getCreateOnCompleteOptions(method: MethodIdentifier, app: AlgoAppSpec) {\n const callConfig = method === BARE_CALL ? app.bare_call_config : app.hints?.[method]?.call_config\n const hasNoOp = callConfig?.no_op === 'ALL' || callConfig?.no_op === 'CREATE'\n const onCompleteType = callConfig",
"score": 66.42955005012924
},
{
"filename": "src/client/deploy-types.ts",
"retrieved_chunk": " ? `(${Object.entries(callConfig)\n .filter(([_, value]) => value === 'ALL' || value === 'CREATE')\n .map(([oc]) => OnCompleteCodeMap[oc as keyof CallConfig])\n .join(' | ')})`\n : {}\n return {\n type: onCompleteType,\n isOptional: hasNoOp,\n }\n}",
"score": 34.784450944699984
},
{
"filename": "src/client/call-client.ts",
"retrieved_chunk": "}\nfunction* noopMethods({ app, name, callConfig, methodSignatureToUniqueName }: GeneratorContext): DocumentParts {\n for (const method of app.contract.methods) {\n const methodSignature = algokit.getABIMethodSignature(method)\n const methodName = makeSafeMethodIdentifier(methodSignatureToUniqueName[methodSignature])\n // Skip methods which don't support a no_op call config\n if (!callConfig.callMethods.includes(methodSignature)) continue\n yield* jsDoc({\n description: `Calls the ${algokit.getABIMethodSignature(method)} ABI method.`,\n abiDescription: method.desc,",
"score": 30.189498570299058
},
{
"filename": "src/client/call-composer.ts",
"retrieved_chunk": " for (const method of app.contract.methods) {\n const methodSignature = algokit.getABIMethodSignature(method)\n const methodName = makeSafeMethodIdentifier(methodSignatureToUniqueName[methodSignature])\n // Skip methods which don't support a no_op call config\n if (!callConfig.callMethods.includes(methodSignature)) continue\n yield `${methodName}(args: MethodArgs<'${methodSignature}'>, params?: AppClientCallCoreParams & CoreAppCallArgs) {`\n yield IncIndent\n yield `promiseChain = promiseChain.then(() => client.${methodName}(args, {...params, sendParams: {...params?.sendParams, skipSending: true, atc}}))`\n const outputTypeName = app.hints?.[methodSignature]?.structs?.output?.name\n yield `resultMappers.push(${outputTypeName ?? 'undefined'})`",
"score": 24.073902900059302
},
{
"filename": "src/client/deploy-types.ts",
"retrieved_chunk": "export function* deployTypes({ app, callConfig }: GeneratorContext): DocumentParts {\n const name = makeSafeTypeIdentifier(app.contract.name)\n if (callConfig.createMethods.length > 0) {\n yield* jsDoc(`A factory for available 'create' calls`)\n yield `export type ${name}CreateCalls = (typeof ${name}CallFactory)['create']`\n yield* jsDoc('Defines supported create methods for this smart contract')\n yield `export type ${name}CreateCallParams =`\n yield IncIndent\n for (const method of callConfig.createMethods) {\n const onComplete = getCreateOnCompleteOptions(method, app)",
"score": 22.892774150949272
}
] | typescript | (config: CallConfig) => { |
import { ContractMethod } from '../schema/application'
import { DecIndent, DecIndentAndCloseBlock, DocumentParts, IncIndent, jsDoc, NewLine } from '../output/writer'
import { isSafeVariableIdentifier, makeSafeMethodIdentifier, makeSafePropertyIdentifier } from '../util/sanitization'
import * as algokit from '@algorandfoundation/algokit-utils'
import { GeneratorContext } from './generator-context'
import { BARE_CALL, MethodList } from './helpers/get-call-config-summary'
import { getCreateOnCompleteOptions } from './deploy-types'
export function* callFactory(ctx: GeneratorContext): DocumentParts {
yield* jsDoc('Exposes methods for constructing all available smart contract calls')
yield `export abstract class ${ctx.name}CallFactory {`
yield IncIndent
yield* opMethods(ctx)
for (const method of ctx.app.contract.methods) {
yield* callFactoryMethod(ctx, method)
}
yield DecIndent
yield '}'
}
function* opMethods(ctx: GeneratorContext): DocumentParts {
const { app, callConfig } = ctx
yield* operationMethod(
ctx,
`Constructs a create call for the ${app.contract.name} smart contract`,
callConfig.createMethods,
'create',
true,
)
yield* operationMethod(
ctx,
`Constructs an update call for the ${app.contract.name} smart contract`,
callConfig.updateMethods,
'update',
true,
)
yield* operationMethod(ctx, `Constructs a delete call for the ${app.contract.name} smart contract`, callConfig.deleteMethods, 'delete')
yield* operationMethod(ctx, `Constructs an opt in call for the ${app.contract.name} smart contract`, callConfig.optInMethods, 'optIn')
yield* operationMethod(
ctx,
`Constructs a close out call for the ${app.contract.name} smart contract`,
callConfig.closeOutMethods,
'closeOut',
)
}
function* operationMethod(
{ app, methodSignatureToUniqueName }: GeneratorContext,
description: string,
methods: MethodList,
verb: 'create' | 'update' | 'optIn' | 'closeOut' | 'delete',
includeCompilation?: boolean,
): DocumentParts {
if (methods.length) {
yield* jsDoc(`Gets available ${verb} call factories`)
yield `static get ${verb}() {`
yield IncIndent
yield `return {`
yield IncIndent
for (const methodSig of methods) {
const onComplete = verb === 'create' ? getCreateOnCompleteOptions(methodSig, app) : undefined
if (methodSig === BARE_CALL) {
yield* jsDoc({
description: `${description} using a bare call`,
params: {
params: `Any parameters for the call`,
},
returns: `A TypedCallParams object for the call`,
})
yield* factoryMethod({
isNested: true,
name: 'bare',
paramTypes: `BareCallArgs & AppClientCallCoreParams & CoreAppCallArgs${
includeCompilation ? ' & AppClientCompilationParams' : ''
}${onComplete?.type ? ` & ${onComplete.type}` : ''}${onComplete?.isOptional !== false ? ' = {}' : ''}`,
})
} else {
const method = app.contract.methods.find((m) => algokit.getABIMethodSignature(m) === methodSig)!
const uniqueName = methodSignatureToUniqueName[methodSig]
yield* jsDoc({
description: `${description} using the ${methodSig} ABI method`,
params: {
args: `Any args for the contract call`,
params: `Any additional parameters for the call`,
},
returns: `A TypedCallParams object for the call`,
})
yield* factoryMethod({
isNested: true,
name: makeSafeMethodIdentifier(uniqueName),
signature: methodSig,
args: method.args,
paramTypes: `AppClientCallCoreParams & CoreAppCallArgs${includeCompilation ? ' & AppClientCompilationParams' : ''}${
onComplete?.type ? ` & ${onComplete.type}` : ''
}${onComplete?.isOptional !== false ? ' = {}' : ''}`,
})
}
}
yield DecIndentAndCloseBlock
yield DecIndentAndCloseBlock
yield NewLine
}
}
function* callFactoryMethod({ methodSignatureToUniqueName, callConfig }: GeneratorContext, method: ContractMethod) {
const methodSignature = algokit.getABIMethodSignature(method)
if (!callConfig.callMethods.includes(methodSignature)) return
yield* jsDoc({
description: `Constructs a no op call for the ${methodSignature} ABI method`,
| abiDescription: method.desc,
params: { |
args: `Any args for the contract call`,
params: `Any additional parameters for the call`,
},
returns: `A TypedCallParams object for the call`,
})
yield* factoryMethod({
isNested: false,
name: makeSafeMethodIdentifier(methodSignatureToUniqueName[methodSignature]),
signature: methodSignature,
args: method.args,
paramTypes: 'AppClientCallCoreParams & CoreAppCallArgs',
})
}
function* factoryMethod({
isNested,
name,
signature,
args,
paramTypes,
}:
| {
isNested: boolean
name?: string
signature?: undefined
args?: undefined
paramTypes: string
}
| {
isNested: boolean
name?: string
signature: string
args: Array<{ name: string }>
paramTypes: string
}) {
yield `${isNested ? '' : 'static '}${name}(${signature === undefined ? '' : `args: MethodArgs<'${signature}'>, `}params: ${paramTypes}) {`
yield IncIndent
yield `return {`
yield IncIndent
if (signature) {
yield `method: '${signature}' as const,`
yield `methodArgs: Array.isArray(args) ? args : [${args
.map((a) => (isSafeVariableIdentifier(a.name) ? `args.${a.name}` : `args['${makeSafePropertyIdentifier(a.name)}']`))
.join(', ')}],`
} else {
yield `method: undefined,`
yield `methodArgs: undefined,`
}
yield '...params,'
yield DecIndent
yield '}'
yield DecIndent
yield `}${isNested ? ',' : ''}`
}
| src/client/call-factory.ts | algorandfoundation-algokit-client-generator-ts-2de43ed | [
{
"filename": "src/client/call-client.ts",
"retrieved_chunk": "}\nfunction* noopMethods({ app, name, callConfig, methodSignatureToUniqueName }: GeneratorContext): DocumentParts {\n for (const method of app.contract.methods) {\n const methodSignature = algokit.getABIMethodSignature(method)\n const methodName = makeSafeMethodIdentifier(methodSignatureToUniqueName[methodSignature])\n // Skip methods which don't support a no_op call config\n if (!callConfig.callMethods.includes(methodSignature)) continue\n yield* jsDoc({\n description: `Calls the ${algokit.getABIMethodSignature(method)} ABI method.`,\n abiDescription: method.desc,",
"score": 61.65890167442487
},
{
"filename": "src/client/call-composer-types.ts",
"retrieved_chunk": " if (!callConfig.callMethods.includes(methodSignature)) continue\n yield* jsDoc({\n description: `Calls the ${algokit.getABIMethodSignature(method)} ABI method.`,\n abiDescription: method.desc,\n params: {\n args: `The arguments for the contract call`,\n params: `Any additional parameters for the call`,\n },\n returns: `The typed transaction composer so you can fluently chain multiple calls or call execute to execute all queued up transactions`,\n })",
"score": 47.29890309682143
},
{
"filename": "src/client/call-composer.ts",
"retrieved_chunk": " for (const method of app.contract.methods) {\n const methodSignature = algokit.getABIMethodSignature(method)\n const methodName = makeSafeMethodIdentifier(methodSignatureToUniqueName[methodSignature])\n // Skip methods which don't support a no_op call config\n if (!callConfig.callMethods.includes(methodSignature)) continue\n yield `${methodName}(args: MethodArgs<'${methodSignature}'>, params?: AppClientCallCoreParams & CoreAppCallArgs) {`\n yield IncIndent\n yield `promiseChain = promiseChain.then(() => client.${methodName}(args, {...params, sendParams: {...params?.sendParams, skipSending: true, atc}}))`\n const outputTypeName = app.hints?.[methodSignature]?.structs?.output?.name\n yield `resultMappers.push(${outputTypeName ?? 'undefined'})`",
"score": 43.15507528207998
},
{
"filename": "src/client/call-composer-types.ts",
"retrieved_chunk": " returns: `The typed transaction composer so you can fluently chain multiple calls or call execute to execute all queued up transactions`,\n })\n yield `clearState(args?: BareCallArgs & AppClientCallCoreParams & CoreAppCallArgs): ${name}Composer<[...TReturns, undefined]>`\n yield NewLine\n}\nfunction* callComposerTypeNoops({ app, name, callConfig, methodSignatureToUniqueName }: GeneratorContext): DocumentParts {\n for (const method of app.contract.methods) {\n const methodSignature = algokit.getABIMethodSignature(method)\n const methodName = makeSafeMethodIdentifier(methodSignatureToUniqueName[methodSignature])\n // Skip methods which don't support a no_op call config",
"score": 34.89523759572161
},
{
"filename": "src/client/call-client.ts",
"retrieved_chunk": " params: {\n args: `The arguments for the contract call`,\n params: `Any additional parameters for the call`,\n },\n returns: `The result of the call${method?.returns?.desc ? `: ${method.returns.desc}` : ''}`,\n })\n yield `public ${methodName}(args: MethodArgs<'${methodSignature}'>, params: AppClientCallCoreParams & CoreAppCallArgs = {}) {`\n yield IncIndent\n const outputTypeName = app.hints?.[methodSignature]?.structs?.output?.name\n yield `return this.call(${name}CallFactory.${methodName}(args, params)${",
"score": 33.79943315641654
}
] | typescript | abiDescription: method.desc,
params: { |
import { splitSignature } from '@ethersproject/bytes';
import { fetchProposal, Space } from '../../helpers/snapshot';
import {
validateProposal,
getProposalContract,
signer,
numberizeProposalId,
validateMintInput,
mintingAllowed
} from './utils';
import abi from './spaceCollectionImplementationAbi.json';
import { FormatTypes, Interface } from '@ethersproject/abi';
const MintType = {
Mint: [
{ name: 'proposer', type: 'address' },
{ name: 'recipient', type: 'address' },
{ name: 'proposalId', type: 'uint256' },
{ name: 'salt', type: 'uint256' }
]
};
const NFT_CLAIMER_NETWORK = process.env.NFT_CLAIMER_NETWORK;
export default async function payload(input: {
proposalAuthor: string;
recipient: string;
id: string;
salt: string;
}) {
const params = await validateMintInput(input);
const proposal = await fetchProposal(params.id);
validateProposal(proposal, params.proposalAuthor);
const spaceId = proposal?.space.id as string;
const verifyingContract = await getProposalContract(spaceId);
if (!mintingAllowed(proposal?.space as Space)) {
throw new Error('Space has closed minting');
}
const message = {
proposer: params.proposalAuthor,
recipient: params.recipient,
proposalId: numberizeProposalId(params.id),
salt: BigInt(params.salt)
};
return {
signature: await generateSignature(verifyingContract, spaceId, message),
contractAddress: verifyingContract,
spaceId: proposal?.space.id,
...message,
salt: params.salt,
abi: | new Interface(abi).getFunction('mint').format(FormatTypes.full)
}; |
}
async function generateSignature(
verifyingContract: string,
domain: string,
message: Record<string, string | bigint>
) {
return splitSignature(
await signer._signTypedData(
{
name: domain,
version: '0.1',
chainId: NFT_CLAIMER_NETWORK,
verifyingContract
},
MintType,
message
)
);
}
| src/lib/nftClaimer/mint.ts | snapshot-labs-snapshot-sidekick-800dacf | [
{
"filename": "src/lib/nftClaimer/deploy.ts",
"retrieved_chunk": " const result = {\n initializer,\n salt: params.salt,\n abi: new Interface(spaceFactoryAbi).getFunction('deployProxy').format(FormatTypes.full),\n verifyingContract: VERIFYING_CONTRACT,\n implementation: IMPLEMENTATION_ADDRESS,\n signature: await generateSignature(IMPLEMENTATION_ADDRESS, initializer, params.salt)\n };\n console.debug('Signer', signer.address);\n console.debug('Payload', result);",
"score": 52.53738976481085
},
{
"filename": "src/lib/nftClaimer/deploy.ts",
"retrieved_chunk": " const space = await fetchSpace(params.id);\n await validateSpace(params.spaceOwner, space);\n const initializer = getInitializer({\n spaceOwner: params.spaceOwner,\n spaceId: space?.id as string,\n maxSupply: params.maxSupply,\n mintPrice: params.mintPrice,\n proposerFee: params.proposerFee,\n spaceTreasury: params.spaceTreasury\n });",
"score": 15.071477907254927
},
{
"filename": "src/lib/nftClaimer/utils.ts",
"retrieved_chunk": " }\n}\nexport async function getProposalContract(spaceId: string) {\n const contract = await getSpaceCollection(spaceId);\n if (!contract) {\n throw new Error(`SpaceCollection contract is not found for space ${spaceId}`);\n }\n return contract.id;\n}\nconst client = new ApolloClient({",
"score": 13.894637822882451
},
{
"filename": "src/lib/nftClaimer/deploy.ts",
"retrieved_chunk": " salt: BigInt(salt)\n }\n };\n return splitSignature(await signer._signTypedData(params.domain, params.types, params.value));\n}",
"score": 13.40452377763578
},
{
"filename": "src/lib/nftClaimer/deploy.ts",
"retrieved_chunk": " // the smart contract version\n // NOTE Do not forget to remove the last 4 params in the ABI when copy/pasting\n // from the smart contract\n const initializer = new Interface(spaceCollectionAbi).encodeFunctionData('initialize', params);\n const result = `${INITIALIZE_SELECTOR}${initializer.slice(10)}`;\n console.debug('Initializer params', params);\n return result;\n}\nasync function generateSignature(implementation: string, initializer: string, salt: string) {\n const params = {",
"score": 12.879708855741956
}
] | typescript | new Interface(abi).getFunction('mint').format(FormatTypes.full)
}; |
import { ContractMethod } from '../schema/application'
import { DecIndent, DecIndentAndCloseBlock, DocumentParts, IncIndent, jsDoc, NewLine } from '../output/writer'
import { isSafeVariableIdentifier, makeSafeMethodIdentifier, makeSafePropertyIdentifier } from '../util/sanitization'
import * as algokit from '@algorandfoundation/algokit-utils'
import { GeneratorContext } from './generator-context'
import { BARE_CALL, MethodList } from './helpers/get-call-config-summary'
import { getCreateOnCompleteOptions } from './deploy-types'
export function* callFactory(ctx: GeneratorContext): DocumentParts {
yield* jsDoc('Exposes methods for constructing all available smart contract calls')
yield `export abstract class ${ctx.name}CallFactory {`
yield IncIndent
yield* opMethods(ctx)
for (const method of ctx.app.contract.methods) {
yield* callFactoryMethod(ctx, method)
}
yield DecIndent
yield '}'
}
function* opMethods(ctx: GeneratorContext): DocumentParts {
const { app, callConfig } = ctx
yield* operationMethod(
ctx,
`Constructs a create call for the ${app.contract.name} smart contract`,
callConfig.createMethods,
'create',
true,
)
yield* operationMethod(
ctx,
`Constructs an update call for the ${app.contract.name} smart contract`,
callConfig.updateMethods,
'update',
true,
)
yield* operationMethod(ctx, `Constructs a delete call for the ${app.contract.name} smart contract`, callConfig.deleteMethods, 'delete')
yield* operationMethod(ctx, `Constructs an opt in call for the ${app.contract.name} smart contract`, callConfig.optInMethods, 'optIn')
yield* operationMethod(
ctx,
`Constructs a close out call for the ${app.contract.name} smart contract`,
callConfig.closeOutMethods,
'closeOut',
)
}
function* operationMethod(
{ app, methodSignatureToUniqueName }: GeneratorContext,
description: string,
methods: MethodList,
verb: 'create' | 'update' | 'optIn' | 'closeOut' | 'delete',
includeCompilation?: boolean,
): DocumentParts {
if (methods.length) {
yield* jsDoc(`Gets available ${verb} call factories`)
yield `static get ${verb}() {`
yield IncIndent
yield `return {`
yield IncIndent
for (const methodSig of methods) {
const onComplete = verb === 'create' ? getCreateOnCompleteOptions(methodSig, app) : undefined
if (methodSig === BARE_CALL) {
yield* jsDoc({
description: `${description} using a bare call`,
params: {
params: `Any parameters for the call`,
},
returns: `A TypedCallParams object for the call`,
})
yield* factoryMethod({
isNested: true,
name: 'bare',
paramTypes: `BareCallArgs & AppClientCallCoreParams & CoreAppCallArgs${
includeCompilation ? ' & AppClientCompilationParams' : ''
}${onComplete?.type ? ` & ${onComplete.type}` : ''}${onComplete?.isOptional !== false ? ' = {}' : ''}`,
})
} else {
const method = app.contract.methods.find((m) => algokit.getABIMethodSignature(m) === methodSig)!
const uniqueName = methodSignatureToUniqueName[methodSig]
yield* jsDoc({
description: `${description} using the ${methodSig} ABI method`,
params: {
args: `Any args for the contract call`,
params: `Any additional parameters for the call`,
},
returns: `A TypedCallParams object for the call`,
})
yield* factoryMethod({
isNested: true,
name: makeSafeMethodIdentifier(uniqueName),
signature: methodSig,
args: method.args,
paramTypes: `AppClientCallCoreParams & CoreAppCallArgs${includeCompilation ? ' & AppClientCompilationParams' : ''}${
onComplete?.type ? ` & ${onComplete.type}` : ''
}${onComplete?.isOptional !== false ? ' = {}' : ''}`,
})
}
}
yield DecIndentAndCloseBlock
yield DecIndentAndCloseBlock
yield NewLine
}
}
function* callFactoryMethod({ methodSignatureToUniqueName, callConfig }: GeneratorContext, method: ContractMethod) {
const | methodSignature = algokit.getABIMethodSignature(method)
if (!callConfig.callMethods.includes(methodSignature)) return
yield* jsDoc({ |
description: `Constructs a no op call for the ${methodSignature} ABI method`,
abiDescription: method.desc,
params: {
args: `Any args for the contract call`,
params: `Any additional parameters for the call`,
},
returns: `A TypedCallParams object for the call`,
})
yield* factoryMethod({
isNested: false,
name: makeSafeMethodIdentifier(methodSignatureToUniqueName[methodSignature]),
signature: methodSignature,
args: method.args,
paramTypes: 'AppClientCallCoreParams & CoreAppCallArgs',
})
}
function* factoryMethod({
isNested,
name,
signature,
args,
paramTypes,
}:
| {
isNested: boolean
name?: string
signature?: undefined
args?: undefined
paramTypes: string
}
| {
isNested: boolean
name?: string
signature: string
args: Array<{ name: string }>
paramTypes: string
}) {
yield `${isNested ? '' : 'static '}${name}(${signature === undefined ? '' : `args: MethodArgs<'${signature}'>, `}params: ${paramTypes}) {`
yield IncIndent
yield `return {`
yield IncIndent
if (signature) {
yield `method: '${signature}' as const,`
yield `methodArgs: Array.isArray(args) ? args : [${args
.map((a) => (isSafeVariableIdentifier(a.name) ? `args.${a.name}` : `args['${makeSafePropertyIdentifier(a.name)}']`))
.join(', ')}],`
} else {
yield `method: undefined,`
yield `methodArgs: undefined,`
}
yield '...params,'
yield DecIndent
yield '}'
yield DecIndent
yield `}${isNested ? ',' : ''}`
}
| src/client/call-factory.ts | algorandfoundation-algokit-client-generator-ts-2de43ed | [
{
"filename": "src/client/call-client.ts",
"retrieved_chunk": "}\nfunction* noopMethods({ app, name, callConfig, methodSignatureToUniqueName }: GeneratorContext): DocumentParts {\n for (const method of app.contract.methods) {\n const methodSignature = algokit.getABIMethodSignature(method)\n const methodName = makeSafeMethodIdentifier(methodSignatureToUniqueName[methodSignature])\n // Skip methods which don't support a no_op call config\n if (!callConfig.callMethods.includes(methodSignature)) continue\n yield* jsDoc({\n description: `Calls the ${algokit.getABIMethodSignature(method)} ABI method.`,\n abiDescription: method.desc,",
"score": 40.56849766238722
},
{
"filename": "src/client/call-composer.ts",
"retrieved_chunk": " for (const method of app.contract.methods) {\n const methodSignature = algokit.getABIMethodSignature(method)\n const methodName = makeSafeMethodIdentifier(methodSignatureToUniqueName[methodSignature])\n // Skip methods which don't support a no_op call config\n if (!callConfig.callMethods.includes(methodSignature)) continue\n yield `${methodName}(args: MethodArgs<'${methodSignature}'>, params?: AppClientCallCoreParams & CoreAppCallArgs) {`\n yield IncIndent\n yield `promiseChain = promiseChain.then(() => client.${methodName}(args, {...params, sendParams: {...params?.sendParams, skipSending: true, atc}}))`\n const outputTypeName = app.hints?.[methodSignature]?.structs?.output?.name\n yield `resultMappers.push(${outputTypeName ?? 'undefined'})`",
"score": 32.65355475029358
},
{
"filename": "src/client/call-composer-types.ts",
"retrieved_chunk": " returns: `The typed transaction composer so you can fluently chain multiple calls or call execute to execute all queued up transactions`,\n })\n yield `clearState(args?: BareCallArgs & AppClientCallCoreParams & CoreAppCallArgs): ${name}Composer<[...TReturns, undefined]>`\n yield NewLine\n}\nfunction* callComposerTypeNoops({ app, name, callConfig, methodSignatureToUniqueName }: GeneratorContext): DocumentParts {\n for (const method of app.contract.methods) {\n const methodSignature = algokit.getABIMethodSignature(method)\n const methodName = makeSafeMethodIdentifier(methodSignatureToUniqueName[methodSignature])\n // Skip methods which don't support a no_op call config",
"score": 26.880503935669555
},
{
"filename": "src/client/call-composer-types.ts",
"retrieved_chunk": " if (!callConfig.callMethods.includes(methodSignature)) continue\n yield* jsDoc({\n description: `Calls the ${algokit.getABIMethodSignature(method)} ABI method.`,\n abiDescription: method.desc,\n params: {\n args: `The arguments for the contract call`,\n params: `Any additional parameters for the call`,\n },\n returns: `The typed transaction composer so you can fluently chain multiple calls or call execute to execute all queued up transactions`,\n })",
"score": 26.313772860230948
},
{
"filename": "src/client/call-composer-types.ts",
"retrieved_chunk": " yield `${methodName}(args: MethodArgs<'${methodSignature}'>, params?: AppClientCallCoreParams & CoreAppCallArgs): ${name}Composer<[...TReturns, MethodReturn<'${methodSignature}'>]>`\n yield NewLine\n }\n}\nfunction* callComposerOperationMethodType(\n { app, methodSignatureToUniqueName, name }: GeneratorContext,\n description: string,\n methods: MethodList,\n verb: 'create' | 'update' | 'optIn' | 'closeOut' | 'delete',\n includeCompilation?: boolean,",
"score": 22.726136601447177
}
] | typescript | methodSignature = algokit.getABIMethodSignature(method)
if (!callConfig.callMethods.includes(methodSignature)) return
yield* jsDoc({ |
import express from 'express';
import { capture } from './helpers/sentry';
import { rpcError, rpcSuccess, storageEngine } from './helpers/utils';
import getModerationList from './lib/moderationList';
import VotesReport from './lib/votesReport';
import mintPayload from './lib/nftClaimer/mint';
import deployPayload from './lib/nftClaimer/deploy';
import { queue, getProgress } from './lib/queue';
import { snapshotFee } from './lib/nftClaimer/utils';
const router = express.Router();
router.post('/votes/:id', async (req, res) => {
const { id } = req.params;
const votesReport = new VotesReport(id, storageEngine(process.env.VOTE_REPORT_SUBDIR));
try {
const file = await votesReport.getCache();
if (file) {
res.header('Content-Type', 'text/csv');
res.attachment(votesReport.filename);
return res.end(file);
}
try {
await votesReport.isCacheable();
queue(votesReport);
return rpcSuccess(res.status(202), getProgress(id).toString(), id);
} catch (e: any) {
capture(e);
rpcError(res, e, id);
}
} catch (e) {
capture(e);
return rpcError(res, 'INTERNAL_ERROR', id);
}
});
router.get('/moderation', async (req, res) => {
const { list } = req.query;
try {
res.json(await getModerationList(list ? (list as string).split(',') : undefined));
} catch (e) {
capture(e);
return rpcError(res, 'INTERNAL_ERROR', '');
}
});
router.get('/nft-claimer', async (req, res) => {
try {
return res.json({ snapshotFee: await snapshotFee() });
} catch (e: any) {
capture(e);
return rpcError(res, e, '');
}
});
router.post('/nft-claimer/deploy', async (req, res) => {
const { address, id, salt, maxSupply, mintPrice, spaceTreasury, proposerFee } = req.body;
try {
return res.json(
await deployPayload({
spaceOwner: address,
id,
maxSupply,
mintPrice,
proposerFee,
salt,
spaceTreasury
})
);
} catch (e: any) {
capture(e);
return rpcError(res, e, salt);
}
});
router.post('/nft-claimer/mint', async (req, res) => {
const { proposalAuthor, address, id, salt } = req.body;
try {
| return res.json(await mintPayload({ proposalAuthor, recipient: address, id, salt })); |
} catch (e: any) {
capture(e);
return rpcError(res, e, salt);
}
});
export default router;
| src/api.ts | snapshot-labs-snapshot-sidekick-800dacf | [
{
"filename": "src/sentryTunnel.ts",
"retrieved_chunk": " if (status !== 200) {\n console.debug(await response.text());\n }\n return res.sendStatus(status);\n } catch (e: any) {\n capture(e);\n rpcError(res, e, '');\n }\n});\nexport default router;",
"score": 34.43578332944277
},
{
"filename": "src/webhook.ts",
"retrieved_chunk": " return rpcError(res, 'Invalid Request', id);\n }\n try {\n processVotesReport(id, event);\n return rpcSuccess(res, 'Webhook received', id);\n } catch (e) {\n capture(e);\n return rpcError(res, 'INTERNAL_ERROR', id);\n }\n});",
"score": 32.98067608124836
},
{
"filename": "src/lib/nftClaimer/utils.ts",
"retrieved_chunk": " };\n}\nexport async function validateMintInput(params: any) {\n validateAddresses({ proposalAuthor: params.proposalAuthor, recipient: params.recipient });\n validateNumbers({\n salt: params.salt\n });\n return {\n proposalAuthor: getAddress(params.proposalAuthor),\n recipient: getAddress(params.recipient),",
"score": 32.42907292224482
},
{
"filename": "src/webhook.ts",
"retrieved_chunk": "}\nrouter.post('/webhook', (req, res) => {\n const body = req.body || {};\n const event = body.event?.toString() ?? '';\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n const { type, id } = body.id?.toString().split('/');\n if (req.headers['authentication'] !== `${process.env.WEBHOOK_AUTH_TOKEN ?? ''}`) {\n return rpcError(res, 'UNAUTHORIZED', id);\n }\n if (!event || !id) {",
"score": 32.079435806432215
},
{
"filename": "src/helpers/sentry.ts",
"retrieved_chunk": " return;\n }\n app.use(Sentry.Handlers.errorHandler());\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n app.use(function onError(err: any, req: any, res: any, _: any) {\n res.statusCode = 500;\n res.end(`${res.sentry}\\n`);\n });\n}\nexport function capture(e: any) {",
"score": 27.215890743158482
}
] | typescript | return res.json(await mintPayload({ proposalAuthor, recipient: address, id, salt })); |
import { ContractMethod } from '../schema/application'
import { DecIndent, DecIndentAndCloseBlock, DocumentParts, IncIndent, jsDoc, NewLine } from '../output/writer'
import { isSafeVariableIdentifier, makeSafeMethodIdentifier, makeSafePropertyIdentifier } from '../util/sanitization'
import * as algokit from '@algorandfoundation/algokit-utils'
import { GeneratorContext } from './generator-context'
import { BARE_CALL, MethodList } from './helpers/get-call-config-summary'
import { getCreateOnCompleteOptions } from './deploy-types'
export function* callFactory(ctx: GeneratorContext): DocumentParts {
yield* jsDoc('Exposes methods for constructing all available smart contract calls')
yield `export abstract class ${ctx.name}CallFactory {`
yield IncIndent
yield* opMethods(ctx)
for (const method of ctx.app.contract.methods) {
yield* callFactoryMethod(ctx, method)
}
yield DecIndent
yield '}'
}
function* opMethods(ctx: GeneratorContext): DocumentParts {
const { app, callConfig } = ctx
yield* operationMethod(
ctx,
`Constructs a create call for the ${app.contract.name} smart contract`,
callConfig.createMethods,
'create',
true,
)
yield* operationMethod(
ctx,
`Constructs an update call for the ${app.contract.name} smart contract`,
callConfig.updateMethods,
'update',
true,
)
yield* operationMethod(ctx, `Constructs a delete call for the ${app.contract.name} smart contract`, callConfig.deleteMethods, 'delete')
yield* operationMethod(ctx, `Constructs an opt in call for the ${app.contract.name} smart contract`, callConfig.optInMethods, 'optIn')
yield* operationMethod(
ctx,
`Constructs a close out call for the ${app.contract.name} smart contract`,
callConfig.closeOutMethods,
'closeOut',
)
}
function* operationMethod(
{ app, methodSignatureToUniqueName }: GeneratorContext,
description: string,
methods: MethodList,
verb: 'create' | 'update' | 'optIn' | 'closeOut' | 'delete',
includeCompilation?: boolean,
): DocumentParts {
if (methods.length) {
yield* jsDoc(`Gets available ${verb} call factories`)
yield `static get ${verb}() {`
yield IncIndent
yield `return {`
yield IncIndent
for (const methodSig of methods) {
const onComplete = verb === 'create' ? getCreateOnCompleteOptions(methodSig, app) : undefined
if (methodSig === BARE_CALL) {
yield* jsDoc({
description: `${description} using a bare call`,
params: {
params: `Any parameters for the call`,
},
returns: `A TypedCallParams object for the call`,
})
yield* factoryMethod({
isNested: true,
name: 'bare',
paramTypes: `BareCallArgs & AppClientCallCoreParams & CoreAppCallArgs${
includeCompilation ? ' & AppClientCompilationParams' : ''
}${onComplete?.type ? ` & ${onComplete.type}` : ''}${onComplete?.isOptional !== false ? ' = {}' : ''}`,
})
} else {
const method = app.contract.methods.find((m) => algokit.getABIMethodSignature(m) === methodSig)!
const uniqueName = methodSignatureToUniqueName[methodSig]
yield* jsDoc({
description: `${description} using the ${methodSig} ABI method`,
params: {
args: `Any args for the contract call`,
params: `Any additional parameters for the call`,
},
returns: `A TypedCallParams object for the call`,
})
yield* factoryMethod({
isNested: true,
name: makeSafeMethodIdentifier(uniqueName),
signature: methodSig,
args: method.args,
paramTypes: `AppClientCallCoreParams & CoreAppCallArgs${includeCompilation ? ' & AppClientCompilationParams' : ''}${
onComplete?.type ? ` & ${onComplete.type}` : ''
}${onComplete?.isOptional !== false ? ' = {}' : ''}`,
})
}
}
yield DecIndentAndCloseBlock
yield DecIndentAndCloseBlock
yield NewLine
}
}
function* callFactoryMethod({ methodSignatureToUniqueName, callConfig }: GeneratorContext, method: ContractMethod) {
const methodSignature = algokit.getABIMethodSignature(method)
if (!callConfig.callMethods.includes(methodSignature)) return
yield* jsDoc({
description: `Constructs a no op call for the ${methodSignature} ABI method`,
abiDescription: method.desc,
params: {
args: `Any args for the contract call`,
params: `Any additional parameters for the call`,
},
returns: `A TypedCallParams object for the call`,
})
yield* factoryMethod({
isNested: false,
name: makeSafeMethodIdentifier(methodSignatureToUniqueName[methodSignature]),
signature: methodSignature,
args | : method.args,
paramTypes: 'AppClientCallCoreParams & CoreAppCallArgs',
})
} |
function* factoryMethod({
isNested,
name,
signature,
args,
paramTypes,
}:
| {
isNested: boolean
name?: string
signature?: undefined
args?: undefined
paramTypes: string
}
| {
isNested: boolean
name?: string
signature: string
args: Array<{ name: string }>
paramTypes: string
}) {
yield `${isNested ? '' : 'static '}${name}(${signature === undefined ? '' : `args: MethodArgs<'${signature}'>, `}params: ${paramTypes}) {`
yield IncIndent
yield `return {`
yield IncIndent
if (signature) {
yield `method: '${signature}' as const,`
yield `methodArgs: Array.isArray(args) ? args : [${args
.map((a) => (isSafeVariableIdentifier(a.name) ? `args.${a.name}` : `args['${makeSafePropertyIdentifier(a.name)}']`))
.join(', ')}],`
} else {
yield `method: undefined,`
yield `methodArgs: undefined,`
}
yield '...params,'
yield DecIndent
yield '}'
yield DecIndent
yield `}${isNested ? ',' : ''}`
}
| src/client/call-factory.ts | algorandfoundation-algokit-client-generator-ts-2de43ed | [
{
"filename": "src/client/call-composer.ts",
"retrieved_chunk": " for (const method of app.contract.methods) {\n const methodSignature = algokit.getABIMethodSignature(method)\n const methodName = makeSafeMethodIdentifier(methodSignatureToUniqueName[methodSignature])\n // Skip methods which don't support a no_op call config\n if (!callConfig.callMethods.includes(methodSignature)) continue\n yield `${methodName}(args: MethodArgs<'${methodSignature}'>, params?: AppClientCallCoreParams & CoreAppCallArgs) {`\n yield IncIndent\n yield `promiseChain = promiseChain.then(() => client.${methodName}(args, {...params, sendParams: {...params?.sendParams, skipSending: true, atc}}))`\n const outputTypeName = app.hints?.[methodSignature]?.structs?.output?.name\n yield `resultMappers.push(${outputTypeName ?? 'undefined'})`",
"score": 24.79233494493879
},
{
"filename": "src/client/call-composer-types.ts",
"retrieved_chunk": " yield `${methodName}(args: MethodArgs<'${methodSignature}'>, params?: AppClientCallCoreParams & CoreAppCallArgs): ${name}Composer<[...TReturns, MethodReturn<'${methodSignature}'>]>`\n yield NewLine\n }\n}\nfunction* callComposerOperationMethodType(\n { app, methodSignatureToUniqueName, name }: GeneratorContext,\n description: string,\n methods: MethodList,\n verb: 'create' | 'update' | 'optIn' | 'closeOut' | 'delete',\n includeCompilation?: boolean,",
"score": 22.889812143466187
},
{
"filename": "src/client/call-client.ts",
"retrieved_chunk": " params: {\n args: `The arguments for the contract call`,\n params: `Any additional parameters for the call`,\n },\n returns: `The result of the call${method?.returns?.desc ? `: ${method.returns.desc}` : ''}`,\n })\n yield `public ${methodName}(args: MethodArgs<'${methodSignature}'>, params: AppClientCallCoreParams & CoreAppCallArgs = {}) {`\n yield IncIndent\n const outputTypeName = app.hints?.[methodSignature]?.structs?.output?.name\n yield `return this.call(${name}CallFactory.${methodName}(args, params)${",
"score": 20.98394252085584
},
{
"filename": "src/client/call-composer-types.ts",
"retrieved_chunk": " returns: `The typed transaction composer so you can fluently chain multiple calls or call execute to execute all queued up transactions`,\n })\n yield `clearState(args?: BareCallArgs & AppClientCallCoreParams & CoreAppCallArgs): ${name}Composer<[...TReturns, undefined]>`\n yield NewLine\n}\nfunction* callComposerTypeNoops({ app, name, callConfig, methodSignatureToUniqueName }: GeneratorContext): DocumentParts {\n for (const method of app.contract.methods) {\n const methodSignature = algokit.getABIMethodSignature(method)\n const methodName = makeSafeMethodIdentifier(methodSignatureToUniqueName[methodSignature])\n // Skip methods which don't support a no_op call config",
"score": 20.977698154205058
},
{
"filename": "src/client/call-client.ts",
"retrieved_chunk": "}\nfunction* noopMethods({ app, name, callConfig, methodSignatureToUniqueName }: GeneratorContext): DocumentParts {\n for (const method of app.contract.methods) {\n const methodSignature = algokit.getABIMethodSignature(method)\n const methodName = makeSafeMethodIdentifier(methodSignatureToUniqueName[methodSignature])\n // Skip methods which don't support a no_op call config\n if (!callConfig.callMethods.includes(methodSignature)) continue\n yield* jsDoc({\n description: `Calls the ${algokit.getABIMethodSignature(method)} ABI method.`,\n abiDescription: method.desc,",
"score": 18.336316242964614
}
] | typescript | : method.args,
paramTypes: 'AppClientCallCoreParams & CoreAppCallArgs',
})
} |
import { readFileSync } from 'fs';
import path from 'path';
import db from '../helpers/mysql';
type MODERATION_LIST = Record<string, string[] | JSON>;
const CACHE_PATH = path.resolve(__dirname, `../../${process.env.MODERATION_LIST_PATH || 'data'}`);
const FIELDS = new Map<keyof MODERATION_LIST, Record<string, string>>([
['flaggedLinks', { action: 'flag', type: 'link' }],
['flaggedProposals', { action: 'flag', type: 'proposal' }],
['flaggedSpaces', { action: 'flag', type: 'space' }],
['flaggedIps', { action: 'flag', type: 'ip' }],
['verifiedSpaces', { action: 'verify', type: 'space' }],
['verifiedTokens', { file: 'verifiedTokens.json' }]
]);
export function readFile(filename: string) {
return parseFileContent(
readFileSync(path.join(CACHE_PATH, filename), { encoding: 'utf8' }),
filename.split('.')[1]
);
}
function parseFileContent(content: string, parser: string): MODERATION_LIST[keyof MODERATION_LIST] {
switch (parser) {
case 'txt':
return content.split('\n').filter(value => value !== '');
case 'json':
return JSON.parse(content);
default:
throw new Error('Invalid file type');
}
}
export default async function getModerationList(fields = Array.from(FIELDS.keys())) {
const list: Partial<MODERATION_LIST> = {};
const reverseMapping: Record<string, keyof MODERATION_LIST> = {};
const queryWhereStatement: string[] = [];
let queryWhereArgs: string[] = [];
fields.forEach(field => {
if (FIELDS.has(field)) {
const args = FIELDS.get(field) as Record<string, string>;
if (!args.file) {
list[field] = [];
reverseMapping[`${args.action}-${args.type}`] = field;
queryWhereStatement.push(`(action = ? AND type = ?)`);
queryWhereArgs = queryWhereArgs.concat([args.action, args.type]);
} else {
list[field] = readFile(args.file);
}
}
});
if (queryWhereStatement.length > 0) {
| const dbResults = await db.queryAsync(
`SELECT * FROM moderation WHERE ${queryWhereStatement.join(' OR ')}`,
queryWhereArgs
); |
dbResults.forEach(row => {
(list[reverseMapping[`${row.action}-${row.type}`]] as string[]).push(row.value as string);
});
}
return list;
}
| src/lib/moderationList.ts | snapshot-labs-snapshot-sidekick-800dacf | [
{
"filename": "src/helpers/mysql.ts",
"retrieved_chunk": "interface PromisedPool {\n queryAsync: (query: string, args?: SqlQueryArgs | SqlQueryArgs[]) => Promise<SqlRow[]>;\n endAsync: () => Promise<any>;\n}\nconst config = new ConnectionString(process.env.DATABASE_URL || '');\nbluebird.promisifyAll([Pool, Connection]);\nconst db: PromisedPool = mysql.createPool({\n ...config,\n host: config.hosts?.[0].name,\n port: config.hosts?.[0].port,",
"score": 11.963798346590384
},
{
"filename": "src/api.ts",
"retrieved_chunk": " return rpcError(res, 'INTERNAL_ERROR', id);\n }\n});\nrouter.get('/moderation', async (req, res) => {\n const { list } = req.query;\n try {\n res.json(await getModerationList(list ? (list as string).split(',') : undefined));\n } catch (e) {\n capture(e);\n return rpcError(res, 'INTERNAL_ERROR', '');",
"score": 11.8517694821042
},
{
"filename": "src/lib/votesReport.ts",
"retrieved_chunk": " page = 0;\n createdPivot = newVotes[newVotes.length - 1].created;\n } else {\n page++;\n }\n votes = votes.concat(newVotes);\n this.generationProgress = Number(\n ((votes.length / (this.proposal?.votes as number)) * 100).toFixed(2)\n );\n } while (resultsSize === pageSize);",
"score": 8.47421837996561
},
{
"filename": "src/lib/nftClaimer/deploy.ts",
"retrieved_chunk": " const params = [\n args.spaceId,\n '0.1',\n args.maxSupply,\n BigInt(args.mintPrice),\n args.proposerFee,\n getAddress(args.spaceTreasury),\n getAddress(args.spaceOwner)\n ];\n // This encodeFunctionData should ignore the last 4 params compared to",
"score": 8.462227096116312
},
{
"filename": "src/lib/votesReport.ts",
"retrieved_chunk": " ].flat();\n content += headers.join(',');\n content += `\\n${votes.map(vote => this.#formatCsvLine(vote)).join('\\n')}`;\n console.log(`[votes-report] Report for ${this.id} ready with ${votes.length} items`);\n return content;\n };\n fetchAllVotes = async () => {\n let votes: Vote[] = [];\n let page = 0;\n let createdPivot = 0;",
"score": 7.674036233450025
}
] | typescript | const dbResults = await db.queryAsync(
`SELECT * FROM moderation WHERE ${queryWhereStatement.join(' OR ')}`,
queryWhereArgs
); |
import express from 'express';
import { capture } from './helpers/sentry';
import { rpcError, rpcSuccess, storageEngine } from './helpers/utils';
import getModerationList from './lib/moderationList';
import VotesReport from './lib/votesReport';
import mintPayload from './lib/nftClaimer/mint';
import deployPayload from './lib/nftClaimer/deploy';
import { queue, getProgress } from './lib/queue';
import { snapshotFee } from './lib/nftClaimer/utils';
const router = express.Router();
router.post('/votes/:id', async (req, res) => {
const { id } = req.params;
const votesReport = new VotesReport(id, storageEngine(process.env.VOTE_REPORT_SUBDIR));
try {
const file = await votesReport.getCache();
if (file) {
res.header('Content-Type', 'text/csv');
res.attachment(votesReport.filename);
return res.end(file);
}
try {
await votesReport.isCacheable();
queue(votesReport);
return rpcSuccess(res.status(202), getProgress(id).toString(), id);
} catch (e: any) {
capture(e);
rpcError(res, e, id);
}
} catch (e) {
capture(e);
return rpcError(res, 'INTERNAL_ERROR', id);
}
});
router.get('/moderation', async (req, res) => {
const { list } = req.query;
try {
res.json(await getModerationList(list ? (list as string).split(',') : undefined));
} catch (e) {
capture(e);
return rpcError(res, 'INTERNAL_ERROR', '');
}
});
router.get('/nft-claimer', async (req, res) => {
try {
return res.json({ snapshotFee: await snapshotFee() });
} catch (e: any) {
capture(e);
return rpcError(res, e, '');
}
});
router.post('/nft-claimer/deploy', async (req, res) => {
const { address, id, salt, maxSupply, mintPrice, spaceTreasury, proposerFee } = req.body;
try {
return res.json(
| await deployPayload({ |
spaceOwner: address,
id,
maxSupply,
mintPrice,
proposerFee,
salt,
spaceTreasury
})
);
} catch (e: any) {
capture(e);
return rpcError(res, e, salt);
}
});
router.post('/nft-claimer/mint', async (req, res) => {
const { proposalAuthor, address, id, salt } = req.body;
try {
return res.json(await mintPayload({ proposalAuthor, recipient: address, id, salt }));
} catch (e: any) {
capture(e);
return rpcError(res, e, salt);
}
});
export default router;
| src/api.ts | snapshot-labs-snapshot-sidekick-800dacf | [
{
"filename": "src/sentryTunnel.ts",
"retrieved_chunk": " if (status !== 200) {\n console.debug(await response.text());\n }\n return res.sendStatus(status);\n } catch (e: any) {\n capture(e);\n rpcError(res, e, '');\n }\n});\nexport default router;",
"score": 34.43578332944277
},
{
"filename": "src/webhook.ts",
"retrieved_chunk": " return rpcError(res, 'Invalid Request', id);\n }\n try {\n processVotesReport(id, event);\n return rpcSuccess(res, 'Webhook received', id);\n } catch (e) {\n capture(e);\n return rpcError(res, 'INTERNAL_ERROR', id);\n }\n});",
"score": 31.740145553995387
},
{
"filename": "src/webhook.ts",
"retrieved_chunk": "}\nrouter.post('/webhook', (req, res) => {\n const body = req.body || {};\n const event = body.event?.toString() ?? '';\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n const { type, id } = body.id?.toString().split('/');\n if (req.headers['authentication'] !== `${process.env.WEBHOOK_AUTH_TOKEN ?? ''}`) {\n return rpcError(res, 'UNAUTHORIZED', id);\n }\n if (!event || !id) {",
"score": 30.992576453499435
},
{
"filename": "src/helpers/sentry.ts",
"retrieved_chunk": " return;\n }\n app.use(Sentry.Handlers.errorHandler());\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n app.use(function onError(err: any, req: any, res: any, _: any) {\n res.statusCode = 500;\n res.end(`${res.sentry}\\n`);\n });\n}\nexport function capture(e: any) {",
"score": 27.215890743158482
},
{
"filename": "src/sentryTunnel.ts",
"retrieved_chunk": "import express from 'express';\nimport fetch from 'cross-fetch';\nimport bodyParser from 'body-parser';\nimport { URL } from 'url';\nimport { rpcError } from './helpers/utils';\nimport { capture } from './helpers/sentry';\nconst router = express.Router();\nrouter.post('/sentry', bodyParser.raw({ type: () => true, limit: '4mb' }), async (req, res) => {\n try {\n const { dsn, event_id } = JSON.parse(req.body.toString().split('\\n')[0]);",
"score": 26.106213887408483
}
] | typescript | await deployPayload({ |
import { getAddress } from '@ethersproject/address';
import { splitSignature } from '@ethersproject/bytes';
import { FormatTypes, Interface } from '@ethersproject/abi';
import { fetchSpace } from '../../helpers/snapshot';
import { signer, validateDeployInput, validateSpace } from './utils';
import spaceCollectionAbi from './spaceCollectionImplementationAbi.json';
import spaceFactoryAbi from './spaceFactoryAbi.json';
const DeployType = {
Deploy: [
{ name: 'implementation', type: 'address' },
{ name: 'initializer', type: 'bytes' },
{ name: 'salt', type: 'uint256' }
]
};
const VERIFYING_CONTRACT = getAddress(process.env.NFT_CLAIMER_DEPLOY_VERIFYING_CONTRACT as string);
const IMPLEMENTATION_ADDRESS = getAddress(
process.env.NFT_CLAIMER_DEPLOY_IMPLEMENTATION_ADDRESS as string
);
const NFT_CLAIMER_NETWORK = process.env.NFT_CLAIMER_NETWORK;
const INITIALIZE_SELECTOR = process.env.NFT_CLAIMER_DEPLOY_INITIALIZE_SELECTOR;
export default async function payload(input: {
spaceOwner: string;
id: string;
maxSupply: string;
mintPrice: string;
proposerFee: string;
salt: string;
spaceTreasury: string;
}) {
const params = await validateDeployInput(input);
const space = await fetchSpace(params.id);
await validateSpace(params.spaceOwner, space);
const initializer = getInitializer({
spaceOwner: params.spaceOwner,
spaceId: space?.id as string,
maxSupply: params.maxSupply,
mintPrice: params.mintPrice,
proposerFee: params.proposerFee,
spaceTreasury: params.spaceTreasury
});
const result = {
initializer,
salt: params.salt,
abi: new Interface(spaceFactoryAbi).getFunction('deployProxy').format(FormatTypes.full),
verifyingContract: VERIFYING_CONTRACT,
implementation: IMPLEMENTATION_ADDRESS,
signature: await generateSignature(IMPLEMENTATION_ADDRESS, initializer, params.salt)
};
console.debug('Signer', signer.address);
console.debug('Payload', result);
return result;
}
function getInitializer(args: {
spaceId: string;
maxSupply: number;
mintPrice: string;
proposerFee: number;
spaceTreasury: string;
spaceOwner: string;
}) {
const params = [
args.spaceId,
'0.1',
args.maxSupply,
BigInt(args.mintPrice),
args.proposerFee,
getAddress(args.spaceTreasury),
getAddress(args.spaceOwner)
];
// This encodeFunctionData should ignore the last 4 params compared to
// the smart contract version
// NOTE Do not forget to remove the last 4 params in the ABI when copy/pasting
// from the smart contract
| const initializer = new Interface(spaceCollectionAbi).encodeFunctionData('initialize', params); |
const result = `${INITIALIZE_SELECTOR}${initializer.slice(10)}`;
console.debug('Initializer params', params);
return result;
}
async function generateSignature(implementation: string, initializer: string, salt: string) {
const params = {
domain: {
name: 'SpaceCollectionFactory',
version: '0.1',
chainId: NFT_CLAIMER_NETWORK,
verifyingContract: VERIFYING_CONTRACT
},
types: DeployType,
value: {
implementation,
initializer,
salt: BigInt(salt)
}
};
return splitSignature(await signer._signTypedData(params.domain, params.types, params.value));
}
| src/lib/nftClaimer/deploy.ts | snapshot-labs-snapshot-sidekick-800dacf | [
{
"filename": "src/lib/nftClaimer/utils.ts",
"retrieved_chunk": " salt: params.salt\n });\n await validateProposerFee(parseInt(params.proposerFee));\n return {\n spaceOwner: getAddress(params.spaceOwner),\n spaceTreasury: getAddress(params.spaceTreasury),\n proposerFee: parseInt(params.proposerFee),\n maxSupply: parseInt(params.maxSupply),\n mintPrice: parseInt(params.mintPrice),\n ...params",
"score": 42.84005741192223
},
{
"filename": "src/lib/nftClaimer/utils.ts",
"retrieved_chunk": " );\n return contract.snapshotFee();\n } catch (e: any) {\n capture(e);\n throw 'Unable to retrieve the snapshotFee';\n }\n}",
"score": 40.615423306442615
},
{
"filename": "src/lib/nftClaimer/utils.ts",
"retrieved_chunk": " throw new Error(`proposerFee should not be greater than ${100 - sFee}`);\n }\n return true;\n}\nexport async function validateDeployInput(params: any) {\n validateAddresses({ spaceOwner: params.spaceOwner, spaceTreasury: params.spaceTreasury });\n validateNumbers({\n maxSupply: params.maxSupply,\n proposerFee: params.proposerFee,\n mintPrice: params.mintPrice,",
"score": 39.352886543245326
},
{
"filename": "src/lib/nftClaimer/utils.ts",
"retrieved_chunk": " if (NFT_CLAIMER_NETWORK !== 5 && !(await isSpaceOwner(space.id, address))) {\n throw new Error('Address is not the space owner');\n }\n const contract = await getSpaceCollection(space.id);\n if (contract) {\n throw new Error(`SpaceCollection contract already exist (${contract.id})`);\n }\n}\nasync function isSpaceOwner(spaceId: string, address: string) {\n return (await snapshot.utils.getSpaceController(spaceId, HUB_NETWORK)) === getAddress(address);",
"score": 31.911352421524693
},
{
"filename": "src/lib/nftClaimer/utils.ts",
"retrieved_chunk": " };\n}\nexport async function validateMintInput(params: any) {\n validateAddresses({ proposalAuthor: params.proposalAuthor, recipient: params.recipient });\n validateNumbers({\n salt: params.salt\n });\n return {\n proposalAuthor: getAddress(params.proposalAuthor),\n recipient: getAddress(params.recipient),",
"score": 23.283240880400157
}
] | typescript | const initializer = new Interface(spaceCollectionAbi).encodeFunctionData('initialize', params); |
import express from 'express';
import { capture } from './helpers/sentry';
import { rpcError, rpcSuccess, storageEngine } from './helpers/utils';
import getModerationList from './lib/moderationList';
import VotesReport from './lib/votesReport';
import mintPayload from './lib/nftClaimer/mint';
import deployPayload from './lib/nftClaimer/deploy';
import { queue, getProgress } from './lib/queue';
import { snapshotFee } from './lib/nftClaimer/utils';
const router = express.Router();
router.post('/votes/:id', async (req, res) => {
const { id } = req.params;
const votesReport = new VotesReport(id, storageEngine(process.env.VOTE_REPORT_SUBDIR));
try {
const file = await votesReport.getCache();
if (file) {
res.header('Content-Type', 'text/csv');
res.attachment(votesReport.filename);
return res.end(file);
}
try {
await votesReport.isCacheable();
queue(votesReport);
return rpcSuccess(res.status(202), getProgress(id).toString(), id);
} catch (e: any) {
capture(e);
rpcError(res, e, id);
}
} catch (e) {
capture(e);
return rpcError(res, 'INTERNAL_ERROR', id);
}
});
router.get('/moderation', async (req, res) => {
const { list } = req.query;
try {
res.json(await getModerationList(list ? (list as string).split(',') : undefined));
} catch (e) {
capture(e);
return rpcError(res, 'INTERNAL_ERROR', '');
}
});
router.get('/nft-claimer', async (req, res) => {
try {
return res.json( | { snapshotFee: await snapshotFee() }); |
} catch (e: any) {
capture(e);
return rpcError(res, e, '');
}
});
router.post('/nft-claimer/deploy', async (req, res) => {
const { address, id, salt, maxSupply, mintPrice, spaceTreasury, proposerFee } = req.body;
try {
return res.json(
await deployPayload({
spaceOwner: address,
id,
maxSupply,
mintPrice,
proposerFee,
salt,
spaceTreasury
})
);
} catch (e: any) {
capture(e);
return rpcError(res, e, salt);
}
});
router.post('/nft-claimer/mint', async (req, res) => {
const { proposalAuthor, address, id, salt } = req.body;
try {
return res.json(await mintPayload({ proposalAuthor, recipient: address, id, salt }));
} catch (e: any) {
capture(e);
return rpcError(res, e, salt);
}
});
export default router;
| src/api.ts | snapshot-labs-snapshot-sidekick-800dacf | [
{
"filename": "src/webhook.ts",
"retrieved_chunk": " return rpcError(res, 'Invalid Request', id);\n }\n try {\n processVotesReport(id, event);\n return rpcSuccess(res, 'Webhook received', id);\n } catch (e) {\n capture(e);\n return rpcError(res, 'INTERNAL_ERROR', id);\n }\n});",
"score": 36.13096441931303
},
{
"filename": "src/sentryTunnel.ts",
"retrieved_chunk": " if (status !== 200) {\n console.debug(await response.text());\n }\n return res.sendStatus(status);\n } catch (e: any) {\n capture(e);\n rpcError(res, e, '');\n }\n});\nexport default router;",
"score": 33.010358609352394
},
{
"filename": "src/lib/nftClaimer/utils.ts",
"retrieved_chunk": " );\n return contract.snapshotFee();\n } catch (e: any) {\n capture(e);\n throw 'Unable to retrieve the snapshotFee';\n }\n}",
"score": 23.868087967721127
},
{
"filename": "src/helpers/utils.ts",
"retrieved_chunk": " jsonrpc: '2.0',\n result,\n id\n });\n}\nexport function rpcError(res: Response, e: Error | string, id: string | number) {\n const errorMessage = e instanceof Error ? e.message : e;\n const errorCode = ERROR_CODES[errorMessage] ? ERROR_CODES[errorMessage] : -32603;\n res.status(errorCode > 0 ? errorCode : 500).json({\n jsonrpc: '2.0',",
"score": 23.615352177665965
},
{
"filename": "src/index.ts",
"retrieved_chunk": "app.use('/', sentryTunnel);\napp.get('/', (req, res) => {\n const commit = process.env.COMMIT_HASH || '';\n const v = commit ? `${version}#${commit.substring(0, 7)}` : version;\n return res.json({\n name,\n version: v\n });\n});\nfallbackLogger(app);",
"score": 23.414176015138953
}
] | typescript | { snapshotFee: await snapshotFee() }); |
import { sleep } from '../helpers/utils';
import { capture } from '../helpers/sentry';
import Cache from './cache';
const queues = new Set<Cache>();
const processingItems = new Map<string, Cache>();
async function processItem(cacheable: Cache) {
console.log(`[queue] Processing queue item: ${cacheable}`);
try {
processingItems.set(cacheable.id, cacheable);
await cacheable.createCache();
} catch (e) {
capture(e);
console.error(`[queue] Error while processing item`, e);
} finally {
queues.delete(cacheable);
processingItems.delete(cacheable.id);
}
}
export function queue(cacheable: Cache) {
queues.add(cacheable);
return queues.size;
}
export function getProgress(id: string) {
if (processingItems.has(id)) {
return processingItems.get(id)?.generationProgress as number;
}
return 0;
}
async function run() {
try {
console.log(`[queue] Poll queue (found ${queues.size} items)`);
queues.forEach(async cacheable => {
if (processingItems.has(cacheable.id)) {
console.log(
`[queue] Skip: ${cacheable} is currently being processed, progress: ${processingItems.get(
cacheable.id
)?.generationProgress}%`
);
return;
}
processItem(cacheable);
});
} catch (e) {
capture(e);
} finally {
await | sleep(15e3); |
await run();
}
}
run();
| src/lib/queue.ts | snapshot-labs-snapshot-sidekick-800dacf | [
{
"filename": "src/api.ts",
"retrieved_chunk": " try {\n await votesReport.isCacheable();\n queue(votesReport);\n return rpcSuccess(res.status(202), getProgress(id).toString(), id);\n } catch (e: any) {\n capture(e);\n rpcError(res, e, id);\n }\n } catch (e) {\n capture(e);",
"score": 12.658037017666565
},
{
"filename": "src/api.ts",
"retrieved_chunk": " }\n});\nrouter.get('/nft-claimer', async (req, res) => {\n try {\n return res.json({ snapshotFee: await snapshotFee() });\n } catch (e: any) {\n capture(e);\n return rpcError(res, e, '');\n }\n});",
"score": 11.00115981387655
},
{
"filename": "src/sentryTunnel.ts",
"retrieved_chunk": " if (status !== 200) {\n console.debug(await response.text());\n }\n return res.sendStatus(status);\n } catch (e: any) {\n capture(e);\n rpcError(res, e, '');\n }\n});\nexport default router;",
"score": 10.955775482192049
},
{
"filename": "src/lib/nftClaimer/utils.ts",
"retrieved_chunk": " );\n return contract.snapshotFee();\n } catch (e: any) {\n capture(e);\n throw 'Unable to retrieve the snapshotFee';\n }\n}",
"score": 10.468160704387987
},
{
"filename": "src/api.ts",
"retrieved_chunk": " salt,\n spaceTreasury\n })\n );\n } catch (e: any) {\n capture(e);\n return rpcError(res, e, salt);\n }\n});\nrouter.post('/nft-claimer/mint', async (req, res) => {",
"score": 10.264901460117944
}
] | typescript | sleep(15e3); |
import { splitSignature } from '@ethersproject/bytes';
import { fetchProposal, Space } from '../../helpers/snapshot';
import {
validateProposal,
getProposalContract,
signer,
numberizeProposalId,
validateMintInput,
mintingAllowed
} from './utils';
import abi from './spaceCollectionImplementationAbi.json';
import { FormatTypes, Interface } from '@ethersproject/abi';
const MintType = {
Mint: [
{ name: 'proposer', type: 'address' },
{ name: 'recipient', type: 'address' },
{ name: 'proposalId', type: 'uint256' },
{ name: 'salt', type: 'uint256' }
]
};
const NFT_CLAIMER_NETWORK = process.env.NFT_CLAIMER_NETWORK;
export default async function payload(input: {
proposalAuthor: string;
recipient: string;
id: string;
salt: string;
}) {
const params = await validateMintInput(input);
const proposal = await fetchProposal(params.id);
validateProposal(proposal, params.proposalAuthor);
const spaceId = proposal?.space.id as string;
const verifyingContract = await getProposalContract(spaceId);
if (!mintingAllowed(proposal?.space as Space)) {
throw new Error('Space has closed minting');
}
const message = {
proposer: params.proposalAuthor,
recipient: params.recipient,
proposalId: numberizeProposalId(params.id),
salt: BigInt(params.salt)
};
return {
signature: await generateSignature(verifyingContract, spaceId, message),
contractAddress: verifyingContract,
spaceId: proposal?.space.id,
...message,
salt: params.salt,
abi: new | Interface(abi).getFunction('mint').format(FormatTypes.full)
}; |
}
async function generateSignature(
verifyingContract: string,
domain: string,
message: Record<string, string | bigint>
) {
return splitSignature(
await signer._signTypedData(
{
name: domain,
version: '0.1',
chainId: NFT_CLAIMER_NETWORK,
verifyingContract
},
MintType,
message
)
);
}
| src/lib/nftClaimer/mint.ts | snapshot-labs-snapshot-sidekick-800dacf | [
{
"filename": "src/lib/nftClaimer/deploy.ts",
"retrieved_chunk": " const result = {\n initializer,\n salt: params.salt,\n abi: new Interface(spaceFactoryAbi).getFunction('deployProxy').format(FormatTypes.full),\n verifyingContract: VERIFYING_CONTRACT,\n implementation: IMPLEMENTATION_ADDRESS,\n signature: await generateSignature(IMPLEMENTATION_ADDRESS, initializer, params.salt)\n };\n console.debug('Signer', signer.address);\n console.debug('Payload', result);",
"score": 52.53738976481085
},
{
"filename": "src/lib/nftClaimer/deploy.ts",
"retrieved_chunk": " const space = await fetchSpace(params.id);\n await validateSpace(params.spaceOwner, space);\n const initializer = getInitializer({\n spaceOwner: params.spaceOwner,\n spaceId: space?.id as string,\n maxSupply: params.maxSupply,\n mintPrice: params.mintPrice,\n proposerFee: params.proposerFee,\n spaceTreasury: params.spaceTreasury\n });",
"score": 15.071477907254927
},
{
"filename": "src/lib/nftClaimer/utils.ts",
"retrieved_chunk": " }\n}\nexport async function getProposalContract(spaceId: string) {\n const contract = await getSpaceCollection(spaceId);\n if (!contract) {\n throw new Error(`SpaceCollection contract is not found for space ${spaceId}`);\n }\n return contract.id;\n}\nconst client = new ApolloClient({",
"score": 13.894637822882451
},
{
"filename": "src/lib/nftClaimer/deploy.ts",
"retrieved_chunk": " salt: BigInt(salt)\n }\n };\n return splitSignature(await signer._signTypedData(params.domain, params.types, params.value));\n}",
"score": 13.40452377763578
},
{
"filename": "src/lib/nftClaimer/deploy.ts",
"retrieved_chunk": " // the smart contract version\n // NOTE Do not forget to remove the last 4 params in the ABI when copy/pasting\n // from the smart contract\n const initializer = new Interface(spaceCollectionAbi).encodeFunctionData('initialize', params);\n const result = `${INITIALIZE_SELECTOR}${initializer.slice(10)}`;\n console.debug('Initializer params', params);\n return result;\n}\nasync function generateSignature(implementation: string, initializer: string, salt: string) {\n const params = {",
"score": 12.879708855741956
}
] | typescript | Interface(abi).getFunction('mint').format(FormatTypes.full)
}; |
import express from 'express';
import { capture } from './helpers/sentry';
import { rpcError, rpcSuccess, storageEngine } from './helpers/utils';
import getModerationList from './lib/moderationList';
import VotesReport from './lib/votesReport';
import mintPayload from './lib/nftClaimer/mint';
import deployPayload from './lib/nftClaimer/deploy';
import { queue, getProgress } from './lib/queue';
import { snapshotFee } from './lib/nftClaimer/utils';
const router = express.Router();
router.post('/votes/:id', async (req, res) => {
const { id } = req.params;
const votesReport = new VotesReport(id, storageEngine(process.env.VOTE_REPORT_SUBDIR));
try {
const file = await votesReport.getCache();
if (file) {
res.header('Content-Type', 'text/csv');
res.attachment(votesReport.filename);
return res.end(file);
}
try {
await votesReport.isCacheable();
queue(votesReport);
return rpcSuccess(res.status(202), getProgress(id).toString(), id);
} catch (e: any) {
capture(e);
rpcError(res, e, id);
}
} catch (e) {
capture(e);
return rpcError(res, 'INTERNAL_ERROR', id);
}
});
router.get('/moderation', async (req, res) => {
const { list } = req.query;
try {
res.json(await getModerationList(list ? (list as string).split(',') : undefined));
} catch (e) {
capture(e);
return rpcError(res, 'INTERNAL_ERROR', '');
}
});
router.get('/nft-claimer', async (req, res) => {
try {
| return res.json({ snapshotFee: await snapshotFee() }); |
} catch (e: any) {
capture(e);
return rpcError(res, e, '');
}
});
router.post('/nft-claimer/deploy', async (req, res) => {
const { address, id, salt, maxSupply, mintPrice, spaceTreasury, proposerFee } = req.body;
try {
return res.json(
await deployPayload({
spaceOwner: address,
id,
maxSupply,
mintPrice,
proposerFee,
salt,
spaceTreasury
})
);
} catch (e: any) {
capture(e);
return rpcError(res, e, salt);
}
});
router.post('/nft-claimer/mint', async (req, res) => {
const { proposalAuthor, address, id, salt } = req.body;
try {
return res.json(await mintPayload({ proposalAuthor, recipient: address, id, salt }));
} catch (e: any) {
capture(e);
return rpcError(res, e, salt);
}
});
export default router;
| src/api.ts | snapshot-labs-snapshot-sidekick-800dacf | [
{
"filename": "src/webhook.ts",
"retrieved_chunk": " return rpcError(res, 'Invalid Request', id);\n }\n try {\n processVotesReport(id, event);\n return rpcSuccess(res, 'Webhook received', id);\n } catch (e) {\n capture(e);\n return rpcError(res, 'INTERNAL_ERROR', id);\n }\n});",
"score": 38.56027012060595
},
{
"filename": "src/sentryTunnel.ts",
"retrieved_chunk": " if (status !== 200) {\n console.debug(await response.text());\n }\n return res.sendStatus(status);\n } catch (e: any) {\n capture(e);\n rpcError(res, e, '');\n }\n});\nexport default router;",
"score": 33.010358609352394
},
{
"filename": "src/lib/nftClaimer/utils.ts",
"retrieved_chunk": " );\n return contract.snapshotFee();\n } catch (e: any) {\n capture(e);\n throw 'Unable to retrieve the snapshotFee';\n }\n}",
"score": 23.868087967721127
},
{
"filename": "src/helpers/utils.ts",
"retrieved_chunk": " jsonrpc: '2.0',\n result,\n id\n });\n}\nexport function rpcError(res: Response, e: Error | string, id: string | number) {\n const errorMessage = e instanceof Error ? e.message : e;\n const errorCode = ERROR_CODES[errorMessage] ? ERROR_CODES[errorMessage] : -32603;\n res.status(errorCode > 0 ? errorCode : 500).json({\n jsonrpc: '2.0',",
"score": 23.615352177665965
},
{
"filename": "src/index.ts",
"retrieved_chunk": "app.use('/', sentryTunnel);\napp.get('/', (req, res) => {\n const commit = process.env.COMMIT_HASH || '';\n const v = commit ? `${version}#${commit.substring(0, 7)}` : version;\n return res.json({\n name,\n version: v\n });\n});\nfallbackLogger(app);",
"score": 23.414176015138953
}
] | typescript | return res.json({ snapshotFee: await snapshotFee() }); |
import { fetchProposal, fetchVotes, Proposal, Vote } from '../helpers/snapshot';
import type { IStorage } from './storage/types';
import Cache from './cache';
class VotesReport extends Cache {
proposal?: Proposal | null;
constructor(id: string, storage: IStorage) {
super(id, storage);
this.filename = `snapshot-votes-report-${this.id}.csv`;
}
async isCacheable() {
this.proposal = await fetchProposal(this.id);
if (!this.proposal || this.proposal.state !== 'closed') {
return Promise.reject('RECORD_NOT_FOUND');
}
return true;
}
getContent = async () => {
this.isCacheable();
const votes = await this.fetchAllVotes();
let content = '';
console.log(`[votes-report] Generating report for ${this.id}`);
const headers = [
'address',
votes.length === 0 || typeof votes[0].choice === 'number'
? 'choice'
: this.proposal && this.proposal.choices.map((_choice, index) => `choice.${index + 1}`),
'voting_power',
'timestamp',
'author_ipfs_hash',
'reason'
].flat();
content += headers.join(',');
content += `\n${votes.map(vote => this.#formatCsvLine(vote)).join('\n')}`;
console.log(`[votes-report] Report for ${this.id} ready with ${votes.length} items`);
return content;
};
fetchAllVotes = async () => {
let votes: Vote[] = [];
let page = 0;
let createdPivot = 0;
const pageSize = 1000;
let resultsSize = 0;
const maxPage = 5;
do {
let newVotes | = await fetchVotes(this.id, { |
first: pageSize,
skip: page * pageSize,
created_gte: createdPivot,
orderBy: 'created',
orderDirection: 'asc'
});
resultsSize = newVotes.length;
if (page === 0 && createdPivot > 0) {
// Loosely assuming that there will never be more than 1000 duplicates
const existingIpfs = votes.slice(-pageSize).map(vote => vote.ipfs);
newVotes = newVotes.filter(vote => {
return !existingIpfs.includes(vote.ipfs);
});
}
if (page === maxPage) {
page = 0;
createdPivot = newVotes[newVotes.length - 1].created;
} else {
page++;
}
votes = votes.concat(newVotes);
this.generationProgress = Number(
((votes.length / (this.proposal?.votes as number)) * 100).toFixed(2)
);
} while (resultsSize === pageSize);
return votes;
};
toString() {
return `VotesReport#${this.id}`;
}
#formatCsvLine = (vote: Vote) => {
let choices: Vote['choice'][] = [];
if (typeof vote.choice !== 'number' && this.proposal) {
choices = Array.from({ length: this.proposal.choices.length });
for (const [key, value] of Object.entries(vote.choice)) {
choices[parseInt(key) - 1] = value;
}
} else {
choices.push(vote.choice);
}
return [
vote.voter,
...choices,
vote.vp,
vote.created,
vote.ipfs,
`"${vote.reason.replace(/(\r\n|\n|\r)/gm, '')}"`
]
.flat()
.join(',');
};
}
export default VotesReport;
| src/lib/votesReport.ts | snapshot-labs-snapshot-sidekick-800dacf | [
{
"filename": "src/helpers/snapshot.ts",
"retrieved_chunk": "export async function fetchVotes(\n id: string,\n { first = 1000, skip = 0, orderBy = 'created_gte', orderDirection = 'asc', created_gte = 0 } = {}\n) {\n const {\n data: { votes }\n }: { data: { votes: Vote[] } } = await client.query({\n query: VOTES_QUERY,\n variables: {\n id,",
"score": 26.46027548688808
},
{
"filename": "src/lib/moderationList.ts",
"retrieved_chunk": " const list: Partial<MODERATION_LIST> = {};\n const reverseMapping: Record<string, keyof MODERATION_LIST> = {};\n const queryWhereStatement: string[] = [];\n let queryWhereArgs: string[] = [];\n fields.forEach(field => {\n if (FIELDS.has(field)) {\n const args = FIELDS.get(field) as Record<string, string>;\n if (!args.file) {\n list[field] = [];\n reverseMapping[`${args.action}-${args.type}`] = field;",
"score": 18.018085228658666
},
{
"filename": "src/lib/cache.ts",
"retrieved_chunk": " this.generationProgress = 0;\n }\n async getContent(): Promise<string | Buffer> {\n return '';\n }\n getCache() {\n return this.storage.get(this.filename);\n }\n async isCacheable() {\n return true;",
"score": 11.090546261142388
},
{
"filename": "src/lib/nftClaimer/utils.ts",
"retrieved_chunk": " }\n });\n return true;\n}\nexport async function validateProposerFee(fee: number) {\n if (fee < 0 || fee > 100) {\n throw new Error('proposerFee should be between 0 and 100');\n }\n const sFee = await snapshotFee();\n if (sFee + fee > 100) {",
"score": 9.076634364487667
},
{
"filename": "src/helpers/utils.ts",
"retrieved_chunk": " jsonrpc: '2.0',\n result,\n id\n });\n}\nexport function rpcError(res: Response, e: Error | string, id: string | number) {\n const errorMessage = e instanceof Error ? e.message : e;\n const errorCode = ERROR_CODES[errorMessage] ? ERROR_CODES[errorMessage] : -32603;\n res.status(errorCode > 0 ? errorCode : 500).json({\n jsonrpc: '2.0',",
"score": 8.846125507888043
}
] | typescript | = await fetchVotes(this.id, { |
import { fetchProposal, fetchVotes, Proposal, Vote } from '../helpers/snapshot';
import type { IStorage } from './storage/types';
import Cache from './cache';
class VotesReport extends Cache {
proposal?: Proposal | null;
constructor(id: string, storage: IStorage) {
super(id, storage);
this.filename = `snapshot-votes-report-${this.id}.csv`;
}
async isCacheable() {
this.proposal = await fetchProposal(this.id);
if (!this.proposal || this.proposal.state !== 'closed') {
return Promise.reject('RECORD_NOT_FOUND');
}
return true;
}
getContent = async () => {
this.isCacheable();
const votes = await this.fetchAllVotes();
let content = '';
console.log(`[votes-report] Generating report for ${this.id}`);
const headers = [
'address',
votes.length === 0 || typeof votes[0].choice === 'number'
? 'choice'
: this.proposal && this.proposal.choices.map((_choice, index) => `choice.${index + 1}`),
'voting_power',
'timestamp',
'author_ipfs_hash',
'reason'
].flat();
content += headers.join(',');
content += `\n${votes.map(vote => this.#formatCsvLine(vote)).join('\n')}`;
console.log(`[votes-report] Report for ${this.id} ready with ${votes.length} items`);
return content;
};
fetchAllVotes = async () => {
let votes: Vote[] = [];
let page = 0;
let createdPivot = 0;
const pageSize = 1000;
let resultsSize = 0;
const maxPage = 5;
do {
let newVotes = await fetchVotes(this.id, {
first: pageSize,
skip: page * pageSize,
created_gte: createdPivot,
orderBy: 'created',
orderDirection: 'asc'
});
resultsSize = newVotes.length;
if (page === 0 && createdPivot > 0) {
// Loosely assuming that there will never be more than 1000 duplicates
const existingIpfs = votes.slice(-pageSize).map(vote => vote.ipfs);
newVotes = newVotes.filter(vote => {
return !existingIpfs.includes(vote.ipfs);
});
}
if (page === maxPage) {
page = 0;
createdPivot = newVotes[newVotes.length - 1].created;
} else {
page++;
}
votes = votes.concat(newVotes);
this.generationProgress = Number(
| ((votes.length / (this.proposal?.votes as number)) * 100).toFixed(2)
); |
} while (resultsSize === pageSize);
return votes;
};
toString() {
return `VotesReport#${this.id}`;
}
#formatCsvLine = (vote: Vote) => {
let choices: Vote['choice'][] = [];
if (typeof vote.choice !== 'number' && this.proposal) {
choices = Array.from({ length: this.proposal.choices.length });
for (const [key, value] of Object.entries(vote.choice)) {
choices[parseInt(key) - 1] = value;
}
} else {
choices.push(vote.choice);
}
return [
vote.voter,
...choices,
vote.vp,
vote.created,
vote.ipfs,
`"${vote.reason.replace(/(\r\n|\n|\r)/gm, '')}"`
]
.flat()
.join(',');
};
}
export default VotesReport;
| src/lib/votesReport.ts | snapshot-labs-snapshot-sidekick-800dacf | [
{
"filename": "src/lib/cache.ts",
"retrieved_chunk": " }\n async createCache() {\n await this.isCacheable();\n const content = await this.getContent();\n console.log(`[votes-report] File cache ready to be saved`);\n this.storage.set(this.filename, content);\n return content;\n }\n}",
"score": 18.196582012624045
},
{
"filename": "src/helpers/snapshot.ts",
"retrieved_chunk": "export async function fetchVotes(\n id: string,\n { first = 1000, skip = 0, orderBy = 'created_gte', orderDirection = 'asc', created_gte = 0 } = {}\n) {\n const {\n data: { votes }\n }: { data: { votes: Vote[] } } = await client.query({\n query: VOTES_QUERY,\n variables: {\n id,",
"score": 17.462547062125363
},
{
"filename": "src/helpers/snapshot.ts",
"retrieved_chunk": "});\nconst PROPOSAL_QUERY = gql`\n query Proposal($id: String) {\n proposal(id: $id) {\n id\n state\n choices\n votes\n author\n space {",
"score": 16.099467726299494
},
{
"filename": "src/lib/moderationList.ts",
"retrieved_chunk": " queryWhereStatement.push(`(action = ? AND type = ?)`);\n queryWhereArgs = queryWhereArgs.concat([args.action, args.type]);\n } else {\n list[field] = readFile(args.file);\n }\n }\n });\n if (queryWhereStatement.length > 0) {\n const dbResults = await db.queryAsync(\n `SELECT * FROM moderation WHERE ${queryWhereStatement.join(' OR ')}`,",
"score": 15.277787225037804
},
{
"filename": "src/helpers/snapshot.ts",
"retrieved_chunk": " $skip: Int\n $orderBy: String\n $orderDirection: OrderDirection\n $created_gte: Int\n ) {\n votes(\n first: $first\n skip: $skip\n where: { proposal: $id, created_gte: $created_gte }\n orderBy: $orderBy",
"score": 14.962805586566258
}
] | typescript | ((votes.length / (this.proposal?.votes as number)) * 100).toFixed(2)
); |
import { getAddress } from '@ethersproject/address';
import { splitSignature } from '@ethersproject/bytes';
import { FormatTypes, Interface } from '@ethersproject/abi';
import { fetchSpace } from '../../helpers/snapshot';
import { signer, validateDeployInput, validateSpace } from './utils';
import spaceCollectionAbi from './spaceCollectionImplementationAbi.json';
import spaceFactoryAbi from './spaceFactoryAbi.json';
const DeployType = {
Deploy: [
{ name: 'implementation', type: 'address' },
{ name: 'initializer', type: 'bytes' },
{ name: 'salt', type: 'uint256' }
]
};
const VERIFYING_CONTRACT = getAddress(process.env.NFT_CLAIMER_DEPLOY_VERIFYING_CONTRACT as string);
const IMPLEMENTATION_ADDRESS = getAddress(
process.env.NFT_CLAIMER_DEPLOY_IMPLEMENTATION_ADDRESS as string
);
const NFT_CLAIMER_NETWORK = process.env.NFT_CLAIMER_NETWORK;
const INITIALIZE_SELECTOR = process.env.NFT_CLAIMER_DEPLOY_INITIALIZE_SELECTOR;
export default async function payload(input: {
spaceOwner: string;
id: string;
maxSupply: string;
mintPrice: string;
proposerFee: string;
salt: string;
spaceTreasury: string;
}) {
const params = await validateDeployInput(input);
const space = await fetchSpace(params.id);
await validateSpace(params.spaceOwner, space);
const initializer = getInitializer({
spaceOwner: params.spaceOwner,
spaceId: space?.id as string,
maxSupply: params.maxSupply,
mintPrice: params.mintPrice,
proposerFee: params.proposerFee,
spaceTreasury: params.spaceTreasury
});
const result = {
initializer,
salt: params.salt,
abi: new Interface(spaceFactoryAbi).getFunction('deployProxy').format(FormatTypes.full),
verifyingContract: VERIFYING_CONTRACT,
implementation: IMPLEMENTATION_ADDRESS,
signature: await generateSignature(IMPLEMENTATION_ADDRESS, initializer, params.salt)
};
console.debug('Signer', signer.address);
console.debug('Payload', result);
return result;
}
function getInitializer(args: {
spaceId: string;
maxSupply: number;
mintPrice: string;
proposerFee: number;
spaceTreasury: string;
spaceOwner: string;
}) {
const params = [
args.spaceId,
'0.1',
args.maxSupply,
BigInt(args.mintPrice),
args.proposerFee,
getAddress(args.spaceTreasury),
getAddress(args.spaceOwner)
];
// This encodeFunctionData should ignore the last 4 params compared to
// the smart contract version
// NOTE Do not forget to remove the last 4 params in the ABI when copy/pasting
// from the smart contract
const initializer = new Interface(spaceCollectionAbi).encodeFunctionData('initialize', params);
const result = `${INITIALIZE_SELECTOR}${initializer.slice(10)}`;
console.debug('Initializer params', params);
return result;
}
async function generateSignature(implementation: string, initializer: string, salt: string) {
const params = {
domain: {
name: 'SpaceCollectionFactory',
version: '0.1',
chainId: NFT_CLAIMER_NETWORK,
verifyingContract: VERIFYING_CONTRACT
},
types: DeployType,
value: {
implementation,
initializer,
salt: BigInt(salt)
}
};
return splitSignature | (await signer._signTypedData(params.domain, params.types, params.value)); |
}
| src/lib/nftClaimer/deploy.ts | snapshot-labs-snapshot-sidekick-800dacf | [
{
"filename": "src/lib/nftClaimer/utils.ts",
"retrieved_chunk": " salt: params.salt\n });\n await validateProposerFee(parseInt(params.proposerFee));\n return {\n spaceOwner: getAddress(params.spaceOwner),\n spaceTreasury: getAddress(params.spaceTreasury),\n proposerFee: parseInt(params.proposerFee),\n maxSupply: parseInt(params.maxSupply),\n mintPrice: parseInt(params.mintPrice),\n ...params",
"score": 23.271863431851845
},
{
"filename": "src/lib/nftClaimer/mint.ts",
"retrieved_chunk": " const spaceId = proposal?.space.id as string;\n const verifyingContract = await getProposalContract(spaceId);\n if (!mintingAllowed(proposal?.space as Space)) {\n throw new Error('Space has closed minting');\n }\n const message = {\n proposer: params.proposalAuthor,\n recipient: params.recipient,\n proposalId: numberizeProposalId(params.id),\n salt: BigInt(params.salt)",
"score": 22.991409501835978
},
{
"filename": "src/lib/nftClaimer/utils.ts",
"retrieved_chunk": " };\n}\nexport async function validateMintInput(params: any) {\n validateAddresses({ proposalAuthor: params.proposalAuthor, recipient: params.recipient });\n validateNumbers({\n salt: params.salt\n });\n return {\n proposalAuthor: getAddress(params.proposalAuthor),\n recipient: getAddress(params.recipient),",
"score": 22.118656384615463
},
{
"filename": "src/lib/nftClaimer/mint.ts",
"retrieved_chunk": "async function generateSignature(\n verifyingContract: string,\n domain: string,\n message: Record<string, string | bigint>\n) {\n return splitSignature(\n await signer._signTypedData(\n {\n name: domain,\n version: '0.1',",
"score": 20.82037163274014
},
{
"filename": "src/lib/nftClaimer/mint.ts",
"retrieved_chunk": "const NFT_CLAIMER_NETWORK = process.env.NFT_CLAIMER_NETWORK;\nexport default async function payload(input: {\n proposalAuthor: string;\n recipient: string;\n id: string;\n salt: string;\n}) {\n const params = await validateMintInput(input);\n const proposal = await fetchProposal(params.id);\n validateProposal(proposal, params.proposalAuthor);",
"score": 17.680780046359974
}
] | typescript | (await signer._signTypedData(params.domain, params.types, params.value)); |
import { gql, ApolloClient, InMemoryCache, HttpLink } from '@apollo/client/core';
import fetch from 'cross-fetch';
import snapshot from '@snapshot-labs/snapshot.js';
import { CID } from 'multiformats/cid';
import { Wallet } from '@ethersproject/wallet';
import { Contract } from '@ethersproject/contracts';
import { getAddress, isAddress } from '@ethersproject/address';
import { BigNumber } from '@ethersproject/bignumber';
import { capture } from '../../helpers/sentry';
import type { Proposal, Space } from '../../helpers/snapshot';
const requiredEnvKeys = [
'NFT_CLAIMER_PRIVATE_KEY',
'NFT_CLAIMER_NETWORK',
'NFT_CLAIMER_DEPLOY_VERIFYING_CONTRACT',
'NFT_CLAIMER_DEPLOY_IMPLEMENTATION_ADDRESS',
'NFT_CLAIMER_DEPLOY_INITIALIZE_SELECTOR',
'NFT_CLAIMER_SUBGRAPH_URL'
];
const HUB_NETWORK = process.env.HUB_URL === 'https://hub.snapshot.org' ? '1' : '5';
const DEPLOY_CONTRACT = getAddress(process.env.NFT_CLAIMER_DEPLOY_VERIFYING_CONTRACT as string);
const NFT_CLAIMER_NETWORK = parseInt(process.env.NFT_CLAIMER_NETWORK as string);
const missingEnvKeys: string[] = [];
requiredEnvKeys.forEach(key => {
if (!process.env[key]) {
missingEnvKeys.push(key);
}
});
if (missingEnvKeys.length > 0) {
throw new Error(
`NFT Claimer not configured properly, missing env keys: ${missingEnvKeys.join(', ')}`
);
}
export const signer = new Wallet(process.env.NFT_CLAIMER_PRIVATE_KEY as string);
export async function mintingAllowed(space: Space) {
return (await getSpaceCollection(space.id)).enabled;
}
export async function validateSpace(address: string, space: Space | null) {
if (!space) {
throw new Error('RECORD_NOT_FOUND');
}
if (NFT_CLAIMER_NETWORK !== 5 && !(await isSpaceOwner(space.id, address))) {
throw new Error('Address is not the space owner');
}
const contract = await getSpaceCollection(space.id);
if (contract) {
throw new Error(`SpaceCollection contract already exist (${contract.id})`);
}
}
async function isSpaceOwner(spaceId: string, address: string) {
return (await snapshot.utils.getSpaceController(spaceId, HUB_NETWORK)) === getAddress(address);
}
export function validateProposal(proposal: Proposal | null, proposer: string) {
if (!proposal) {
throw new Error('RECORD_NOT_FOUND');
}
| if (getAddress(proposer) !== getAddress(proposal.author)) { |
throw new Error('Proposal author is not matching');
}
if (!mintingAllowed(proposal.space)) {
throw new Error('Space has not allowed minting');
}
}
export async function getProposalContract(spaceId: string) {
const contract = await getSpaceCollection(spaceId);
if (!contract) {
throw new Error(`SpaceCollection contract is not found for space ${spaceId}`);
}
return contract.id;
}
const client = new ApolloClient({
link: new HttpLink({ uri: process.env.NFT_CLAIMER_SUBGRAPH_URL, fetch }),
cache: new InMemoryCache({
addTypename: false
}),
defaultOptions: {
query: {
fetchPolicy: 'no-cache'
}
}
});
const SPACE_COLLECTION_QUERY = gql`
query SpaceCollections($spaceId: String) {
spaceCollections(where: { spaceId: $spaceId }, first: 1) {
id
enabled
}
}
`;
type SpaceCollection = {
id: string;
enabled: boolean;
};
export async function getSpaceCollection(spaceId: string) {
const {
data: { spaceCollections }
}: { data: { spaceCollections: SpaceCollection[] } } = await client.query({
query: SPACE_COLLECTION_QUERY,
variables: {
spaceId
}
});
return spaceCollections[0];
}
export function numberizeProposalId(id: string) {
return BigNumber.from(id.startsWith('0x') ? id : CID.parse(id).bytes).toString();
}
export function validateAddresses(addresses: Record<string, string>) {
Object.entries(addresses).forEach(([key, value]) => {
if (!isAddress(value)) {
throw new Error(`Value for ${key} is not a valid address (${value})`);
}
});
return true;
}
function validateNumbers(numbers: Record<string, string>) {
Object.entries(numbers).forEach(([key, value]) => {
try {
BigNumber.from(value).toString();
} catch (e: any) {
throw new Error(`Value for ${key} is not a valid number (${value})`);
}
});
return true;
}
export async function validateProposerFee(fee: number) {
if (fee < 0 || fee > 100) {
throw new Error('proposerFee should be between 0 and 100');
}
const sFee = await snapshotFee();
if (sFee + fee > 100) {
throw new Error(`proposerFee should not be greater than ${100 - sFee}`);
}
return true;
}
export async function validateDeployInput(params: any) {
validateAddresses({ spaceOwner: params.spaceOwner, spaceTreasury: params.spaceTreasury });
validateNumbers({
maxSupply: params.maxSupply,
proposerFee: params.proposerFee,
mintPrice: params.mintPrice,
salt: params.salt
});
await validateProposerFee(parseInt(params.proposerFee));
return {
spaceOwner: getAddress(params.spaceOwner),
spaceTreasury: getAddress(params.spaceTreasury),
proposerFee: parseInt(params.proposerFee),
maxSupply: parseInt(params.maxSupply),
mintPrice: parseInt(params.mintPrice),
...params
};
}
export async function validateMintInput(params: any) {
validateAddresses({ proposalAuthor: params.proposalAuthor, recipient: params.recipient });
validateNumbers({
salt: params.salt
});
return {
proposalAuthor: getAddress(params.proposalAuthor),
recipient: getAddress(params.recipient),
...params
};
}
export async function snapshotFee(): Promise<number> {
try {
const provider = snapshot.utils.getProvider(NFT_CLAIMER_NETWORK);
const contract = new Contract(
DEPLOY_CONTRACT,
['function snapshotFee() public view returns (uint8)'],
provider
);
return contract.snapshotFee();
} catch (e: any) {
capture(e);
throw 'Unable to retrieve the snapshotFee';
}
}
| src/lib/nftClaimer/utils.ts | snapshot-labs-snapshot-sidekick-800dacf | [
{
"filename": "src/lib/nftClaimer/mint.ts",
"retrieved_chunk": " const spaceId = proposal?.space.id as string;\n const verifyingContract = await getProposalContract(spaceId);\n if (!mintingAllowed(proposal?.space as Space)) {\n throw new Error('Space has closed minting');\n }\n const message = {\n proposer: params.proposalAuthor,\n recipient: params.recipient,\n proposalId: numberizeProposalId(params.id),\n salt: BigInt(params.salt)",
"score": 30.23112674476678
},
{
"filename": "src/lib/nftClaimer/deploy.ts",
"retrieved_chunk": " const params = [\n args.spaceId,\n '0.1',\n args.maxSupply,\n BigInt(args.mintPrice),\n args.proposerFee,\n getAddress(args.spaceTreasury),\n getAddress(args.spaceOwner)\n ];\n // This encodeFunctionData should ignore the last 4 params compared to",
"score": 20.073641514335726
},
{
"filename": "src/helpers/snapshot.ts",
"retrieved_chunk": " const {\n data: { proposal }\n }: { data: { proposal: Proposal | null } } = await client.query({\n query: PROPOSAL_QUERY,\n variables: {\n id\n }\n });\n return proposal;\n}",
"score": 19.660678535191636
},
{
"filename": "src/lib/nftClaimer/deploy.ts",
"retrieved_chunk": "import { getAddress } from '@ethersproject/address';\nimport { splitSignature } from '@ethersproject/bytes';\nimport { FormatTypes, Interface } from '@ethersproject/abi';\nimport { fetchSpace } from '../../helpers/snapshot';\nimport { signer, validateDeployInput, validateSpace } from './utils';\nimport spaceCollectionAbi from './spaceCollectionImplementationAbi.json';\nimport spaceFactoryAbi from './spaceFactoryAbi.json';\nconst DeployType = {\n Deploy: [\n { name: 'implementation', type: 'address' },",
"score": 19.353263375857587
},
{
"filename": "src/lib/nftClaimer/mint.ts",
"retrieved_chunk": "const NFT_CLAIMER_NETWORK = process.env.NFT_CLAIMER_NETWORK;\nexport default async function payload(input: {\n proposalAuthor: string;\n recipient: string;\n id: string;\n salt: string;\n}) {\n const params = await validateMintInput(input);\n const proposal = await fetchProposal(params.id);\n validateProposal(proposal, params.proposalAuthor);",
"score": 18.61420259168217
}
] | typescript | if (getAddress(proposer) !== getAddress(proposal.author)) { |
import { fetchProposal, fetchVotes, Proposal, Vote } from '../helpers/snapshot';
import type { IStorage } from './storage/types';
import Cache from './cache';
class VotesReport extends Cache {
proposal?: Proposal | null;
constructor(id: string, storage: IStorage) {
super(id, storage);
this.filename = `snapshot-votes-report-${this.id}.csv`;
}
async isCacheable() {
this.proposal = await fetchProposal(this.id);
if (!this.proposal || this.proposal.state !== 'closed') {
return Promise.reject('RECORD_NOT_FOUND');
}
return true;
}
getContent = async () => {
this.isCacheable();
const votes = await this.fetchAllVotes();
let content = '';
console.log(`[votes-report] Generating report for ${this.id}`);
const headers = [
'address',
votes.length === 0 || typeof votes[0].choice === 'number'
? 'choice'
: this.proposal && this.proposal.choices.map((_choice, index) => `choice.${index + 1}`),
'voting_power',
'timestamp',
'author_ipfs_hash',
'reason'
].flat();
content += headers.join(',');
content += `\n${votes.map(vote => this.#formatCsvLine(vote)).join('\n')}`;
console.log(`[votes-report] Report for ${this.id} ready with ${votes.length} items`);
return content;
};
fetchAllVotes = async () => {
let votes: Vote[] = [];
let page = 0;
let createdPivot = 0;
const pageSize = 1000;
let resultsSize = 0;
const maxPage = 5;
do {
let newVotes = await fetchVotes(this.id, {
first: pageSize,
skip: page * pageSize,
created_gte: createdPivot,
orderBy: 'created',
orderDirection: 'asc'
});
resultsSize = newVotes.length;
if (page === 0 && createdPivot > 0) {
// Loosely assuming that there will never be more than 1000 duplicates
const existingIpfs = votes.slice(-pageSize).map(vote => vote.ipfs);
| newVotes = newVotes.filter(vote => { |
return !existingIpfs.includes(vote.ipfs);
});
}
if (page === maxPage) {
page = 0;
createdPivot = newVotes[newVotes.length - 1].created;
} else {
page++;
}
votes = votes.concat(newVotes);
this.generationProgress = Number(
((votes.length / (this.proposal?.votes as number)) * 100).toFixed(2)
);
} while (resultsSize === pageSize);
return votes;
};
toString() {
return `VotesReport#${this.id}`;
}
#formatCsvLine = (vote: Vote) => {
let choices: Vote['choice'][] = [];
if (typeof vote.choice !== 'number' && this.proposal) {
choices = Array.from({ length: this.proposal.choices.length });
for (const [key, value] of Object.entries(vote.choice)) {
choices[parseInt(key) - 1] = value;
}
} else {
choices.push(vote.choice);
}
return [
vote.voter,
...choices,
vote.vp,
vote.created,
vote.ipfs,
`"${vote.reason.replace(/(\r\n|\n|\r)/gm, '')}"`
]
.flat()
.join(',');
};
}
export default VotesReport;
| src/lib/votesReport.ts | snapshot-labs-snapshot-sidekick-800dacf | [
{
"filename": "src/helpers/snapshot.ts",
"retrieved_chunk": "export async function fetchVotes(\n id: string,\n { first = 1000, skip = 0, orderBy = 'created_gte', orderDirection = 'asc', created_gte = 0 } = {}\n) {\n const {\n data: { votes }\n }: { data: { votes: Vote[] } } = await client.query({\n query: VOTES_QUERY,\n variables: {\n id,",
"score": 32.386696867949354
},
{
"filename": "src/helpers/snapshot.ts",
"retrieved_chunk": " $skip: Int\n $orderBy: String\n $orderDirection: OrderDirection\n $created_gte: Int\n ) {\n votes(\n first: $first\n skip: $skip\n where: { proposal: $id, created_gte: $created_gte }\n orderBy: $orderBy",
"score": 25.26621616722193
},
{
"filename": "src/helpers/snapshot.ts",
"retrieved_chunk": " orderBy,\n orderDirection,\n first,\n skip,\n created_gte\n }\n });\n return votes;\n}\nexport async function fetchSpace(id: string) {",
"score": 21.367413163348928
},
{
"filename": "src/helpers/snapshot.ts",
"retrieved_chunk": " orderDirection: $orderDirection\n ) {\n ipfs\n voter\n choice\n vp\n reason\n created\n }\n }",
"score": 17.031312203968675
},
{
"filename": "src/helpers/snapshot.ts",
"retrieved_chunk": " if (apiKey && apiKey.length > 0) {\n apiHeaders['x-api-key'] = apiKey;\n }\n return {\n headers: {\n ...headers,\n ...apiHeaders\n }\n };\n});",
"score": 10.045875219526106
}
] | typescript | newVotes = newVotes.filter(vote => { |
import { gql, ApolloClient, InMemoryCache, HttpLink } from '@apollo/client/core';
import fetch from 'cross-fetch';
import snapshot from '@snapshot-labs/snapshot.js';
import { CID } from 'multiformats/cid';
import { Wallet } from '@ethersproject/wallet';
import { Contract } from '@ethersproject/contracts';
import { getAddress, isAddress } from '@ethersproject/address';
import { BigNumber } from '@ethersproject/bignumber';
import { capture } from '../../helpers/sentry';
import type { Proposal, Space } from '../../helpers/snapshot';
const requiredEnvKeys = [
'NFT_CLAIMER_PRIVATE_KEY',
'NFT_CLAIMER_NETWORK',
'NFT_CLAIMER_DEPLOY_VERIFYING_CONTRACT',
'NFT_CLAIMER_DEPLOY_IMPLEMENTATION_ADDRESS',
'NFT_CLAIMER_DEPLOY_INITIALIZE_SELECTOR',
'NFT_CLAIMER_SUBGRAPH_URL'
];
const HUB_NETWORK = process.env.HUB_URL === 'https://hub.snapshot.org' ? '1' : '5';
const DEPLOY_CONTRACT = getAddress(process.env.NFT_CLAIMER_DEPLOY_VERIFYING_CONTRACT as string);
const NFT_CLAIMER_NETWORK = parseInt(process.env.NFT_CLAIMER_NETWORK as string);
const missingEnvKeys: string[] = [];
requiredEnvKeys.forEach(key => {
if (!process.env[key]) {
missingEnvKeys.push(key);
}
});
if (missingEnvKeys.length > 0) {
throw new Error(
`NFT Claimer not configured properly, missing env keys: ${missingEnvKeys.join(', ')}`
);
}
export const signer = new Wallet(process.env.NFT_CLAIMER_PRIVATE_KEY as string);
export async function mintingAllowed(space: Space) {
return (await getSpaceCollection(space.id)).enabled;
}
export async function validateSpace(address: string, space: Space | null) {
if (!space) {
throw new Error('RECORD_NOT_FOUND');
}
if (NFT_CLAIMER_NETWORK !== 5 && !(await isSpaceOwner(space.id, address))) {
throw new Error('Address is not the space owner');
}
const contract = await getSpaceCollection(space.id);
if (contract) {
throw new Error(`SpaceCollection contract already exist (${contract.id})`);
}
}
async function isSpaceOwner(spaceId: string, address: string) {
return (await snapshot.utils.getSpaceController(spaceId, HUB_NETWORK)) === getAddress(address);
}
export function validateProposal(proposal: Proposal | null, proposer: string) {
if (!proposal) {
throw new Error('RECORD_NOT_FOUND');
}
if (getAddress(proposer) !== getAddress(proposal.author)) {
throw new Error('Proposal author is not matching');
}
| if (!mintingAllowed(proposal.space)) { |
throw new Error('Space has not allowed minting');
}
}
export async function getProposalContract(spaceId: string) {
const contract = await getSpaceCollection(spaceId);
if (!contract) {
throw new Error(`SpaceCollection contract is not found for space ${spaceId}`);
}
return contract.id;
}
const client = new ApolloClient({
link: new HttpLink({ uri: process.env.NFT_CLAIMER_SUBGRAPH_URL, fetch }),
cache: new InMemoryCache({
addTypename: false
}),
defaultOptions: {
query: {
fetchPolicy: 'no-cache'
}
}
});
const SPACE_COLLECTION_QUERY = gql`
query SpaceCollections($spaceId: String) {
spaceCollections(where: { spaceId: $spaceId }, first: 1) {
id
enabled
}
}
`;
type SpaceCollection = {
id: string;
enabled: boolean;
};
export async function getSpaceCollection(spaceId: string) {
const {
data: { spaceCollections }
}: { data: { spaceCollections: SpaceCollection[] } } = await client.query({
query: SPACE_COLLECTION_QUERY,
variables: {
spaceId
}
});
return spaceCollections[0];
}
export function numberizeProposalId(id: string) {
return BigNumber.from(id.startsWith('0x') ? id : CID.parse(id).bytes).toString();
}
export function validateAddresses(addresses: Record<string, string>) {
Object.entries(addresses).forEach(([key, value]) => {
if (!isAddress(value)) {
throw new Error(`Value for ${key} is not a valid address (${value})`);
}
});
return true;
}
function validateNumbers(numbers: Record<string, string>) {
Object.entries(numbers).forEach(([key, value]) => {
try {
BigNumber.from(value).toString();
} catch (e: any) {
throw new Error(`Value for ${key} is not a valid number (${value})`);
}
});
return true;
}
export async function validateProposerFee(fee: number) {
if (fee < 0 || fee > 100) {
throw new Error('proposerFee should be between 0 and 100');
}
const sFee = await snapshotFee();
if (sFee + fee > 100) {
throw new Error(`proposerFee should not be greater than ${100 - sFee}`);
}
return true;
}
export async function validateDeployInput(params: any) {
validateAddresses({ spaceOwner: params.spaceOwner, spaceTreasury: params.spaceTreasury });
validateNumbers({
maxSupply: params.maxSupply,
proposerFee: params.proposerFee,
mintPrice: params.mintPrice,
salt: params.salt
});
await validateProposerFee(parseInt(params.proposerFee));
return {
spaceOwner: getAddress(params.spaceOwner),
spaceTreasury: getAddress(params.spaceTreasury),
proposerFee: parseInt(params.proposerFee),
maxSupply: parseInt(params.maxSupply),
mintPrice: parseInt(params.mintPrice),
...params
};
}
export async function validateMintInput(params: any) {
validateAddresses({ proposalAuthor: params.proposalAuthor, recipient: params.recipient });
validateNumbers({
salt: params.salt
});
return {
proposalAuthor: getAddress(params.proposalAuthor),
recipient: getAddress(params.recipient),
...params
};
}
export async function snapshotFee(): Promise<number> {
try {
const provider = snapshot.utils.getProvider(NFT_CLAIMER_NETWORK);
const contract = new Contract(
DEPLOY_CONTRACT,
['function snapshotFee() public view returns (uint8)'],
provider
);
return contract.snapshotFee();
} catch (e: any) {
capture(e);
throw 'Unable to retrieve the snapshotFee';
}
}
| src/lib/nftClaimer/utils.ts | snapshot-labs-snapshot-sidekick-800dacf | [
{
"filename": "src/lib/nftClaimer/mint.ts",
"retrieved_chunk": " const spaceId = proposal?.space.id as string;\n const verifyingContract = await getProposalContract(spaceId);\n if (!mintingAllowed(proposal?.space as Space)) {\n throw new Error('Space has closed minting');\n }\n const message = {\n proposer: params.proposalAuthor,\n recipient: params.recipient,\n proposalId: numberizeProposalId(params.id),\n salt: BigInt(params.salt)",
"score": 41.13520612962702
},
{
"filename": "src/helpers/snapshot.ts",
"retrieved_chunk": "});\nconst PROPOSAL_QUERY = gql`\n query Proposal($id: String) {\n proposal(id: $id) {\n id\n state\n choices\n votes\n author\n space {",
"score": 29.179800931033732
},
{
"filename": "src/helpers/snapshot.ts",
"retrieved_chunk": " const {\n data: { proposal }\n }: { data: { proposal: Proposal | null } } = await client.query({\n query: PROPOSAL_QUERY,\n variables: {\n id\n }\n });\n return proposal;\n}",
"score": 27.01570210715337
},
{
"filename": "src/lib/votesReport.ts",
"retrieved_chunk": " this.proposal = await fetchProposal(this.id);\n if (!this.proposal || this.proposal.state !== 'closed') {\n return Promise.reject('RECORD_NOT_FOUND');\n }\n return true;\n }\n getContent = async () => {\n this.isCacheable();\n const votes = await this.fetchAllVotes();\n let content = '';",
"score": 20.817445218921414
},
{
"filename": "src/lib/votesReport.ts",
"retrieved_chunk": "import { fetchProposal, fetchVotes, Proposal, Vote } from '../helpers/snapshot';\nimport type { IStorage } from './storage/types';\nimport Cache from './cache';\nclass VotesReport extends Cache {\n proposal?: Proposal | null;\n constructor(id: string, storage: IStorage) {\n super(id, storage);\n this.filename = `snapshot-votes-report-${this.id}.csv`;\n }\n async isCacheable() {",
"score": 20.49439998950567
}
] | typescript | if (!mintingAllowed(proposal.space)) { |
import { readFileSync } from 'fs';
import path from 'path';
import db from '../helpers/mysql';
type MODERATION_LIST = Record<string, string[] | JSON>;
const CACHE_PATH = path.resolve(__dirname, `../../${process.env.MODERATION_LIST_PATH || 'data'}`);
const FIELDS = new Map<keyof MODERATION_LIST, Record<string, string>>([
['flaggedLinks', { action: 'flag', type: 'link' }],
['flaggedProposals', { action: 'flag', type: 'proposal' }],
['flaggedSpaces', { action: 'flag', type: 'space' }],
['flaggedIps', { action: 'flag', type: 'ip' }],
['verifiedSpaces', { action: 'verify', type: 'space' }],
['verifiedTokens', { file: 'verifiedTokens.json' }]
]);
export function readFile(filename: string) {
return parseFileContent(
readFileSync(path.join(CACHE_PATH, filename), { encoding: 'utf8' }),
filename.split('.')[1]
);
}
function parseFileContent(content: string, parser: string): MODERATION_LIST[keyof MODERATION_LIST] {
switch (parser) {
case 'txt':
return content.split('\n').filter(value => value !== '');
case 'json':
return JSON.parse(content);
default:
throw new Error('Invalid file type');
}
}
export default async function getModerationList(fields = Array.from(FIELDS.keys())) {
const list: Partial<MODERATION_LIST> = {};
const reverseMapping: Record<string, keyof MODERATION_LIST> = {};
const queryWhereStatement: string[] = [];
let queryWhereArgs: string[] = [];
fields.forEach(field => {
if (FIELDS.has(field)) {
const args = FIELDS.get(field) as Record<string, string>;
if (!args.file) {
list[field] = [];
reverseMapping[`${args.action}-${args.type}`] = field;
queryWhereStatement.push(`(action = ? AND type = ?)`);
queryWhereArgs = queryWhereArgs.concat([args.action, args.type]);
} else {
list[field] = readFile(args.file);
}
}
});
if (queryWhereStatement.length > 0) {
const dbResults = | await db.queryAsync(
`SELECT * FROM moderation WHERE ${queryWhereStatement.join(' OR ')}`,
queryWhereArgs
); |
dbResults.forEach(row => {
(list[reverseMapping[`${row.action}-${row.type}`]] as string[]).push(row.value as string);
});
}
return list;
}
| src/lib/moderationList.ts | snapshot-labs-snapshot-sidekick-800dacf | [
{
"filename": "src/helpers/mysql.ts",
"retrieved_chunk": "interface PromisedPool {\n queryAsync: (query: string, args?: SqlQueryArgs | SqlQueryArgs[]) => Promise<SqlRow[]>;\n endAsync: () => Promise<any>;\n}\nconst config = new ConnectionString(process.env.DATABASE_URL || '');\nbluebird.promisifyAll([Pool, Connection]);\nconst db: PromisedPool = mysql.createPool({\n ...config,\n host: config.hosts?.[0].name,\n port: config.hosts?.[0].port,",
"score": 11.963798346590384
},
{
"filename": "src/api.ts",
"retrieved_chunk": " return rpcError(res, 'INTERNAL_ERROR', id);\n }\n});\nrouter.get('/moderation', async (req, res) => {\n const { list } = req.query;\n try {\n res.json(await getModerationList(list ? (list as string).split(',') : undefined));\n } catch (e) {\n capture(e);\n return rpcError(res, 'INTERNAL_ERROR', '');",
"score": 11.8517694821042
},
{
"filename": "src/lib/nftClaimer/deploy.ts",
"retrieved_chunk": " const params = [\n args.spaceId,\n '0.1',\n args.maxSupply,\n BigInt(args.mintPrice),\n args.proposerFee,\n getAddress(args.spaceTreasury),\n getAddress(args.spaceOwner)\n ];\n // This encodeFunctionData should ignore the last 4 params compared to",
"score": 8.462227096116312
},
{
"filename": "src/lib/votesReport.ts",
"retrieved_chunk": " ].flat();\n content += headers.join(',');\n content += `\\n${votes.map(vote => this.#formatCsvLine(vote)).join('\\n')}`;\n console.log(`[votes-report] Report for ${this.id} ready with ${votes.length} items`);\n return content;\n };\n fetchAllVotes = async () => {\n let votes: Vote[] = [];\n let page = 0;\n let createdPivot = 0;",
"score": 7.674036233450025
},
{
"filename": "src/lib/nftClaimer/utils.ts",
"retrieved_chunk": "const NFT_CLAIMER_NETWORK = parseInt(process.env.NFT_CLAIMER_NETWORK as string);\nconst missingEnvKeys: string[] = [];\nrequiredEnvKeys.forEach(key => {\n if (!process.env[key]) {\n missingEnvKeys.push(key);\n }\n});\nif (missingEnvKeys.length > 0) {\n throw new Error(\n `NFT Claimer not configured properly, missing env keys: ${missingEnvKeys.join(', ')}`",
"score": 7.5120294905008596
}
] | typescript | await db.queryAsync(
`SELECT * FROM moderation WHERE ${queryWhereStatement.join(' OR ')}`,
queryWhereArgs
); |
import { gql, ApolloClient, InMemoryCache, HttpLink } from '@apollo/client/core';
import fetch from 'cross-fetch';
import snapshot from '@snapshot-labs/snapshot.js';
import { CID } from 'multiformats/cid';
import { Wallet } from '@ethersproject/wallet';
import { Contract } from '@ethersproject/contracts';
import { getAddress, isAddress } from '@ethersproject/address';
import { BigNumber } from '@ethersproject/bignumber';
import { capture } from '../../helpers/sentry';
import type { Proposal, Space } from '../../helpers/snapshot';
const requiredEnvKeys = [
'NFT_CLAIMER_PRIVATE_KEY',
'NFT_CLAIMER_NETWORK',
'NFT_CLAIMER_DEPLOY_VERIFYING_CONTRACT',
'NFT_CLAIMER_DEPLOY_IMPLEMENTATION_ADDRESS',
'NFT_CLAIMER_DEPLOY_INITIALIZE_SELECTOR',
'NFT_CLAIMER_SUBGRAPH_URL'
];
const HUB_NETWORK = process.env.HUB_URL === 'https://hub.snapshot.org' ? '1' : '5';
const DEPLOY_CONTRACT = getAddress(process.env.NFT_CLAIMER_DEPLOY_VERIFYING_CONTRACT as string);
const NFT_CLAIMER_NETWORK = parseInt(process.env.NFT_CLAIMER_NETWORK as string);
const missingEnvKeys: string[] = [];
requiredEnvKeys.forEach(key => {
if (!process.env[key]) {
missingEnvKeys.push(key);
}
});
if (missingEnvKeys.length > 0) {
throw new Error(
`NFT Claimer not configured properly, missing env keys: ${missingEnvKeys.join(', ')}`
);
}
export const signer = new Wallet(process.env.NFT_CLAIMER_PRIVATE_KEY as string);
export async function mintingAllowed(space: Space) {
return (await getSpaceCollection(space.id)).enabled;
}
export async function validateSpace(address: string, space: Space | null) {
if (!space) {
throw new Error('RECORD_NOT_FOUND');
}
if (NFT_CLAIMER_NETWORK !== 5 && !(await isSpaceOwner(space.id, address))) {
throw new Error('Address is not the space owner');
}
const contract = await getSpaceCollection(space.id);
if (contract) {
throw new Error(`SpaceCollection contract already exist (${contract.id})`);
}
}
async function isSpaceOwner(spaceId: string, address: string) {
return (await snapshot.utils.getSpaceController(spaceId, HUB_NETWORK)) === getAddress(address);
}
export function validateProposal( | proposal: Proposal | null, proposer: string) { |
if (!proposal) {
throw new Error('RECORD_NOT_FOUND');
}
if (getAddress(proposer) !== getAddress(proposal.author)) {
throw new Error('Proposal author is not matching');
}
if (!mintingAllowed(proposal.space)) {
throw new Error('Space has not allowed minting');
}
}
export async function getProposalContract(spaceId: string) {
const contract = await getSpaceCollection(spaceId);
if (!contract) {
throw new Error(`SpaceCollection contract is not found for space ${spaceId}`);
}
return contract.id;
}
const client = new ApolloClient({
link: new HttpLink({ uri: process.env.NFT_CLAIMER_SUBGRAPH_URL, fetch }),
cache: new InMemoryCache({
addTypename: false
}),
defaultOptions: {
query: {
fetchPolicy: 'no-cache'
}
}
});
const SPACE_COLLECTION_QUERY = gql`
query SpaceCollections($spaceId: String) {
spaceCollections(where: { spaceId: $spaceId }, first: 1) {
id
enabled
}
}
`;
type SpaceCollection = {
id: string;
enabled: boolean;
};
export async function getSpaceCollection(spaceId: string) {
const {
data: { spaceCollections }
}: { data: { spaceCollections: SpaceCollection[] } } = await client.query({
query: SPACE_COLLECTION_QUERY,
variables: {
spaceId
}
});
return spaceCollections[0];
}
export function numberizeProposalId(id: string) {
return BigNumber.from(id.startsWith('0x') ? id : CID.parse(id).bytes).toString();
}
export function validateAddresses(addresses: Record<string, string>) {
Object.entries(addresses).forEach(([key, value]) => {
if (!isAddress(value)) {
throw new Error(`Value for ${key} is not a valid address (${value})`);
}
});
return true;
}
function validateNumbers(numbers: Record<string, string>) {
Object.entries(numbers).forEach(([key, value]) => {
try {
BigNumber.from(value).toString();
} catch (e: any) {
throw new Error(`Value for ${key} is not a valid number (${value})`);
}
});
return true;
}
export async function validateProposerFee(fee: number) {
if (fee < 0 || fee > 100) {
throw new Error('proposerFee should be between 0 and 100');
}
const sFee = await snapshotFee();
if (sFee + fee > 100) {
throw new Error(`proposerFee should not be greater than ${100 - sFee}`);
}
return true;
}
export async function validateDeployInput(params: any) {
validateAddresses({ spaceOwner: params.spaceOwner, spaceTreasury: params.spaceTreasury });
validateNumbers({
maxSupply: params.maxSupply,
proposerFee: params.proposerFee,
mintPrice: params.mintPrice,
salt: params.salt
});
await validateProposerFee(parseInt(params.proposerFee));
return {
spaceOwner: getAddress(params.spaceOwner),
spaceTreasury: getAddress(params.spaceTreasury),
proposerFee: parseInt(params.proposerFee),
maxSupply: parseInt(params.maxSupply),
mintPrice: parseInt(params.mintPrice),
...params
};
}
export async function validateMintInput(params: any) {
validateAddresses({ proposalAuthor: params.proposalAuthor, recipient: params.recipient });
validateNumbers({
salt: params.salt
});
return {
proposalAuthor: getAddress(params.proposalAuthor),
recipient: getAddress(params.recipient),
...params
};
}
export async function snapshotFee(): Promise<number> {
try {
const provider = snapshot.utils.getProvider(NFT_CLAIMER_NETWORK);
const contract = new Contract(
DEPLOY_CONTRACT,
['function snapshotFee() public view returns (uint8)'],
provider
);
return contract.snapshotFee();
} catch (e: any) {
capture(e);
throw 'Unable to retrieve the snapshotFee';
}
}
| src/lib/nftClaimer/utils.ts | snapshot-labs-snapshot-sidekick-800dacf | [
{
"filename": "src/lib/nftClaimer/mint.ts",
"retrieved_chunk": " const spaceId = proposal?.space.id as string;\n const verifyingContract = await getProposalContract(spaceId);\n if (!mintingAllowed(proposal?.space as Space)) {\n throw new Error('Space has closed minting');\n }\n const message = {\n proposer: params.proposalAuthor,\n recipient: params.recipient,\n proposalId: numberizeProposalId(params.id),\n salt: BigInt(params.salt)",
"score": 26.454876300685385
},
{
"filename": "src/lib/nftClaimer/deploy.ts",
"retrieved_chunk": " // the smart contract version\n // NOTE Do not forget to remove the last 4 params in the ABI when copy/pasting\n // from the smart contract\n const initializer = new Interface(spaceCollectionAbi).encodeFunctionData('initialize', params);\n const result = `${INITIALIZE_SELECTOR}${initializer.slice(10)}`;\n console.debug('Initializer params', params);\n return result;\n}\nasync function generateSignature(implementation: string, initializer: string, salt: string) {\n const params = {",
"score": 23.873610021979733
},
{
"filename": "src/lib/nftClaimer/mint.ts",
"retrieved_chunk": " };\n return {\n signature: await generateSignature(verifyingContract, spaceId, message),\n contractAddress: verifyingContract,\n spaceId: proposal?.space.id,\n ...message,\n salt: params.salt,\n abi: new Interface(abi).getFunction('mint').format(FormatTypes.full)\n };\n}",
"score": 17.520851873345013
},
{
"filename": "src/lib/nftClaimer/mint.ts",
"retrieved_chunk": "const NFT_CLAIMER_NETWORK = process.env.NFT_CLAIMER_NETWORK;\nexport default async function payload(input: {\n proposalAuthor: string;\n recipient: string;\n id: string;\n salt: string;\n}) {\n const params = await validateMintInput(input);\n const proposal = await fetchProposal(params.id);\n validateProposal(proposal, params.proposalAuthor);",
"score": 16.357401951674376
},
{
"filename": "src/helpers/snapshot.ts",
"retrieved_chunk": " const {\n data: { proposal }\n }: { data: { proposal: Proposal | null } } = await client.query({\n query: PROPOSAL_QUERY,\n variables: {\n id\n }\n });\n return proposal;\n}",
"score": 15.250369054780224
}
] | typescript | proposal: Proposal | null, proposer: string) { |
import express from 'express';
import { capture } from './helpers/sentry';
import { rpcError, rpcSuccess, storageEngine } from './helpers/utils';
import getModerationList from './lib/moderationList';
import VotesReport from './lib/votesReport';
import mintPayload from './lib/nftClaimer/mint';
import deployPayload from './lib/nftClaimer/deploy';
import { queue, getProgress } from './lib/queue';
import { snapshotFee } from './lib/nftClaimer/utils';
const router = express.Router();
router.post('/votes/:id', async (req, res) => {
const { id } = req.params;
const votesReport = new VotesReport(id, storageEngine(process.env.VOTE_REPORT_SUBDIR));
try {
const file = await votesReport.getCache();
if (file) {
res.header('Content-Type', 'text/csv');
res.attachment(votesReport.filename);
return res.end(file);
}
try {
await votesReport.isCacheable();
queue(votesReport);
return rpcSuccess(res.status(202), getProgress(id).toString(), id);
} catch (e: any) {
capture(e);
rpcError(res, e, id);
}
} catch (e) {
capture(e);
return rpcError(res, 'INTERNAL_ERROR', id);
}
});
router.get('/moderation', async (req, res) => {
const { list } = req.query;
try {
res.json(await getModerationList(list ? (list as string).split(',') : undefined));
} catch (e) {
capture(e);
return rpcError(res, 'INTERNAL_ERROR', '');
}
});
router.get('/nft-claimer', async (req, res) => {
try {
return res.json({ snapshotFee: await snapshotFee() });
} catch (e: any) {
capture(e);
return rpcError(res, e, '');
}
});
router.post('/nft-claimer/deploy', async (req, res) => {
const { address, id, salt, maxSupply, mintPrice, spaceTreasury, proposerFee } = req.body;
try {
return res.json(
await deployPayload({
spaceOwner: address,
id,
maxSupply,
mintPrice,
proposerFee,
salt,
spaceTreasury
})
);
} catch (e: any) {
capture(e);
return rpcError(res, e, salt);
}
});
router.post('/nft-claimer/mint', async (req, res) => {
const { proposalAuthor, address, id, salt } = req.body;
try {
return res.json( | await mintPayload({ proposalAuthor, recipient: address, id, salt })); |
} catch (e: any) {
capture(e);
return rpcError(res, e, salt);
}
});
export default router;
| src/api.ts | snapshot-labs-snapshot-sidekick-800dacf | [
{
"filename": "src/sentryTunnel.ts",
"retrieved_chunk": " if (status !== 200) {\n console.debug(await response.text());\n }\n return res.sendStatus(status);\n } catch (e: any) {\n capture(e);\n rpcError(res, e, '');\n }\n});\nexport default router;",
"score": 34.43578332944277
},
{
"filename": "src/webhook.ts",
"retrieved_chunk": " return rpcError(res, 'Invalid Request', id);\n }\n try {\n processVotesReport(id, event);\n return rpcSuccess(res, 'Webhook received', id);\n } catch (e) {\n capture(e);\n return rpcError(res, 'INTERNAL_ERROR', id);\n }\n});",
"score": 32.98067608124836
},
{
"filename": "src/lib/nftClaimer/utils.ts",
"retrieved_chunk": " };\n}\nexport async function validateMintInput(params: any) {\n validateAddresses({ proposalAuthor: params.proposalAuthor, recipient: params.recipient });\n validateNumbers({\n salt: params.salt\n });\n return {\n proposalAuthor: getAddress(params.proposalAuthor),\n recipient: getAddress(params.recipient),",
"score": 32.42907292224482
},
{
"filename": "src/webhook.ts",
"retrieved_chunk": "}\nrouter.post('/webhook', (req, res) => {\n const body = req.body || {};\n const event = body.event?.toString() ?? '';\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n const { type, id } = body.id?.toString().split('/');\n if (req.headers['authentication'] !== `${process.env.WEBHOOK_AUTH_TOKEN ?? ''}`) {\n return rpcError(res, 'UNAUTHORIZED', id);\n }\n if (!event || !id) {",
"score": 32.079435806432215
},
{
"filename": "src/helpers/sentry.ts",
"retrieved_chunk": " return;\n }\n app.use(Sentry.Handlers.errorHandler());\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n app.use(function onError(err: any, req: any, res: any, _: any) {\n res.statusCode = 500;\n res.end(`${res.sentry}\\n`);\n });\n}\nexport function capture(e: any) {",
"score": 27.215890743158482
}
] | typescript | await mintPayload({ proposalAuthor, recipient: address, id, salt })); |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.