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 { CfnResource, Stack } from "aws-cdk-lib"; import { Baselime as Config } from "../config"; import { QueryProps, Filter, DeploymentQueryParameters } from "../types/query"; import { AlertProps } from "../types/alert"; import { Alert } from './alert'; import { getServiceName } from '../utils/service-name'; function buildCalculation(cal: { alias?: string; operation: string; key?: string }) { const short = buildShortCalculation(cal); return `${short}${cal.alias ? ` as ${cal.alias}` : ""}`; } function hasDuplicates<T>(array: T[]) { return (new Set(array)).size !== array.length; } function buildShortCalculation(cal: { alias?: string; operation: string; key?: string }) { if (cal.operation === "COUNT") { return cal.operation; } return `${cal.operation}(${cal.key})`; } function getCalculationAlias(cal: { alias?: string; operation: string; key?: string }) { return cal.alias ? cal.alias : buildShortCalculation(cal); } export function stringifyFilter(filter: Filter): string { const { key, operation, value } = filter; if (!operation) { return `${key} = ${value}`; } if (["EXISTS", "DOES_NOT_EXIST"].includes(operation)) { return `${key} ${operation}`; } if (["IN", "NOT_IN"].some(o => o === operation)) { return `${key} ${operation} (${value})`; } return `${key} ${operation} ${value}`; } /** * */ export class Query<TKey extends string> extends CfnResource { id: string; props: QueryProps<TKey> constructor(id: string, props: QueryProps<TKey>) { const stack = Stack.of(Config.getConstruct()); const calcs = props.parameters.calculations; const orderByOptions = calcs?.map(cal => getCalculationAlias(cal)); if (calcs?.length && hasDuplicates(calcs.filter(c => c.alias).map(c => c.alias))) { throw Error("Aliases must me unique across all calculations / visualisations.") } if (props.parameters.orderBy && !orderByOptions?.includes(props.parameters.orderBy.value)) { throw Error("The orderBy must be present in the calculations / visualisations.") } const disableStackFilter = props.disableStackFilter || Config.getDisableStackFilter(); if (!disableStackFilter) { props.parameters.filters?.push({ operation: "=", key: "$baselime.stackId", value: stack.stackName }) } const Parameters: DeploymentQueryParameters = { ...props.parameters, datasets: props.parameters.datasets || ['lambda-logs'], calculations: props.parameters.calculations ? props.parameters.calculations.map(buildCalculation) : [], filters: props.parameters.filters?.map(stringifyFilter),
groupBys: props.parameters.groupBys?.map(groupBy => {
return { ...groupBy, type: groupBy?.type || "string" } }), filterCombination: props.parameters.filterCombination || "AND", }; super(Config.getConstruct(), id, { type: "Custom::BaselimeQuery", properties: { id, ServiceToken: Config.getServiceToken(), BaselimeApiKey: Config.getApiKey(), Description: props.description, Service: getServiceName(stack), Parameters, Origin: "cdk" }, }); this.id = id; this.props = props; } addAlert(alert: ChangeFields<AlertProps<TKey>, { parameters: Omit<AlertProps<TKey>['parameters'], "query"> }>) { const alertProps = { ...alert, parameters: { ...alert.parameters, query: this } } new Alert(`${this.id}-alert`, alertProps); } addFilters(filters: QueryProps<string>["parameters"]["filters"]) { this.addPropertyOverride('Parameters.filters', [...filters || []]) } }; type ChangeFields<T, R> = Omit<T, keyof R> & R;
src/resources/query.ts
baselime-cdk-82637d8
[ { "filename": "src/resources/alert.ts", "retrieved_chunk": "\t\t\t};\n\t\t}\n\t\tif (\"filters\" in props.parameters.query) {\n\t\t\tconst query = new Query(`${id}-query`, {\n\t\t\t\tparameters: {\n\t\t\t\t\t...props.parameters.query,\n\t\t\t\t\tcalculations: props.parameters.query.calculations || [\n\t\t\t\t\t\t{ operation: \"COUNT\" },\n\t\t\t\t\t],\n\t\t\t\t},", "score": 0.7642792463302612 }, { "filename": "src/resources/alert.ts", "retrieved_chunk": "\t\tconst defaultWindow = \"1hour\";\n\t\tlet Parameters: DeploymentAlertParameters | undefined = undefined;\n\t\tif (\"ref\" in props.parameters.query) {\n\t\t\tParameters = {\n\t\t\t\t...props.parameters,\n\t\t\t\tthreshold: `${props.parameters.threshold?.operation || \">\"} ${props.parameters.threshold?.value\n\t\t\t\t\t}`,\n\t\t\t\tquery: props.parameters.query.ref,\n\t\t\t\tfrequency: props.parameters.frequency || defaultFrequency,\n\t\t\t\twindow: props.parameters.window || defaultWindow,", "score": 0.7577710747718811 }, { "filename": "src/resources/alert.ts", "retrieved_chunk": "\t\t\t});\n\t\t\tParameters = {\n\t\t\t\t...props.parameters,\n\t\t\t\tthreshold: `${props.parameters.threshold?.operation || \">\"} ${props.parameters.threshold?.value || 0\n\t\t\t\t\t}`,\n\t\t\t\tquery: query.ref,\n\t\t\t\tfrequency: props.parameters.frequency || defaultFrequency,\n\t\t\t\twindow: props.parameters.window || defaultWindow,\n\t\t\t};\n\t\t}", "score": 0.6681969165802002 }, { "filename": "src/resources/dashboard.ts", "retrieved_chunk": "import { CfnResource, Stack } from \"aws-cdk-lib\";\nimport { Baselime as Config } from \"../config\";\nimport { DashboardProps } from \"../types/dashboard\";\nimport { getServiceName } from \"../utils/service-name\";\nexport class Dashboard extends CfnResource {\n\tconstructor(id: string, props: DashboardProps) {\n\t\tconst stack = Stack.of(Config.getConstruct());\n\t\tconst parameters = {\n\t\t\t...props.parameters,\n\t\t\twidgets: props.parameters.widgets.map(el => ({ ...el, query: el.query.ref }))", "score": 0.6619586944580078 }, { "filename": "src/config.ts", "retrieved_chunk": "\t\tconstruct = target;\n\t\tbaselimeSecret = options.apiKey;\n\t\tserviceName = options.serviceName;\n\t\tserviceToken = `arn:aws:lambda:${options.region || process.env.CDK_DEPLOY_REGION || \"eu-west-1\"\n\t\t\t}:${options._account || \"097948374213\"}:function:baselime-orl-cloudformation`;\n\t\tdefaultChannel = options.defaultChannel;\n\t\tdisableStackFilter = options.disableStackFilter;\n\t}\n\texport function getConstruct() {\n\t\treturn construct;", "score": 0.6524303555488586 } ]
typescript
groupBys: props.parameters.groupBys?.map(groupBy => {
import { CfnResource, Stack } from "aws-cdk-lib"; import { Baselime as Config } from "../config"; import { QueryProps, Filter, DeploymentQueryParameters } from "../types/query"; import { AlertProps } from "../types/alert"; import { Alert } from './alert'; import { getServiceName } from '../utils/service-name'; function buildCalculation(cal: { alias?: string; operation: string; key?: string }) { const short = buildShortCalculation(cal); return `${short}${cal.alias ? ` as ${cal.alias}` : ""}`; } function hasDuplicates<T>(array: T[]) { return (new Set(array)).size !== array.length; } function buildShortCalculation(cal: { alias?: string; operation: string; key?: string }) { if (cal.operation === "COUNT") { return cal.operation; } return `${cal.operation}(${cal.key})`; } function getCalculationAlias(cal: { alias?: string; operation: string; key?: string }) { return cal.alias ? cal.alias : buildShortCalculation(cal); } export function stringifyFilter(filter: Filter): string { const { key, operation, value } = filter; if (!operation) { return `${key} = ${value}`; } if (["EXISTS", "DOES_NOT_EXIST"].includes(operation)) { return `${key} ${operation}`; } if (["IN", "NOT_IN"].some(o => o === operation)) { return `${key} ${operation} (${value})`; } return `${key} ${operation} ${value}`; } /** * */ export class Query<TKey extends string> extends CfnResource { id: string;
props: QueryProps<TKey> constructor(id: string, props: QueryProps<TKey>) {
const stack = Stack.of(Config.getConstruct()); const calcs = props.parameters.calculations; const orderByOptions = calcs?.map(cal => getCalculationAlias(cal)); if (calcs?.length && hasDuplicates(calcs.filter(c => c.alias).map(c => c.alias))) { throw Error("Aliases must me unique across all calculations / visualisations.") } if (props.parameters.orderBy && !orderByOptions?.includes(props.parameters.orderBy.value)) { throw Error("The orderBy must be present in the calculations / visualisations.") } const disableStackFilter = props.disableStackFilter || Config.getDisableStackFilter(); if (!disableStackFilter) { props.parameters.filters?.push({ operation: "=", key: "$baselime.stackId", value: stack.stackName }) } const Parameters: DeploymentQueryParameters = { ...props.parameters, datasets: props.parameters.datasets || ['lambda-logs'], calculations: props.parameters.calculations ? props.parameters.calculations.map(buildCalculation) : [], filters: props.parameters.filters?.map(stringifyFilter), groupBys: props.parameters.groupBys?.map(groupBy => { return { ...groupBy, type: groupBy?.type || "string" } }), filterCombination: props.parameters.filterCombination || "AND", }; super(Config.getConstruct(), id, { type: "Custom::BaselimeQuery", properties: { id, ServiceToken: Config.getServiceToken(), BaselimeApiKey: Config.getApiKey(), Description: props.description, Service: getServiceName(stack), Parameters, Origin: "cdk" }, }); this.id = id; this.props = props; } addAlert(alert: ChangeFields<AlertProps<TKey>, { parameters: Omit<AlertProps<TKey>['parameters'], "query"> }>) { const alertProps = { ...alert, parameters: { ...alert.parameters, query: this } } new Alert(`${this.id}-alert`, alertProps); } addFilters(filters: QueryProps<string>["parameters"]["filters"]) { this.addPropertyOverride('Parameters.filters', [...filters || []]) } }; type ChangeFields<T, R> = Omit<T, keyof R> & R;
src/resources/query.ts
baselime-cdk-82637d8
[ { "filename": "src/types/query.ts", "retrieved_chunk": "import { F } from \"ts-toolbelt\";\nexport type QueryProps<TKey extends string> = {\n\tdescription?: string;\n\tparameters: QueryParameters<TKey>\n\tdisableStackFilter?: boolean\n};\nexport type QueryParameters<TKey extends string> = {\n\tdatasets?: Datasets[];\n\tfilterCombination?: \"AND\" | \"OR\";\n\tfilters: Filter[];", "score": 0.7915846705436707 }, { "filename": "src/types/alert.ts", "retrieved_chunk": "import { CfnResource } from \"aws-cdk-lib\";\nimport { QueryOperationString, QueryParameters } from \"./query\";\nexport type AlertProps<TKey extends string> = {\n\tdescription?: string;\n\tenabled?: boolean;\n\tparameters: {\n\t\tquery: CfnResource | QueryParameters<TKey>,\n\t\tthreshold?: {\n\t\t\toperation?: QueryOperationString,\n\t\t\tvalue: string | number", "score": 0.7809557914733887 }, { "filename": "src/resources/alert.ts", "retrieved_chunk": "import { CfnResource, Stack } from \"aws-cdk-lib\";\nimport { Baselime as Config } from \"../config\";\nimport { Query } from \"./query\";\nimport { AlertProps, DeploymentAlertParameters } from \"../types/alert\";\nimport { QueryProps } from \"../types/query\";\nimport { getServiceName } from \"../utils/service-name\";\nexport class Alert<TKey extends string> extends CfnResource {\n\tconstructor(id: string, props: AlertProps<TKey>) {\n\t\tconst stack = Stack.of(Config.getConstruct());\n\t\tconst defaultFrequency = \"1hour\";", "score": 0.7419925928115845 }, { "filename": "src/types/query.ts", "retrieved_chunk": "export type Filter =\n\t| { key: Keys; operation: QueryOperationArray; value: string[] }\n\t| { key: Keys; operation: QueryOperationNull; value?: never }\n\t| {\n\t\tkey: Keys;\n\t\toperation?: QueryOperationString;\n\t\tvalue: string | number | boolean;\n\t};\ntype Keys =\n\t| string", "score": 0.7392103672027588 }, { "filename": "src/config.ts", "retrieved_chunk": "\t * @param {BaselimeConfiguration} options\n\t * @example\n\t * import { Baselime } from '@baselime/cdk'\n\t * import * as cdk from 'aws-cdk-lib'\n\t * import { Construct } from 'constructs'\n\t *\n\t * export class ExamplesStack extends cdk.Stack {\n\t * constructor(scope: Construct, id: string, props?: cdk.StackProps) {\n\t * super(scope, id, props)\n\t *", "score": 0.7178824543952942 } ]
typescript
props: QueryProps<TKey> constructor(id: string, props: QueryProps<TKey>) {
import { CfnResource, Stack } from "aws-cdk-lib"; import { Baselime as Config } from "../config"; import { QueryProps, Filter, DeploymentQueryParameters } from "../types/query"; import { AlertProps } from "../types/alert"; import { Alert } from './alert'; import { getServiceName } from '../utils/service-name'; function buildCalculation(cal: { alias?: string; operation: string; key?: string }) { const short = buildShortCalculation(cal); return `${short}${cal.alias ? ` as ${cal.alias}` : ""}`; } function hasDuplicates<T>(array: T[]) { return (new Set(array)).size !== array.length; } function buildShortCalculation(cal: { alias?: string; operation: string; key?: string }) { if (cal.operation === "COUNT") { return cal.operation; } return `${cal.operation}(${cal.key})`; } function getCalculationAlias(cal: { alias?: string; operation: string; key?: string }) { return cal.alias ? cal.alias : buildShortCalculation(cal); } export function stringifyFilter(filter: Filter): string { const { key, operation, value } = filter; if (!operation) { return `${key} = ${value}`; } if (["EXISTS", "DOES_NOT_EXIST"].includes(operation)) { return `${key} ${operation}`; } if (["IN", "NOT_IN"].some(o => o === operation)) { return `${key} ${operation} (${value})`; } return `${key} ${operation} ${value}`; } /** * */ export class Query<TKey extends string> extends CfnResource { id: string; props: QueryProps<TKey> constructor(id: string, props: QueryProps<TKey>) { const stack = Stack.of(Config.getConstruct()); const calcs = props.parameters.calculations; const orderByOptions = calcs?.map(cal => getCalculationAlias(cal)); if (calcs?.length && hasDuplicates(calcs.filter(c => c.alias).map(c => c.alias))) { throw Error("Aliases must me unique across all calculations / visualisations.") } if (props.parameters.orderBy && !orderByOptions?.includes(props.parameters.orderBy.value)) { throw Error("The orderBy must be present in the calculations / visualisations.") } const disableStackFilter = props.disableStackFilter || Config.getDisableStackFilter(); if (!disableStackFilter) { props.parameters.filters?.push({ operation: "=", key: "$baselime.stackId", value: stack.stackName }) } const Parameters: DeploymentQueryParameters = { ...props.parameters, datasets: props.parameters.datasets || ['lambda-logs'], calculations: props.parameters.calculations ? props.parameters.calculations.map(buildCalculation) : [], filters: props.parameters.filters?.map(stringifyFilter), groupBys: props.parameters.
groupBys?.map(groupBy => {
return { ...groupBy, type: groupBy?.type || "string" } }), filterCombination: props.parameters.filterCombination || "AND", }; super(Config.getConstruct(), id, { type: "Custom::BaselimeQuery", properties: { id, ServiceToken: Config.getServiceToken(), BaselimeApiKey: Config.getApiKey(), Description: props.description, Service: getServiceName(stack), Parameters, Origin: "cdk" }, }); this.id = id; this.props = props; } addAlert(alert: ChangeFields<AlertProps<TKey>, { parameters: Omit<AlertProps<TKey>['parameters'], "query"> }>) { const alertProps = { ...alert, parameters: { ...alert.parameters, query: this } } new Alert(`${this.id}-alert`, alertProps); } addFilters(filters: QueryProps<string>["parameters"]["filters"]) { this.addPropertyOverride('Parameters.filters', [...filters || []]) } }; type ChangeFields<T, R> = Omit<T, keyof R> & R;
src/resources/query.ts
baselime-cdk-82637d8
[ { "filename": "src/resources/alert.ts", "retrieved_chunk": "\t\t\t};\n\t\t}\n\t\tif (\"filters\" in props.parameters.query) {\n\t\t\tconst query = new Query(`${id}-query`, {\n\t\t\t\tparameters: {\n\t\t\t\t\t...props.parameters.query,\n\t\t\t\t\tcalculations: props.parameters.query.calculations || [\n\t\t\t\t\t\t{ operation: \"COUNT\" },\n\t\t\t\t\t],\n\t\t\t\t},", "score": 0.7766956686973572 }, { "filename": "src/resources/alert.ts", "retrieved_chunk": "\t\tconst defaultWindow = \"1hour\";\n\t\tlet Parameters: DeploymentAlertParameters | undefined = undefined;\n\t\tif (\"ref\" in props.parameters.query) {\n\t\t\tParameters = {\n\t\t\t\t...props.parameters,\n\t\t\t\tthreshold: `${props.parameters.threshold?.operation || \">\"} ${props.parameters.threshold?.value\n\t\t\t\t\t}`,\n\t\t\t\tquery: props.parameters.query.ref,\n\t\t\t\tfrequency: props.parameters.frequency || defaultFrequency,\n\t\t\t\twindow: props.parameters.window || defaultWindow,", "score": 0.7564277648925781 }, { "filename": "src/resources/dashboard.ts", "retrieved_chunk": "import { CfnResource, Stack } from \"aws-cdk-lib\";\nimport { Baselime as Config } from \"../config\";\nimport { DashboardProps } from \"../types/dashboard\";\nimport { getServiceName } from \"../utils/service-name\";\nexport class Dashboard extends CfnResource {\n\tconstructor(id: string, props: DashboardProps) {\n\t\tconst stack = Stack.of(Config.getConstruct());\n\t\tconst parameters = {\n\t\t\t...props.parameters,\n\t\t\twidgets: props.parameters.widgets.map(el => ({ ...el, query: el.query.ref }))", "score": 0.6714249849319458 }, { "filename": "src/resources/alert.ts", "retrieved_chunk": "\t\t\t});\n\t\t\tParameters = {\n\t\t\t\t...props.parameters,\n\t\t\t\tthreshold: `${props.parameters.threshold?.operation || \">\"} ${props.parameters.threshold?.value || 0\n\t\t\t\t\t}`,\n\t\t\t\tquery: query.ref,\n\t\t\t\tfrequency: props.parameters.frequency || defaultFrequency,\n\t\t\t\twindow: props.parameters.window || defaultWindow,\n\t\t\t};\n\t\t}", "score": 0.6686147451400757 }, { "filename": "src/types/dashboard.ts", "retrieved_chunk": "import { CfnResource } from \"aws-cdk-lib\";\nexport type DashboardProps = {\n\tdescription?: string;\n\tparameters: DeploymentDashboardParameters;\n};\ninterface DeploymentDashboardParameters {\n\twidgets: Array<{\n\t\tname?: string;\n\t\tdescription?: string;\n\t\tquery: CfnResource;", "score": 0.636215090751648 } ]
typescript
groupBys?.map(groupBy => {
import { CfnResource, Stack } from "aws-cdk-lib"; import { Baselime as Config } from "../config"; import { QueryProps, Filter, DeploymentQueryParameters } from "../types/query"; import { AlertProps } from "../types/alert"; import { Alert } from './alert'; import { getServiceName } from '../utils/service-name'; function buildCalculation(cal: { alias?: string; operation: string; key?: string }) { const short = buildShortCalculation(cal); return `${short}${cal.alias ? ` as ${cal.alias}` : ""}`; } function hasDuplicates<T>(array: T[]) { return (new Set(array)).size !== array.length; } function buildShortCalculation(cal: { alias?: string; operation: string; key?: string }) { if (cal.operation === "COUNT") { return cal.operation; } return `${cal.operation}(${cal.key})`; } function getCalculationAlias(cal: { alias?: string; operation: string; key?: string }) { return cal.alias ? cal.alias : buildShortCalculation(cal); } export function stringifyFilter(filter: Filter): string { const { key, operation, value } = filter; if (!operation) { return `${key} = ${value}`; } if (["EXISTS", "DOES_NOT_EXIST"].includes(operation)) { return `${key} ${operation}`; } if (["IN", "NOT_IN"].some(o => o === operation)) { return `${key} ${operation} (${value})`; } return `${key} ${operation} ${value}`; } /** * */ export class Query<TKey extends string> extends CfnResource { id: string; props: QueryProps<TKey> constructor(id: string, props: QueryProps<TKey>) { const stack = Stack.of(Config.getConstruct()); const calcs = props.parameters.calculations; const orderByOptions = calcs?.map(cal => getCalculationAlias(cal)); if (calcs?.length && hasDuplicates(calcs.filter(c => c.alias).map(c => c.alias))) { throw Error("Aliases must me unique across all calculations / visualisations.") } if (props.parameters.orderBy && !orderByOptions?.includes(props.parameters.orderBy.value)) { throw Error("The orderBy must be present in the calculations / visualisations.") } const disableStackFilter = props.disableStackFilter || Config.getDisableStackFilter(); if (!disableStackFilter) { props.parameters.filters?.push({ operation: "=", key: "$baselime.stackId", value: stack.stackName }) } const Parameters: DeploymentQueryParameters = { ...props.parameters, datasets: props.parameters.datasets || ['lambda-logs'], calculations: props.parameters.calculations ? props.parameters.calculations.map(buildCalculation) : [], filters: props.parameters.filters?.map(stringifyFilter), groupBys: props.parameters.groupBys?.map(groupBy => { return { ...groupBy, type: groupBy?.type || "string" } }), filterCombination: props.parameters.filterCombination || "AND", }; super(Config.getConstruct(), id, { type: "Custom::BaselimeQuery", properties: { id, ServiceToken: Config.getServiceToken(), BaselimeApiKey: Config.getApiKey(), Description: props.description, Service: getServiceName(stack), Parameters, Origin: "cdk" }, }); this.id = id; this.props = props; } addAlert(alert: ChangeFields<AlertProps<TKey>, { parameters: Omit<AlertProps<TKey>['parameters'], "query"> }>) { const alertProps = { ...alert, parameters: { ...alert.parameters, query: this } }
new Alert(`${this.id}-alert`, alertProps);
} addFilters(filters: QueryProps<string>["parameters"]["filters"]) { this.addPropertyOverride('Parameters.filters', [...filters || []]) } }; type ChangeFields<T, R> = Omit<T, keyof R> & R;
src/resources/query.ts
baselime-cdk-82637d8
[ { "filename": "src/resources/alert.ts", "retrieved_chunk": "\t\t\t};\n\t\t}\n\t\tif (\"filters\" in props.parameters.query) {\n\t\t\tconst query = new Query(`${id}-query`, {\n\t\t\t\tparameters: {\n\t\t\t\t\t...props.parameters.query,\n\t\t\t\t\tcalculations: props.parameters.query.calculations || [\n\t\t\t\t\t\t{ operation: \"COUNT\" },\n\t\t\t\t\t],\n\t\t\t\t},", "score": 0.7833746671676636 }, { "filename": "src/resources/alert.ts", "retrieved_chunk": "\t\tconst defaultWindow = \"1hour\";\n\t\tlet Parameters: DeploymentAlertParameters | undefined = undefined;\n\t\tif (\"ref\" in props.parameters.query) {\n\t\t\tParameters = {\n\t\t\t\t...props.parameters,\n\t\t\t\tthreshold: `${props.parameters.threshold?.operation || \">\"} ${props.parameters.threshold?.value\n\t\t\t\t\t}`,\n\t\t\t\tquery: props.parameters.query.ref,\n\t\t\t\tfrequency: props.parameters.frequency || defaultFrequency,\n\t\t\t\twindow: props.parameters.window || defaultWindow,", "score": 0.7590444087982178 }, { "filename": "src/resources/alert.ts", "retrieved_chunk": "\t\t\t});\n\t\t\tParameters = {\n\t\t\t\t...props.parameters,\n\t\t\t\tthreshold: `${props.parameters.threshold?.operation || \">\"} ${props.parameters.threshold?.value || 0\n\t\t\t\t\t}`,\n\t\t\t\tquery: query.ref,\n\t\t\t\tfrequency: props.parameters.frequency || defaultFrequency,\n\t\t\t\twindow: props.parameters.window || defaultWindow,\n\t\t\t};\n\t\t}", "score": 0.6956689953804016 }, { "filename": "src/resources/dashboard.ts", "retrieved_chunk": "import { CfnResource, Stack } from \"aws-cdk-lib\";\nimport { Baselime as Config } from \"../config\";\nimport { DashboardProps } from \"../types/dashboard\";\nimport { getServiceName } from \"../utils/service-name\";\nexport class Dashboard extends CfnResource {\n\tconstructor(id: string, props: DashboardProps) {\n\t\tconst stack = Stack.of(Config.getConstruct());\n\t\tconst parameters = {\n\t\t\t...props.parameters,\n\t\t\twidgets: props.parameters.widgets.map(el => ({ ...el, query: el.query.ref }))", "score": 0.6872575283050537 }, { "filename": "src/resources/alert.ts", "retrieved_chunk": "\t\tif (!Parameters) throw new Error(\"Invalid alert parameters. Declare at least one of filters or ref in the query.\")\n\t\tsuper(Config.getConstruct(), id, {\n\t\t\ttype: \"Custom::BaselimeAlert\",\n\t\t\tproperties: {\n\t\t\t\tid,\n\t\t\t\tServiceToken: Config.getServiceToken(),\n\t\t\t\tBaselimeApiKey: Config.getApiKey(),\n\t\t\t\tenabled: props.enabled,\n\t\t\t\tDescription: props.description,\n\t\t\t\tService: getServiceName(stack),", "score": 0.6541869640350342 } ]
typescript
new Alert(`${this.id}-alert`, alertProps);
import { CfnResource, Stack } from "aws-cdk-lib"; import { Baselime as Config } from "../config"; import { QueryProps, Filter, DeploymentQueryParameters } from "../types/query"; import { AlertProps } from "../types/alert"; import { Alert } from './alert'; import { getServiceName } from '../utils/service-name'; function buildCalculation(cal: { alias?: string; operation: string; key?: string }) { const short = buildShortCalculation(cal); return `${short}${cal.alias ? ` as ${cal.alias}` : ""}`; } function hasDuplicates<T>(array: T[]) { return (new Set(array)).size !== array.length; } function buildShortCalculation(cal: { alias?: string; operation: string; key?: string }) { if (cal.operation === "COUNT") { return cal.operation; } return `${cal.operation}(${cal.key})`; } function getCalculationAlias(cal: { alias?: string; operation: string; key?: string }) { return cal.alias ? cal.alias : buildShortCalculation(cal); } export function stringifyFilter(filter: Filter): string { const { key, operation, value } = filter; if (!operation) { return `${key} = ${value}`; } if (["EXISTS", "DOES_NOT_EXIST"].includes(operation)) { return `${key} ${operation}`; } if (["IN", "NOT_IN"].some(o => o === operation)) { return `${key} ${operation} (${value})`; } return `${key} ${operation} ${value}`; } /** * */ export class Query<TKey extends string> extends CfnResource { id: string; props: QueryProps<TKey>
constructor(id: string, props: QueryProps<TKey>) {
const stack = Stack.of(Config.getConstruct()); const calcs = props.parameters.calculations; const orderByOptions = calcs?.map(cal => getCalculationAlias(cal)); if (calcs?.length && hasDuplicates(calcs.filter(c => c.alias).map(c => c.alias))) { throw Error("Aliases must me unique across all calculations / visualisations.") } if (props.parameters.orderBy && !orderByOptions?.includes(props.parameters.orderBy.value)) { throw Error("The orderBy must be present in the calculations / visualisations.") } const disableStackFilter = props.disableStackFilter || Config.getDisableStackFilter(); if (!disableStackFilter) { props.parameters.filters?.push({ operation: "=", key: "$baselime.stackId", value: stack.stackName }) } const Parameters: DeploymentQueryParameters = { ...props.parameters, datasets: props.parameters.datasets || ['lambda-logs'], calculations: props.parameters.calculations ? props.parameters.calculations.map(buildCalculation) : [], filters: props.parameters.filters?.map(stringifyFilter), groupBys: props.parameters.groupBys?.map(groupBy => { return { ...groupBy, type: groupBy?.type || "string" } }), filterCombination: props.parameters.filterCombination || "AND", }; super(Config.getConstruct(), id, { type: "Custom::BaselimeQuery", properties: { id, ServiceToken: Config.getServiceToken(), BaselimeApiKey: Config.getApiKey(), Description: props.description, Service: getServiceName(stack), Parameters, Origin: "cdk" }, }); this.id = id; this.props = props; } addAlert(alert: ChangeFields<AlertProps<TKey>, { parameters: Omit<AlertProps<TKey>['parameters'], "query"> }>) { const alertProps = { ...alert, parameters: { ...alert.parameters, query: this } } new Alert(`${this.id}-alert`, alertProps); } addFilters(filters: QueryProps<string>["parameters"]["filters"]) { this.addPropertyOverride('Parameters.filters', [...filters || []]) } }; type ChangeFields<T, R> = Omit<T, keyof R> & R;
src/resources/query.ts
baselime-cdk-82637d8
[ { "filename": "src/types/query.ts", "retrieved_chunk": "import { F } from \"ts-toolbelt\";\nexport type QueryProps<TKey extends string> = {\n\tdescription?: string;\n\tparameters: QueryParameters<TKey>\n\tdisableStackFilter?: boolean\n};\nexport type QueryParameters<TKey extends string> = {\n\tdatasets?: Datasets[];\n\tfilterCombination?: \"AND\" | \"OR\";\n\tfilters: Filter[];", "score": 0.7915846705436707 }, { "filename": "src/types/alert.ts", "retrieved_chunk": "import { CfnResource } from \"aws-cdk-lib\";\nimport { QueryOperationString, QueryParameters } from \"./query\";\nexport type AlertProps<TKey extends string> = {\n\tdescription?: string;\n\tenabled?: boolean;\n\tparameters: {\n\t\tquery: CfnResource | QueryParameters<TKey>,\n\t\tthreshold?: {\n\t\t\toperation?: QueryOperationString,\n\t\t\tvalue: string | number", "score": 0.7809557914733887 }, { "filename": "src/resources/alert.ts", "retrieved_chunk": "import { CfnResource, Stack } from \"aws-cdk-lib\";\nimport { Baselime as Config } from \"../config\";\nimport { Query } from \"./query\";\nimport { AlertProps, DeploymentAlertParameters } from \"../types/alert\";\nimport { QueryProps } from \"../types/query\";\nimport { getServiceName } from \"../utils/service-name\";\nexport class Alert<TKey extends string> extends CfnResource {\n\tconstructor(id: string, props: AlertProps<TKey>) {\n\t\tconst stack = Stack.of(Config.getConstruct());\n\t\tconst defaultFrequency = \"1hour\";", "score": 0.7419925928115845 }, { "filename": "src/types/query.ts", "retrieved_chunk": "export type Filter =\n\t| { key: Keys; operation: QueryOperationArray; value: string[] }\n\t| { key: Keys; operation: QueryOperationNull; value?: never }\n\t| {\n\t\tkey: Keys;\n\t\toperation?: QueryOperationString;\n\t\tvalue: string | number | boolean;\n\t};\ntype Keys =\n\t| string", "score": 0.7392103672027588 }, { "filename": "src/config.ts", "retrieved_chunk": "\t * @param {BaselimeConfiguration} options\n\t * @example\n\t * import { Baselime } from '@baselime/cdk'\n\t * import * as cdk from 'aws-cdk-lib'\n\t * import { Construct } from 'constructs'\n\t *\n\t * export class ExamplesStack extends cdk.Stack {\n\t * constructor(scope: Construct, id: string, props?: cdk.StackProps) {\n\t * super(scope, id, props)\n\t *", "score": 0.7178824543952942 } ]
typescript
constructor(id: string, props: QueryProps<TKey>) {
import { CfnResource, Stack } from "aws-cdk-lib"; import { Baselime as Config } from "../config"; import { QueryProps, Filter, DeploymentQueryParameters } from "../types/query"; import { AlertProps } from "../types/alert"; import { Alert } from './alert'; import { getServiceName } from '../utils/service-name'; function buildCalculation(cal: { alias?: string; operation: string; key?: string }) { const short = buildShortCalculation(cal); return `${short}${cal.alias ? ` as ${cal.alias}` : ""}`; } function hasDuplicates<T>(array: T[]) { return (new Set(array)).size !== array.length; } function buildShortCalculation(cal: { alias?: string; operation: string; key?: string }) { if (cal.operation === "COUNT") { return cal.operation; } return `${cal.operation}(${cal.key})`; } function getCalculationAlias(cal: { alias?: string; operation: string; key?: string }) { return cal.alias ? cal.alias : buildShortCalculation(cal); } export function stringifyFilter(filter: Filter): string { const { key, operation, value } = filter; if (!operation) { return `${key} = ${value}`; } if (["EXISTS", "DOES_NOT_EXIST"].includes(operation)) { return `${key} ${operation}`; } if (["IN", "NOT_IN"].some(o => o === operation)) { return `${key} ${operation} (${value})`; } return `${key} ${operation} ${value}`; } /** * */ export class Query<TKey extends string> extends CfnResource { id: string; props:
QueryProps<TKey> constructor(id: string, props: QueryProps<TKey>) {
const stack = Stack.of(Config.getConstruct()); const calcs = props.parameters.calculations; const orderByOptions = calcs?.map(cal => getCalculationAlias(cal)); if (calcs?.length && hasDuplicates(calcs.filter(c => c.alias).map(c => c.alias))) { throw Error("Aliases must me unique across all calculations / visualisations.") } if (props.parameters.orderBy && !orderByOptions?.includes(props.parameters.orderBy.value)) { throw Error("The orderBy must be present in the calculations / visualisations.") } const disableStackFilter = props.disableStackFilter || Config.getDisableStackFilter(); if (!disableStackFilter) { props.parameters.filters?.push({ operation: "=", key: "$baselime.stackId", value: stack.stackName }) } const Parameters: DeploymentQueryParameters = { ...props.parameters, datasets: props.parameters.datasets || ['lambda-logs'], calculations: props.parameters.calculations ? props.parameters.calculations.map(buildCalculation) : [], filters: props.parameters.filters?.map(stringifyFilter), groupBys: props.parameters.groupBys?.map(groupBy => { return { ...groupBy, type: groupBy?.type || "string" } }), filterCombination: props.parameters.filterCombination || "AND", }; super(Config.getConstruct(), id, { type: "Custom::BaselimeQuery", properties: { id, ServiceToken: Config.getServiceToken(), BaselimeApiKey: Config.getApiKey(), Description: props.description, Service: getServiceName(stack), Parameters, Origin: "cdk" }, }); this.id = id; this.props = props; } addAlert(alert: ChangeFields<AlertProps<TKey>, { parameters: Omit<AlertProps<TKey>['parameters'], "query"> }>) { const alertProps = { ...alert, parameters: { ...alert.parameters, query: this } } new Alert(`${this.id}-alert`, alertProps); } addFilters(filters: QueryProps<string>["parameters"]["filters"]) { this.addPropertyOverride('Parameters.filters', [...filters || []]) } }; type ChangeFields<T, R> = Omit<T, keyof R> & R;
src/resources/query.ts
baselime-cdk-82637d8
[ { "filename": "src/types/query.ts", "retrieved_chunk": "import { F } from \"ts-toolbelt\";\nexport type QueryProps<TKey extends string> = {\n\tdescription?: string;\n\tparameters: QueryParameters<TKey>\n\tdisableStackFilter?: boolean\n};\nexport type QueryParameters<TKey extends string> = {\n\tdatasets?: Datasets[];\n\tfilterCombination?: \"AND\" | \"OR\";\n\tfilters: Filter[];", "score": 0.7959356904029846 }, { "filename": "src/types/alert.ts", "retrieved_chunk": "import { CfnResource } from \"aws-cdk-lib\";\nimport { QueryOperationString, QueryParameters } from \"./query\";\nexport type AlertProps<TKey extends string> = {\n\tdescription?: string;\n\tenabled?: boolean;\n\tparameters: {\n\t\tquery: CfnResource | QueryParameters<TKey>,\n\t\tthreshold?: {\n\t\t\toperation?: QueryOperationString,\n\t\t\tvalue: string | number", "score": 0.7885007262229919 }, { "filename": "src/types/query.ts", "retrieved_chunk": "export type Filter =\n\t| { key: Keys; operation: QueryOperationArray; value: string[] }\n\t| { key: Keys; operation: QueryOperationNull; value?: never }\n\t| {\n\t\tkey: Keys;\n\t\toperation?: QueryOperationString;\n\t\tvalue: string | number | boolean;\n\t};\ntype Keys =\n\t| string", "score": 0.7559291124343872 }, { "filename": "src/config.ts", "retrieved_chunk": "\t * @param {BaselimeConfiguration} options\n\t * @example\n\t * import { Baselime } from '@baselime/cdk'\n\t * import * as cdk from 'aws-cdk-lib'\n\t * import { Construct } from 'constructs'\n\t *\n\t * export class ExamplesStack extends cdk.Stack {\n\t * constructor(scope: Construct, id: string, props?: cdk.StackProps) {\n\t * super(scope, id, props)\n\t *", "score": 0.7467608451843262 }, { "filename": "src/resources/alert.ts", "retrieved_chunk": "import { CfnResource, Stack } from \"aws-cdk-lib\";\nimport { Baselime as Config } from \"../config\";\nimport { Query } from \"./query\";\nimport { AlertProps, DeploymentAlertParameters } from \"../types/alert\";\nimport { QueryProps } from \"../types/query\";\nimport { getServiceName } from \"../utils/service-name\";\nexport class Alert<TKey extends string> extends CfnResource {\n\tconstructor(id: string, props: AlertProps<TKey>) {\n\t\tconst stack = Stack.of(Config.getConstruct());\n\t\tconst defaultFrequency = \"1hour\";", "score": 0.7392397522926331 } ]
typescript
QueryProps<TKey> constructor(id: string, props: QueryProps<TKey>) {
import { CfnResource, Stack } from "aws-cdk-lib"; import { Baselime as Config } from "../config"; import { QueryProps, Filter, DeploymentQueryParameters } from "../types/query"; import { AlertProps } from "../types/alert"; import { Alert } from './alert'; import { getServiceName } from '../utils/service-name'; function buildCalculation(cal: { alias?: string; operation: string; key?: string }) { const short = buildShortCalculation(cal); return `${short}${cal.alias ? ` as ${cal.alias}` : ""}`; } function hasDuplicates<T>(array: T[]) { return (new Set(array)).size !== array.length; } function buildShortCalculation(cal: { alias?: string; operation: string; key?: string }) { if (cal.operation === "COUNT") { return cal.operation; } return `${cal.operation}(${cal.key})`; } function getCalculationAlias(cal: { alias?: string; operation: string; key?: string }) { return cal.alias ? cal.alias : buildShortCalculation(cal); } export function stringifyFilter(filter: Filter): string { const { key, operation, value } = filter; if (!operation) { return `${key} = ${value}`; } if (["EXISTS", "DOES_NOT_EXIST"].includes(operation)) { return `${key} ${operation}`; } if (["IN", "NOT_IN"].some(o => o === operation)) { return `${key} ${operation} (${value})`; } return `${key} ${operation} ${value}`; } /** * */ export class Query<TKey extends string> extends CfnResource { id: string; props: QueryProps<TKey> constructor(id: string, props: QueryProps<TKey>) { const stack = Stack.of(Config.getConstruct()); const calcs = props.parameters.calculations; const orderByOptions = calcs?.map(cal => getCalculationAlias(cal)); if (calcs?.length && hasDuplicates(calcs.filter(c => c.alias).map(c => c.alias))) { throw Error("Aliases must me unique across all calculations / visualisations.") } if (props.parameters.orderBy && !orderByOptions?.includes(props.parameters.orderBy.value)) { throw Error("The orderBy must be present in the calculations / visualisations.") } const disableStackFilter = props.disableStackFilter || Config.getDisableStackFilter(); if (!disableStackFilter) { props.parameters.filters?.push({ operation: "=", key: "$baselime.stackId", value: stack.stackName }) } const Parameters: DeploymentQueryParameters = { ...props.parameters, datasets: props.parameters.datasets || ['lambda-logs'], calculations: props.parameters.calculations ? props.parameters.calculations.map(buildCalculation) : [], filters: props.parameters.filters?.map(stringifyFilter), groupBys: props.parameters.groupBys?.map(groupBy => { return { ...groupBy, type: groupBy?.type || "string" } }), filterCombination: props.parameters.filterCombination || "AND", }; super(Config.getConstruct(), id, { type: "Custom::BaselimeQuery", properties: { id, ServiceToken: Config.getServiceToken(), BaselimeApiKey: Config.getApiKey(), Description: props.description, Service: getServiceName(stack), Parameters, Origin: "cdk" }, }); this.id = id; this.props = props; } addAlert
(alert: ChangeFields<AlertProps<TKey>, {
parameters: Omit<AlertProps<TKey>['parameters'], "query"> }>) { const alertProps = { ...alert, parameters: { ...alert.parameters, query: this } } new Alert(`${this.id}-alert`, alertProps); } addFilters(filters: QueryProps<string>["parameters"]["filters"]) { this.addPropertyOverride('Parameters.filters', [...filters || []]) } }; type ChangeFields<T, R> = Omit<T, keyof R> & R;
src/resources/query.ts
baselime-cdk-82637d8
[ { "filename": "src/resources/alert.ts", "retrieved_chunk": "\t\tif (!Parameters) throw new Error(\"Invalid alert parameters. Declare at least one of filters or ref in the query.\")\n\t\tsuper(Config.getConstruct(), id, {\n\t\t\ttype: \"Custom::BaselimeAlert\",\n\t\t\tproperties: {\n\t\t\t\tid,\n\t\t\t\tServiceToken: Config.getServiceToken(),\n\t\t\t\tBaselimeApiKey: Config.getApiKey(),\n\t\t\t\tenabled: props.enabled,\n\t\t\t\tDescription: props.description,\n\t\t\t\tService: getServiceName(stack),", "score": 0.7470953464508057 }, { "filename": "src/resources/alert.ts", "retrieved_chunk": "\t\t\t\tParameters,\n\t\t\t\tChannels: props.channels || Config.getDefaultChannel() && [Config.getDefaultChannel()],\n\t\t\t\tOrigin: \"cdk\",\n\t\t\t},\n\t\t});\n\t}\n}", "score": 0.7268885374069214 }, { "filename": "src/resources/dashboard.ts", "retrieved_chunk": "\t\t}\n\t\tsuper(Config.getConstruct(), id, {\n\t\t\ttype: \"Custom::BaselimeDashboard\",\n\t\t\tproperties: {\n\t\t\t\tid,\n\t\t\t\tServiceToken: Config.getServiceToken(),\n\t\t\t\tBaselimeApiKey: Config.getApiKey(),\n\t\t\t\tDescription: props.description,\n\t\t\t\tService: getServiceName(stack),\n\t\t\t\tParameters: parameters,", "score": 0.718850314617157 }, { "filename": "src/types/dashboard.ts", "retrieved_chunk": "import { CfnResource } from \"aws-cdk-lib\";\nexport type DashboardProps = {\n\tdescription?: string;\n\tparameters: DeploymentDashboardParameters;\n};\ninterface DeploymentDashboardParameters {\n\twidgets: Array<{\n\t\tname?: string;\n\t\tdescription?: string;\n\t\tquery: CfnResource;", "score": 0.6980288028717041 }, { "filename": "src/types/alert.ts", "retrieved_chunk": "import { CfnResource } from \"aws-cdk-lib\";\nimport { QueryOperationString, QueryParameters } from \"./query\";\nexport type AlertProps<TKey extends string> = {\n\tdescription?: string;\n\tenabled?: boolean;\n\tparameters: {\n\t\tquery: CfnResource | QueryParameters<TKey>,\n\t\tthreshold?: {\n\t\t\toperation?: QueryOperationString,\n\t\t\tvalue: string | number", "score": 0.6967551708221436 } ]
typescript
(alert: ChangeFields<AlertProps<TKey>, {
import { CfnResource, Stack } from "aws-cdk-lib"; import { Baselime as Config } from "../config"; import { QueryProps, Filter, DeploymentQueryParameters } from "../types/query"; import { AlertProps } from "../types/alert"; import { Alert } from './alert'; import { getServiceName } from '../utils/service-name'; function buildCalculation(cal: { alias?: string; operation: string; key?: string }) { const short = buildShortCalculation(cal); return `${short}${cal.alias ? ` as ${cal.alias}` : ""}`; } function hasDuplicates<T>(array: T[]) { return (new Set(array)).size !== array.length; } function buildShortCalculation(cal: { alias?: string; operation: string; key?: string }) { if (cal.operation === "COUNT") { return cal.operation; } return `${cal.operation}(${cal.key})`; } function getCalculationAlias(cal: { alias?: string; operation: string; key?: string }) { return cal.alias ? cal.alias : buildShortCalculation(cal); } export function stringifyFilter(filter: Filter): string { const { key, operation, value } = filter; if (!operation) { return `${key} = ${value}`; } if (["EXISTS", "DOES_NOT_EXIST"].includes(operation)) { return `${key} ${operation}`; } if (["IN", "NOT_IN"].some(o => o === operation)) { return `${key} ${operation} (${value})`; } return `${key} ${operation} ${value}`; } /** * */ export class Query<TKey extends string> extends CfnResource { id: string; props: QueryProps<TKey> constructor(id: string, props: QueryProps<TKey>) { const stack = Stack.of(Config.getConstruct()); const calcs = props.parameters.calculations; const orderByOptions = calcs?.map(cal => getCalculationAlias(cal)); if (calcs?.length && hasDuplicates(calcs.filter(c => c.alias).map(c => c.alias))) { throw Error("Aliases must me unique across all calculations / visualisations.") } if (props.parameters.orderBy && !orderByOptions?.includes(props.parameters.orderBy.value)) { throw Error("The orderBy must be present in the calculations / visualisations.") } const disableStackFilter = props.disableStackFilter || Config.getDisableStackFilter(); if (!disableStackFilter) { props.parameters.filters?.push({ operation: "=", key: "$baselime.stackId", value: stack.stackName }) } const Parameters: DeploymentQueryParameters = { ...props.parameters, datasets: props.parameters.datasets || ['lambda-logs'], calculations: props.parameters.calculations ? props.parameters.calculations.map(buildCalculation) : [], filters: props.parameters.filters?.map(stringifyFilter), groupBys: props.parameters.groupBys?.map(groupBy => { return { ...groupBy, type: groupBy?.type || "string" } }), filterCombination: props.parameters.filterCombination || "AND", }; super(Config.getConstruct(), id, { type: "Custom::BaselimeQuery", properties: { id, ServiceToken: Config.getServiceToken(), BaselimeApiKey: Config.getApiKey(), Description: props.description, Service: getServiceName(stack), Parameters, Origin: "cdk" }, }); this.id = id; this.props = props; } addAlert(alert: ChangeFields<AlertProps<TKey>, { parameters: Omit<AlertProps<TKey>['parameters'], "query"> }>) { const alertProps = { ...alert, parameters: { ...alert.parameters, query: this } } new Alert(`${this.id}-alert`, alertProps); } addFilters(filters:
QueryProps<string>["parameters"]["filters"]) {
this.addPropertyOverride('Parameters.filters', [...filters || []]) } }; type ChangeFields<T, R> = Omit<T, keyof R> & R;
src/resources/query.ts
baselime-cdk-82637d8
[ { "filename": "src/resources/alert.ts", "retrieved_chunk": "\t\t\t};\n\t\t}\n\t\tif (\"filters\" in props.parameters.query) {\n\t\t\tconst query = new Query(`${id}-query`, {\n\t\t\t\tparameters: {\n\t\t\t\t\t...props.parameters.query,\n\t\t\t\t\tcalculations: props.parameters.query.calculations || [\n\t\t\t\t\t\t{ operation: \"COUNT\" },\n\t\t\t\t\t],\n\t\t\t\t},", "score": 0.7573410272598267 }, { "filename": "src/resources/alert.ts", "retrieved_chunk": "\t\tconst defaultWindow = \"1hour\";\n\t\tlet Parameters: DeploymentAlertParameters | undefined = undefined;\n\t\tif (\"ref\" in props.parameters.query) {\n\t\t\tParameters = {\n\t\t\t\t...props.parameters,\n\t\t\t\tthreshold: `${props.parameters.threshold?.operation || \">\"} ${props.parameters.threshold?.value\n\t\t\t\t\t}`,\n\t\t\t\tquery: props.parameters.query.ref,\n\t\t\t\tfrequency: props.parameters.frequency || defaultFrequency,\n\t\t\t\twindow: props.parameters.window || defaultWindow,", "score": 0.7534523606300354 }, { "filename": "src/resources/alert.ts", "retrieved_chunk": "\t\t\t});\n\t\t\tParameters = {\n\t\t\t\t...props.parameters,\n\t\t\t\tthreshold: `${props.parameters.threshold?.operation || \">\"} ${props.parameters.threshold?.value || 0\n\t\t\t\t\t}`,\n\t\t\t\tquery: query.ref,\n\t\t\t\tfrequency: props.parameters.frequency || defaultFrequency,\n\t\t\t\twindow: props.parameters.window || defaultWindow,\n\t\t\t};\n\t\t}", "score": 0.737902045249939 }, { "filename": "src/types/dashboard.ts", "retrieved_chunk": "import { CfnResource } from \"aws-cdk-lib\";\nexport type DashboardProps = {\n\tdescription?: string;\n\tparameters: DeploymentDashboardParameters;\n};\ninterface DeploymentDashboardParameters {\n\twidgets: Array<{\n\t\tname?: string;\n\t\tdescription?: string;\n\t\tquery: CfnResource;", "score": 0.6938930749893188 }, { "filename": "src/resources/alert.ts", "retrieved_chunk": "\t\tif (!Parameters) throw new Error(\"Invalid alert parameters. Declare at least one of filters or ref in the query.\")\n\t\tsuper(Config.getConstruct(), id, {\n\t\t\ttype: \"Custom::BaselimeAlert\",\n\t\t\tproperties: {\n\t\t\t\tid,\n\t\t\t\tServiceToken: Config.getServiceToken(),\n\t\t\t\tBaselimeApiKey: Config.getApiKey(),\n\t\t\t\tenabled: props.enabled,\n\t\t\t\tDescription: props.description,\n\t\t\t\tService: getServiceName(stack),", "score": 0.6891227960586548 } ]
typescript
QueryProps<string>["parameters"]["filters"]) {
import { CfnResource, Stack } from "aws-cdk-lib"; import { Baselime as Config } from "../config"; import { QueryProps, Filter, DeploymentQueryParameters } from "../types/query"; import { AlertProps } from "../types/alert"; import { Alert } from './alert'; import { getServiceName } from '../utils/service-name'; function buildCalculation(cal: { alias?: string; operation: string; key?: string }) { const short = buildShortCalculation(cal); return `${short}${cal.alias ? ` as ${cal.alias}` : ""}`; } function hasDuplicates<T>(array: T[]) { return (new Set(array)).size !== array.length; } function buildShortCalculation(cal: { alias?: string; operation: string; key?: string }) { if (cal.operation === "COUNT") { return cal.operation; } return `${cal.operation}(${cal.key})`; } function getCalculationAlias(cal: { alias?: string; operation: string; key?: string }) { return cal.alias ? cal.alias : buildShortCalculation(cal); } export function stringifyFilter(filter: Filter): string { const { key, operation, value } = filter; if (!operation) { return `${key} = ${value}`; } if (["EXISTS", "DOES_NOT_EXIST"].includes(operation)) { return `${key} ${operation}`; } if (["IN", "NOT_IN"].some(o => o === operation)) { return `${key} ${operation} (${value})`; } return `${key} ${operation} ${value}`; } /** * */ export class Query<TKey extends string> extends CfnResource { id: string; props: QueryProps<TKey> constructor(id: string, props: QueryProps<TKey>) { const stack = Stack.of(Config.getConstruct()); const calcs = props.parameters.calculations; const orderByOptions = calcs?.map(cal => getCalculationAlias(cal));
if (calcs?.length && hasDuplicates(calcs.filter(c => c.alias).map(c => c.alias))) {
throw Error("Aliases must me unique across all calculations / visualisations.") } if (props.parameters.orderBy && !orderByOptions?.includes(props.parameters.orderBy.value)) { throw Error("The orderBy must be present in the calculations / visualisations.") } const disableStackFilter = props.disableStackFilter || Config.getDisableStackFilter(); if (!disableStackFilter) { props.parameters.filters?.push({ operation: "=", key: "$baselime.stackId", value: stack.stackName }) } const Parameters: DeploymentQueryParameters = { ...props.parameters, datasets: props.parameters.datasets || ['lambda-logs'], calculations: props.parameters.calculations ? props.parameters.calculations.map(buildCalculation) : [], filters: props.parameters.filters?.map(stringifyFilter), groupBys: props.parameters.groupBys?.map(groupBy => { return { ...groupBy, type: groupBy?.type || "string" } }), filterCombination: props.parameters.filterCombination || "AND", }; super(Config.getConstruct(), id, { type: "Custom::BaselimeQuery", properties: { id, ServiceToken: Config.getServiceToken(), BaselimeApiKey: Config.getApiKey(), Description: props.description, Service: getServiceName(stack), Parameters, Origin: "cdk" }, }); this.id = id; this.props = props; } addAlert(alert: ChangeFields<AlertProps<TKey>, { parameters: Omit<AlertProps<TKey>['parameters'], "query"> }>) { const alertProps = { ...alert, parameters: { ...alert.parameters, query: this } } new Alert(`${this.id}-alert`, alertProps); } addFilters(filters: QueryProps<string>["parameters"]["filters"]) { this.addPropertyOverride('Parameters.filters', [...filters || []]) } }; type ChangeFields<T, R> = Omit<T, keyof R> & R;
src/resources/query.ts
baselime-cdk-82637d8
[ { "filename": "src/resources/dashboard.ts", "retrieved_chunk": "import { CfnResource, Stack } from \"aws-cdk-lib\";\nimport { Baselime as Config } from \"../config\";\nimport { DashboardProps } from \"../types/dashboard\";\nimport { getServiceName } from \"../utils/service-name\";\nexport class Dashboard extends CfnResource {\n\tconstructor(id: string, props: DashboardProps) {\n\t\tconst stack = Stack.of(Config.getConstruct());\n\t\tconst parameters = {\n\t\t\t...props.parameters,\n\t\t\twidgets: props.parameters.widgets.map(el => ({ ...el, query: el.query.ref }))", "score": 0.7306323647499084 }, { "filename": "src/resources/alert.ts", "retrieved_chunk": "\t\t\t};\n\t\t}\n\t\tif (\"filters\" in props.parameters.query) {\n\t\t\tconst query = new Query(`${id}-query`, {\n\t\t\t\tparameters: {\n\t\t\t\t\t...props.parameters.query,\n\t\t\t\t\tcalculations: props.parameters.query.calculations || [\n\t\t\t\t\t\t{ operation: \"COUNT\" },\n\t\t\t\t\t],\n\t\t\t\t},", "score": 0.7181938886642456 }, { "filename": "src/types/query.ts", "retrieved_chunk": "import { F } from \"ts-toolbelt\";\nexport type QueryProps<TKey extends string> = {\n\tdescription?: string;\n\tparameters: QueryParameters<TKey>\n\tdisableStackFilter?: boolean\n};\nexport type QueryParameters<TKey extends string> = {\n\tdatasets?: Datasets[];\n\tfilterCombination?: \"AND\" | \"OR\";\n\tfilters: Filter[];", "score": 0.6925532817840576 }, { "filename": "src/resources/alert.ts", "retrieved_chunk": "import { CfnResource, Stack } from \"aws-cdk-lib\";\nimport { Baselime as Config } from \"../config\";\nimport { Query } from \"./query\";\nimport { AlertProps, DeploymentAlertParameters } from \"../types/alert\";\nimport { QueryProps } from \"../types/query\";\nimport { getServiceName } from \"../utils/service-name\";\nexport class Alert<TKey extends string> extends CfnResource {\n\tconstructor(id: string, props: AlertProps<TKey>) {\n\t\tconst stack = Stack.of(Config.getConstruct());\n\t\tconst defaultFrequency = \"1hour\";", "score": 0.6894464492797852 }, { "filename": "src/types/alert.ts", "retrieved_chunk": "import { CfnResource } from \"aws-cdk-lib\";\nimport { QueryOperationString, QueryParameters } from \"./query\";\nexport type AlertProps<TKey extends string> = {\n\tdescription?: string;\n\tenabled?: boolean;\n\tparameters: {\n\t\tquery: CfnResource | QueryParameters<TKey>,\n\t\tthreshold?: {\n\t\t\toperation?: QueryOperationString,\n\t\t\tvalue: string | number", "score": 0.6738206744194031 } ]
typescript
if (calcs?.length && hasDuplicates(calcs.filter(c => c.alias).map(c => c.alias))) {
import { CfnResource, Stack } from "aws-cdk-lib"; import { Baselime as Config } from "../config"; import { QueryProps, Filter, DeploymentQueryParameters } from "../types/query"; import { AlertProps } from "../types/alert"; import { Alert } from './alert'; import { getServiceName } from '../utils/service-name'; function buildCalculation(cal: { alias?: string; operation: string; key?: string }) { const short = buildShortCalculation(cal); return `${short}${cal.alias ? ` as ${cal.alias}` : ""}`; } function hasDuplicates<T>(array: T[]) { return (new Set(array)).size !== array.length; } function buildShortCalculation(cal: { alias?: string; operation: string; key?: string }) { if (cal.operation === "COUNT") { return cal.operation; } return `${cal.operation}(${cal.key})`; } function getCalculationAlias(cal: { alias?: string; operation: string; key?: string }) { return cal.alias ? cal.alias : buildShortCalculation(cal); } export function stringifyFilter(filter: Filter): string { const { key, operation, value } = filter; if (!operation) { return `${key} = ${value}`; } if (["EXISTS", "DOES_NOT_EXIST"].includes(operation)) { return `${key} ${operation}`; } if (["IN", "NOT_IN"].some(o => o === operation)) { return `${key} ${operation} (${value})`; } return `${key} ${operation} ${value}`; } /** * */ export class Query<TKey extends string> extends CfnResource { id: string; props: QueryProps<TKey> constructor(id: string, props: QueryProps<TKey>) { const stack = Stack.of(Config.getConstruct()); const calcs = props.parameters.calculations; const orderByOptions = calcs?.map(cal => getCalculationAlias(cal)); if (calcs?.length && hasDuplicates(calcs.filter(c => c.alias).map(c => c.alias))) { throw Error("Aliases must me unique across all calculations / visualisations.") } if (props.parameters.orderBy && !orderByOptions?.includes(props.parameters.orderBy.value)) { throw Error("The orderBy must be present in the calculations / visualisations.") } const disableStackFilter = props.disableStackFilter || Config.getDisableStackFilter(); if (!disableStackFilter) { props.parameters.filters?.push({ operation: "=", key: "$baselime.stackId", value: stack.stackName }) } const Parameters: DeploymentQueryParameters = { ...props.parameters, datasets: props.parameters.datasets || ['lambda-logs'], calculations: props.parameters.calculations ? props.parameters.calculations.map(buildCalculation) : [], filters: props.parameters.filters?.map(stringifyFilter), groupBys: props.parameters.groupBys?.map(groupBy => { return { ...groupBy, type: groupBy?.type || "string" } }), filterCombination: props.parameters.filterCombination || "AND", }; super(Config.getConstruct(), id, { type: "Custom::BaselimeQuery", properties: { id, ServiceToken: Config.getServiceToken(), BaselimeApiKey: Config.getApiKey(), Description: props.description, Service: getServiceName(stack), Parameters, Origin: "cdk" }, }); this.id = id; this.props = props; } addAlert(
alert: ChangeFields<AlertProps<TKey>, {
parameters: Omit<AlertProps<TKey>['parameters'], "query"> }>) { const alertProps = { ...alert, parameters: { ...alert.parameters, query: this } } new Alert(`${this.id}-alert`, alertProps); } addFilters(filters: QueryProps<string>["parameters"]["filters"]) { this.addPropertyOverride('Parameters.filters', [...filters || []]) } }; type ChangeFields<T, R> = Omit<T, keyof R> & R;
src/resources/query.ts
baselime-cdk-82637d8
[ { "filename": "src/resources/alert.ts", "retrieved_chunk": "\t\tif (!Parameters) throw new Error(\"Invalid alert parameters. Declare at least one of filters or ref in the query.\")\n\t\tsuper(Config.getConstruct(), id, {\n\t\t\ttype: \"Custom::BaselimeAlert\",\n\t\t\tproperties: {\n\t\t\t\tid,\n\t\t\t\tServiceToken: Config.getServiceToken(),\n\t\t\t\tBaselimeApiKey: Config.getApiKey(),\n\t\t\t\tenabled: props.enabled,\n\t\t\t\tDescription: props.description,\n\t\t\t\tService: getServiceName(stack),", "score": 0.7480829954147339 }, { "filename": "src/resources/alert.ts", "retrieved_chunk": "\t\t\t\tParameters,\n\t\t\t\tChannels: props.channels || Config.getDefaultChannel() && [Config.getDefaultChannel()],\n\t\t\t\tOrigin: \"cdk\",\n\t\t\t},\n\t\t});\n\t}\n}", "score": 0.7351624369621277 }, { "filename": "src/resources/dashboard.ts", "retrieved_chunk": "\t\t}\n\t\tsuper(Config.getConstruct(), id, {\n\t\t\ttype: \"Custom::BaselimeDashboard\",\n\t\t\tproperties: {\n\t\t\t\tid,\n\t\t\t\tServiceToken: Config.getServiceToken(),\n\t\t\t\tBaselimeApiKey: Config.getApiKey(),\n\t\t\t\tDescription: props.description,\n\t\t\t\tService: getServiceName(stack),\n\t\t\t\tParameters: parameters,", "score": 0.7231504917144775 }, { "filename": "src/types/dashboard.ts", "retrieved_chunk": "import { CfnResource } from \"aws-cdk-lib\";\nexport type DashboardProps = {\n\tdescription?: string;\n\tparameters: DeploymentDashboardParameters;\n};\ninterface DeploymentDashboardParameters {\n\twidgets: Array<{\n\t\tname?: string;\n\t\tdescription?: string;\n\t\tquery: CfnResource;", "score": 0.6960238814353943 }, { "filename": "src/resources/alert.ts", "retrieved_chunk": "\t\tconst defaultWindow = \"1hour\";\n\t\tlet Parameters: DeploymentAlertParameters | undefined = undefined;\n\t\tif (\"ref\" in props.parameters.query) {\n\t\t\tParameters = {\n\t\t\t\t...props.parameters,\n\t\t\t\tthreshold: `${props.parameters.threshold?.operation || \">\"} ${props.parameters.threshold?.value\n\t\t\t\t\t}`,\n\t\t\t\tquery: props.parameters.query.ref,\n\t\t\t\tfrequency: props.parameters.frequency || defaultFrequency,\n\t\t\t\twindow: props.parameters.window || defaultWindow,", "score": 0.6867208480834961 } ]
typescript
alert: ChangeFields<AlertProps<TKey>, {
import { CfnResource, Stack } from "aws-cdk-lib"; import { Baselime as Config } from "../config"; import { QueryProps, Filter, DeploymentQueryParameters } from "../types/query"; import { AlertProps } from "../types/alert"; import { Alert } from './alert'; import { getServiceName } from '../utils/service-name'; function buildCalculation(cal: { alias?: string; operation: string; key?: string }) { const short = buildShortCalculation(cal); return `${short}${cal.alias ? ` as ${cal.alias}` : ""}`; } function hasDuplicates<T>(array: T[]) { return (new Set(array)).size !== array.length; } function buildShortCalculation(cal: { alias?: string; operation: string; key?: string }) { if (cal.operation === "COUNT") { return cal.operation; } return `${cal.operation}(${cal.key})`; } function getCalculationAlias(cal: { alias?: string; operation: string; key?: string }) { return cal.alias ? cal.alias : buildShortCalculation(cal); } export function stringifyFilter(filter: Filter): string { const { key, operation, value } = filter; if (!operation) { return `${key} = ${value}`; } if (["EXISTS", "DOES_NOT_EXIST"].includes(operation)) { return `${key} ${operation}`; } if (["IN", "NOT_IN"].some(o => o === operation)) { return `${key} ${operation} (${value})`; } return `${key} ${operation} ${value}`; } /** * */ export class Query<TKey extends string> extends CfnResource { id: string; props: QueryProps<TKey> constructor(id: string, props: QueryProps<TKey>) { const stack = Stack.of(Config.getConstruct()); const calcs = props.parameters.calculations; const orderByOptions = calcs?.map(cal => getCalculationAlias(cal)); if (calcs?.length && hasDuplicates(calcs
.filter(c => c.alias).map(c => c.alias))) {
throw Error("Aliases must me unique across all calculations / visualisations.") } if (props.parameters.orderBy && !orderByOptions?.includes(props.parameters.orderBy.value)) { throw Error("The orderBy must be present in the calculations / visualisations.") } const disableStackFilter = props.disableStackFilter || Config.getDisableStackFilter(); if (!disableStackFilter) { props.parameters.filters?.push({ operation: "=", key: "$baselime.stackId", value: stack.stackName }) } const Parameters: DeploymentQueryParameters = { ...props.parameters, datasets: props.parameters.datasets || ['lambda-logs'], calculations: props.parameters.calculations ? props.parameters.calculations.map(buildCalculation) : [], filters: props.parameters.filters?.map(stringifyFilter), groupBys: props.parameters.groupBys?.map(groupBy => { return { ...groupBy, type: groupBy?.type || "string" } }), filterCombination: props.parameters.filterCombination || "AND", }; super(Config.getConstruct(), id, { type: "Custom::BaselimeQuery", properties: { id, ServiceToken: Config.getServiceToken(), BaselimeApiKey: Config.getApiKey(), Description: props.description, Service: getServiceName(stack), Parameters, Origin: "cdk" }, }); this.id = id; this.props = props; } addAlert(alert: ChangeFields<AlertProps<TKey>, { parameters: Omit<AlertProps<TKey>['parameters'], "query"> }>) { const alertProps = { ...alert, parameters: { ...alert.parameters, query: this } } new Alert(`${this.id}-alert`, alertProps); } addFilters(filters: QueryProps<string>["parameters"]["filters"]) { this.addPropertyOverride('Parameters.filters', [...filters || []]) } }; type ChangeFields<T, R> = Omit<T, keyof R> & R;
src/resources/query.ts
baselime-cdk-82637d8
[ { "filename": "src/resources/dashboard.ts", "retrieved_chunk": "import { CfnResource, Stack } from \"aws-cdk-lib\";\nimport { Baselime as Config } from \"../config\";\nimport { DashboardProps } from \"../types/dashboard\";\nimport { getServiceName } from \"../utils/service-name\";\nexport class Dashboard extends CfnResource {\n\tconstructor(id: string, props: DashboardProps) {\n\t\tconst stack = Stack.of(Config.getConstruct());\n\t\tconst parameters = {\n\t\t\t...props.parameters,\n\t\t\twidgets: props.parameters.widgets.map(el => ({ ...el, query: el.query.ref }))", "score": 0.7334237694740295 }, { "filename": "src/resources/alert.ts", "retrieved_chunk": "\t\t\t};\n\t\t}\n\t\tif (\"filters\" in props.parameters.query) {\n\t\t\tconst query = new Query(`${id}-query`, {\n\t\t\t\tparameters: {\n\t\t\t\t\t...props.parameters.query,\n\t\t\t\t\tcalculations: props.parameters.query.calculations || [\n\t\t\t\t\t\t{ operation: \"COUNT\" },\n\t\t\t\t\t],\n\t\t\t\t},", "score": 0.7082237005233765 }, { "filename": "src/types/query.ts", "retrieved_chunk": "import { F } from \"ts-toolbelt\";\nexport type QueryProps<TKey extends string> = {\n\tdescription?: string;\n\tparameters: QueryParameters<TKey>\n\tdisableStackFilter?: boolean\n};\nexport type QueryParameters<TKey extends string> = {\n\tdatasets?: Datasets[];\n\tfilterCombination?: \"AND\" | \"OR\";\n\tfilters: Filter[];", "score": 0.6951031684875488 }, { "filename": "src/resources/alert.ts", "retrieved_chunk": "import { CfnResource, Stack } from \"aws-cdk-lib\";\nimport { Baselime as Config } from \"../config\";\nimport { Query } from \"./query\";\nimport { AlertProps, DeploymentAlertParameters } from \"../types/alert\";\nimport { QueryProps } from \"../types/query\";\nimport { getServiceName } from \"../utils/service-name\";\nexport class Alert<TKey extends string> extends CfnResource {\n\tconstructor(id: string, props: AlertProps<TKey>) {\n\t\tconst stack = Stack.of(Config.getConstruct());\n\t\tconst defaultFrequency = \"1hour\";", "score": 0.6937078237533569 }, { "filename": "src/types/alert.ts", "retrieved_chunk": "import { CfnResource } from \"aws-cdk-lib\";\nimport { QueryOperationString, QueryParameters } from \"./query\";\nexport type AlertProps<TKey extends string> = {\n\tdescription?: string;\n\tenabled?: boolean;\n\tparameters: {\n\t\tquery: CfnResource | QueryParameters<TKey>,\n\t\tthreshold?: {\n\t\t\toperation?: QueryOperationString,\n\t\t\tvalue: string | number", "score": 0.6817800998687744 } ]
typescript
.filter(c => c.alias).map(c => c.alias))) {
import { CfnResource, Stack } from "aws-cdk-lib"; import { Baselime as Config } from "../config"; import { QueryProps, Filter, DeploymentQueryParameters } from "../types/query"; import { AlertProps } from "../types/alert"; import { Alert } from './alert'; import { getServiceName } from '../utils/service-name'; function buildCalculation(cal: { alias?: string; operation: string; key?: string }) { const short = buildShortCalculation(cal); return `${short}${cal.alias ? ` as ${cal.alias}` : ""}`; } function hasDuplicates<T>(array: T[]) { return (new Set(array)).size !== array.length; } function buildShortCalculation(cal: { alias?: string; operation: string; key?: string }) { if (cal.operation === "COUNT") { return cal.operation; } return `${cal.operation}(${cal.key})`; } function getCalculationAlias(cal: { alias?: string; operation: string; key?: string }) { return cal.alias ? cal.alias : buildShortCalculation(cal); } export function stringifyFilter(filter: Filter): string { const { key, operation, value } = filter; if (!operation) { return `${key} = ${value}`; } if (["EXISTS", "DOES_NOT_EXIST"].includes(operation)) { return `${key} ${operation}`; } if (["IN", "NOT_IN"].some(o => o === operation)) { return `${key} ${operation} (${value})`; } return `${key} ${operation} ${value}`; } /** * */ export class Query<TKey extends string> extends CfnResource { id: string; props: QueryProps<TKey> constructor(id: string, props: QueryProps<TKey>) { const stack = Stack.of(Config.getConstruct()); const calcs = props.parameters.calculations; const orderByOptions = calcs?.map(cal => getCalculationAlias(cal)); if (calcs?.length && hasDuplicates(calcs.filter(c => c.alias).map(c => c.alias))) { throw Error("Aliases must me unique across all calculations / visualisations.") } if (props.parameters.orderBy && !orderByOptions?.includes(props.parameters.orderBy.value)) { throw Error("The orderBy must be present in the calculations / visualisations.") } const disableStackFilter = props.disableStackFilter || Config.getDisableStackFilter(); if (!disableStackFilter) { props.parameters.filters?.push({ operation: "=", key: "$baselime.stackId", value: stack.stackName }) } const Parameters: DeploymentQueryParameters = { ...props.parameters, datasets: props.parameters.datasets || ['lambda-logs'], calculations: props.parameters.calculations ? props.parameters.calculations.map(buildCalculation) : [], filters: props.parameters.filters?.map(stringifyFilter), groupBys: props.parameters.groupBys?.map(groupBy => { return { ...groupBy, type: groupBy?.type || "string" } }), filterCombination: props.parameters.filterCombination || "AND", }; super(Config.getConstruct(), id, { type: "Custom::BaselimeQuery", properties: { id, ServiceToken: Config.getServiceToken(), BaselimeApiKey: Config.getApiKey(), Description: props.description,
Service: getServiceName(stack), Parameters, Origin: "cdk" }, });
this.id = id; this.props = props; } addAlert(alert: ChangeFields<AlertProps<TKey>, { parameters: Omit<AlertProps<TKey>['parameters'], "query"> }>) { const alertProps = { ...alert, parameters: { ...alert.parameters, query: this } } new Alert(`${this.id}-alert`, alertProps); } addFilters(filters: QueryProps<string>["parameters"]["filters"]) { this.addPropertyOverride('Parameters.filters', [...filters || []]) } }; type ChangeFields<T, R> = Omit<T, keyof R> & R;
src/resources/query.ts
baselime-cdk-82637d8
[ { "filename": "src/resources/dashboard.ts", "retrieved_chunk": "\t\t}\n\t\tsuper(Config.getConstruct(), id, {\n\t\t\ttype: \"Custom::BaselimeDashboard\",\n\t\t\tproperties: {\n\t\t\t\tid,\n\t\t\t\tServiceToken: Config.getServiceToken(),\n\t\t\t\tBaselimeApiKey: Config.getApiKey(),\n\t\t\t\tDescription: props.description,\n\t\t\t\tService: getServiceName(stack),\n\t\t\t\tParameters: parameters,", "score": 0.8934703469276428 }, { "filename": "src/resources/alert.ts", "retrieved_chunk": "\t\tif (!Parameters) throw new Error(\"Invalid alert parameters. Declare at least one of filters or ref in the query.\")\n\t\tsuper(Config.getConstruct(), id, {\n\t\t\ttype: \"Custom::BaselimeAlert\",\n\t\t\tproperties: {\n\t\t\t\tid,\n\t\t\t\tServiceToken: Config.getServiceToken(),\n\t\t\t\tBaselimeApiKey: Config.getApiKey(),\n\t\t\t\tenabled: props.enabled,\n\t\t\t\tDescription: props.description,\n\t\t\t\tService: getServiceName(stack),", "score": 0.8283084034919739 }, { "filename": "src/resources/alert.ts", "retrieved_chunk": "\t\t\t\tParameters,\n\t\t\t\tChannels: props.channels || Config.getDefaultChannel() && [Config.getDefaultChannel()],\n\t\t\t\tOrigin: \"cdk\",\n\t\t\t},\n\t\t});\n\t}\n}", "score": 0.7642984986305237 }, { "filename": "src/config.ts", "retrieved_chunk": "\t * Baselime.init(this, {\n\t * apiKey: process.env.BASELIME_API_KEY, // Ideally use SSM or Secrets Manager\n\t * serviceName: 'my-service',\n\t *\t\t defaultChannel: { type: \"slack\", targets: [\"baselime-alerts\"] },\n\t * });\n\t */\n\texport function init(\n\t\ttarget: Construct,\n\t\toptions: BaselimeConfiguration,\n\t) {", "score": 0.6814429759979248 }, { "filename": "src/config.ts", "retrieved_chunk": "\t\tconstruct = target;\n\t\tbaselimeSecret = options.apiKey;\n\t\tserviceName = options.serviceName;\n\t\tserviceToken = `arn:aws:lambda:${options.region || process.env.CDK_DEPLOY_REGION || \"eu-west-1\"\n\t\t\t}:${options._account || \"097948374213\"}:function:baselime-orl-cloudformation`;\n\t\tdefaultChannel = options.defaultChannel;\n\t\tdisableStackFilter = options.disableStackFilter;\n\t}\n\texport function getConstruct() {\n\t\treturn construct;", "score": 0.6632522344589233 } ]
typescript
Service: getServiceName(stack), Parameters, Origin: "cdk" }, });
import { CfnResource, Stack } from "aws-cdk-lib"; import { Baselime as Config } from "../config"; import { QueryProps, Filter, DeploymentQueryParameters } from "../types/query"; import { AlertProps } from "../types/alert"; import { Alert } from './alert'; import { getServiceName } from '../utils/service-name'; function buildCalculation(cal: { alias?: string; operation: string; key?: string }) { const short = buildShortCalculation(cal); return `${short}${cal.alias ? ` as ${cal.alias}` : ""}`; } function hasDuplicates<T>(array: T[]) { return (new Set(array)).size !== array.length; } function buildShortCalculation(cal: { alias?: string; operation: string; key?: string }) { if (cal.operation === "COUNT") { return cal.operation; } return `${cal.operation}(${cal.key})`; } function getCalculationAlias(cal: { alias?: string; operation: string; key?: string }) { return cal.alias ? cal.alias : buildShortCalculation(cal); } export function stringifyFilter(filter: Filter): string { const { key, operation, value } = filter; if (!operation) { return `${key} = ${value}`; } if (["EXISTS", "DOES_NOT_EXIST"].includes(operation)) { return `${key} ${operation}`; } if (["IN", "NOT_IN"].some(o => o === operation)) { return `${key} ${operation} (${value})`; } return `${key} ${operation} ${value}`; } /** * */ export class Query<TKey extends string> extends CfnResource { id: string; props: QueryProps<TKey> constructor(id: string, props: QueryProps<TKey>) { const stack = Stack.of(Config.getConstruct()); const calcs = props.parameters.calculations; const orderByOptions = calcs?.map(cal => getCalculationAlias(cal)); if (calcs?.length && hasDuplicates(calcs.filter(c => c.alias).map(c => c.alias))) { throw Error("Aliases must me unique across all calculations / visualisations.") } if (props.parameters.orderBy && !orderByOptions?.includes(props.parameters.orderBy.value)) { throw Error("The orderBy must be present in the calculations / visualisations.") } const disableStackFilter = props.disableStackFilter || Config.getDisableStackFilter(); if (!disableStackFilter) { props.parameters.filters?.push({ operation: "=", key: "$baselime.stackId", value: stack.stackName }) } const Parameters: DeploymentQueryParameters = { ...props.parameters, datasets: props.parameters.datasets || ['lambda-logs'], calculations: props.parameters.calculations ? props.parameters.calculations.map(buildCalculation) : [], filters: props.parameters.filters?.map(stringifyFilter), groupBys: props.parameters.groupBys?.map(groupBy => { return { ...groupBy, type: groupBy?.type || "string" } }), filterCombination: props.parameters.filterCombination || "AND", }; super(Config.getConstruct(), id, { type: "Custom::BaselimeQuery", properties: { id, ServiceToken: Config.getServiceToken(), BaselimeApiKey: Config.getApiKey(), Description: props.description, Service: getServiceName(stack), Parameters, Origin: "cdk" }, }); this.id = id; this.props = props; } addAlert(alert
: ChangeFields<AlertProps<TKey>, {
parameters: Omit<AlertProps<TKey>['parameters'], "query"> }>) { const alertProps = { ...alert, parameters: { ...alert.parameters, query: this } } new Alert(`${this.id}-alert`, alertProps); } addFilters(filters: QueryProps<string>["parameters"]["filters"]) { this.addPropertyOverride('Parameters.filters', [...filters || []]) } }; type ChangeFields<T, R> = Omit<T, keyof R> & R;
src/resources/query.ts
baselime-cdk-82637d8
[ { "filename": "src/resources/alert.ts", "retrieved_chunk": "\t\tif (!Parameters) throw new Error(\"Invalid alert parameters. Declare at least one of filters or ref in the query.\")\n\t\tsuper(Config.getConstruct(), id, {\n\t\t\ttype: \"Custom::BaselimeAlert\",\n\t\t\tproperties: {\n\t\t\t\tid,\n\t\t\t\tServiceToken: Config.getServiceToken(),\n\t\t\t\tBaselimeApiKey: Config.getApiKey(),\n\t\t\t\tenabled: props.enabled,\n\t\t\t\tDescription: props.description,\n\t\t\t\tService: getServiceName(stack),", "score": 0.7489153146743774 }, { "filename": "src/resources/alert.ts", "retrieved_chunk": "\t\t\t\tParameters,\n\t\t\t\tChannels: props.channels || Config.getDefaultChannel() && [Config.getDefaultChannel()],\n\t\t\t\tOrigin: \"cdk\",\n\t\t\t},\n\t\t});\n\t}\n}", "score": 0.7317581176757812 }, { "filename": "src/resources/dashboard.ts", "retrieved_chunk": "\t\t}\n\t\tsuper(Config.getConstruct(), id, {\n\t\t\ttype: \"Custom::BaselimeDashboard\",\n\t\t\tproperties: {\n\t\t\t\tid,\n\t\t\t\tServiceToken: Config.getServiceToken(),\n\t\t\t\tBaselimeApiKey: Config.getApiKey(),\n\t\t\t\tDescription: props.description,\n\t\t\t\tService: getServiceName(stack),\n\t\t\t\tParameters: parameters,", "score": 0.7209449410438538 }, { "filename": "src/types/dashboard.ts", "retrieved_chunk": "import { CfnResource } from \"aws-cdk-lib\";\nexport type DashboardProps = {\n\tdescription?: string;\n\tparameters: DeploymentDashboardParameters;\n};\ninterface DeploymentDashboardParameters {\n\twidgets: Array<{\n\t\tname?: string;\n\t\tdescription?: string;\n\t\tquery: CfnResource;", "score": 0.6883068084716797 }, { "filename": "src/resources/alert.ts", "retrieved_chunk": "\t\tconst defaultWindow = \"1hour\";\n\t\tlet Parameters: DeploymentAlertParameters | undefined = undefined;\n\t\tif (\"ref\" in props.parameters.query) {\n\t\t\tParameters = {\n\t\t\t\t...props.parameters,\n\t\t\t\tthreshold: `${props.parameters.threshold?.operation || \">\"} ${props.parameters.threshold?.value\n\t\t\t\t\t}`,\n\t\t\t\tquery: props.parameters.query.ref,\n\t\t\t\tfrequency: props.parameters.frequency || defaultFrequency,\n\t\t\t\twindow: props.parameters.window || defaultWindow,", "score": 0.6853476762771606 } ]
typescript
: ChangeFields<AlertProps<TKey>, {
import { CfnResource, Stack } from "aws-cdk-lib"; import { Baselime as Config } from "../config"; import { QueryProps, Filter, DeploymentQueryParameters } from "../types/query"; import { AlertProps } from "../types/alert"; import { Alert } from './alert'; import { getServiceName } from '../utils/service-name'; function buildCalculation(cal: { alias?: string; operation: string; key?: string }) { const short = buildShortCalculation(cal); return `${short}${cal.alias ? ` as ${cal.alias}` : ""}`; } function hasDuplicates<T>(array: T[]) { return (new Set(array)).size !== array.length; } function buildShortCalculation(cal: { alias?: string; operation: string; key?: string }) { if (cal.operation === "COUNT") { return cal.operation; } return `${cal.operation}(${cal.key})`; } function getCalculationAlias(cal: { alias?: string; operation: string; key?: string }) { return cal.alias ? cal.alias : buildShortCalculation(cal); } export function stringifyFilter(filter: Filter): string { const { key, operation, value } = filter; if (!operation) { return `${key} = ${value}`; } if (["EXISTS", "DOES_NOT_EXIST"].includes(operation)) { return `${key} ${operation}`; } if (["IN", "NOT_IN"].some(o => o === operation)) { return `${key} ${operation} (${value})`; } return `${key} ${operation} ${value}`; } /** * */ export class Query<TKey extends string> extends CfnResource { id: string; props: QueryProps<TKey> constructor(id: string, props: QueryProps<TKey>) { const stack = Stack.of(Config.getConstruct()); const calcs = props.parameters.calculations;
const orderByOptions = calcs?.map(cal => getCalculationAlias(cal));
if (calcs?.length && hasDuplicates(calcs.filter(c => c.alias).map(c => c.alias))) { throw Error("Aliases must me unique across all calculations / visualisations.") } if (props.parameters.orderBy && !orderByOptions?.includes(props.parameters.orderBy.value)) { throw Error("The orderBy must be present in the calculations / visualisations.") } const disableStackFilter = props.disableStackFilter || Config.getDisableStackFilter(); if (!disableStackFilter) { props.parameters.filters?.push({ operation: "=", key: "$baselime.stackId", value: stack.stackName }) } const Parameters: DeploymentQueryParameters = { ...props.parameters, datasets: props.parameters.datasets || ['lambda-logs'], calculations: props.parameters.calculations ? props.parameters.calculations.map(buildCalculation) : [], filters: props.parameters.filters?.map(stringifyFilter), groupBys: props.parameters.groupBys?.map(groupBy => { return { ...groupBy, type: groupBy?.type || "string" } }), filterCombination: props.parameters.filterCombination || "AND", }; super(Config.getConstruct(), id, { type: "Custom::BaselimeQuery", properties: { id, ServiceToken: Config.getServiceToken(), BaselimeApiKey: Config.getApiKey(), Description: props.description, Service: getServiceName(stack), Parameters, Origin: "cdk" }, }); this.id = id; this.props = props; } addAlert(alert: ChangeFields<AlertProps<TKey>, { parameters: Omit<AlertProps<TKey>['parameters'], "query"> }>) { const alertProps = { ...alert, parameters: { ...alert.parameters, query: this } } new Alert(`${this.id}-alert`, alertProps); } addFilters(filters: QueryProps<string>["parameters"]["filters"]) { this.addPropertyOverride('Parameters.filters', [...filters || []]) } }; type ChangeFields<T, R> = Omit<T, keyof R> & R;
src/resources/query.ts
baselime-cdk-82637d8
[ { "filename": "src/resources/dashboard.ts", "retrieved_chunk": "import { CfnResource, Stack } from \"aws-cdk-lib\";\nimport { Baselime as Config } from \"../config\";\nimport { DashboardProps } from \"../types/dashboard\";\nimport { getServiceName } from \"../utils/service-name\";\nexport class Dashboard extends CfnResource {\n\tconstructor(id: string, props: DashboardProps) {\n\t\tconst stack = Stack.of(Config.getConstruct());\n\t\tconst parameters = {\n\t\t\t...props.parameters,\n\t\t\twidgets: props.parameters.widgets.map(el => ({ ...el, query: el.query.ref }))", "score": 0.7655813694000244 }, { "filename": "src/types/query.ts", "retrieved_chunk": "import { F } from \"ts-toolbelt\";\nexport type QueryProps<TKey extends string> = {\n\tdescription?: string;\n\tparameters: QueryParameters<TKey>\n\tdisableStackFilter?: boolean\n};\nexport type QueryParameters<TKey extends string> = {\n\tdatasets?: Datasets[];\n\tfilterCombination?: \"AND\" | \"OR\";\n\tfilters: Filter[];", "score": 0.7648541927337646 }, { "filename": "src/resources/alert.ts", "retrieved_chunk": "import { CfnResource, Stack } from \"aws-cdk-lib\";\nimport { Baselime as Config } from \"../config\";\nimport { Query } from \"./query\";\nimport { AlertProps, DeploymentAlertParameters } from \"../types/alert\";\nimport { QueryProps } from \"../types/query\";\nimport { getServiceName } from \"../utils/service-name\";\nexport class Alert<TKey extends string> extends CfnResource {\n\tconstructor(id: string, props: AlertProps<TKey>) {\n\t\tconst stack = Stack.of(Config.getConstruct());\n\t\tconst defaultFrequency = \"1hour\";", "score": 0.745023250579834 }, { "filename": "src/types/alert.ts", "retrieved_chunk": "import { CfnResource } from \"aws-cdk-lib\";\nimport { QueryOperationString, QueryParameters } from \"./query\";\nexport type AlertProps<TKey extends string> = {\n\tdescription?: string;\n\tenabled?: boolean;\n\tparameters: {\n\t\tquery: CfnResource | QueryParameters<TKey>,\n\t\tthreshold?: {\n\t\t\toperation?: QueryOperationString,\n\t\t\tvalue: string | number", "score": 0.7325615882873535 }, { "filename": "src/types/dashboard.ts", "retrieved_chunk": "import { CfnResource } from \"aws-cdk-lib\";\nexport type DashboardProps = {\n\tdescription?: string;\n\tparameters: DeploymentDashboardParameters;\n};\ninterface DeploymentDashboardParameters {\n\twidgets: Array<{\n\t\tname?: string;\n\t\tdescription?: string;\n\t\tquery: CfnResource;", "score": 0.7114648818969727 } ]
typescript
const orderByOptions = calcs?.map(cal => getCalculationAlias(cal));
import { exec } from 'child_process'; import { GolemFile, GolemTarget, isGolemTarget } from './types'; import { ChatGPTMessage, ChatGPT_completion } from './chat_gpt'; import { readFile } from 'fs/promises'; import { dirname } from 'path'; import logger from './logger'; import { generateCacheKey, isCacheValid, saveOutputToCache, loadOutputFromCache, appendToGolemFile } from './utils'; import { writeFileSync} from 'fs'; // TODO 1: Check if prompt asks for additional targets. // TODO 2: Check if targets have other dependencies. // TODO 3: Saving properly (for example, it saves all of the previous context for imp task) // TODO 4: Use different files interface ExecutionContext { [key: string]: any; } const mainPrompt: ChatGPTMessage = { role: 'system', content: `You are an Agentic LLM assistant, designed only to produce code and helpful information. You may be asked to generate new targets. If the prompt given to you contains the phrase 'generate new targets', your response will be to generate a list of targets to help answer the prompt. The targets must be written as unnumbered items separated by lines starting with 'Target:'. The items in the list will not be arranged in any particular order. For example: Prompt: As an agentic LLM, generate new targets for the next iteration. Response: Target: Write a function to divide two numbers. Target: Create a class called Employee. Target: Write unit tests for the function GetPeopleInterests. It is not always the case that you will be asked to generate new targets. If the prompt does not contain the phrase 'generate new targets', then proceed to answer the prompt as truthfully as possible. For example: Prompt: What is capital of France? Response: Paris. Prompt: How many days are in the month of April? Response: 30 days. You are opinionated. If asked to provide a subjective answer, start by saying 'In my opinion' then answer the prompt. For example: Prompt: What is the best sport? Response: In my opinion, soccer. ` } export async function executeTarget(target: string, golemFile: GolemFile, golemFilePath: string, context: Map<string, any> = new Map()): Promise<void> { const golemTarget = golemFile[target]; if (!golemTarget) { throw new Error(`Target "${target}" not found in Golem file.`); } console.log(`Executing target: ${target}`); if (golemTarget.dependencies) { console.log(`Dependencies for ${target}: ${golemTarget.dependencies}`); for (const dependency of golemTarget.dependencies) { if (dependency) { await executeTarget(dependency, golemFile, golemFilePath, context); } } } await executeAIChatWithCache(target, golemFile, golemFilePath, context); console.log(`Context after ${target} execution:`, context); } function executeCommand(command: string): Promise<void> { return new Promise((resolve, reject) => { exec(command, (error, stdout, stderr) => { if (error) { logger.error(`Error executing command: ${command}`); logger.error(stderr); reject(error); } else { logger.debug(stdout); resolve(); } }); }); } async function executeAIChatWithCache(target: string, golemFile: GolemFile, golemFilePath: string, context: Map<string, any>): Promise<void> { const golemFileToArray: any = []; for (const key in golemFile){ const val = golemFile[key as keyof typeof golemFile]; golemFileToArray.push(val); } const golemTarget = golemFile[target]; if (!golemTarget || !isGolemTarget(golemTarget)) { return; } const cacheKey = generateCacheKey(target, golemTarget.dependencies || [], [...golemFileToArray] || ''); if (isCacheValid(target, cacheKey)) { console.log("Returning Cached output"); const cachedOutput = loadOutputFromCache(target, cacheKey); context.set(target, cachedOutput); } else { await executeAIChat(target, golemFile, golemFilePath, context); saveOutputToCache(target, cacheKey, context); } } async function executeAIChat(target: string, golemFile: GolemFile, golemFilePath: string, context: Map<string, any>): Promise<void> { // ============== Setup start ==================================== const contextOfCurrentTarget: string[] = []; const allOutputs: {[key: string]: any} = {}; const golemTarget = golemFile[target]; console.log("gT", golemTarget); if (!golemTarget) { throw new Error(`Target "${target}" not found in Golem file.`); } if (!isGolemTarget(golemTarget)) { return; } if (!golemTarget.prompt && !golemTarget.model) { golemTarget.model = 'cat'; } let prompt = golemTarget.prompt ?? "{no prompt}"; if (isGolemTarget(golemTarget) && golemTarget.prompt) { prompt = golemTarget.prompt; const placeholderRegex = /{{\s*([\w\/.-]+)\s*}}/g; let match; while ((match = placeholderRegex.exec(prompt)) !== null) { const key = match[1]; if (context.has(key)) { prompt = prompt.replace(match[0], context.get(key)); } else { prompt = prompt.replace(match[0], ""); } } } else if (!golemTarget.prompt) { const defaultValues = new Map(context.entries()); context.set("default", Object.fromEntries(defaultValues)); return; } const model = golemTarget.model ?? 'gpt-3.5-turbo'; // ============== Setup end ==================================== if (model === 'cat') { const concatenatedOutput = golemTarget.dependencies.map(dep => context.get(dep)).join(''); context.set(target, concatenatedOutput); } else if (model == "gpt-3.5-turbo" || model == "gpt-3.5-turbo-0301" || model == "gpt-4-0314" || model == "gpt-4-32k") { if ("model" in golemTarget) { delete golemTarget.model; } // This gets the 'keys' (subtasks) of a target (task) const golemTargetKeys: string[] = Object.keys(golemTarget); // It starts from 1 as index 0 is dependencies. This can be changed if needed for (let i = 1; i < golemTargetKeys.length; i++){ // console.log("gTKi", golemTargetKeys[i]); const val: any = golemTarget[golemTargetKeys[i] as keyof typeof golemTarget]; // console.log("val", val); const previousContext: string | undefined = contextOfCurrentTarget[0] || ''; // Concat the previousContext (if undefined) to the current subtask (here, named val) const content = previousContext + val; // console.log("content", content); // This block of code replaces the {{}} placeholders in the string from the yaml file // with the output of the subtask or task it requires const replacedString = content.replace(/{{(.*?)}}/g, (match, p1) => { // Remove the curly braces from the placeholder const placeholder = p1.trim(); // Replace the placeholder with the corresponding value from the map return context.get(placeholder) || placeholder; }); // console.log("context", context); // console.log("replacedString", replacedString); const taskGenerationMessages: ChatGPTMessage[] = [ mainPrompt, { role: 'user', content: replacedString, }, ];
const response = await ChatGPT_completion(taskGenerationMessages, model, 0.7, 0.9);
contextOfCurrentTarget.length = 0; //clear the previous context contextOfCurrentTarget.push(response); //append the new context to be used in the next iteration allOutputs[golemTargetKeys[i]] = response; const lines: string[] = response.split('\n'); // Extract the targets from the lines that start with "Target:" const targets: string[] = lines.filter((line: string) => line.startsWith("Target:")) .map((line: string) => line.slice(8)); let count = 1; targets.forEach((createdTarget: string) => { const targetName = target.concat("_target".concat(count.toString())); const newTarget: string = `\n${targetName}:\n dependencies: []\n prompt: ${createdTarget}`; appendToGolemFile(golemFilePath, newTarget); golemTargetKeys.push(targetName); golemTarget[targetName] = createdTarget; count += 1; }); if (golemTargetKeys.length === 2){ if (!response) { context.set(target, `Default value for ${target}`); } else { context.set(target, response); console.log(context); } } else if (golemTargetKeys.length > 2){ try { for (const key in allOutputs) { context.set(key, allOutputs[key]); } }catch (error: any) { logger.error(`Error generating AI response: ${error.message}`); } } } }else { throw new Error(`No such supported model ${model}`); } }
src/executor.ts
Confabulation-Corporation-golem-ac8b554
[ { "filename": "src/parser.ts", "retrieved_chunk": "import * as yaml from 'js-yaml';\nimport { GolemFile } from './types';\nexport function parseGolemFile(content: string): GolemFile {\n try {\n const parsedContent = yaml.load(content) as GolemFile;\n // Update the parsing logic to handle the task_generation_prompt field\n return parsedContent;\n } catch (error: any) {\n throw new Error(`Error parsing Golem file: ${error.message}`);\n }", "score": 0.7497203350067139 }, { "filename": "src/chat_gpt.ts", "retrieved_chunk": " const waitTime = resetMs + Math.random() * 1000;\n logger.warn(\n `Rate limit or server error encountered (status: ${error.response.status}). Retrying in ${waitTime} ms...`\n );\n await new Promise((resolve) => setTimeout(resolve, waitTime));\n } else {\n throw error;\n }\n }\n }", "score": 0.7434570789337158 }, { "filename": "src/types.ts", "retrieved_chunk": "export interface GolemTarget {\n dependencies: string[];\n prompt: string;\n model?: string; // Add this line\n task_generation_prompt?: string; // Add this line\n [key: string]: string[] | string | undefined;\n}\nexport type GolemFile = {\n default: string[];\n} & {", "score": 0.7366994619369507 }, { "filename": "src/golem.ts", "retrieved_chunk": " 'Run the specified Golem file or the default Golem file if none is provided.',\n (yargs) => {\n yargs.positional('golemFile', {\n describe: 'Path to the Golem file',\n default: 'Golem.yaml',\n type: 'string',\n });\n },\n async (argv) => {\n try {", "score": 0.7352418303489685 }, { "filename": "src/chat_gpt.ts", "retrieved_chunk": " for (let i = 0; i < maxRetries; i++) {\n try {\n const completion = await openai.createChatCompletion({\n model: model,\n messages: messages,\n });\n return (completion.data!.choices[0]!.message?.content || \"\").trim();\n } catch (error: any) {\n if (error.response && (error.response.status === 429 || (error.response.status >= 500 && error.response.status < 600))) {\n const resetMs = parseInt(error.response.headers['x-ratelimit-reset-requests']) || 1000;", "score": 0.7117428779602051 } ]
typescript
const response = await ChatGPT_completion(taskGenerationMessages, model, 0.7, 0.9);
import { ClassFunction, Enum, Function, HookFunction, LibraryFunction, Panel, PanelFunction, Realm, Struct, WikiPage, isPanel } from '../scrapers/wiki-page-markup-scraper.js'; import { putCommentBeforeEachLine, removeNewlines, safeFileName, toLowerCamelCase } from '../utils/string.js'; import { isClassFunction, isHookFunction, isLibraryFunction, isPanelFunction, isStruct, isEnum, } from '../scrapers/wiki-page-markup-scraper.js'; export const RESERVERD_KEYWORDS = new Set([ 'and', 'break', 'continue', 'do', 'else', 'elseif', 'end', 'false', 'for', 'function', 'goto', 'if', 'in', 'local', 'nil', 'not', 'or', 'repeat', 'return', 'then', 'true', 'until', 'while' ]); export class GluaApiWriter { private readonly writtenClasses: Set<string> = new Set(); private readonly writtenLibraryGlobals: Set<string> = new Set(); private readonly pageOverrides: Map<string, string> = new Map(); constructor() { } public static safeName(name: string) { if (name.includes('/')) name = name.replace(/\//g, ' or '); if (name.includes('=')) name = name.split('=')[0]; if (name.includes(' ')) name = toLowerCamelCase(name); // Remove any remaining characters not valid in a Lua variable/function name. name = name.replace(/[^A-Za-z\d_.]/g, ''); if (RESERVERD_KEYWORDS.has(name)) return `_${name}`; return name; } public addOverride(pageAddress: string, override: string) { this.pageOverrides.set(safeFileName(pageAddress, '.'), override); } public writePage(page: WikiPage) { const fileSafeAddress = safeFileName(page.address, '.'); if (this.pageOverrides.has(fileSafeAddress)) { let api = ''; if (isClassFunction(page)) api += this.writeClass(page.parent); else if (isLibraryFunction(page)) api += this.writeLibraryGlobal(page); api += this.pageOverrides.get(fileSafeAddress); return `${api}\n\n`; } else if (isClassFunction(page)) return this.writeClassFunction(page); else if (isLibraryFunction(page)) return this.writeLibraryFunction(page); else if (isHookFunction(page)) return this.writeHookFunction(page);
else if (isPanel(page)) return this.writePanel(page);
else if (isPanelFunction(page)) return this.writePanelFunction(page); else if (isEnum(page)) return this.writeEnum(page); else if (isStruct(page)) return this.writeStruct(page); } private writeClass(className: string, parent?: string, classFields: string = '') { let api: string = ''; if (!this.writtenClasses.has(className)) { const classOverride = `class.${className}`; if (this.pageOverrides.has(classOverride)) { api += this.pageOverrides.get(classOverride)!.replace(/\n$/g, '') + '\n\n'; api = api.replace('---{{CLASS_FIELDS}}\n', classFields); } else { api += `---@class ${className}`; if (parent) api += ` : ${parent}`; api += '\n'; api += classFields; api += `local ${className} = {}\n\n`; } this.writtenClasses.add(className); } return api; } private writeLibraryGlobal(func: LibraryFunction) { if (!func.dontDefineParent && !this.writtenLibraryGlobals.has(func.parent)) { const global = `${func.parent} = {}\n\n`; this.writtenLibraryGlobals.add(func.parent); return global; } return ''; } private writeClassFunction(func: ClassFunction) { let api: string = this.writeClass(func.parent); api += this.writeFunctionLuaDocComment(func, func.realm); api += this.writeFunctionDeclaration(func, func.realm, ':'); return api; } private writeLibraryFunction(func: LibraryFunction) { let api: string = this.writeLibraryGlobal(func); api += this.writeFunctionLuaDocComment(func, func.realm); api += this.writeFunctionDeclaration(func, func.realm); return api; } private writeHookFunction(func: HookFunction) { return this.writeClassFunction(func); } private writePanel(panel: Panel) { return this.writeClass(panel.name, panel.parent); } private writePanelFunction(func: PanelFunction) { let api: string = ''; api += this.writeFunctionLuaDocComment(func, func.realm); api += this.writeFunctionDeclaration(func, func.realm, ':'); return api; } private writeEnum(_enum: Enum) { let api: string = ''; const isContainedInTable = _enum.items[0]?.key.includes('.') ?? false; api += `---@enum ${_enum.name}\n`; if (isContainedInTable) api += `local ${_enum.name} = {\n`; const writeItem = (key: string, item: typeof _enum.items[0]) => { if (isContainedInTable) { key = key.split('.')[1]; api += ` ${key} = ${item.value}, ` + (item.description ? `--[[ ${item.description} ]]` : '') + '\n'; } else { const comment = item.description ? `${putCommentBeforeEachLine(item.description, false)}\n` : ''; api += `${comment}${key} = ${item.value}\n`; } }; for (const item of _enum.items) writeItem(item.key, item); if (isContainedInTable) api += '}'; api += `\n\n`; return api; } private writeStruct(struct: Struct) { let fields: string = ''; for (const field of struct.fields) { fields += `---@field ${GluaApiWriter.safeName(field.name)} ${this.transformType(field.type)} ${removeNewlines(field.description!)}\n`; } return this.writeClass(struct.name, undefined, fields); } public writePages(pages: WikiPage[]) { let api: string = ''; for (const page of pages) { api += this.writePage(page); } return api; } private transformType(type: string) { if (type === 'vararg') return '...'; return type; } private writeFunctionLuaDocComment(func: Function, realm: Realm) { let luaDocComment = `---[${realm.toUpperCase()}] ${putCommentBeforeEachLine(func.description!.trim())}\n`; luaDocComment += `---\n---[(View on wiki)](${func.url})\n`; if (func.arguments) { func.arguments.forEach((arg, index) => { if (!arg.name) arg.name = arg.type; if (arg.type === 'vararg') arg.name = '...'; luaDocComment += `---@param ${GluaApiWriter.safeName(arg.name)}${arg.default !== undefined ? `?` : ''} ${this.transformType(arg.type)} ${putCommentBeforeEachLine(arg.description!)}\n`; }); } if (func.returns) { const returns = `---@return ${func.returns.map(ret => this.transformType(ret.type)).join(', ')}`; func.returns.forEach(ret => { const description = removeNewlines(ret.description ?? ''); if (func.returns!.length === 1) { luaDocComment += `${returns} #${description}\n`; return; } luaDocComment += `${returns} #${this.transformType(ret.type)} - ${description}\n`; }); } return luaDocComment; } private writeFunctionDeclaration(func: Function, realm: Realm, indexer: string = '.') { let declaration = `function ${func.parent ? `${func.parent}${indexer}` : ''}${GluaApiWriter.safeName(func.name)}(`; if (func.arguments) { declaration += func.arguments.map(arg => { if (arg.type === 'vararg') return '...'; return GluaApiWriter.safeName(arg.name!); }).join(', '); } declaration += ') end\n\n'; return declaration; } }
src/api-writer/glua-api-writer.ts
luttje-glua-api-snippets-9f40376
[ { "filename": "src/scrapers/wiki-page-markup-scraper.ts", "retrieved_chunk": " return page.type === 'libraryfunc';\n}\nexport function isHookFunction(page: WikiPage): page is HookFunction {\n return page.type === 'hook';\n}\nexport function isPanelFunction(page: WikiPage): page is PanelFunction {\n return page.type === 'panelfunc';\n}\nexport function isPanel(page: WikiPage): page is Panel {\n return page.type === 'panel';", "score": 0.7822469472885132 }, { "filename": "src/scrapers/wiki-page-markup-scraper.ts", "retrieved_chunk": " parent: string;\n};\nexport type WikiPage = ClassFunction | LibraryFunction | HookFunction | PanelFunction | Panel | Enum | Struct;\n/**\n * Guards\n */\nexport function isClassFunction(page: WikiPage): page is ClassFunction {\n return page.type === 'classfunc';\n}\nexport function isLibraryFunction(page: WikiPage): page is LibraryFunction {", "score": 0.7567369937896729 }, { "filename": "src/scrapers/wiki-page-markup-scraper.ts", "retrieved_chunk": " realm: $('realm:first').text() as Realm,\n arguments: arguments_,\n returns\n };\n if (isClassFunction) {\n return <ClassFunction> {\n ...base,\n type: 'classfunc'\n };\n } else if (isLibraryFunction) {", "score": 0.713171660900116 }, { "filename": "src/scrapers/wiki-page-markup-scraper.ts", "retrieved_chunk": " if (base.parent === 'Global') {\n base.parent = '_G';\n (<LibraryFunction>base).dontDefineParent = true;\n }\n return <LibraryFunction> {\n ...base,\n type: 'libraryfunc'\n };\n } else if (isHookFunction) {\n return <HookFunction> {", "score": 0.7085372805595398 }, { "filename": "src/scrapers/wiki-page-markup-scraper.ts", "retrieved_chunk": "}\nexport function isEnum(page: WikiPage): page is Enum {\n return page.type === 'enum';\n}\nexport function isStruct(page: WikiPage): page is Struct {\n return page.type === 'struct';\n}\n/**\n * Scraper\n */", "score": 0.7081499099731445 } ]
typescript
else if (isPanel(page)) return this.writePanel(page);
import { CfnResource, Stack } from "aws-cdk-lib"; import { Baselime as Config } from "../config"; import { QueryProps, Filter, DeploymentQueryParameters } from "../types/query"; import { AlertProps } from "../types/alert"; import { Alert } from './alert'; import { getServiceName } from '../utils/service-name'; function buildCalculation(cal: { alias?: string; operation: string; key?: string }) { const short = buildShortCalculation(cal); return `${short}${cal.alias ? ` as ${cal.alias}` : ""}`; } function hasDuplicates<T>(array: T[]) { return (new Set(array)).size !== array.length; } function buildShortCalculation(cal: { alias?: string; operation: string; key?: string }) { if (cal.operation === "COUNT") { return cal.operation; } return `${cal.operation}(${cal.key})`; } function getCalculationAlias(cal: { alias?: string; operation: string; key?: string }) { return cal.alias ? cal.alias : buildShortCalculation(cal); } export function stringifyFilter(filter: Filter): string { const { key, operation, value } = filter; if (!operation) { return `${key} = ${value}`; } if (["EXISTS", "DOES_NOT_EXIST"].includes(operation)) { return `${key} ${operation}`; } if (["IN", "NOT_IN"].some(o => o === operation)) { return `${key} ${operation} (${value})`; } return `${key} ${operation} ${value}`; } /** * */ export class Query<TKey extends string> extends CfnResource { id: string; props: QueryProps<TKey> constructor(id: string, props: QueryProps<TKey>) { const stack = Stack.of(Config.getConstruct()); const calcs = props.parameters.calculations; const orderByOptions = calcs?.map(cal => getCalculationAlias(cal)); if (calcs?.length && hasDuplicates(calcs.filter(c => c.alias).map(c => c.alias))) { throw Error("Aliases must me unique across all calculations / visualisations.") } if (props.parameters.orderBy && !orderByOptions?.includes(props.parameters.orderBy.value)) { throw Error("The orderBy must be present in the calculations / visualisations.") } const disableStackFilter = props.disableStackFilter || Config.getDisableStackFilter(); if (!disableStackFilter) { props.parameters.filters?.push({ operation: "=", key: "$baselime.stackId", value: stack.stackName }) } const Parameters: DeploymentQueryParameters = { ...props.parameters, datasets: props.parameters.datasets || ['lambda-logs'], calculations: props.parameters.calculations ? props.parameters.calculations.map(buildCalculation) : [], filters: props.parameters.filters?.map(stringifyFilter), groupBys: props.parameters.groupBys?.map(groupBy => { return { ...groupBy, type: groupBy?.type || "string" } }), filterCombination: props.parameters.filterCombination || "AND", }; super(Config.getConstruct(), id, { type: "Custom::BaselimeQuery", properties: { id, ServiceToken: Config.getServiceToken(), BaselimeApiKey: Config.getApiKey(), Description: props.description, Service
: getServiceName(stack), Parameters, Origin: "cdk" }, });
this.id = id; this.props = props; } addAlert(alert: ChangeFields<AlertProps<TKey>, { parameters: Omit<AlertProps<TKey>['parameters'], "query"> }>) { const alertProps = { ...alert, parameters: { ...alert.parameters, query: this } } new Alert(`${this.id}-alert`, alertProps); } addFilters(filters: QueryProps<string>["parameters"]["filters"]) { this.addPropertyOverride('Parameters.filters', [...filters || []]) } }; type ChangeFields<T, R> = Omit<T, keyof R> & R;
src/resources/query.ts
baselime-cdk-82637d8
[ { "filename": "src/resources/dashboard.ts", "retrieved_chunk": "\t\t}\n\t\tsuper(Config.getConstruct(), id, {\n\t\t\ttype: \"Custom::BaselimeDashboard\",\n\t\t\tproperties: {\n\t\t\t\tid,\n\t\t\t\tServiceToken: Config.getServiceToken(),\n\t\t\t\tBaselimeApiKey: Config.getApiKey(),\n\t\t\t\tDescription: props.description,\n\t\t\t\tService: getServiceName(stack),\n\t\t\t\tParameters: parameters,", "score": 0.8738981485366821 }, { "filename": "src/resources/alert.ts", "retrieved_chunk": "\t\tif (!Parameters) throw new Error(\"Invalid alert parameters. Declare at least one of filters or ref in the query.\")\n\t\tsuper(Config.getConstruct(), id, {\n\t\t\ttype: \"Custom::BaselimeAlert\",\n\t\t\tproperties: {\n\t\t\t\tid,\n\t\t\t\tServiceToken: Config.getServiceToken(),\n\t\t\t\tBaselimeApiKey: Config.getApiKey(),\n\t\t\t\tenabled: props.enabled,\n\t\t\t\tDescription: props.description,\n\t\t\t\tService: getServiceName(stack),", "score": 0.7996922135353088 }, { "filename": "src/resources/alert.ts", "retrieved_chunk": "\t\t\t\tParameters,\n\t\t\t\tChannels: props.channels || Config.getDefaultChannel() && [Config.getDefaultChannel()],\n\t\t\t\tOrigin: \"cdk\",\n\t\t\t},\n\t\t});\n\t}\n}", "score": 0.7937507629394531 }, { "filename": "src/config.ts", "retrieved_chunk": "\t\tconstruct = target;\n\t\tbaselimeSecret = options.apiKey;\n\t\tserviceName = options.serviceName;\n\t\tserviceToken = `arn:aws:lambda:${options.region || process.env.CDK_DEPLOY_REGION || \"eu-west-1\"\n\t\t\t}:${options._account || \"097948374213\"}:function:baselime-orl-cloudformation`;\n\t\tdefaultChannel = options.defaultChannel;\n\t\tdisableStackFilter = options.disableStackFilter;\n\t}\n\texport function getConstruct() {\n\t\treturn construct;", "score": 0.6926488876342773 }, { "filename": "src/config.ts", "retrieved_chunk": "\t}\n\texport function getApiKey() {\n\t\treturn baselimeSecret;\n\t}\n\texport function getServiceName() {\n\t\treturn serviceName;\n\t}\n\texport function getServiceToken() {\n\t\treturn serviceToken;\n\t}", "score": 0.6566614508628845 } ]
typescript
: getServiceName(stack), Parameters, Origin: "cdk" }, });
import { ClassFunction, Enum, Function, HookFunction, LibraryFunction, Panel, PanelFunction, Realm, Struct, WikiPage, isPanel } from '../scrapers/wiki-page-markup-scraper.js'; import { putCommentBeforeEachLine, removeNewlines, safeFileName, toLowerCamelCase } from '../utils/string.js'; import { isClassFunction, isHookFunction, isLibraryFunction, isPanelFunction, isStruct, isEnum, } from '../scrapers/wiki-page-markup-scraper.js'; export const RESERVERD_KEYWORDS = new Set([ 'and', 'break', 'continue', 'do', 'else', 'elseif', 'end', 'false', 'for', 'function', 'goto', 'if', 'in', 'local', 'nil', 'not', 'or', 'repeat', 'return', 'then', 'true', 'until', 'while' ]); export class GluaApiWriter { private readonly writtenClasses: Set<string> = new Set(); private readonly writtenLibraryGlobals: Set<string> = new Set(); private readonly pageOverrides: Map<string, string> = new Map(); constructor() { } public static safeName(name: string) { if (name.includes('/')) name = name.replace(/\//g, ' or '); if (name.includes('=')) name = name.split('=')[0]; if (name.includes(' ')) name = toLowerCamelCase(name); // Remove any remaining characters not valid in a Lua variable/function name. name = name.replace(/[^A-Za-z\d_.]/g, ''); if (RESERVERD_KEYWORDS.has(name)) return `_${name}`; return name; } public addOverride(pageAddress: string, override: string) { this.pageOverrides.set(safeFileName(pageAddress, '.'), override); } public writePage(page: WikiPage) { const fileSafeAddress = safeFileName(page.address, '.'); if (this.pageOverrides.has(fileSafeAddress)) { let api = ''; if (isClassFunction(page)) api += this.writeClass(page.parent); else if (isLibraryFunction(page)) api += this.writeLibraryGlobal(page); api += this.pageOverrides.get(fileSafeAddress); return `${api}\n\n`; } else if (isClassFunction(page)) return this.writeClassFunction(page); else if (isLibraryFunction(page)) return this.writeLibraryFunction(page); else if (isHookFunction(page)) return this.writeHookFunction(page); else if (isPanel(page)) return this.writePanel(page); else if (isPanelFunction(page)) return this.writePanelFunction(page); else if (isEnum(page)) return this.writeEnum(page); else if (isStruct(page)) return this.writeStruct(page); } private writeClass(className: string, parent?: string, classFields: string = '') { let api: string = ''; if (!this.writtenClasses.has(className)) { const classOverride = `class.${className}`; if (this.pageOverrides.has(classOverride)) { api += this.pageOverrides.get(classOverride)!.replace(/\n$/g, '') + '\n\n'; api = api.replace('---{{CLASS_FIELDS}}\n', classFields); } else { api += `---@class ${className}`; if (parent) api += ` : ${parent}`; api += '\n'; api += classFields; api += `local ${className} = {}\n\n`; } this.writtenClasses.add(className); } return api; } private writeLibraryGlobal(func: LibraryFunction) { if (!func.dontDefineParent && !this.writtenLibraryGlobals.has(func.parent)) { const global = `${func.parent} = {}\n\n`; this.writtenLibraryGlobals.add(func.parent); return global; } return ''; } private writeClassFunction(func: ClassFunction) { let api: string = this.writeClass(func.parent); api += this.writeFunctionLuaDocComment(func, func.realm); api += this.writeFunctionDeclaration(func, func.realm, ':'); return api; } private writeLibraryFunction(func: LibraryFunction) { let api: string = this.writeLibraryGlobal(func); api += this.writeFunctionLuaDocComment(func, func.realm); api += this.writeFunctionDeclaration(func, func.realm); return api; } private writeHookFunction(func: HookFunction) { return this.writeClassFunction(func); } private writePanel(panel: Panel) { return this.writeClass(panel.name, panel.parent); } private writePanelFunction(func: PanelFunction) { let api: string = ''; api += this.writeFunctionLuaDocComment(func, func.realm); api += this.writeFunctionDeclaration(func, func.realm, ':'); return api; } private writeEnum(_enum: Enum) { let api: string = ''; const isContainedInTable = _enum.items[0]?.key.includes('.') ?? false; api += `---@enum ${_enum.name}\n`; if (isContainedInTable) api += `local ${_enum.name} = {\n`; const writeItem = (key: string, item: typeof _enum.items[0]) => { if (isContainedInTable) { key = key.split('.')[1]; api += ` ${key} = ${item.value}, ` + (item.description ? `--[[ ${item.description} ]]` : '') + '\n'; } else { const comment = item.
description ? `${putCommentBeforeEachLine(item.description, false)}\n` : '';
api += `${comment}${key} = ${item.value}\n`; } }; for (const item of _enum.items) writeItem(item.key, item); if (isContainedInTable) api += '}'; api += `\n\n`; return api; } private writeStruct(struct: Struct) { let fields: string = ''; for (const field of struct.fields) { fields += `---@field ${GluaApiWriter.safeName(field.name)} ${this.transformType(field.type)} ${removeNewlines(field.description!)}\n`; } return this.writeClass(struct.name, undefined, fields); } public writePages(pages: WikiPage[]) { let api: string = ''; for (const page of pages) { api += this.writePage(page); } return api; } private transformType(type: string) { if (type === 'vararg') return '...'; return type; } private writeFunctionLuaDocComment(func: Function, realm: Realm) { let luaDocComment = `---[${realm.toUpperCase()}] ${putCommentBeforeEachLine(func.description!.trim())}\n`; luaDocComment += `---\n---[(View on wiki)](${func.url})\n`; if (func.arguments) { func.arguments.forEach((arg, index) => { if (!arg.name) arg.name = arg.type; if (arg.type === 'vararg') arg.name = '...'; luaDocComment += `---@param ${GluaApiWriter.safeName(arg.name)}${arg.default !== undefined ? `?` : ''} ${this.transformType(arg.type)} ${putCommentBeforeEachLine(arg.description!)}\n`; }); } if (func.returns) { const returns = `---@return ${func.returns.map(ret => this.transformType(ret.type)).join(', ')}`; func.returns.forEach(ret => { const description = removeNewlines(ret.description ?? ''); if (func.returns!.length === 1) { luaDocComment += `${returns} #${description}\n`; return; } luaDocComment += `${returns} #${this.transformType(ret.type)} - ${description}\n`; }); } return luaDocComment; } private writeFunctionDeclaration(func: Function, realm: Realm, indexer: string = '.') { let declaration = `function ${func.parent ? `${func.parent}${indexer}` : ''}${GluaApiWriter.safeName(func.name)}(`; if (func.arguments) { declaration += func.arguments.map(arg => { if (arg.type === 'vararg') return '...'; return GluaApiWriter.safeName(arg.name!); }).join(', '); } declaration += ') end\n\n'; return declaration; } }
src/api-writer/glua-api-writer.ts
luttje-glua-api-snippets-9f40376
[ { "filename": "src/utils/string.ts", "retrieved_chunk": " */\nexport function putCommentBeforeEachLine(text: string, skipLineOne: boolean = true) {\n return text.split(/\\r?\\n/g).map((line, index) => {\n if (index === 0 && skipLineOne)\n return line;\n return `--- ${line}`;\n }).join('\\n');\n}\n/**\n * Makes a string safe for use as a file name", "score": 0.7487598657608032 }, { "filename": "src/scrapers/table-scraper.ts", "retrieved_chunk": " if (!tableColumnDefinition) {\n const properties = Object.getOwnPropertyNames(rowResult);\n const propertyKey = properties.find(property => property.toLowerCase() === headingText.toLowerCase());\n if (!propertyKey)\n continue;\n tableColumnDefinition = {\n propertyKey,\n columnName: headingText,\n typeConverter: (value: string) => value\n };", "score": 0.7460196018218994 }, { "filename": "src/scrapers/table-scraper.ts", "retrieved_chunk": "export function tableColumn(columnName: string): PropertyDecorator {\n return (target: object, propertyKey: string | symbol) => {\n const existingColumns: TableColumnDefinition[] = Reflect.getMetadata(tableColumnMetadataKey, target) || [];\n const propertyType = Reflect.getMetadata(\"design:type\", target, propertyKey);\n existingColumns.push({\n propertyKey,\n columnName,\n typeConverter: (value: string) => {\n switch (propertyType) {\n case String:", "score": 0.7224199771881104 }, { "filename": "src/scrapers/wiki-page-markup-scraper.ts", "retrieved_chunk": " const isEnum = $('enum').length > 0;\n const isStruct = $('structure').length > 0;\n const isFunction = $('function').length > 0;\n const isPanel = $('panel').length > 0;\n const mainElement = $(isEnum ? 'enum' : isStruct ? 'struct' : isPanel ? 'panel' : 'function');\n const address = response.url.split('/').pop()!.split('?')[0];\n if (isEnum) {\n const items = $('items item').map(function () {\n const $el = $(this);\n return <EnumValue>{", "score": 0.7177549600601196 }, { "filename": "src/cli-library-publisher.ts", "retrieved_chunk": " \"/**/\",\n \"continue\",\n ],\n \"Lua.diagnostics.disable\": [\n \"duplicate-set-field\", // Prevents complaining when a function exists twice in both the CLIENT and SERVER realm\n ],\n // TODO: runtime.path\n });\n fs.writeFileSync(path.join(options.output, 'config.json'), JSON.stringify(config, null, 2));\n const files = walk(options.input, (file, isDirectory) => isDirectory || (file.endsWith(`.lua`)));", "score": 0.7122222185134888 } ]
typescript
description ? `${putCommentBeforeEachLine(item.description, false)}\n` : '';
import { ClassFunction, Enum, Function, HookFunction, LibraryFunction, Panel, PanelFunction, Realm, Struct, WikiPage, isPanel } from '../scrapers/wiki-page-markup-scraper.js'; import { putCommentBeforeEachLine, removeNewlines, safeFileName, toLowerCamelCase } from '../utils/string.js'; import { isClassFunction, isHookFunction, isLibraryFunction, isPanelFunction, isStruct, isEnum, } from '../scrapers/wiki-page-markup-scraper.js'; export const RESERVERD_KEYWORDS = new Set([ 'and', 'break', 'continue', 'do', 'else', 'elseif', 'end', 'false', 'for', 'function', 'goto', 'if', 'in', 'local', 'nil', 'not', 'or', 'repeat', 'return', 'then', 'true', 'until', 'while' ]); export class GluaApiWriter { private readonly writtenClasses: Set<string> = new Set(); private readonly writtenLibraryGlobals: Set<string> = new Set(); private readonly pageOverrides: Map<string, string> = new Map(); constructor() { } public static safeName(name: string) { if (name.includes('/')) name = name.replace(/\//g, ' or '); if (name.includes('=')) name = name.split('=')[0]; if (name.includes(' ')) name =
toLowerCamelCase(name);
// Remove any remaining characters not valid in a Lua variable/function name. name = name.replace(/[^A-Za-z\d_.]/g, ''); if (RESERVERD_KEYWORDS.has(name)) return `_${name}`; return name; } public addOverride(pageAddress: string, override: string) { this.pageOverrides.set(safeFileName(pageAddress, '.'), override); } public writePage(page: WikiPage) { const fileSafeAddress = safeFileName(page.address, '.'); if (this.pageOverrides.has(fileSafeAddress)) { let api = ''; if (isClassFunction(page)) api += this.writeClass(page.parent); else if (isLibraryFunction(page)) api += this.writeLibraryGlobal(page); api += this.pageOverrides.get(fileSafeAddress); return `${api}\n\n`; } else if (isClassFunction(page)) return this.writeClassFunction(page); else if (isLibraryFunction(page)) return this.writeLibraryFunction(page); else if (isHookFunction(page)) return this.writeHookFunction(page); else if (isPanel(page)) return this.writePanel(page); else if (isPanelFunction(page)) return this.writePanelFunction(page); else if (isEnum(page)) return this.writeEnum(page); else if (isStruct(page)) return this.writeStruct(page); } private writeClass(className: string, parent?: string, classFields: string = '') { let api: string = ''; if (!this.writtenClasses.has(className)) { const classOverride = `class.${className}`; if (this.pageOverrides.has(classOverride)) { api += this.pageOverrides.get(classOverride)!.replace(/\n$/g, '') + '\n\n'; api = api.replace('---{{CLASS_FIELDS}}\n', classFields); } else { api += `---@class ${className}`; if (parent) api += ` : ${parent}`; api += '\n'; api += classFields; api += `local ${className} = {}\n\n`; } this.writtenClasses.add(className); } return api; } private writeLibraryGlobal(func: LibraryFunction) { if (!func.dontDefineParent && !this.writtenLibraryGlobals.has(func.parent)) { const global = `${func.parent} = {}\n\n`; this.writtenLibraryGlobals.add(func.parent); return global; } return ''; } private writeClassFunction(func: ClassFunction) { let api: string = this.writeClass(func.parent); api += this.writeFunctionLuaDocComment(func, func.realm); api += this.writeFunctionDeclaration(func, func.realm, ':'); return api; } private writeLibraryFunction(func: LibraryFunction) { let api: string = this.writeLibraryGlobal(func); api += this.writeFunctionLuaDocComment(func, func.realm); api += this.writeFunctionDeclaration(func, func.realm); return api; } private writeHookFunction(func: HookFunction) { return this.writeClassFunction(func); } private writePanel(panel: Panel) { return this.writeClass(panel.name, panel.parent); } private writePanelFunction(func: PanelFunction) { let api: string = ''; api += this.writeFunctionLuaDocComment(func, func.realm); api += this.writeFunctionDeclaration(func, func.realm, ':'); return api; } private writeEnum(_enum: Enum) { let api: string = ''; const isContainedInTable = _enum.items[0]?.key.includes('.') ?? false; api += `---@enum ${_enum.name}\n`; if (isContainedInTable) api += `local ${_enum.name} = {\n`; const writeItem = (key: string, item: typeof _enum.items[0]) => { if (isContainedInTable) { key = key.split('.')[1]; api += ` ${key} = ${item.value}, ` + (item.description ? `--[[ ${item.description} ]]` : '') + '\n'; } else { const comment = item.description ? `${putCommentBeforeEachLine(item.description, false)}\n` : ''; api += `${comment}${key} = ${item.value}\n`; } }; for (const item of _enum.items) writeItem(item.key, item); if (isContainedInTable) api += '}'; api += `\n\n`; return api; } private writeStruct(struct: Struct) { let fields: string = ''; for (const field of struct.fields) { fields += `---@field ${GluaApiWriter.safeName(field.name)} ${this.transformType(field.type)} ${removeNewlines(field.description!)}\n`; } return this.writeClass(struct.name, undefined, fields); } public writePages(pages: WikiPage[]) { let api: string = ''; for (const page of pages) { api += this.writePage(page); } return api; } private transformType(type: string) { if (type === 'vararg') return '...'; return type; } private writeFunctionLuaDocComment(func: Function, realm: Realm) { let luaDocComment = `---[${realm.toUpperCase()}] ${putCommentBeforeEachLine(func.description!.trim())}\n`; luaDocComment += `---\n---[(View on wiki)](${func.url})\n`; if (func.arguments) { func.arguments.forEach((arg, index) => { if (!arg.name) arg.name = arg.type; if (arg.type === 'vararg') arg.name = '...'; luaDocComment += `---@param ${GluaApiWriter.safeName(arg.name)}${arg.default !== undefined ? `?` : ''} ${this.transformType(arg.type)} ${putCommentBeforeEachLine(arg.description!)}\n`; }); } if (func.returns) { const returns = `---@return ${func.returns.map(ret => this.transformType(ret.type)).join(', ')}`; func.returns.forEach(ret => { const description = removeNewlines(ret.description ?? ''); if (func.returns!.length === 1) { luaDocComment += `${returns} #${description}\n`; return; } luaDocComment += `${returns} #${this.transformType(ret.type)} - ${description}\n`; }); } return luaDocComment; } private writeFunctionDeclaration(func: Function, realm: Realm, indexer: string = '.') { let declaration = `function ${func.parent ? `${func.parent}${indexer}` : ''}${GluaApiWriter.safeName(func.name)}(`; if (func.arguments) { declaration += func.arguments.map(arg => { if (arg.type === 'vararg') return '...'; return GluaApiWriter.safeName(arg.name!); }).join(', '); } declaration += ') end\n\n'; return declaration; } }
src/api-writer/glua-api-writer.ts
luttje-glua-api-snippets-9f40376
[ { "filename": "src/utils/string.ts", "retrieved_chunk": "/**\n * Converts a string to lowerCamelCase \n * \n * @param str The string to convert\n * @returns The converted string\n */\nexport function toLowerCamelCase(str: string) {\n str = str.replace(/[_-]/g, ' ');\n return str.replace(/(?:^\\w|\\b\\w)/g, (letter, index) => {\n return index === 0 ? letter.toLowerCase() : letter.toUpperCase();", "score": 0.7767382264137268 }, { "filename": "src/utils/filesystem.ts", "retrieved_chunk": " * @param windowsPath The Windows path to convert.\n * @returns The Unix path.\n */\nexport function convertWindowsToUnixPath(windowsPath: string) {\n let unixPath = windowsPath;\n unixPath = unixPath.replace(/^[A-Z]:/, (match) => match.toLowerCase());\n unixPath = unixPath.replace(/\\\\/g, '/');\n let colonIndex = unixPath.indexOf(':');\n if (colonIndex > -1)\n unixPath = unixPath.replace(/:/, '');", "score": 0.7730112075805664 }, { "filename": "src/cli-scraper.ts", "retrieved_chunk": " return;\n const api = writer.writePages(pageMarkups);\n let fileName = pageIndex.address;\n let moduleName = fileName;\n if (fileName.includes('.') || fileName.includes(':') || fileName.includes('/')) {\n [moduleName, fileName] = fileName.split(/[:.\\/]/, 2);\n }\n // Make sure modules like Entity and ENTITY are placed in the same file.\n moduleName = moduleName.toLowerCase();\n const moduleFile = path.join(baseDirectory, moduleName);", "score": 0.7608904838562012 }, { "filename": "src/scrapers/traverse-scraper.ts", "retrieved_chunk": " if (url.endsWith('/'))\n url = url.substring(0, url.length - 1);\n if (url.includes('#'))\n url = url.substring(0, url.indexOf('#'));\n if (this.traversedUrls.has(url))\n return false;\n if (this.childPageFilter && !this.childPageFilter(url))\n return false;\n return url;\n }", "score": 0.7120975255966187 }, { "filename": "src/utils/string.ts", "retrieved_chunk": " */\nexport function putCommentBeforeEachLine(text: string, skipLineOne: boolean = true) {\n return text.split(/\\r?\\n/g).map((line, index) => {\n if (index === 0 && skipLineOne)\n return line;\n return `--- ${line}`;\n }).join('\\n');\n}\n/**\n * Makes a string safe for use as a file name", "score": 0.7031224370002747 } ]
typescript
toLowerCamelCase(name);
import { exec } from 'child_process'; import { GolemFile, GolemTarget, isGolemTarget } from './types'; import { ChatGPTMessage, ChatGPT_completion } from './chat_gpt'; import { readFile } from 'fs/promises'; import { dirname } from 'path'; import logger from './logger'; import { generateCacheKey, isCacheValid, saveOutputToCache, loadOutputFromCache, appendToGolemFile } from './utils'; import { writeFileSync} from 'fs'; // TODO 1: Check if prompt asks for additional targets. // TODO 2: Check if targets have other dependencies. // TODO 3: Saving properly (for example, it saves all of the previous context for imp task) // TODO 4: Use different files interface ExecutionContext { [key: string]: any; } const mainPrompt: ChatGPTMessage = { role: 'system', content: `You are an Agentic LLM assistant, designed only to produce code and helpful information. You may be asked to generate new targets. If the prompt given to you contains the phrase 'generate new targets', your response will be to generate a list of targets to help answer the prompt. The targets must be written as unnumbered items separated by lines starting with 'Target:'. The items in the list will not be arranged in any particular order. For example: Prompt: As an agentic LLM, generate new targets for the next iteration. Response: Target: Write a function to divide two numbers. Target: Create a class called Employee. Target: Write unit tests for the function GetPeopleInterests. It is not always the case that you will be asked to generate new targets. If the prompt does not contain the phrase 'generate new targets', then proceed to answer the prompt as truthfully as possible. For example: Prompt: What is capital of France? Response: Paris. Prompt: How many days are in the month of April? Response: 30 days. You are opinionated. If asked to provide a subjective answer, start by saying 'In my opinion' then answer the prompt. For example: Prompt: What is the best sport? Response: In my opinion, soccer. ` } export async function executeTarget(target:
string, golemFile: GolemFile, golemFilePath: string, context: Map<string, any> = new Map()): Promise<void> {
const golemTarget = golemFile[target]; if (!golemTarget) { throw new Error(`Target "${target}" not found in Golem file.`); } console.log(`Executing target: ${target}`); if (golemTarget.dependencies) { console.log(`Dependencies for ${target}: ${golemTarget.dependencies}`); for (const dependency of golemTarget.dependencies) { if (dependency) { await executeTarget(dependency, golemFile, golemFilePath, context); } } } await executeAIChatWithCache(target, golemFile, golemFilePath, context); console.log(`Context after ${target} execution:`, context); } function executeCommand(command: string): Promise<void> { return new Promise((resolve, reject) => { exec(command, (error, stdout, stderr) => { if (error) { logger.error(`Error executing command: ${command}`); logger.error(stderr); reject(error); } else { logger.debug(stdout); resolve(); } }); }); } async function executeAIChatWithCache(target: string, golemFile: GolemFile, golemFilePath: string, context: Map<string, any>): Promise<void> { const golemFileToArray: any = []; for (const key in golemFile){ const val = golemFile[key as keyof typeof golemFile]; golemFileToArray.push(val); } const golemTarget = golemFile[target]; if (!golemTarget || !isGolemTarget(golemTarget)) { return; } const cacheKey = generateCacheKey(target, golemTarget.dependencies || [], [...golemFileToArray] || ''); if (isCacheValid(target, cacheKey)) { console.log("Returning Cached output"); const cachedOutput = loadOutputFromCache(target, cacheKey); context.set(target, cachedOutput); } else { await executeAIChat(target, golemFile, golemFilePath, context); saveOutputToCache(target, cacheKey, context); } } async function executeAIChat(target: string, golemFile: GolemFile, golemFilePath: string, context: Map<string, any>): Promise<void> { // ============== Setup start ==================================== const contextOfCurrentTarget: string[] = []; const allOutputs: {[key: string]: any} = {}; const golemTarget = golemFile[target]; console.log("gT", golemTarget); if (!golemTarget) { throw new Error(`Target "${target}" not found in Golem file.`); } if (!isGolemTarget(golemTarget)) { return; } if (!golemTarget.prompt && !golemTarget.model) { golemTarget.model = 'cat'; } let prompt = golemTarget.prompt ?? "{no prompt}"; if (isGolemTarget(golemTarget) && golemTarget.prompt) { prompt = golemTarget.prompt; const placeholderRegex = /{{\s*([\w\/.-]+)\s*}}/g; let match; while ((match = placeholderRegex.exec(prompt)) !== null) { const key = match[1]; if (context.has(key)) { prompt = prompt.replace(match[0], context.get(key)); } else { prompt = prompt.replace(match[0], ""); } } } else if (!golemTarget.prompt) { const defaultValues = new Map(context.entries()); context.set("default", Object.fromEntries(defaultValues)); return; } const model = golemTarget.model ?? 'gpt-3.5-turbo'; // ============== Setup end ==================================== if (model === 'cat') { const concatenatedOutput = golemTarget.dependencies.map(dep => context.get(dep)).join(''); context.set(target, concatenatedOutput); } else if (model == "gpt-3.5-turbo" || model == "gpt-3.5-turbo-0301" || model == "gpt-4-0314" || model == "gpt-4-32k") { if ("model" in golemTarget) { delete golemTarget.model; } // This gets the 'keys' (subtasks) of a target (task) const golemTargetKeys: string[] = Object.keys(golemTarget); // It starts from 1 as index 0 is dependencies. This can be changed if needed for (let i = 1; i < golemTargetKeys.length; i++){ // console.log("gTKi", golemTargetKeys[i]); const val: any = golemTarget[golemTargetKeys[i] as keyof typeof golemTarget]; // console.log("val", val); const previousContext: string | undefined = contextOfCurrentTarget[0] || ''; // Concat the previousContext (if undefined) to the current subtask (here, named val) const content = previousContext + val; // console.log("content", content); // This block of code replaces the {{}} placeholders in the string from the yaml file // with the output of the subtask or task it requires const replacedString = content.replace(/{{(.*?)}}/g, (match, p1) => { // Remove the curly braces from the placeholder const placeholder = p1.trim(); // Replace the placeholder with the corresponding value from the map return context.get(placeholder) || placeholder; }); // console.log("context", context); // console.log("replacedString", replacedString); const taskGenerationMessages: ChatGPTMessage[] = [ mainPrompt, { role: 'user', content: replacedString, }, ]; const response = await ChatGPT_completion(taskGenerationMessages, model, 0.7, 0.9); contextOfCurrentTarget.length = 0; //clear the previous context contextOfCurrentTarget.push(response); //append the new context to be used in the next iteration allOutputs[golemTargetKeys[i]] = response; const lines: string[] = response.split('\n'); // Extract the targets from the lines that start with "Target:" const targets: string[] = lines.filter((line: string) => line.startsWith("Target:")) .map((line: string) => line.slice(8)); let count = 1; targets.forEach((createdTarget: string) => { const targetName = target.concat("_target".concat(count.toString())); const newTarget: string = `\n${targetName}:\n dependencies: []\n prompt: ${createdTarget}`; appendToGolemFile(golemFilePath, newTarget); golemTargetKeys.push(targetName); golemTarget[targetName] = createdTarget; count += 1; }); if (golemTargetKeys.length === 2){ if (!response) { context.set(target, `Default value for ${target}`); } else { context.set(target, response); console.log(context); } } else if (golemTargetKeys.length > 2){ try { for (const key in allOutputs) { context.set(key, allOutputs[key]); } }catch (error: any) { logger.error(`Error generating AI response: ${error.message}`); } } } }else { throw new Error(`No such supported model ${model}`); } }
src/executor.ts
Confabulation-Corporation-golem-ac8b554
[ { "filename": "src/golem.ts", "retrieved_chunk": " 'Run the specified Golem file or the default Golem file if none is provided.',\n (yargs) => {\n yargs.positional('golemFile', {\n describe: 'Path to the Golem file',\n default: 'Golem.yaml',\n type: 'string',\n });\n },\n async (argv) => {\n try {", "score": 0.7717010378837585 }, { "filename": "src/types.ts", "retrieved_chunk": "export interface GolemTarget {\n dependencies: string[];\n prompt: string;\n model?: string; // Add this line\n task_generation_prompt?: string; // Add this line\n [key: string]: string[] | string | undefined;\n}\nexport type GolemFile = {\n default: string[];\n} & {", "score": 0.7671269774436951 }, { "filename": "src/parser.ts", "retrieved_chunk": "import * as yaml from 'js-yaml';\nimport { GolemFile } from './types';\nexport function parseGolemFile(content: string): GolemFile {\n try {\n const parsedContent = yaml.load(content) as GolemFile;\n // Update the parsing logic to handle the task_generation_prompt field\n return parsedContent;\n } catch (error: any) {\n throw new Error(`Error parsing Golem file: ${error.message}`);\n }", "score": 0.7486770153045654 }, { "filename": "src/chat_gpt.ts", "retrieved_chunk": " const waitTime = resetMs + Math.random() * 1000;\n logger.warn(\n `Rate limit or server error encountered (status: ${error.response.status}). Retrying in ${waitTime} ms...`\n );\n await new Promise((resolve) => setTimeout(resolve, waitTime));\n } else {\n throw error;\n }\n }\n }", "score": 0.7462683916091919 }, { "filename": "src/validator.ts", "retrieved_chunk": "import { GolemFile } from './types';\n// import { GolemFileError } from './errors';\nexport function validateGolemFile(golemFile: GolemFile): void {\n // Validate the Golem file structure and content\n // If any errors are found, throw a GolemFileError with a specific error message\n}", "score": 0.7454922199249268 } ]
typescript
string, golemFile: GolemFile, golemFilePath: string, context: Map<string, any> = new Map()): Promise<void> {
import { exec } from 'child_process'; import { GolemFile, GolemTarget, isGolemTarget } from './types'; import { ChatGPTMessage, ChatGPT_completion } from './chat_gpt'; import { readFile } from 'fs/promises'; import { dirname } from 'path'; import logger from './logger'; import { generateCacheKey, isCacheValid, saveOutputToCache, loadOutputFromCache, appendToGolemFile } from './utils'; import { writeFileSync} from 'fs'; // TODO 1: Check if prompt asks for additional targets. // TODO 2: Check if targets have other dependencies. // TODO 3: Saving properly (for example, it saves all of the previous context for imp task) // TODO 4: Use different files interface ExecutionContext { [key: string]: any; } const mainPrompt: ChatGPTMessage = { role: 'system', content: `You are an Agentic LLM assistant, designed only to produce code and helpful information. You may be asked to generate new targets. If the prompt given to you contains the phrase 'generate new targets', your response will be to generate a list of targets to help answer the prompt. The targets must be written as unnumbered items separated by lines starting with 'Target:'. The items in the list will not be arranged in any particular order. For example: Prompt: As an agentic LLM, generate new targets for the next iteration. Response: Target: Write a function to divide two numbers. Target: Create a class called Employee. Target: Write unit tests for the function GetPeopleInterests. It is not always the case that you will be asked to generate new targets. If the prompt does not contain the phrase 'generate new targets', then proceed to answer the prompt as truthfully as possible. For example: Prompt: What is capital of France? Response: Paris. Prompt: How many days are in the month of April? Response: 30 days. You are opinionated. If asked to provide a subjective answer, start by saying 'In my opinion' then answer the prompt. For example: Prompt: What is the best sport? Response: In my opinion, soccer. ` } export async function executeTarget(target: string, golemFile: GolemFile, golemFilePath: string, context: Map<string, any> = new Map()): Promise<void> { const golemTarget = golemFile[target]; if (!golemTarget) { throw new Error(`Target "${target}" not found in Golem file.`); } console.log(`Executing target: ${target}`); if (golemTarget.dependencies) { console.log(`Dependencies for ${target}: ${golemTarget.dependencies}`); for (const dependency of golemTarget.dependencies) { if (dependency) { await executeTarget(dependency, golemFile, golemFilePath, context); } } } await executeAIChatWithCache(target, golemFile, golemFilePath, context); console.log(`Context after ${target} execution:`, context); } function executeCommand(command: string): Promise<void> { return new Promise((resolve, reject) => { exec(command, (error, stdout, stderr) => { if (error) { logger.error(`Error executing command: ${command}`); logger.error(stderr); reject(error); } else { logger.debug(stdout); resolve(); } }); }); } async function executeAIChatWithCache(target: string, golemFile: GolemFile, golemFilePath: string, context: Map<string, any>): Promise<void> { const golemFileToArray: any = []; for (const key in golemFile){ const val = golemFile[key as keyof typeof golemFile]; golemFileToArray.push(val); } const golemTarget = golemFile[target]; if (!golemTarget || !isGolemTarget(golemTarget)) { return; } const cacheKey = generateCacheKey(target, golemTarget.dependencies || [], [...golemFileToArray] || ''); if (isCacheValid(target, cacheKey)) { console.log("Returning Cached output"); const cachedOutput = loadOutputFromCache(target, cacheKey); context.set(target, cachedOutput); } else { await executeAIChat(target, golemFile, golemFilePath, context); saveOutputToCache(target, cacheKey, context); } } async function executeAIChat(target: string, golemFile: GolemFile, golemFilePath: string, context: Map<string, any>): Promise<void> { // ============== Setup start ==================================== const contextOfCurrentTarget: string[] = []; const allOutputs: {[key: string]: any} = {}; const golemTarget = golemFile[target]; console.log("gT", golemTarget); if (!golemTarget) { throw new Error(`Target "${target}" not found in Golem file.`); } if (!isGolemTarget(golemTarget)) { return; } if (!golemTarget.prompt && !golemTarget.model) { golemTarget.model = 'cat'; } let prompt = golemTarget.prompt ?? "{no prompt}"; if (isGolemTarget(golemTarget) && golemTarget.prompt) { prompt = golemTarget.prompt; const placeholderRegex = /{{\s*([\w\/.-]+)\s*}}/g; let match; while ((match = placeholderRegex.exec(prompt)) !== null) { const key = match[1]; if (context.has(key)) { prompt = prompt.replace(match[0], context.get(key)); } else { prompt = prompt.replace(match[0], ""); } } } else if (!golemTarget.prompt) { const defaultValues = new Map(context.entries()); context.set("default", Object.fromEntries(defaultValues)); return; } const model = golemTarget.model ?? 'gpt-3.5-turbo'; // ============== Setup end ==================================== if (model === 'cat') {
const concatenatedOutput = golemTarget.dependencies.map(dep => context.get(dep)).join('');
context.set(target, concatenatedOutput); } else if (model == "gpt-3.5-turbo" || model == "gpt-3.5-turbo-0301" || model == "gpt-4-0314" || model == "gpt-4-32k") { if ("model" in golemTarget) { delete golemTarget.model; } // This gets the 'keys' (subtasks) of a target (task) const golemTargetKeys: string[] = Object.keys(golemTarget); // It starts from 1 as index 0 is dependencies. This can be changed if needed for (let i = 1; i < golemTargetKeys.length; i++){ // console.log("gTKi", golemTargetKeys[i]); const val: any = golemTarget[golemTargetKeys[i] as keyof typeof golemTarget]; // console.log("val", val); const previousContext: string | undefined = contextOfCurrentTarget[0] || ''; // Concat the previousContext (if undefined) to the current subtask (here, named val) const content = previousContext + val; // console.log("content", content); // This block of code replaces the {{}} placeholders in the string from the yaml file // with the output of the subtask or task it requires const replacedString = content.replace(/{{(.*?)}}/g, (match, p1) => { // Remove the curly braces from the placeholder const placeholder = p1.trim(); // Replace the placeholder with the corresponding value from the map return context.get(placeholder) || placeholder; }); // console.log("context", context); // console.log("replacedString", replacedString); const taskGenerationMessages: ChatGPTMessage[] = [ mainPrompt, { role: 'user', content: replacedString, }, ]; const response = await ChatGPT_completion(taskGenerationMessages, model, 0.7, 0.9); contextOfCurrentTarget.length = 0; //clear the previous context contextOfCurrentTarget.push(response); //append the new context to be used in the next iteration allOutputs[golemTargetKeys[i]] = response; const lines: string[] = response.split('\n'); // Extract the targets from the lines that start with "Target:" const targets: string[] = lines.filter((line: string) => line.startsWith("Target:")) .map((line: string) => line.slice(8)); let count = 1; targets.forEach((createdTarget: string) => { const targetName = target.concat("_target".concat(count.toString())); const newTarget: string = `\n${targetName}:\n dependencies: []\n prompt: ${createdTarget}`; appendToGolemFile(golemFilePath, newTarget); golemTargetKeys.push(targetName); golemTarget[targetName] = createdTarget; count += 1; }); if (golemTargetKeys.length === 2){ if (!response) { context.set(target, `Default value for ${target}`); } else { context.set(target, response); console.log(context); } } else if (golemTargetKeys.length > 2){ try { for (const key in allOutputs) { context.set(key, allOutputs[key]); } }catch (error: any) { logger.error(`Error generating AI response: ${error.message}`); } } } }else { throw new Error(`No such supported model ${model}`); } }
src/executor.ts
Confabulation-Corporation-golem-ac8b554
[ { "filename": "src/dependencies.ts", "retrieved_chunk": "import { GolemFile, isGolemTarget } from './types';\nimport { GolemError } from './errors';\nexport function resolveDependencies(golemFile: GolemFile): string[] {\n const resolvedDependencies: string[] = [];\n if (!golemFile.default) {\n throw new GolemError(\"No default target specified\");\n }\n const defaultTarget = golemFile.default;\n if (isGolemTarget(defaultTarget)) {\n const defaultDependencies = defaultTarget.dependencies;", "score": 0.7984263896942139 }, { "filename": "src/parser.ts", "retrieved_chunk": "import * as yaml from 'js-yaml';\nimport { GolemFile } from './types';\nexport function parseGolemFile(content: string): GolemFile {\n try {\n const parsedContent = yaml.load(content) as GolemFile;\n // Update the parsing logic to handle the task_generation_prompt field\n return parsedContent;\n } catch (error: any) {\n throw new Error(`Error parsing Golem file: ${error.message}`);\n }", "score": 0.73673415184021 }, { "filename": "src/utils.ts", "retrieved_chunk": " return join('.golem', `${target}_${cacheKey}_output.txt`);\n}\nexport function isCacheValid(target: string, cacheKey: string): boolean {\n const cachedOutputPath = getCachedOutputPath(target, cacheKey);\n return existsSync(cachedOutputPath);\n}\nexport function saveOutputToCache(target: string, cacheKey: string, context: Map<string, any>): void {\n const cachedOutputPath = getCachedOutputPath(target, cacheKey);\n const defaultMap = new Map();\n if (context.has(\"default\")) {", "score": 0.7367087602615356 }, { "filename": "src/golem.ts", "retrieved_chunk": " const golemFilePath = argv.golemFile as string;\n // console.log(golemFilePath);\n // Add this line to create the .golem/ directory\n createGolemCacheDir();\n // Read the Golem file content\n const golemFileContent = fs.readFileSync(golemFilePath, 'utf8');\n const golemFile = parseGolemFile(golemFileContent);\n console.log(golemFile);\n // Execute the default target with an empty context\n await executeTarget('default', golemFile, golemFilePath, new Map());", "score": 0.7361568212509155 }, { "filename": "src/types.ts", "retrieved_chunk": " [target: string]: GolemTarget | undefined;\n};\nexport function isGolemTarget(target: GolemTarget | string[] | undefined): target is GolemTarget {\n return target !== undefined && (target as GolemTarget).dependencies !== undefined;\n}", "score": 0.6970298290252686 } ]
typescript
const concatenatedOutput = golemTarget.dependencies.map(dep => context.get(dep)).join('');
import { ClassFunction, Enum, Function, HookFunction, LibraryFunction, Panel, PanelFunction, Realm, Struct, WikiPage, isPanel } from '../scrapers/wiki-page-markup-scraper.js'; import { putCommentBeforeEachLine, removeNewlines, safeFileName, toLowerCamelCase } from '../utils/string.js'; import { isClassFunction, isHookFunction, isLibraryFunction, isPanelFunction, isStruct, isEnum, } from '../scrapers/wiki-page-markup-scraper.js'; export const RESERVERD_KEYWORDS = new Set([ 'and', 'break', 'continue', 'do', 'else', 'elseif', 'end', 'false', 'for', 'function', 'goto', 'if', 'in', 'local', 'nil', 'not', 'or', 'repeat', 'return', 'then', 'true', 'until', 'while' ]); export class GluaApiWriter { private readonly writtenClasses: Set<string> = new Set(); private readonly writtenLibraryGlobals: Set<string> = new Set(); private readonly pageOverrides: Map<string, string> = new Map(); constructor() { } public static safeName(name: string) { if (name.includes('/')) name = name.replace(/\//g, ' or '); if (name.includes('=')) name = name.split('=')[0]; if (name.includes(' ')) name = toLowerCamelCase(name); // Remove any remaining characters not valid in a Lua variable/function name. name = name.replace(/[^A-Za-z\d_.]/g, ''); if (RESERVERD_KEYWORDS.has(name)) return `_${name}`; return name; } public addOverride(pageAddress: string, override: string) { this.pageOverrides.set(safeFileName(pageAddress, '.'), override); } public writePage(page: WikiPage) { const fileSafeAddress = safeFileName(page.address, '.'); if (this.pageOverrides.has(fileSafeAddress)) { let api = ''; if (isClassFunction(page)) api += this.writeClass(page.parent); else if (isLibraryFunction(page)) api += this.writeLibraryGlobal(page); api += this.pageOverrides.get(fileSafeAddress); return `${api}\n\n`; } else if (isClassFunction(page)) return this.writeClassFunction(page); else if (isLibraryFunction(page)) return this.writeLibraryFunction(page); else if (isHookFunction(page)) return this.writeHookFunction(page); else if (isPanel(page)) return this.writePanel(page); else if (isPanelFunction(page)) return this.writePanelFunction(page); else if (isEnum(page)) return this.writeEnum(page); else if (isStruct(page)) return this.writeStruct(page); } private writeClass(className: string, parent?: string, classFields: string = '') { let api: string = ''; if (!this.writtenClasses.has(className)) { const classOverride = `class.${className}`; if (this.pageOverrides.has(classOverride)) { api += this.pageOverrides.get(classOverride)!.replace(/\n$/g, '') + '\n\n'; api = api.replace('---{{CLASS_FIELDS}}\n', classFields); } else { api += `---@class ${className}`; if (parent) api += ` : ${parent}`; api += '\n'; api += classFields; api += `local ${className} = {}\n\n`; } this.writtenClasses.add(className); } return api; } private writeLibraryGlobal(func: LibraryFunction) { if (!func.dontDefineParent && !this.writtenLibraryGlobals.has(func.parent)) { const global = `${func.parent} = {}\n\n`; this.writtenLibraryGlobals.add(func.parent); return global; } return ''; } private writeClassFunction(func: ClassFunction) { let api: string = this.writeClass(func.parent); api += this.writeFunctionLuaDocComment(func, func.realm); api += this.writeFunctionDeclaration(func, func.realm, ':'); return api; } private writeLibraryFunction(func: LibraryFunction) { let api: string = this.writeLibraryGlobal(func); api += this.writeFunctionLuaDocComment(func, func.realm); api += this.writeFunctionDeclaration(func, func.realm); return api; } private writeHookFunction(func: HookFunction) { return this.writeClassFunction(func); } private writePanel(panel: Panel) { return this.writeClass(panel.name, panel.parent); } private writePanelFunction(func: PanelFunction) { let api: string = ''; api += this.writeFunctionLuaDocComment(func, func.realm); api += this.writeFunctionDeclaration(func, func.realm, ':'); return api; } private writeEnum(_enum: Enum) { let api: string = ''; const isContainedInTable = _enum.items[0]?.key.includes('.') ?? false; api += `---@enum ${_enum.name}\n`; if (isContainedInTable) api += `local ${_enum.name} = {\n`; const writeItem = (key: string, item: typeof _enum.items[0]) => { if (isContainedInTable) { key = key.split('.')[1]; api += ` ${key} = ${item.value}, ` + (item.description ? `--[[ ${item.description} ]]` : '') + '\n'; } else { const comment = item.description ? `${putCommentBeforeEachLine(item.description, false)}\n` : ''; api += `${comment}${key} = ${item.value}\n`; } }; for (const item of _enum.items) writeItem(item.key, item); if (isContainedInTable) api += '}'; api += `\n\n`; return api; } private writeStruct(struct: Struct) { let fields: string = ''; for (const field of struct.fields) { fields += `---@field ${GluaApiWriter.safeName(field.name)} ${this.transformType(field.type)} ${removeNewlines(field.description!)}\n`; } return this.writeClass(struct.name, undefined, fields); }
public writePages(pages: WikiPage[]) {
let api: string = ''; for (const page of pages) { api += this.writePage(page); } return api; } private transformType(type: string) { if (type === 'vararg') return '...'; return type; } private writeFunctionLuaDocComment(func: Function, realm: Realm) { let luaDocComment = `---[${realm.toUpperCase()}] ${putCommentBeforeEachLine(func.description!.trim())}\n`; luaDocComment += `---\n---[(View on wiki)](${func.url})\n`; if (func.arguments) { func.arguments.forEach((arg, index) => { if (!arg.name) arg.name = arg.type; if (arg.type === 'vararg') arg.name = '...'; luaDocComment += `---@param ${GluaApiWriter.safeName(arg.name)}${arg.default !== undefined ? `?` : ''} ${this.transformType(arg.type)} ${putCommentBeforeEachLine(arg.description!)}\n`; }); } if (func.returns) { const returns = `---@return ${func.returns.map(ret => this.transformType(ret.type)).join(', ')}`; func.returns.forEach(ret => { const description = removeNewlines(ret.description ?? ''); if (func.returns!.length === 1) { luaDocComment += `${returns} #${description}\n`; return; } luaDocComment += `${returns} #${this.transformType(ret.type)} - ${description}\n`; }); } return luaDocComment; } private writeFunctionDeclaration(func: Function, realm: Realm, indexer: string = '.') { let declaration = `function ${func.parent ? `${func.parent}${indexer}` : ''}${GluaApiWriter.safeName(func.name)}(`; if (func.arguments) { declaration += func.arguments.map(arg => { if (arg.type === 'vararg') return '...'; return GluaApiWriter.safeName(arg.name!); }).join(', '); } declaration += ') end\n\n'; return declaration; } }
src/api-writer/glua-api-writer.ts
luttje-glua-api-snippets-9f40376
[ { "filename": "src/scrapers/wiki-page-markup-scraper.ts", "retrieved_chunk": "}\nexport function isEnum(page: WikiPage): page is Enum {\n return page.type === 'enum';\n}\nexport function isStruct(page: WikiPage): page is Struct {\n return page.type === 'struct';\n}\n/**\n * Scraper\n */", "score": 0.7695742845535278 }, { "filename": "src/scrapers/wiki-page-markup-scraper.ts", "retrieved_chunk": " type: string;\n default?: any;\n description: string;\n};\nexport type Struct = CommonWikiProperties & {\n type: 'struct';\n fields: StructField[];\n};\nexport type Panel = CommonWikiProperties & {\n type: 'panel';", "score": 0.7306668758392334 }, { "filename": "src/cli-scraper.ts", "retrieved_chunk": " const fileContent = fs.readFileSync(filePath, { encoding: 'utf-8' });\n const pageName = file.replace(/\\.lua$/, '');\n writer.addOverride(pageName, fileContent);\n }\n }\n const pageIndexes = await scrapeAndCollect(pageListScraper);\n for (const pageIndex of pageIndexes) {\n const pageMarkupScraper = new WikiPageMarkupScraper(`${baseUrl}/${pageIndex.address}?format=text`);\n pageMarkupScraper.on('scraped', (url, pageMarkups) => {\n if (pageMarkups.length === 0)", "score": 0.7233238220214844 }, { "filename": "src/scrapers/wiki-history-scraper.ts", "retrieved_chunk": " public history: WikiHistory[] = [];\n constructor(url: string, title: string) {\n super(url, title);\n }\n}\nexport class WikiHistoryPageScraper extends PageTraverseScraper<WikiHistoryPage> {\n constructor(baseUrl: string) {\n super(baseUrl, (url: string, title: string) => new WikiHistoryPage(url, title));\n }\n /**", "score": 0.7213826775550842 }, { "filename": "src/scrapers/wiki-page-markup-scraper.ts", "retrieved_chunk": " key: string;\n value: string;\n description: string;\n};\nexport type Enum = CommonWikiProperties & {\n type: 'enum';\n items: EnumValue[];\n};\nexport type StructField = {\n name: string;", "score": 0.7205450534820557 } ]
typescript
public writePages(pages: WikiPage[]) {
import { exec } from 'child_process'; import { GolemFile, GolemTarget, isGolemTarget } from './types'; import { ChatGPTMessage, ChatGPT_completion } from './chat_gpt'; import { readFile } from 'fs/promises'; import { dirname } from 'path'; import logger from './logger'; import { generateCacheKey, isCacheValid, saveOutputToCache, loadOutputFromCache, appendToGolemFile } from './utils'; import { writeFileSync} from 'fs'; // TODO 1: Check if prompt asks for additional targets. // TODO 2: Check if targets have other dependencies. // TODO 3: Saving properly (for example, it saves all of the previous context for imp task) // TODO 4: Use different files interface ExecutionContext { [key: string]: any; } const mainPrompt: ChatGPTMessage = { role: 'system', content: `You are an Agentic LLM assistant, designed only to produce code and helpful information. You may be asked to generate new targets. If the prompt given to you contains the phrase 'generate new targets', your response will be to generate a list of targets to help answer the prompt. The targets must be written as unnumbered items separated by lines starting with 'Target:'. The items in the list will not be arranged in any particular order. For example: Prompt: As an agentic LLM, generate new targets for the next iteration. Response: Target: Write a function to divide two numbers. Target: Create a class called Employee. Target: Write unit tests for the function GetPeopleInterests. It is not always the case that you will be asked to generate new targets. If the prompt does not contain the phrase 'generate new targets', then proceed to answer the prompt as truthfully as possible. For example: Prompt: What is capital of France? Response: Paris. Prompt: How many days are in the month of April? Response: 30 days. You are opinionated. If asked to provide a subjective answer, start by saying 'In my opinion' then answer the prompt. For example: Prompt: What is the best sport? Response: In my opinion, soccer. ` } export async function executeTarget(target: string, golemFile: GolemFile, golemFilePath: string, context: Map<string, any> = new Map()): Promise<void> { const golemTarget = golemFile[target]; if (!golemTarget) { throw new Error(`Target "${target}" not found in Golem file.`); } console.log(`Executing target: ${target}`); if (golemTarget.dependencies) { console.log(`Dependencies for ${target}: ${golemTarget.dependencies}`); for (const dependency of golemTarget.dependencies) { if (dependency) { await executeTarget(dependency, golemFile, golemFilePath, context); } } } await executeAIChatWithCache(target, golemFile, golemFilePath, context); console.log(`Context after ${target} execution:`, context); } function executeCommand(command: string): Promise<void> { return new Promise((resolve, reject) => { exec(command, (error, stdout, stderr) => { if (error) { logger.error(`Error executing command: ${command}`); logger.error(stderr); reject(error); } else { logger.debug(stdout); resolve(); } }); }); } async function executeAIChatWithCache(target: string, golemFile: GolemFile, golemFilePath: string, context: Map<string, any>): Promise<void> { const golemFileToArray: any = []; for (const key in golemFile){ const val = golemFile[key as keyof typeof golemFile]; golemFileToArray.push(val); } const golemTarget = golemFile[target]; if (!golemTarget ||
!isGolemTarget(golemTarget)) {
return; } const cacheKey = generateCacheKey(target, golemTarget.dependencies || [], [...golemFileToArray] || ''); if (isCacheValid(target, cacheKey)) { console.log("Returning Cached output"); const cachedOutput = loadOutputFromCache(target, cacheKey); context.set(target, cachedOutput); } else { await executeAIChat(target, golemFile, golemFilePath, context); saveOutputToCache(target, cacheKey, context); } } async function executeAIChat(target: string, golemFile: GolemFile, golemFilePath: string, context: Map<string, any>): Promise<void> { // ============== Setup start ==================================== const contextOfCurrentTarget: string[] = []; const allOutputs: {[key: string]: any} = {}; const golemTarget = golemFile[target]; console.log("gT", golemTarget); if (!golemTarget) { throw new Error(`Target "${target}" not found in Golem file.`); } if (!isGolemTarget(golemTarget)) { return; } if (!golemTarget.prompt && !golemTarget.model) { golemTarget.model = 'cat'; } let prompt = golemTarget.prompt ?? "{no prompt}"; if (isGolemTarget(golemTarget) && golemTarget.prompt) { prompt = golemTarget.prompt; const placeholderRegex = /{{\s*([\w\/.-]+)\s*}}/g; let match; while ((match = placeholderRegex.exec(prompt)) !== null) { const key = match[1]; if (context.has(key)) { prompt = prompt.replace(match[0], context.get(key)); } else { prompt = prompt.replace(match[0], ""); } } } else if (!golemTarget.prompt) { const defaultValues = new Map(context.entries()); context.set("default", Object.fromEntries(defaultValues)); return; } const model = golemTarget.model ?? 'gpt-3.5-turbo'; // ============== Setup end ==================================== if (model === 'cat') { const concatenatedOutput = golemTarget.dependencies.map(dep => context.get(dep)).join(''); context.set(target, concatenatedOutput); } else if (model == "gpt-3.5-turbo" || model == "gpt-3.5-turbo-0301" || model == "gpt-4-0314" || model == "gpt-4-32k") { if ("model" in golemTarget) { delete golemTarget.model; } // This gets the 'keys' (subtasks) of a target (task) const golemTargetKeys: string[] = Object.keys(golemTarget); // It starts from 1 as index 0 is dependencies. This can be changed if needed for (let i = 1; i < golemTargetKeys.length; i++){ // console.log("gTKi", golemTargetKeys[i]); const val: any = golemTarget[golemTargetKeys[i] as keyof typeof golemTarget]; // console.log("val", val); const previousContext: string | undefined = contextOfCurrentTarget[0] || ''; // Concat the previousContext (if undefined) to the current subtask (here, named val) const content = previousContext + val; // console.log("content", content); // This block of code replaces the {{}} placeholders in the string from the yaml file // with the output of the subtask or task it requires const replacedString = content.replace(/{{(.*?)}}/g, (match, p1) => { // Remove the curly braces from the placeholder const placeholder = p1.trim(); // Replace the placeholder with the corresponding value from the map return context.get(placeholder) || placeholder; }); // console.log("context", context); // console.log("replacedString", replacedString); const taskGenerationMessages: ChatGPTMessage[] = [ mainPrompt, { role: 'user', content: replacedString, }, ]; const response = await ChatGPT_completion(taskGenerationMessages, model, 0.7, 0.9); contextOfCurrentTarget.length = 0; //clear the previous context contextOfCurrentTarget.push(response); //append the new context to be used in the next iteration allOutputs[golemTargetKeys[i]] = response; const lines: string[] = response.split('\n'); // Extract the targets from the lines that start with "Target:" const targets: string[] = lines.filter((line: string) => line.startsWith("Target:")) .map((line: string) => line.slice(8)); let count = 1; targets.forEach((createdTarget: string) => { const targetName = target.concat("_target".concat(count.toString())); const newTarget: string = `\n${targetName}:\n dependencies: []\n prompt: ${createdTarget}`; appendToGolemFile(golemFilePath, newTarget); golemTargetKeys.push(targetName); golemTarget[targetName] = createdTarget; count += 1; }); if (golemTargetKeys.length === 2){ if (!response) { context.set(target, `Default value for ${target}`); } else { context.set(target, response); console.log(context); } } else if (golemTargetKeys.length > 2){ try { for (const key in allOutputs) { context.set(key, allOutputs[key]); } }catch (error: any) { logger.error(`Error generating AI response: ${error.message}`); } } } }else { throw new Error(`No such supported model ${model}`); } }
src/executor.ts
Confabulation-Corporation-golem-ac8b554
[ { "filename": "src/dependencies.ts", "retrieved_chunk": "import { GolemFile, isGolemTarget } from './types';\nimport { GolemError } from './errors';\nexport function resolveDependencies(golemFile: GolemFile): string[] {\n const resolvedDependencies: string[] = [];\n if (!golemFile.default) {\n throw new GolemError(\"No default target specified\");\n }\n const defaultTarget = golemFile.default;\n if (isGolemTarget(defaultTarget)) {\n const defaultDependencies = defaultTarget.dependencies;", "score": 0.827380895614624 }, { "filename": "src/golem.ts", "retrieved_chunk": " const golemFilePath = argv.golemFile as string;\n // console.log(golemFilePath);\n // Add this line to create the .golem/ directory\n createGolemCacheDir();\n // Read the Golem file content\n const golemFileContent = fs.readFileSync(golemFilePath, 'utf8');\n const golemFile = parseGolemFile(golemFileContent);\n console.log(golemFile);\n // Execute the default target with an empty context\n await executeTarget('default', golemFile, golemFilePath, new Map());", "score": 0.8182529211044312 }, { "filename": "src/types.ts", "retrieved_chunk": " [target: string]: GolemTarget | undefined;\n};\nexport function isGolemTarget(target: GolemTarget | string[] | undefined): target is GolemTarget {\n return target !== undefined && (target as GolemTarget).dependencies !== undefined;\n}", "score": 0.756656289100647 }, { "filename": "src/parser.ts", "retrieved_chunk": "import * as yaml from 'js-yaml';\nimport { GolemFile } from './types';\nexport function parseGolemFile(content: string): GolemFile {\n try {\n const parsedContent = yaml.load(content) as GolemFile;\n // Update the parsing logic to handle the task_generation_prompt field\n return parsedContent;\n } catch (error: any) {\n throw new Error(`Error parsing Golem file: ${error.message}`);\n }", "score": 0.7442235946655273 }, { "filename": "src/validator.ts", "retrieved_chunk": "import { GolemFile } from './types';\n// import { GolemFileError } from './errors';\nexport function validateGolemFile(golemFile: GolemFile): void {\n // Validate the Golem file structure and content\n // If any errors are found, throw a GolemFileError with a specific error message\n}", "score": 0.7286158800125122 } ]
typescript
!isGolemTarget(golemTarget)) {
import { ClassFunction, Enum, Function, HookFunction, LibraryFunction, Panel, PanelFunction, Realm, Struct, WikiPage, isPanel } from '../scrapers/wiki-page-markup-scraper.js'; import { putCommentBeforeEachLine, removeNewlines, safeFileName, toLowerCamelCase } from '../utils/string.js'; import { isClassFunction, isHookFunction, isLibraryFunction, isPanelFunction, isStruct, isEnum, } from '../scrapers/wiki-page-markup-scraper.js'; export const RESERVERD_KEYWORDS = new Set([ 'and', 'break', 'continue', 'do', 'else', 'elseif', 'end', 'false', 'for', 'function', 'goto', 'if', 'in', 'local', 'nil', 'not', 'or', 'repeat', 'return', 'then', 'true', 'until', 'while' ]); export class GluaApiWriter { private readonly writtenClasses: Set<string> = new Set(); private readonly writtenLibraryGlobals: Set<string> = new Set(); private readonly pageOverrides: Map<string, string> = new Map(); constructor() { } public static safeName(name: string) { if (name.includes('/')) name = name.replace(/\//g, ' or '); if (name.includes('=')) name = name.split('=')[0]; if (name.includes(' ')) name = toLowerCamelCase(name); // Remove any remaining characters not valid in a Lua variable/function name. name = name.replace(/[^A-Za-z\d_.]/g, ''); if (RESERVERD_KEYWORDS.has(name)) return `_${name}`; return name; } public addOverride(pageAddress: string, override: string) { this.
pageOverrides.set(safeFileName(pageAddress, '.'), override);
} public writePage(page: WikiPage) { const fileSafeAddress = safeFileName(page.address, '.'); if (this.pageOverrides.has(fileSafeAddress)) { let api = ''; if (isClassFunction(page)) api += this.writeClass(page.parent); else if (isLibraryFunction(page)) api += this.writeLibraryGlobal(page); api += this.pageOverrides.get(fileSafeAddress); return `${api}\n\n`; } else if (isClassFunction(page)) return this.writeClassFunction(page); else if (isLibraryFunction(page)) return this.writeLibraryFunction(page); else if (isHookFunction(page)) return this.writeHookFunction(page); else if (isPanel(page)) return this.writePanel(page); else if (isPanelFunction(page)) return this.writePanelFunction(page); else if (isEnum(page)) return this.writeEnum(page); else if (isStruct(page)) return this.writeStruct(page); } private writeClass(className: string, parent?: string, classFields: string = '') { let api: string = ''; if (!this.writtenClasses.has(className)) { const classOverride = `class.${className}`; if (this.pageOverrides.has(classOverride)) { api += this.pageOverrides.get(classOverride)!.replace(/\n$/g, '') + '\n\n'; api = api.replace('---{{CLASS_FIELDS}}\n', classFields); } else { api += `---@class ${className}`; if (parent) api += ` : ${parent}`; api += '\n'; api += classFields; api += `local ${className} = {}\n\n`; } this.writtenClasses.add(className); } return api; } private writeLibraryGlobal(func: LibraryFunction) { if (!func.dontDefineParent && !this.writtenLibraryGlobals.has(func.parent)) { const global = `${func.parent} = {}\n\n`; this.writtenLibraryGlobals.add(func.parent); return global; } return ''; } private writeClassFunction(func: ClassFunction) { let api: string = this.writeClass(func.parent); api += this.writeFunctionLuaDocComment(func, func.realm); api += this.writeFunctionDeclaration(func, func.realm, ':'); return api; } private writeLibraryFunction(func: LibraryFunction) { let api: string = this.writeLibraryGlobal(func); api += this.writeFunctionLuaDocComment(func, func.realm); api += this.writeFunctionDeclaration(func, func.realm); return api; } private writeHookFunction(func: HookFunction) { return this.writeClassFunction(func); } private writePanel(panel: Panel) { return this.writeClass(panel.name, panel.parent); } private writePanelFunction(func: PanelFunction) { let api: string = ''; api += this.writeFunctionLuaDocComment(func, func.realm); api += this.writeFunctionDeclaration(func, func.realm, ':'); return api; } private writeEnum(_enum: Enum) { let api: string = ''; const isContainedInTable = _enum.items[0]?.key.includes('.') ?? false; api += `---@enum ${_enum.name}\n`; if (isContainedInTable) api += `local ${_enum.name} = {\n`; const writeItem = (key: string, item: typeof _enum.items[0]) => { if (isContainedInTable) { key = key.split('.')[1]; api += ` ${key} = ${item.value}, ` + (item.description ? `--[[ ${item.description} ]]` : '') + '\n'; } else { const comment = item.description ? `${putCommentBeforeEachLine(item.description, false)}\n` : ''; api += `${comment}${key} = ${item.value}\n`; } }; for (const item of _enum.items) writeItem(item.key, item); if (isContainedInTable) api += '}'; api += `\n\n`; return api; } private writeStruct(struct: Struct) { let fields: string = ''; for (const field of struct.fields) { fields += `---@field ${GluaApiWriter.safeName(field.name)} ${this.transformType(field.type)} ${removeNewlines(field.description!)}\n`; } return this.writeClass(struct.name, undefined, fields); } public writePages(pages: WikiPage[]) { let api: string = ''; for (const page of pages) { api += this.writePage(page); } return api; } private transformType(type: string) { if (type === 'vararg') return '...'; return type; } private writeFunctionLuaDocComment(func: Function, realm: Realm) { let luaDocComment = `---[${realm.toUpperCase()}] ${putCommentBeforeEachLine(func.description!.trim())}\n`; luaDocComment += `---\n---[(View on wiki)](${func.url})\n`; if (func.arguments) { func.arguments.forEach((arg, index) => { if (!arg.name) arg.name = arg.type; if (arg.type === 'vararg') arg.name = '...'; luaDocComment += `---@param ${GluaApiWriter.safeName(arg.name)}${arg.default !== undefined ? `?` : ''} ${this.transformType(arg.type)} ${putCommentBeforeEachLine(arg.description!)}\n`; }); } if (func.returns) { const returns = `---@return ${func.returns.map(ret => this.transformType(ret.type)).join(', ')}`; func.returns.forEach(ret => { const description = removeNewlines(ret.description ?? ''); if (func.returns!.length === 1) { luaDocComment += `${returns} #${description}\n`; return; } luaDocComment += `${returns} #${this.transformType(ret.type)} - ${description}\n`; }); } return luaDocComment; } private writeFunctionDeclaration(func: Function, realm: Realm, indexer: string = '.') { let declaration = `function ${func.parent ? `${func.parent}${indexer}` : ''}${GluaApiWriter.safeName(func.name)}(`; if (func.arguments) { declaration += func.arguments.map(arg => { if (arg.type === 'vararg') return '...'; return GluaApiWriter.safeName(arg.name!); }).join(', '); } declaration += ') end\n\n'; return declaration; } }
src/api-writer/glua-api-writer.ts
luttje-glua-api-snippets-9f40376
[ { "filename": "src/utils/string.ts", "retrieved_chunk": "/**\n * Converts a string to lowerCamelCase \n * \n * @param str The string to convert\n * @returns The converted string\n */\nexport function toLowerCamelCase(str: string) {\n str = str.replace(/[_-]/g, ' ');\n return str.replace(/(?:^\\w|\\b\\w)/g, (letter, index) => {\n return index === 0 ? letter.toLowerCase() : letter.toUpperCase();", "score": 0.7858216762542725 }, { "filename": "src/utils/string.ts", "retrieved_chunk": " * \n * @param str The string to make safe\n * @param replacement The string to replace unsafe characters with\n * @returns The safe string\n */\nexport function safeFileName(str: string, replacement: string = '_') {\n return str.replace(/[^a-z0-9_\\-\\. ]/gi, replacement);\n}", "score": 0.7692766785621643 }, { "filename": "src/cli-scraper.ts", "retrieved_chunk": " return;\n const api = writer.writePages(pageMarkups);\n let fileName = pageIndex.address;\n let moduleName = fileName;\n if (fileName.includes('.') || fileName.includes(':') || fileName.includes('/')) {\n [moduleName, fileName] = fileName.split(/[:.\\/]/, 2);\n }\n // Make sure modules like Entity and ENTITY are placed in the same file.\n moduleName = moduleName.toLowerCase();\n const moduleFile = path.join(baseDirectory, moduleName);", "score": 0.7393801212310791 }, { "filename": "src/utils/string.ts", "retrieved_chunk": " */\nexport function putCommentBeforeEachLine(text: string, skipLineOne: boolean = true) {\n return text.split(/\\r?\\n/g).map((line, index) => {\n if (index === 0 && skipLineOne)\n return line;\n return `--- ${line}`;\n }).join('\\n');\n}\n/**\n * Makes a string safe for use as a file name", "score": 0.7304653525352478 }, { "filename": "src/utils/filesystem.ts", "retrieved_chunk": " * @param windowsPath The Windows path to convert.\n * @returns The Unix path.\n */\nexport function convertWindowsToUnixPath(windowsPath: string) {\n let unixPath = windowsPath;\n unixPath = unixPath.replace(/^[A-Z]:/, (match) => match.toLowerCase());\n unixPath = unixPath.replace(/\\\\/g, '/');\n let colonIndex = unixPath.indexOf(':');\n if (colonIndex > -1)\n unixPath = unixPath.replace(/:/, '');", "score": 0.7196184992790222 } ]
typescript
pageOverrides.set(safeFileName(pageAddress, '.'), override);
import { ClassFunction, Enum, Function, HookFunction, LibraryFunction, Panel, PanelFunction, Realm, Struct, WikiPage, isPanel } from '../scrapers/wiki-page-markup-scraper.js'; import { putCommentBeforeEachLine, removeNewlines, safeFileName, toLowerCamelCase } from '../utils/string.js'; import { isClassFunction, isHookFunction, isLibraryFunction, isPanelFunction, isStruct, isEnum, } from '../scrapers/wiki-page-markup-scraper.js'; export const RESERVERD_KEYWORDS = new Set([ 'and', 'break', 'continue', 'do', 'else', 'elseif', 'end', 'false', 'for', 'function', 'goto', 'if', 'in', 'local', 'nil', 'not', 'or', 'repeat', 'return', 'then', 'true', 'until', 'while' ]); export class GluaApiWriter { private readonly writtenClasses: Set<string> = new Set(); private readonly writtenLibraryGlobals: Set<string> = new Set(); private readonly pageOverrides: Map<string, string> = new Map(); constructor() { } public static safeName(name: string) { if (name.includes('/')) name = name.replace(/\//g, ' or '); if (name.includes('=')) name = name.split('=')[0]; if (name.includes(' ')) name = toLowerCamelCase(name); // Remove any remaining characters not valid in a Lua variable/function name. name = name.replace(/[^A-Za-z\d_.]/g, ''); if (RESERVERD_KEYWORDS.has(name)) return `_${name}`; return name; } public addOverride(pageAddress: string, override: string) { this.pageOverrides.set(safeFileName(pageAddress, '.'), override); }
public writePage(page: WikiPage) {
const fileSafeAddress = safeFileName(page.address, '.'); if (this.pageOverrides.has(fileSafeAddress)) { let api = ''; if (isClassFunction(page)) api += this.writeClass(page.parent); else if (isLibraryFunction(page)) api += this.writeLibraryGlobal(page); api += this.pageOverrides.get(fileSafeAddress); return `${api}\n\n`; } else if (isClassFunction(page)) return this.writeClassFunction(page); else if (isLibraryFunction(page)) return this.writeLibraryFunction(page); else if (isHookFunction(page)) return this.writeHookFunction(page); else if (isPanel(page)) return this.writePanel(page); else if (isPanelFunction(page)) return this.writePanelFunction(page); else if (isEnum(page)) return this.writeEnum(page); else if (isStruct(page)) return this.writeStruct(page); } private writeClass(className: string, parent?: string, classFields: string = '') { let api: string = ''; if (!this.writtenClasses.has(className)) { const classOverride = `class.${className}`; if (this.pageOverrides.has(classOverride)) { api += this.pageOverrides.get(classOverride)!.replace(/\n$/g, '') + '\n\n'; api = api.replace('---{{CLASS_FIELDS}}\n', classFields); } else { api += `---@class ${className}`; if (parent) api += ` : ${parent}`; api += '\n'; api += classFields; api += `local ${className} = {}\n\n`; } this.writtenClasses.add(className); } return api; } private writeLibraryGlobal(func: LibraryFunction) { if (!func.dontDefineParent && !this.writtenLibraryGlobals.has(func.parent)) { const global = `${func.parent} = {}\n\n`; this.writtenLibraryGlobals.add(func.parent); return global; } return ''; } private writeClassFunction(func: ClassFunction) { let api: string = this.writeClass(func.parent); api += this.writeFunctionLuaDocComment(func, func.realm); api += this.writeFunctionDeclaration(func, func.realm, ':'); return api; } private writeLibraryFunction(func: LibraryFunction) { let api: string = this.writeLibraryGlobal(func); api += this.writeFunctionLuaDocComment(func, func.realm); api += this.writeFunctionDeclaration(func, func.realm); return api; } private writeHookFunction(func: HookFunction) { return this.writeClassFunction(func); } private writePanel(panel: Panel) { return this.writeClass(panel.name, panel.parent); } private writePanelFunction(func: PanelFunction) { let api: string = ''; api += this.writeFunctionLuaDocComment(func, func.realm); api += this.writeFunctionDeclaration(func, func.realm, ':'); return api; } private writeEnum(_enum: Enum) { let api: string = ''; const isContainedInTable = _enum.items[0]?.key.includes('.') ?? false; api += `---@enum ${_enum.name}\n`; if (isContainedInTable) api += `local ${_enum.name} = {\n`; const writeItem = (key: string, item: typeof _enum.items[0]) => { if (isContainedInTable) { key = key.split('.')[1]; api += ` ${key} = ${item.value}, ` + (item.description ? `--[[ ${item.description} ]]` : '') + '\n'; } else { const comment = item.description ? `${putCommentBeforeEachLine(item.description, false)}\n` : ''; api += `${comment}${key} = ${item.value}\n`; } }; for (const item of _enum.items) writeItem(item.key, item); if (isContainedInTable) api += '}'; api += `\n\n`; return api; } private writeStruct(struct: Struct) { let fields: string = ''; for (const field of struct.fields) { fields += `---@field ${GluaApiWriter.safeName(field.name)} ${this.transformType(field.type)} ${removeNewlines(field.description!)}\n`; } return this.writeClass(struct.name, undefined, fields); } public writePages(pages: WikiPage[]) { let api: string = ''; for (const page of pages) { api += this.writePage(page); } return api; } private transformType(type: string) { if (type === 'vararg') return '...'; return type; } private writeFunctionLuaDocComment(func: Function, realm: Realm) { let luaDocComment = `---[${realm.toUpperCase()}] ${putCommentBeforeEachLine(func.description!.trim())}\n`; luaDocComment += `---\n---[(View on wiki)](${func.url})\n`; if (func.arguments) { func.arguments.forEach((arg, index) => { if (!arg.name) arg.name = arg.type; if (arg.type === 'vararg') arg.name = '...'; luaDocComment += `---@param ${GluaApiWriter.safeName(arg.name)}${arg.default !== undefined ? `?` : ''} ${this.transformType(arg.type)} ${putCommentBeforeEachLine(arg.description!)}\n`; }); } if (func.returns) { const returns = `---@return ${func.returns.map(ret => this.transformType(ret.type)).join(', ')}`; func.returns.forEach(ret => { const description = removeNewlines(ret.description ?? ''); if (func.returns!.length === 1) { luaDocComment += `${returns} #${description}\n`; return; } luaDocComment += `${returns} #${this.transformType(ret.type)} - ${description}\n`; }); } return luaDocComment; } private writeFunctionDeclaration(func: Function, realm: Realm, indexer: string = '.') { let declaration = `function ${func.parent ? `${func.parent}${indexer}` : ''}${GluaApiWriter.safeName(func.name)}(`; if (func.arguments) { declaration += func.arguments.map(arg => { if (arg.type === 'vararg') return '...'; return GluaApiWriter.safeName(arg.name!); }).join(', '); } declaration += ') end\n\n'; return declaration; } }
src/api-writer/glua-api-writer.ts
luttje-glua-api-snippets-9f40376
[ { "filename": "src/utils/string.ts", "retrieved_chunk": " * \n * @param str The string to make safe\n * @param replacement The string to replace unsafe characters with\n * @returns The safe string\n */\nexport function safeFileName(str: string, replacement: string = '_') {\n return str.replace(/[^a-z0-9_\\-\\. ]/gi, replacement);\n}", "score": 0.7691828608512878 }, { "filename": "src/utils/string.ts", "retrieved_chunk": " */\nexport function putCommentBeforeEachLine(text: string, skipLineOne: boolean = true) {\n return text.split(/\\r?\\n/g).map((line, index) => {\n if (index === 0 && skipLineOne)\n return line;\n return `--- ${line}`;\n }).join('\\n');\n}\n/**\n * Makes a string safe for use as a file name", "score": 0.7577286958694458 }, { "filename": "src/utils/string.ts", "retrieved_chunk": "/**\n * Converts a string to lowerCamelCase \n * \n * @param str The string to convert\n * @returns The converted string\n */\nexport function toLowerCamelCase(str: string) {\n str = str.replace(/[_-]/g, ' ');\n return str.replace(/(?:^\\w|\\b\\w)/g, (letter, index) => {\n return index === 0 ? letter.toLowerCase() : letter.toUpperCase();", "score": 0.7484024167060852 }, { "filename": "src/cli-scraper.ts", "retrieved_chunk": " const fileStat = fs.statSync(filePath);\n if (fileStat.isDirectory()) {\n console.warn(`Skipping directory ${file} in custom (not supported)`);\n continue;\n }\n // Besides the prefix helping us discern between overrides and files to copy, it also prevents conflicts with the wiki pages (since none of them start with _)\n if (file.startsWith('_')) {\n fs.copyFileSync(filePath, path.join(baseDirectory, file));\n continue;\n }", "score": 0.7321420907974243 }, { "filename": "src/cli-scraper.ts", "retrieved_chunk": " return;\n const api = writer.writePages(pageMarkups);\n let fileName = pageIndex.address;\n let moduleName = fileName;\n if (fileName.includes('.') || fileName.includes(':') || fileName.includes('/')) {\n [moduleName, fileName] = fileName.split(/[:.\\/]/, 2);\n }\n // Make sure modules like Entity and ENTITY are placed in the same file.\n moduleName = moduleName.toLowerCase();\n const moduleFile = path.join(baseDirectory, moduleName);", "score": 0.7283949851989746 } ]
typescript
public writePage(page: WikiPage) {
import { ClassFunction, Enum, Function, HookFunction, LibraryFunction, Panel, PanelFunction, Realm, Struct, WikiPage, isPanel } from '../scrapers/wiki-page-markup-scraper.js'; import { putCommentBeforeEachLine, removeNewlines, safeFileName, toLowerCamelCase } from '../utils/string.js'; import { isClassFunction, isHookFunction, isLibraryFunction, isPanelFunction, isStruct, isEnum, } from '../scrapers/wiki-page-markup-scraper.js'; export const RESERVERD_KEYWORDS = new Set([ 'and', 'break', 'continue', 'do', 'else', 'elseif', 'end', 'false', 'for', 'function', 'goto', 'if', 'in', 'local', 'nil', 'not', 'or', 'repeat', 'return', 'then', 'true', 'until', 'while' ]); export class GluaApiWriter { private readonly writtenClasses: Set<string> = new Set(); private readonly writtenLibraryGlobals: Set<string> = new Set(); private readonly pageOverrides: Map<string, string> = new Map(); constructor() { } public static safeName(name: string) { if (name.includes('/')) name = name.replace(/\//g, ' or '); if (name.includes('=')) name = name.split('=')[0]; if (name.includes(' ')) name = toLowerCamelCase(name); // Remove any remaining characters not valid in a Lua variable/function name. name = name.replace(/[^A-Za-z\d_.]/g, ''); if (RESERVERD_KEYWORDS.has(name)) return `_${name}`; return name; } public addOverride(pageAddress: string, override: string) { this.pageOverrides.set(safeFileName(pageAddress, '.'), override); } public writePage(page: WikiPage) { const fileSafeAddress = safeFileName(page.address, '.'); if (this.pageOverrides.has(fileSafeAddress)) { let api = ''; if (isClassFunction(page)) api += this.writeClass(page.parent); else if (isLibraryFunction(page)) api += this.writeLibraryGlobal(page); api += this.pageOverrides.get(fileSafeAddress); return `${api}\n\n`; } else if (isClassFunction(page)) return this.writeClassFunction(page); else if (isLibraryFunction(page)) return this.writeLibraryFunction(page); else if (isHookFunction(page)) return this.writeHookFunction(page); else if (isPanel(page)) return this.writePanel(page); else if (isPanelFunction(page)) return this.writePanelFunction(page); else if (isEnum(page)) return this.writeEnum(page); else if (isStruct(page)) return this.writeStruct(page); } private writeClass(className: string, parent?: string, classFields: string = '') { let api: string = ''; if (!this.writtenClasses.has(className)) { const classOverride = `class.${className}`; if (this.pageOverrides.has(classOverride)) { api += this.pageOverrides.get(classOverride)!.replace(/\n$/g, '') + '\n\n'; api = api.replace('---{{CLASS_FIELDS}}\n', classFields); } else { api += `---@class ${className}`; if (parent) api += ` : ${parent}`; api += '\n'; api += classFields; api += `local ${className} = {}\n\n`; } this.writtenClasses.add(className); } return api; } private writeLibraryGlobal(func: LibraryFunction) { if (!func.dontDefineParent && !this.writtenLibraryGlobals.has(func.parent)) { const global = `${func.parent} = {}\n\n`; this.writtenLibraryGlobals.add(func.parent); return global; } return ''; } private writeClassFunction(func: ClassFunction) { let api: string = this.writeClass(func.parent); api += this.writeFunctionLuaDocComment(func, func.realm); api += this.writeFunctionDeclaration(func, func.realm, ':'); return api; } private writeLibraryFunction(func: LibraryFunction) { let api: string = this.writeLibraryGlobal(func); api += this.writeFunctionLuaDocComment(func, func.realm); api += this.writeFunctionDeclaration(func, func.realm); return api; } private writeHookFunction(func: HookFunction) { return this.writeClassFunction(func); } private writePanel(panel: Panel) { return this.writeClass(panel.name, panel.parent); } private writePanelFunction(func: PanelFunction) { let api: string = ''; api += this.writeFunctionLuaDocComment(func, func.realm); api += this.writeFunctionDeclaration(func, func.realm, ':'); return api; } private
writeEnum(_enum: Enum) {
let api: string = ''; const isContainedInTable = _enum.items[0]?.key.includes('.') ?? false; api += `---@enum ${_enum.name}\n`; if (isContainedInTable) api += `local ${_enum.name} = {\n`; const writeItem = (key: string, item: typeof _enum.items[0]) => { if (isContainedInTable) { key = key.split('.')[1]; api += ` ${key} = ${item.value}, ` + (item.description ? `--[[ ${item.description} ]]` : '') + '\n'; } else { const comment = item.description ? `${putCommentBeforeEachLine(item.description, false)}\n` : ''; api += `${comment}${key} = ${item.value}\n`; } }; for (const item of _enum.items) writeItem(item.key, item); if (isContainedInTable) api += '}'; api += `\n\n`; return api; } private writeStruct(struct: Struct) { let fields: string = ''; for (const field of struct.fields) { fields += `---@field ${GluaApiWriter.safeName(field.name)} ${this.transformType(field.type)} ${removeNewlines(field.description!)}\n`; } return this.writeClass(struct.name, undefined, fields); } public writePages(pages: WikiPage[]) { let api: string = ''; for (const page of pages) { api += this.writePage(page); } return api; } private transformType(type: string) { if (type === 'vararg') return '...'; return type; } private writeFunctionLuaDocComment(func: Function, realm: Realm) { let luaDocComment = `---[${realm.toUpperCase()}] ${putCommentBeforeEachLine(func.description!.trim())}\n`; luaDocComment += `---\n---[(View on wiki)](${func.url})\n`; if (func.arguments) { func.arguments.forEach((arg, index) => { if (!arg.name) arg.name = arg.type; if (arg.type === 'vararg') arg.name = '...'; luaDocComment += `---@param ${GluaApiWriter.safeName(arg.name)}${arg.default !== undefined ? `?` : ''} ${this.transformType(arg.type)} ${putCommentBeforeEachLine(arg.description!)}\n`; }); } if (func.returns) { const returns = `---@return ${func.returns.map(ret => this.transformType(ret.type)).join(', ')}`; func.returns.forEach(ret => { const description = removeNewlines(ret.description ?? ''); if (func.returns!.length === 1) { luaDocComment += `${returns} #${description}\n`; return; } luaDocComment += `${returns} #${this.transformType(ret.type)} - ${description}\n`; }); } return luaDocComment; } private writeFunctionDeclaration(func: Function, realm: Realm, indexer: string = '.') { let declaration = `function ${func.parent ? `${func.parent}${indexer}` : ''}${GluaApiWriter.safeName(func.name)}(`; if (func.arguments) { declaration += func.arguments.map(arg => { if (arg.type === 'vararg') return '...'; return GluaApiWriter.safeName(arg.name!); }).join(', '); } declaration += ') end\n\n'; return declaration; } }
src/api-writer/glua-api-writer.ts
luttje-glua-api-snippets-9f40376
[ { "filename": "src/scrapers/wiki-page-markup-scraper.ts", "retrieved_chunk": " parent: string;\n};\nexport type WikiPage = ClassFunction | LibraryFunction | HookFunction | PanelFunction | Panel | Enum | Struct;\n/**\n * Guards\n */\nexport function isClassFunction(page: WikiPage): page is ClassFunction {\n return page.type === 'classfunc';\n}\nexport function isLibraryFunction(page: WikiPage): page is LibraryFunction {", "score": 0.7595343589782715 }, { "filename": "src/scrapers/wiki-page-markup-scraper.ts", "retrieved_chunk": " return page.type === 'libraryfunc';\n}\nexport function isHookFunction(page: WikiPage): page is HookFunction {\n return page.type === 'hook';\n}\nexport function isPanelFunction(page: WikiPage): page is PanelFunction {\n return page.type === 'panelfunc';\n}\nexport function isPanel(page: WikiPage): page is Panel {\n return page.type === 'panel';", "score": 0.7558764219284058 }, { "filename": "src/scrapers/wiki-page-markup-scraper.ts", "retrieved_chunk": " realm: $('realm:first').text() as Realm,\n arguments: arguments_,\n returns\n };\n if (isClassFunction) {\n return <ClassFunction> {\n ...base,\n type: 'classfunc'\n };\n } else if (isLibraryFunction) {", "score": 0.7449499368667603 }, { "filename": "src/scrapers/wiki-page-markup-scraper.ts", "retrieved_chunk": "}\nexport function isEnum(page: WikiPage): page is Enum {\n return page.type === 'enum';\n}\nexport function isStruct(page: WikiPage): page is Struct {\n return page.type === 'struct';\n}\n/**\n * Scraper\n */", "score": 0.7364747524261475 }, { "filename": "src/scrapers/wiki-page-markup-scraper.ts", "retrieved_chunk": "export type FunctionReturn = WikiIdentifier & {};\nexport type Function = CommonWikiProperties & {\n parent: string;\n arguments?: FunctionArgument[];\n returns?: FunctionReturn[];\n};\nexport type ClassFunction = Function & {};\nexport type LibraryFunction = Function & {\n type: 'libraryfunc';\n dontDefineParent?: boolean;", "score": 0.7346560955047607 } ]
typescript
writeEnum(_enum: Enum) {
import { ClassFunction, Enum, Function, HookFunction, LibraryFunction, Panel, PanelFunction, Realm, Struct, WikiPage, isPanel } from '../scrapers/wiki-page-markup-scraper.js'; import { putCommentBeforeEachLine, removeNewlines, safeFileName, toLowerCamelCase } from '../utils/string.js'; import { isClassFunction, isHookFunction, isLibraryFunction, isPanelFunction, isStruct, isEnum, } from '../scrapers/wiki-page-markup-scraper.js'; export const RESERVERD_KEYWORDS = new Set([ 'and', 'break', 'continue', 'do', 'else', 'elseif', 'end', 'false', 'for', 'function', 'goto', 'if', 'in', 'local', 'nil', 'not', 'or', 'repeat', 'return', 'then', 'true', 'until', 'while' ]); export class GluaApiWriter { private readonly writtenClasses: Set<string> = new Set(); private readonly writtenLibraryGlobals: Set<string> = new Set(); private readonly pageOverrides: Map<string, string> = new Map(); constructor() { } public static safeName(name: string) { if (name.includes('/')) name = name.replace(/\//g, ' or '); if (name.includes('=')) name = name.split('=')[0]; if (name.includes(' ')) name = toLowerCamelCase(name); // Remove any remaining characters not valid in a Lua variable/function name. name = name.replace(/[^A-Za-z\d_.]/g, ''); if (RESERVERD_KEYWORDS.has(name)) return `_${name}`; return name; } public addOverride(pageAddress: string, override: string) { this.pageOverrides.set(safeFileName(pageAddress, '.'), override); } public writePage(page: WikiPage) { const fileSafeAddress = safeFileName(page.address, '.'); if (this.pageOverrides.has(fileSafeAddress)) { let api = ''; if (isClassFunction(page)) api += this.writeClass(page.parent); else if (isLibraryFunction(page)) api += this.writeLibraryGlobal(page); api += this.pageOverrides.get(fileSafeAddress); return `${api}\n\n`; } else if (isClassFunction(page)) return this.writeClassFunction(page); else if (isLibraryFunction(page)) return this.writeLibraryFunction(page); else if (isHookFunction(page)) return this.writeHookFunction(page); else if (isPanel(page)) return this.writePanel(page); else if (isPanelFunction(page)) return this.writePanelFunction(page); else if (isEnum(page)) return this.writeEnum(page); else if (isStruct(page)) return this.writeStruct(page); } private writeClass(className: string, parent?: string, classFields: string = '') { let api: string = ''; if (!this.writtenClasses.has(className)) { const classOverride = `class.${className}`; if (this.pageOverrides.has(classOverride)) { api += this.pageOverrides.get(classOverride)!.replace(/\n$/g, '') + '\n\n'; api = api.replace('---{{CLASS_FIELDS}}\n', classFields); } else { api += `---@class ${className}`; if (parent) api += ` : ${parent}`; api += '\n'; api += classFields; api += `local ${className} = {}\n\n`; } this.writtenClasses.add(className); } return api; } private writeLibraryGlobal(func: LibraryFunction) { if (!func.dontDefineParent && !this.writtenLibraryGlobals.has(func.parent)) { const global = `${func.parent} = {}\n\n`; this.writtenLibraryGlobals.add(func.parent); return global; } return ''; } private writeClassFunction(func: ClassFunction) { let api: string = this.writeClass(func.parent); api += this.writeFunctionLuaDocComment(func, func.realm); api += this.writeFunctionDeclaration(func, func.realm, ':'); return api; } private writeLibraryFunction(func: LibraryFunction) { let api: string = this.writeLibraryGlobal(func); api += this.writeFunctionLuaDocComment(func, func.realm); api += this.writeFunctionDeclaration(func, func.realm); return api; } private writeHookFunction(func: HookFunction) { return this.writeClassFunction(func); } private writePanel(panel: Panel) { return this.writeClass(panel.name, panel.parent); } private writePanelFunction(func: PanelFunction) { let api: string = ''; api += this.writeFunctionLuaDocComment(func, func.realm); api += this.writeFunctionDeclaration(func, func.realm, ':'); return api; } private writeEnum(_enum: Enum) { let api: string = ''; const isContainedInTable = _enum.items[0]?.key.includes('.') ?? false; api += `---@enum ${_enum.name}\n`; if (isContainedInTable) api += `local ${_enum.name} = {\n`; const writeItem = (key: string, item: typeof _enum.items[0]) => { if (isContainedInTable) { key = key.split('.')[1]; api += ` ${key} = ${item.value}, ` + (item.description ? `--[[ ${item.description} ]]` : '') + '\n'; } else { const comment = item.description ? `${putCommentBeforeEachLine(item.description, false)}\n` : ''; api += `${comment}${key} = ${item.value}\n`; } }; for (const item of _enum.items) writeItem(item.key, item); if (isContainedInTable) api += '}'; api += `\n\n`; return api; } private writeStruct(struct: Struct) { let fields: string = ''; for (const field of struct.fields) { fields += `---@field ${GluaApiWriter.safeName(field.name)} ${this.transformType(field.type)}
${removeNewlines(field.description!)}\n`;
} return this.writeClass(struct.name, undefined, fields); } public writePages(pages: WikiPage[]) { let api: string = ''; for (const page of pages) { api += this.writePage(page); } return api; } private transformType(type: string) { if (type === 'vararg') return '...'; return type; } private writeFunctionLuaDocComment(func: Function, realm: Realm) { let luaDocComment = `---[${realm.toUpperCase()}] ${putCommentBeforeEachLine(func.description!.trim())}\n`; luaDocComment += `---\n---[(View on wiki)](${func.url})\n`; if (func.arguments) { func.arguments.forEach((arg, index) => { if (!arg.name) arg.name = arg.type; if (arg.type === 'vararg') arg.name = '...'; luaDocComment += `---@param ${GluaApiWriter.safeName(arg.name)}${arg.default !== undefined ? `?` : ''} ${this.transformType(arg.type)} ${putCommentBeforeEachLine(arg.description!)}\n`; }); } if (func.returns) { const returns = `---@return ${func.returns.map(ret => this.transformType(ret.type)).join(', ')}`; func.returns.forEach(ret => { const description = removeNewlines(ret.description ?? ''); if (func.returns!.length === 1) { luaDocComment += `${returns} #${description}\n`; return; } luaDocComment += `${returns} #${this.transformType(ret.type)} - ${description}\n`; }); } return luaDocComment; } private writeFunctionDeclaration(func: Function, realm: Realm, indexer: string = '.') { let declaration = `function ${func.parent ? `${func.parent}${indexer}` : ''}${GluaApiWriter.safeName(func.name)}(`; if (func.arguments) { declaration += func.arguments.map(arg => { if (arg.type === 'vararg') return '...'; return GluaApiWriter.safeName(arg.name!); }).join(', '); } declaration += ') end\n\n'; return declaration; } }
src/api-writer/glua-api-writer.ts
luttje-glua-api-snippets-9f40376
[ { "filename": "src/scrapers/wiki-page-markup-scraper.ts", "retrieved_chunk": "}\nexport function isEnum(page: WikiPage): page is Enum {\n return page.type === 'enum';\n}\nexport function isStruct(page: WikiPage): page is Struct {\n return page.type === 'struct';\n}\n/**\n * Scraper\n */", "score": 0.7137652635574341 }, { "filename": "src/scrapers/wiki-page-markup-scraper.ts", "retrieved_chunk": " realm: $('realm').text() as Realm,\n items\n };\n } else if (isStruct) {\n const fields = $('fields item').map(function () {\n const $el = $(this);\n return <StructField>{\n name: $el.attr('name')!,\n type: $el.attr('type')!,\n default: $el.attr('default'),", "score": 0.712020993232727 }, { "filename": "src/utils/string.ts", "retrieved_chunk": " */\nexport function putCommentBeforeEachLine(text: string, skipLineOne: boolean = true) {\n return text.split(/\\r?\\n/g).map((line, index) => {\n if (index === 0 && skipLineOne)\n return line;\n return `--- ${line}`;\n }).join('\\n');\n}\n/**\n * Makes a string safe for use as a file name", "score": 0.6988970041275024 }, { "filename": "src/scrapers/wiki-page-markup-scraper.ts", "retrieved_chunk": " type: string;\n default?: any;\n description: string;\n};\nexport type Struct = CommonWikiProperties & {\n type: 'struct';\n fields: StructField[];\n};\nexport type Panel = CommonWikiProperties & {\n type: 'panel';", "score": 0.6912930011749268 }, { "filename": "src/scrapers/wiki-page-markup-scraper.ts", "retrieved_chunk": " key: string;\n value: string;\n description: string;\n};\nexport type Enum = CommonWikiProperties & {\n type: 'enum';\n items: EnumValue[];\n};\nexport type StructField = {\n name: string;", "score": 0.6909145712852478 } ]
typescript
${removeNewlines(field.description!)}\n`;
import { ClassFunction, Enum, Function, HookFunction, LibraryFunction, Panel, PanelFunction, Realm, Struct, WikiPage, isPanel } from '../scrapers/wiki-page-markup-scraper.js'; import { putCommentBeforeEachLine, removeNewlines, safeFileName, toLowerCamelCase } from '../utils/string.js'; import { isClassFunction, isHookFunction, isLibraryFunction, isPanelFunction, isStruct, isEnum, } from '../scrapers/wiki-page-markup-scraper.js'; export const RESERVERD_KEYWORDS = new Set([ 'and', 'break', 'continue', 'do', 'else', 'elseif', 'end', 'false', 'for', 'function', 'goto', 'if', 'in', 'local', 'nil', 'not', 'or', 'repeat', 'return', 'then', 'true', 'until', 'while' ]); export class GluaApiWriter { private readonly writtenClasses: Set<string> = new Set(); private readonly writtenLibraryGlobals: Set<string> = new Set(); private readonly pageOverrides: Map<string, string> = new Map(); constructor() { } public static safeName(name: string) { if (name.includes('/')) name = name.replace(/\//g, ' or '); if (name.includes('=')) name = name.split('=')[0]; if (name.includes(' ')) name = toLowerCamelCase(name); // Remove any remaining characters not valid in a Lua variable/function name. name = name.replace(/[^A-Za-z\d_.]/g, ''); if (RESERVERD_KEYWORDS.has(name)) return `_${name}`; return name; } public addOverride(pageAddress: string, override: string) { this.pageOverrides.set(safeFileName(pageAddress, '.'), override); } public writePage(page: WikiPage) { const fileSafeAddress = safeFileName(page.address, '.'); if (this.pageOverrides.has(fileSafeAddress)) { let api = ''; if (isClassFunction(page)) api += this.writeClass(page.parent); else if (isLibraryFunction(page)) api += this.writeLibraryGlobal(page); api += this.pageOverrides.get(fileSafeAddress); return `${api}\n\n`; } else if (isClassFunction(page)) return this.writeClassFunction(page); else if (isLibraryFunction(page)) return this.writeLibraryFunction(page); else if (isHookFunction(page)) return this.writeHookFunction(page); else if (isPanel(page)) return this.writePanel(page); else if (isPanelFunction(page)) return this.writePanelFunction(page); else if (isEnum(page)) return this.writeEnum(page); else if (isStruct(page)) return this.writeStruct(page); } private writeClass(className: string, parent?: string, classFields: string = '') { let api: string = ''; if (!this.writtenClasses.has(className)) { const classOverride = `class.${className}`; if (this.pageOverrides.has(classOverride)) { api += this.pageOverrides.get(classOverride)!.replace(/\n$/g, '') + '\n\n'; api = api.replace('---{{CLASS_FIELDS}}\n', classFields); } else { api += `---@class ${className}`; if (parent) api += ` : ${parent}`; api += '\n'; api += classFields; api += `local ${className} = {}\n\n`; } this.writtenClasses.add(className); } return api; } private writeLibraryGlobal
(func: LibraryFunction) {
if (!func.dontDefineParent && !this.writtenLibraryGlobals.has(func.parent)) { const global = `${func.parent} = {}\n\n`; this.writtenLibraryGlobals.add(func.parent); return global; } return ''; } private writeClassFunction(func: ClassFunction) { let api: string = this.writeClass(func.parent); api += this.writeFunctionLuaDocComment(func, func.realm); api += this.writeFunctionDeclaration(func, func.realm, ':'); return api; } private writeLibraryFunction(func: LibraryFunction) { let api: string = this.writeLibraryGlobal(func); api += this.writeFunctionLuaDocComment(func, func.realm); api += this.writeFunctionDeclaration(func, func.realm); return api; } private writeHookFunction(func: HookFunction) { return this.writeClassFunction(func); } private writePanel(panel: Panel) { return this.writeClass(panel.name, panel.parent); } private writePanelFunction(func: PanelFunction) { let api: string = ''; api += this.writeFunctionLuaDocComment(func, func.realm); api += this.writeFunctionDeclaration(func, func.realm, ':'); return api; } private writeEnum(_enum: Enum) { let api: string = ''; const isContainedInTable = _enum.items[0]?.key.includes('.') ?? false; api += `---@enum ${_enum.name}\n`; if (isContainedInTable) api += `local ${_enum.name} = {\n`; const writeItem = (key: string, item: typeof _enum.items[0]) => { if (isContainedInTable) { key = key.split('.')[1]; api += ` ${key} = ${item.value}, ` + (item.description ? `--[[ ${item.description} ]]` : '') + '\n'; } else { const comment = item.description ? `${putCommentBeforeEachLine(item.description, false)}\n` : ''; api += `${comment}${key} = ${item.value}\n`; } }; for (const item of _enum.items) writeItem(item.key, item); if (isContainedInTable) api += '}'; api += `\n\n`; return api; } private writeStruct(struct: Struct) { let fields: string = ''; for (const field of struct.fields) { fields += `---@field ${GluaApiWriter.safeName(field.name)} ${this.transformType(field.type)} ${removeNewlines(field.description!)}\n`; } return this.writeClass(struct.name, undefined, fields); } public writePages(pages: WikiPage[]) { let api: string = ''; for (const page of pages) { api += this.writePage(page); } return api; } private transformType(type: string) { if (type === 'vararg') return '...'; return type; } private writeFunctionLuaDocComment(func: Function, realm: Realm) { let luaDocComment = `---[${realm.toUpperCase()}] ${putCommentBeforeEachLine(func.description!.trim())}\n`; luaDocComment += `---\n---[(View on wiki)](${func.url})\n`; if (func.arguments) { func.arguments.forEach((arg, index) => { if (!arg.name) arg.name = arg.type; if (arg.type === 'vararg') arg.name = '...'; luaDocComment += `---@param ${GluaApiWriter.safeName(arg.name)}${arg.default !== undefined ? `?` : ''} ${this.transformType(arg.type)} ${putCommentBeforeEachLine(arg.description!)}\n`; }); } if (func.returns) { const returns = `---@return ${func.returns.map(ret => this.transformType(ret.type)).join(', ')}`; func.returns.forEach(ret => { const description = removeNewlines(ret.description ?? ''); if (func.returns!.length === 1) { luaDocComment += `${returns} #${description}\n`; return; } luaDocComment += `${returns} #${this.transformType(ret.type)} - ${description}\n`; }); } return luaDocComment; } private writeFunctionDeclaration(func: Function, realm: Realm, indexer: string = '.') { let declaration = `function ${func.parent ? `${func.parent}${indexer}` : ''}${GluaApiWriter.safeName(func.name)}(`; if (func.arguments) { declaration += func.arguments.map(arg => { if (arg.type === 'vararg') return '...'; return GluaApiWriter.safeName(arg.name!); }).join(', '); } declaration += ') end\n\n'; return declaration; } }
src/api-writer/glua-api-writer.ts
luttje-glua-api-snippets-9f40376
[ { "filename": "src/scrapers/wiki-page-markup-scraper.ts", "retrieved_chunk": " realm: $('realm:first').text() as Realm,\n arguments: arguments_,\n returns\n };\n if (isClassFunction) {\n return <ClassFunction> {\n ...base,\n type: 'classfunc'\n };\n } else if (isLibraryFunction) {", "score": 0.7350317239761353 }, { "filename": "src/scrapers/wiki-history-scraper.ts", "retrieved_chunk": " dateTime,\n user,\n change,\n url\n });\n }\n return [ page ];\n };\n }\n}", "score": 0.7304303646087646 }, { "filename": "src/scrapers/wiki-page-markup-scraper.ts", "retrieved_chunk": " }\n }\n return null;\n });\n if (!page)\n return [];\n page.url = response.url.replace(/\\?format=text$/, '');\n return [page];\n };\n }", "score": 0.726495087146759 }, { "filename": "src/scrapers/wiki-page-markup-scraper.ts", "retrieved_chunk": "export type FunctionReturn = WikiIdentifier & {};\nexport type Function = CommonWikiProperties & {\n parent: string;\n arguments?: FunctionArgument[];\n returns?: FunctionReturn[];\n};\nexport type ClassFunction = Function & {};\nexport type LibraryFunction = Function & {\n type: 'libraryfunc';\n dontDefineParent?: boolean;", "score": 0.7109594345092773 }, { "filename": "src/utils/string.ts", "retrieved_chunk": " */\nexport function putCommentBeforeEachLine(text: string, skipLineOne: boolean = true) {\n return text.split(/\\r?\\n/g).map((line, index) => {\n if (index === 0 && skipLineOne)\n return line;\n return `--- ${line}`;\n }).join('\\n');\n}\n/**\n * Makes a string safe for use as a file name", "score": 0.704461932182312 } ]
typescript
(func: LibraryFunction) {
import { ClassFunction, Enum, Function, HookFunction, LibraryFunction, Panel, PanelFunction, Realm, Struct, WikiPage, isPanel } from '../scrapers/wiki-page-markup-scraper.js'; import { putCommentBeforeEachLine, removeNewlines, safeFileName, toLowerCamelCase } from '../utils/string.js'; import { isClassFunction, isHookFunction, isLibraryFunction, isPanelFunction, isStruct, isEnum, } from '../scrapers/wiki-page-markup-scraper.js'; export const RESERVERD_KEYWORDS = new Set([ 'and', 'break', 'continue', 'do', 'else', 'elseif', 'end', 'false', 'for', 'function', 'goto', 'if', 'in', 'local', 'nil', 'not', 'or', 'repeat', 'return', 'then', 'true', 'until', 'while' ]); export class GluaApiWriter { private readonly writtenClasses: Set<string> = new Set(); private readonly writtenLibraryGlobals: Set<string> = new Set(); private readonly pageOverrides: Map<string, string> = new Map(); constructor() { } public static safeName(name: string) { if (name.includes('/')) name = name.replace(/\//g, ' or '); if (name.includes('=')) name = name.split('=')[0]; if (name.includes(' ')) name = toLowerCamelCase(name); // Remove any remaining characters not valid in a Lua variable/function name. name = name.replace(/[^A-Za-z\d_.]/g, ''); if (RESERVERD_KEYWORDS.has(name)) return `_${name}`; return name; } public addOverride(pageAddress: string, override: string) { this.pageOverrides.set(safeFileName(pageAddress, '.'), override); } public writePage(page: WikiPage) { const fileSafeAddress = safeFileName(page.address, '.'); if (this.pageOverrides.has(fileSafeAddress)) { let api = ''; if (isClassFunction(page)) api += this.writeClass(page.parent); else if (isLibraryFunction(page)) api += this.writeLibraryGlobal(page); api += this.pageOverrides.get(fileSafeAddress); return `${api}\n\n`; } else if (isClassFunction(page)) return this.writeClassFunction(page); else if (isLibraryFunction(page)) return this.writeLibraryFunction(page); else if (isHookFunction(page)) return this.writeHookFunction(page); else if (isPanel(page)) return this.writePanel(page); else if (isPanelFunction(page)) return this.writePanelFunction(page); else if (isEnum(page)) return this.writeEnum(page); else if (isStruct(page)) return this.writeStruct(page); } private writeClass(className: string, parent?: string, classFields: string = '') { let api: string = ''; if (!this.writtenClasses.has(className)) { const classOverride = `class.${className}`; if (this.pageOverrides.has(classOverride)) { api += this.pageOverrides.get(classOverride)!.replace(/\n$/g, '') + '\n\n'; api = api.replace('---{{CLASS_FIELDS}}\n', classFields); } else { api += `---@class ${className}`; if (parent) api += ` : ${parent}`; api += '\n'; api += classFields; api += `local ${className} = {}\n\n`; } this.writtenClasses.add(className); } return api; } private writeLibraryGlobal(func: LibraryFunction) { if (!func.dontDefineParent && !this.writtenLibraryGlobals.has(func.parent)) { const global = `${func.parent} = {}\n\n`; this.writtenLibraryGlobals.add(func.parent); return global; } return ''; } private writeClassFunction(func: ClassFunction) { let api: string = this.writeClass(func.parent); api += this.writeFunctionLuaDocComment(func, func.realm); api += this.writeFunctionDeclaration(func, func.realm, ':'); return api; } private writeLibraryFunction(func: LibraryFunction) { let api: string = this.writeLibraryGlobal(func); api += this.writeFunctionLuaDocComment(func, func.realm); api += this.writeFunctionDeclaration(func, func.realm); return api; } private writeHookFunction(func: HookFunction) { return this.writeClassFunction(func); } private writePanel(panel: Panel) { return this.writeClass(panel.name, panel.parent); } private writePanelFunction(func: PanelFunction) { let api: string = ''; api += this.writeFunctionLuaDocComment(func, func.realm); api += this.writeFunctionDeclaration(func, func.realm, ':'); return api; } private writeEnum(_enum: Enum) { let api: string = ''; const isContainedInTable = _enum.items[0]?.key.includes('.') ?? false; api += `---@enum ${_enum.name}\n`; if (isContainedInTable) api += `local ${_enum.name} = {\n`; const writeItem = (key: string, item: typeof _enum.items[0]) => { if (isContainedInTable) { key = key.split('.')[1]; api += ` ${key} = ${item.value}, ` + (item.description ? `--[[ ${item.description} ]]` : '') + '\n'; } else { const comment = item.description ? `${putCommentBeforeEachLine(item.description, false)}\n` : ''; api += `${comment}${key} = ${item.value}\n`; } }; for (const item of _enum.items) writeItem(item.key, item); if (isContainedInTable) api += '}'; api += `\n\n`; return api; } private writeStruct(struct: Struct) { let fields: string = ''; for (const field of struct.fields) { fields += `---@field ${GluaApiWriter.safeName(field.name)} ${this.transformType(field.type)} ${removeNewlines(field.description!)}\n`; } return this.writeClass(struct.name, undefined, fields); } public writePages(pages: WikiPage[]) { let api: string = ''; for (const page of pages) { api += this.writePage(page); } return api; } private transformType(type: string) { if (type === 'vararg') return '...'; return type; } private writeFunctionLuaDocComment(func: Function, realm: Realm) { let luaDocComment = `---[${realm.toUpperCase()}] ${putCommentBeforeEachLine(func.description!.trim())}\n`;
luaDocComment += `---\n---[(View on wiki)](${func.url})\n`;
if (func.arguments) { func.arguments.forEach((arg, index) => { if (!arg.name) arg.name = arg.type; if (arg.type === 'vararg') arg.name = '...'; luaDocComment += `---@param ${GluaApiWriter.safeName(arg.name)}${arg.default !== undefined ? `?` : ''} ${this.transformType(arg.type)} ${putCommentBeforeEachLine(arg.description!)}\n`; }); } if (func.returns) { const returns = `---@return ${func.returns.map(ret => this.transformType(ret.type)).join(', ')}`; func.returns.forEach(ret => { const description = removeNewlines(ret.description ?? ''); if (func.returns!.length === 1) { luaDocComment += `${returns} #${description}\n`; return; } luaDocComment += `${returns} #${this.transformType(ret.type)} - ${description}\n`; }); } return luaDocComment; } private writeFunctionDeclaration(func: Function, realm: Realm, indexer: string = '.') { let declaration = `function ${func.parent ? `${func.parent}${indexer}` : ''}${GluaApiWriter.safeName(func.name)}(`; if (func.arguments) { declaration += func.arguments.map(arg => { if (arg.type === 'vararg') return '...'; return GluaApiWriter.safeName(arg.name!); }).join(', '); } declaration += ') end\n\n'; return declaration; } }
src/api-writer/glua-api-writer.ts
luttje-glua-api-snippets-9f40376
[ { "filename": "src/utils/string.ts", "retrieved_chunk": " */\nexport function putCommentBeforeEachLine(text: string, skipLineOne: boolean = true) {\n return text.split(/\\r?\\n/g).map((line, index) => {\n if (index === 0 && skipLineOne)\n return line;\n return `--- ${line}`;\n }).join('\\n');\n}\n/**\n * Makes a string safe for use as a file name", "score": 0.7408343553543091 }, { "filename": "src/scrapers/wiki-page-markup-scraper.ts", "retrieved_chunk": " return page.type === 'libraryfunc';\n}\nexport function isHookFunction(page: WikiPage): page is HookFunction {\n return page.type === 'hook';\n}\nexport function isPanelFunction(page: WikiPage): page is PanelFunction {\n return page.type === 'panelfunc';\n}\nexport function isPanel(page: WikiPage): page is Panel {\n return page.type === 'panel';", "score": 0.7304973602294922 }, { "filename": "src/cli-scraper.ts", "retrieved_chunk": " const options = program.opts();\n if (!options.url) {\n console.error('No URL provided');\n process.exit(1);\n }\n const baseDirectory = options.output.replace(/\\/$/, '');\n const customDirectory = options.customOverrides?.replace(/\\/$/, '') ?? null;\n const baseUrl = options.url.replace(/\\/$/, '');\n const pageListScraper = new WikiPageListScraper(`${baseUrl}/~pagelist?format=json`);\n const writer = new GluaApiWriter();", "score": 0.7243718504905701 }, { "filename": "src/cli-library-publisher.ts", "retrieved_chunk": " \"/**/\",\n \"continue\",\n ],\n \"Lua.diagnostics.disable\": [\n \"duplicate-set-field\", // Prevents complaining when a function exists twice in both the CLIENT and SERVER realm\n ],\n // TODO: runtime.path\n });\n fs.writeFileSync(path.join(options.output, 'config.json'), JSON.stringify(config, null, 2));\n const files = walk(options.input, (file, isDirectory) => isDirectory || (file.endsWith(`.lua`)));", "score": 0.7187877297401428 }, { "filename": "src/scrapers/wiki-page-markup-scraper.ts", "retrieved_chunk": "}\nexport function isEnum(page: WikiPage): page is Enum {\n return page.type === 'enum';\n}\nexport function isStruct(page: WikiPage): page is Struct {\n return page.type === 'struct';\n}\n/**\n * Scraper\n */", "score": 0.7176029086112976 } ]
typescript
luaDocComment += `---\n---[(View on wiki)](${func.url})\n`;
import { ClassFunction, Enum, Function, HookFunction, LibraryFunction, Panel, PanelFunction, Realm, Struct, WikiPage, isPanel } from '../scrapers/wiki-page-markup-scraper.js'; import { putCommentBeforeEachLine, removeNewlines, safeFileName, toLowerCamelCase } from '../utils/string.js'; import { isClassFunction, isHookFunction, isLibraryFunction, isPanelFunction, isStruct, isEnum, } from '../scrapers/wiki-page-markup-scraper.js'; export const RESERVERD_KEYWORDS = new Set([ 'and', 'break', 'continue', 'do', 'else', 'elseif', 'end', 'false', 'for', 'function', 'goto', 'if', 'in', 'local', 'nil', 'not', 'or', 'repeat', 'return', 'then', 'true', 'until', 'while' ]); export class GluaApiWriter { private readonly writtenClasses: Set<string> = new Set(); private readonly writtenLibraryGlobals: Set<string> = new Set(); private readonly pageOverrides: Map<string, string> = new Map(); constructor() { } public static safeName(name: string) { if (name.includes('/')) name = name.replace(/\//g, ' or '); if (name.includes('=')) name = name.split('=')[0]; if (name.includes(' ')) name = toLowerCamelCase(name); // Remove any remaining characters not valid in a Lua variable/function name. name = name.replace(/[^A-Za-z\d_.]/g, ''); if (RESERVERD_KEYWORDS.has(name)) return `_${name}`; return name; } public addOverride(pageAddress: string, override: string) { this.pageOverrides.set(safeFileName(pageAddress, '.'), override); } public writePage(page: WikiPage) { const fileSafeAddress = safeFileName(page.address, '.'); if (this.pageOverrides.has(fileSafeAddress)) { let api = ''; if (isClassFunction(page)) api += this.writeClass(page.parent); else if (isLibraryFunction(page)) api += this.writeLibraryGlobal(page); api += this.pageOverrides.get(fileSafeAddress); return `${api}\n\n`; } else if (isClassFunction(page)) return this.writeClassFunction(page); else if (isLibraryFunction(page)) return this.writeLibraryFunction(page); else if (isHookFunction(page)) return this.writeHookFunction(page); else if (isPanel(page)) return this.writePanel(page); else if (isPanelFunction(page)) return this.writePanelFunction(page); else if (isEnum(page)) return this.writeEnum(page); else if (isStruct(page)) return this.writeStruct(page); } private writeClass(className: string, parent?: string, classFields: string = '') { let api: string = ''; if (!this.writtenClasses.has(className)) { const classOverride = `class.${className}`; if (this.pageOverrides.has(classOverride)) { api += this.pageOverrides.get(classOverride)!.replace(/\n$/g, '') + '\n\n'; api = api.replace('---{{CLASS_FIELDS}}\n', classFields); } else { api += `---@class ${className}`; if (parent) api += ` : ${parent}`; api += '\n'; api += classFields; api += `local ${className} = {}\n\n`; } this.writtenClasses.add(className); } return api; } private writeLibraryGlobal(func: LibraryFunction) { if (!func.dontDefineParent && !this.writtenLibraryGlobals.has(func.parent)) { const global = `${func.parent} = {}\n\n`; this.writtenLibraryGlobals.add(func.parent); return global; } return ''; } private writeClassFunction(func: ClassFunction) { let api: string = this.writeClass(func.parent); api += this.writeFunctionLuaDocComment(func, func.realm); api += this.writeFunctionDeclaration(func, func.realm, ':'); return api; } private writeLibraryFunction(func: LibraryFunction) { let api: string = this.writeLibraryGlobal(func); api += this.writeFunctionLuaDocComment(func, func.realm); api += this.writeFunctionDeclaration(func, func.realm); return api; } private writeHookFunction(func: HookFunction) { return this.writeClassFunction(func); } private writePanel(panel: Panel) { return this.writeClass(panel.name, panel.parent); } private writePanelFunction(func: PanelFunction) { let api: string = ''; api += this.writeFunctionLuaDocComment(func, func.realm); api += this.writeFunctionDeclaration(func, func.realm, ':'); return api; } private writeEnum(_enum: Enum) { let api: string = ''; const isContainedInTable = _enum.items[0]?.key.includes('.') ?? false; api += `---@enum ${_enum.name}\n`; if (isContainedInTable) api += `local ${_enum.name} = {\n`; const writeItem = (key: string, item: typeof _enum.items[0]) => { if (isContainedInTable) { key = key.split('.')[1]; api += ` ${key} = ${item.value}, ` + (item.description ? `--[[ ${item.description} ]]` : '') + '\n'; } else { const comment = item.description ? `${putCommentBeforeEachLine(item.description, false)}\n` : ''; api += `${comment}${key} = ${item.value}\n`; } }; for (const item of _enum.items) writeItem(item.key, item); if (isContainedInTable) api += '}'; api += `\n\n`; return api; } private writeStruct(struct: Struct) { let fields: string = ''; for (const field of struct.fields) { fields += `---@field ${GluaApiWriter.safeName(field.name)} ${this.transformType(field.type)} ${removeNewlines(field.description!)}\n`; } return this.writeClass(struct.name, undefined, fields); } public writePages(pages: WikiPage[]) { let api: string = ''; for (const page of pages) { api += this.writePage(page); } return api; } private transformType(type: string) { if (type === 'vararg') return '...'; return type; } private writeFunctionLuaDocComment(func: Function, realm: Realm) { let luaDocComment = `---[${realm.toUpperCase()}] ${putCommentBeforeEachLine(func.description!.trim())}\n`; luaDocComment += `---\n---[(View on wiki)](${func.url})\n`; if (func.arguments) {
func.arguments.forEach((arg, index) => {
if (!arg.name) arg.name = arg.type; if (arg.type === 'vararg') arg.name = '...'; luaDocComment += `---@param ${GluaApiWriter.safeName(arg.name)}${arg.default !== undefined ? `?` : ''} ${this.transformType(arg.type)} ${putCommentBeforeEachLine(arg.description!)}\n`; }); } if (func.returns) { const returns = `---@return ${func.returns.map(ret => this.transformType(ret.type)).join(', ')}`; func.returns.forEach(ret => { const description = removeNewlines(ret.description ?? ''); if (func.returns!.length === 1) { luaDocComment += `${returns} #${description}\n`; return; } luaDocComment += `${returns} #${this.transformType(ret.type)} - ${description}\n`; }); } return luaDocComment; } private writeFunctionDeclaration(func: Function, realm: Realm, indexer: string = '.') { let declaration = `function ${func.parent ? `${func.parent}${indexer}` : ''}${GluaApiWriter.safeName(func.name)}(`; if (func.arguments) { declaration += func.arguments.map(arg => { if (arg.type === 'vararg') return '...'; return GluaApiWriter.safeName(arg.name!); }).join(', '); } declaration += ') end\n\n'; return declaration; } }
src/api-writer/glua-api-writer.ts
luttje-glua-api-snippets-9f40376
[ { "filename": "src/scrapers/wiki-page-markup-scraper.ts", "retrieved_chunk": " } else if (isFunction) {\n const isClassFunction = mainElement.attr('type') === 'classfunc';\n const isLibraryFunction = mainElement.attr('type') === 'libraryfunc';\n const isHookFunction = mainElement.attr('type') === 'hook';\n const isPanelFunction = mainElement.attr('type') === 'panelfunc';\n const arguments_ = $('args arg').map(function() {\n const $el = $(this);\n const argument = <FunctionArgument> {\n name: $el.attr('name')!,\n type: $el.attr('type')!,", "score": 0.7470132112503052 }, { "filename": "src/cli-library-publisher.ts", "retrieved_chunk": " \"/**/\",\n \"continue\",\n ],\n \"Lua.diagnostics.disable\": [\n \"duplicate-set-field\", // Prevents complaining when a function exists twice in both the CLIENT and SERVER realm\n ],\n // TODO: runtime.path\n });\n fs.writeFileSync(path.join(options.output, 'config.json'), JSON.stringify(config, null, 2));\n const files = walk(options.input, (file, isDirectory) => isDirectory || (file.endsWith(`.lua`)));", "score": 0.7334251403808594 }, { "filename": "src/cli-scraper.ts", "retrieved_chunk": " const options = program.opts();\n if (!options.url) {\n console.error('No URL provided');\n process.exit(1);\n }\n const baseDirectory = options.output.replace(/\\/$/, '');\n const customDirectory = options.customOverrides?.replace(/\\/$/, '') ?? null;\n const baseUrl = options.url.replace(/\\/$/, '');\n const pageListScraper = new WikiPageListScraper(`${baseUrl}/~pagelist?format=json`);\n const writer = new GluaApiWriter();", "score": 0.7298521995544434 }, { "filename": "src/utils/string.ts", "retrieved_chunk": " */\nexport function putCommentBeforeEachLine(text: string, skipLineOne: boolean = true) {\n return text.split(/\\r?\\n/g).map((line, index) => {\n if (index === 0 && skipLineOne)\n return line;\n return `--- ${line}`;\n }).join('\\n');\n}\n/**\n * Makes a string safe for use as a file name", "score": 0.7258296012878418 }, { "filename": "src/cli-scraper.ts", "retrieved_chunk": " const fileContent = fs.readFileSync(filePath, { encoding: 'utf-8' });\n const pageName = file.replace(/\\.lua$/, '');\n writer.addOverride(pageName, fileContent);\n }\n }\n const pageIndexes = await scrapeAndCollect(pageListScraper);\n for (const pageIndex of pageIndexes) {\n const pageMarkupScraper = new WikiPageMarkupScraper(`${baseUrl}/${pageIndex.address}?format=text`);\n pageMarkupScraper.on('scraped', (url, pageMarkups) => {\n if (pageMarkups.length === 0)", "score": 0.7247397899627686 } ]
typescript
func.arguments.forEach((arg, index) => {
import { Scrapeable, TraverseScraper } from './traverse-scraper.js'; import { ScrapeCallback } from './scraper.js'; import * as cheerio from 'cheerio'; import "reflect-metadata"; const tableColumnMetadataKey = Symbol("tableColumn"); export type TableColumnDefinition = { propertyKey: string | symbol, columnName: string, typeConverter: (value: string) => any }; export function tableColumn(columnName: string): PropertyDecorator { return (target: object, propertyKey: string | symbol) => { const existingColumns: TableColumnDefinition[] = Reflect.getMetadata(tableColumnMetadataKey, target) || []; const propertyType = Reflect.getMetadata("design:type", target, propertyKey); existingColumns.push({ propertyKey, columnName, typeConverter: (value: string) => { switch (propertyType) { case String: return value; case Number: return Number(value); case Boolean: return Boolean(value); default: return value; } } }); Reflect.defineMetadata(tableColumnMetadataKey, existingColumns, target); }; } export function getTableColumns(target: object): TableColumnDefinition[] { return Reflect.getMetadata(tableColumnMetadataKey, target) || []; } export class Row<T> { constructor(public data: T) { } } export class Table
<T> implements Scrapeable {
public url: string; public childUrls: Set<string> = new Set(); constructor(url: string, public rows: Row<T>[] = []) { this.url = url; } public addRow(row: Row<T>) { this.rows.push(row); } } export class TableScraper<T extends object> extends TraverseScraper<Table<T>> { constructor(baseUrl: string, private readonly factory: () => T) { super(baseUrl); } public getScrapeCallback(): ScrapeCallback<Table<T>> { return (response: Response, content: string): Table<T>[] => { const results: Table<T>[] = []; const $ = cheerio.load(content); const tables = $('table'); for (const table of tables) { const tableResult = this.fromTableElement($, table); if (tableResult) results.push(tableResult); } return results; }; } private fromTableElement($: cheerio.CheerioAPI, tableElement: cheerio.Element): Table<T> | null { const tableResult = new Table<T>(this.baseUrl); let headingRows = $(tableElement).find('thead > tr'); let shouldTrimHeadings = false; if (headingRows.length === 0) { headingRows = $(tableElement).find('tbody > tr:first-child'); shouldTrimHeadings = true; } let headings : cheerio.Element[] | undefined; if (headingRows.length > 0) headings = $(headingRows[0]).find('th').toArray(); if (!headings || headings.length === 0) throw new Error('No headings found in table'); let rows = $(tableElement).find('tbody > tr').toArray(); if (rows.length === 0) rows = $(tableElement).find('tr').toArray(); if (shouldTrimHeadings) rows = rows.slice(headingRows.length); let isEmpty = true; for (const row of rows) { const rowResult = this.fromRowElement($, row, headings); if (rowResult === null) continue; tableResult.addRow(rowResult); isEmpty = false; } if (isEmpty) return null; return tableResult; } private fromRowElement($: cheerio.CheerioAPI, rowElement: cheerio.Element, headings: cheerio.Element[]): Row<T> | null { const cells = $(rowElement).find('td').toArray(); const rowResult = this.factory(); const allTableColumns = getTableColumns(rowResult); let isEmpty = true; for (let i = 0; i < cells.length; i++) { const cell = cells[i]; const heading = headings[i]; if (!heading) continue; const headingText = $(heading).text(); if (!headingText) continue; let tableColumnDefinition = allTableColumns.find(column => column.columnName === headingText); if (!tableColumnDefinition) { const properties = Object.getOwnPropertyNames(rowResult); const propertyKey = properties.find(property => property.toLowerCase() === headingText.toLowerCase()); if (!propertyKey) continue; tableColumnDefinition = { propertyKey, columnName: headingText, typeConverter: (value: string) => value }; } const cellText = $(cell).text(); if (!cellText) continue; (rowResult as any)[tableColumnDefinition.propertyKey] = tableColumnDefinition.typeConverter(cellText); isEmpty = false; } if (isEmpty) return null; return new Row<T>(rowResult); } }
src/scrapers/table-scraper.ts
luttje-glua-api-snippets-9f40376
[ { "filename": "src/scrapers/json-scraper.ts", "retrieved_chunk": " }\n public static makeScrapeCallback<T extends object = object>(): ScrapeCallback<T> {\n return (response: Response, content: string): T[] => {\n return JSON.parse(content);\n };\n }\n}", "score": 0.7888332605361938 }, { "filename": "src/scrapers/traverse-scraper.ts", "retrieved_chunk": "import { Scraper, ScrapeCallback } from './scraper.js';\nexport interface Scrapeable {\n childUrls: Set<string>;\n}\nexport class TraverseScraper<T extends Scrapeable> extends Scraper<T> {\n protected readonly traversedUrls: Set<string> = new Set();\n protected childPageFilter?: (url: string) => boolean;\n public setChildPageFilter(filter: (url: string) => boolean): void {\n this.childPageFilter = filter;\n }", "score": 0.7826569080352783 }, { "filename": "src/scrapers/wiki-page-list-scraper.ts", "retrieved_chunk": "import { JsonScraper } from './json-scraper.js';\nexport type WikiPageIndexObject = {\n address: string;\n updateCount: number;\n viewCount: number;\n}\nexport class WikiPageListScraper extends JsonScraper<WikiPageIndexObject> {}", "score": 0.7617936134338379 }, { "filename": "src/scrapers/scraper.ts", "retrieved_chunk": "export class Scraper<T extends ScrapeResult> extends TypedEventEmitter<ScraperEvents<T>> {\n protected retryOptions: RequestInitWithRetry = {};\n constructor(\n protected readonly baseUrl: string,\n protected readonly scrapeCallback?: ScrapeCallback<T>\n ) { \n super();\n }\n public getScrapeCallback(): ScrapeCallback<T> {\n return this.scrapeCallback || ((_: Response, __: string): T[] => []);", "score": 0.7539787292480469 }, { "filename": "src/scrapers/wiki-history-scraper.ts", "retrieved_chunk": " public history: WikiHistory[] = [];\n constructor(url: string, title: string) {\n super(url, title);\n }\n}\nexport class WikiHistoryPageScraper extends PageTraverseScraper<WikiHistoryPage> {\n constructor(baseUrl: string) {\n super(baseUrl, (url: string, title: string) => new WikiHistoryPage(url, title));\n }\n /**", "score": 0.7532622814178467 } ]
typescript
<T> implements Scrapeable {
import { Scrapeable, TraverseScraper } from './traverse-scraper.js'; import { ScrapeCallback } from './scraper.js'; import * as cheerio from 'cheerio'; import "reflect-metadata"; const tableColumnMetadataKey = Symbol("tableColumn"); export type TableColumnDefinition = { propertyKey: string | symbol, columnName: string, typeConverter: (value: string) => any }; export function tableColumn(columnName: string): PropertyDecorator { return (target: object, propertyKey: string | symbol) => { const existingColumns: TableColumnDefinition[] = Reflect.getMetadata(tableColumnMetadataKey, target) || []; const propertyType = Reflect.getMetadata("design:type", target, propertyKey); existingColumns.push({ propertyKey, columnName, typeConverter: (value: string) => { switch (propertyType) { case String: return value; case Number: return Number(value); case Boolean: return Boolean(value); default: return value; } } }); Reflect.defineMetadata(tableColumnMetadataKey, existingColumns, target); }; } export function getTableColumns(target: object): TableColumnDefinition[] { return Reflect.getMetadata(tableColumnMetadataKey, target) || []; } export class Row<T> { constructor(public data: T) { } } export class Table<T> implements Scrapeable { public url: string; public childUrls: Set<string> = new Set(); constructor(url: string, public rows: Row<T>[] = []) { this.url = url; } public addRow(row: Row<T>) { this.rows.push(row); } } export class TableScraper
<T extends object> extends TraverseScraper<Table<T>> {
constructor(baseUrl: string, private readonly factory: () => T) { super(baseUrl); } public getScrapeCallback(): ScrapeCallback<Table<T>> { return (response: Response, content: string): Table<T>[] => { const results: Table<T>[] = []; const $ = cheerio.load(content); const tables = $('table'); for (const table of tables) { const tableResult = this.fromTableElement($, table); if (tableResult) results.push(tableResult); } return results; }; } private fromTableElement($: cheerio.CheerioAPI, tableElement: cheerio.Element): Table<T> | null { const tableResult = new Table<T>(this.baseUrl); let headingRows = $(tableElement).find('thead > tr'); let shouldTrimHeadings = false; if (headingRows.length === 0) { headingRows = $(tableElement).find('tbody > tr:first-child'); shouldTrimHeadings = true; } let headings : cheerio.Element[] | undefined; if (headingRows.length > 0) headings = $(headingRows[0]).find('th').toArray(); if (!headings || headings.length === 0) throw new Error('No headings found in table'); let rows = $(tableElement).find('tbody > tr').toArray(); if (rows.length === 0) rows = $(tableElement).find('tr').toArray(); if (shouldTrimHeadings) rows = rows.slice(headingRows.length); let isEmpty = true; for (const row of rows) { const rowResult = this.fromRowElement($, row, headings); if (rowResult === null) continue; tableResult.addRow(rowResult); isEmpty = false; } if (isEmpty) return null; return tableResult; } private fromRowElement($: cheerio.CheerioAPI, rowElement: cheerio.Element, headings: cheerio.Element[]): Row<T> | null { const cells = $(rowElement).find('td').toArray(); const rowResult = this.factory(); const allTableColumns = getTableColumns(rowResult); let isEmpty = true; for (let i = 0; i < cells.length; i++) { const cell = cells[i]; const heading = headings[i]; if (!heading) continue; const headingText = $(heading).text(); if (!headingText) continue; let tableColumnDefinition = allTableColumns.find(column => column.columnName === headingText); if (!tableColumnDefinition) { const properties = Object.getOwnPropertyNames(rowResult); const propertyKey = properties.find(property => property.toLowerCase() === headingText.toLowerCase()); if (!propertyKey) continue; tableColumnDefinition = { propertyKey, columnName: headingText, typeConverter: (value: string) => value }; } const cellText = $(cell).text(); if (!cellText) continue; (rowResult as any)[tableColumnDefinition.propertyKey] = tableColumnDefinition.typeConverter(cellText); isEmpty = false; } if (isEmpty) return null; return new Row<T>(rowResult); } }
src/scrapers/table-scraper.ts
luttje-glua-api-snippets-9f40376
[ { "filename": "src/scrapers/traverse-scraper.ts", "retrieved_chunk": "import { Scraper, ScrapeCallback } from './scraper.js';\nexport interface Scrapeable {\n childUrls: Set<string>;\n}\nexport class TraverseScraper<T extends Scrapeable> extends Scraper<T> {\n protected readonly traversedUrls: Set<string> = new Set();\n protected childPageFilter?: (url: string) => boolean;\n public setChildPageFilter(filter: (url: string) => boolean): void {\n this.childPageFilter = filter;\n }", "score": 0.8456271886825562 }, { "filename": "src/scrapers/wiki-history-scraper.ts", "retrieved_chunk": " public history: WikiHistory[] = [];\n constructor(url: string, title: string) {\n super(url, title);\n }\n}\nexport class WikiHistoryPageScraper extends PageTraverseScraper<WikiHistoryPage> {\n constructor(baseUrl: string) {\n super(baseUrl, (url: string, title: string) => new WikiHistoryPage(url, title));\n }\n /**", "score": 0.845622181892395 }, { "filename": "src/scrapers/page-traverse-scraper.ts", "retrieved_chunk": "import { Scrapeable, TraverseScraper } from './traverse-scraper.js';\nimport { decodeEntities } from './decode-entities.js';\nimport { ScrapeCallback } from './scraper.js';\nexport class Page implements Scrapeable {\n public url: string;\n public title: string;\n public childUrls: Set<string> = new Set();\n constructor(url: string, title: string) {\n this.url = url;\n this.title = title;", "score": 0.8249995708465576 }, { "filename": "src/scrapers/page-traverse-scraper.ts", "retrieved_chunk": " }\n}\nexport class PageTraverseScraper<T extends Page = Page> extends TraverseScraper<T> {\n private readonly factory: (url: string, title: string) => T;\n constructor(baseUrl: string, factory?: (url: string, title: string) => T) {\n super(baseUrl);\n this.factory = factory ?? ((url: string, title: string) => new Page(url, title) as T);\n }\n /**\n * Scrapes a page for its URL and title, and returns a list of child URLs", "score": 0.7933926582336426 }, { "filename": "src/scrapers/json-scraper.ts", "retrieved_chunk": " }\n public static makeScrapeCallback<T extends object = object>(): ScrapeCallback<T> {\n return (response: Response, content: string): T[] => {\n return JSON.parse(content);\n };\n }\n}", "score": 0.7898792624473572 } ]
typescript
<T extends object> extends TraverseScraper<Table<T>> {
import { ClassFunction, Enum, Function, HookFunction, LibraryFunction, Panel, PanelFunction, Realm, Struct, WikiPage, isPanel } from '../scrapers/wiki-page-markup-scraper.js'; import { putCommentBeforeEachLine, removeNewlines, safeFileName, toLowerCamelCase } from '../utils/string.js'; import { isClassFunction, isHookFunction, isLibraryFunction, isPanelFunction, isStruct, isEnum, } from '../scrapers/wiki-page-markup-scraper.js'; export const RESERVERD_KEYWORDS = new Set([ 'and', 'break', 'continue', 'do', 'else', 'elseif', 'end', 'false', 'for', 'function', 'goto', 'if', 'in', 'local', 'nil', 'not', 'or', 'repeat', 'return', 'then', 'true', 'until', 'while' ]); export class GluaApiWriter { private readonly writtenClasses: Set<string> = new Set(); private readonly writtenLibraryGlobals: Set<string> = new Set(); private readonly pageOverrides: Map<string, string> = new Map(); constructor() { } public static safeName(name: string) { if (name.includes('/')) name = name.replace(/\//g, ' or '); if (name.includes('=')) name = name.split('=')[0]; if (name.includes(' ')) name = toLowerCamelCase(name); // Remove any remaining characters not valid in a Lua variable/function name. name = name.replace(/[^A-Za-z\d_.]/g, ''); if (RESERVERD_KEYWORDS.has(name)) return `_${name}`; return name; } public addOverride(pageAddress: string, override: string) { this.pageOverrides.set(safeFileName(pageAddress, '.'), override); } public writePage(page: WikiPage) { const fileSafeAddress = safeFileName(page.address, '.'); if (this.pageOverrides.has(fileSafeAddress)) { let api = ''; if (isClassFunction(page)) api += this.writeClass(page.parent); else if (isLibraryFunction(page)) api += this.writeLibraryGlobal(page); api += this.pageOverrides.get(fileSafeAddress); return `${api}\n\n`; } else if (isClassFunction(page)) return this.writeClassFunction(page); else if (isLibraryFunction(page)) return this.writeLibraryFunction(page); else if (isHookFunction(page)) return this.writeHookFunction(page); else if (isPanel(page)) return this.writePanel(page); else if (isPanelFunction(page)) return this.writePanelFunction(page); else if (isEnum(page)) return this.writeEnum(page); else if (isStruct(page)) return this.writeStruct(page); } private writeClass(className: string, parent?: string, classFields: string = '') { let api: string = ''; if (!this.writtenClasses.has(className)) { const classOverride = `class.${className}`; if (this.pageOverrides.has(classOverride)) { api += this.pageOverrides.get(classOverride)!.replace(/\n$/g, '') + '\n\n'; api = api.replace('---{{CLASS_FIELDS}}\n', classFields); } else { api += `---@class ${className}`; if (parent) api += ` : ${parent}`; api += '\n'; api += classFields; api += `local ${className} = {}\n\n`; } this.writtenClasses.add(className); } return api; } private writeLibraryGlobal(func: LibraryFunction) { if (!func.dontDefineParent && !this.writtenLibraryGlobals.has(func.parent)) { const global = `${func.parent} = {}\n\n`; this.writtenLibraryGlobals.add(func.parent); return global; } return ''; } private writeClassFunction(func: ClassFunction) { let api: string = this.writeClass(func.parent); api += this.writeFunctionLuaDocComment(func, func.realm); api += this.writeFunctionDeclaration(func, func.realm, ':'); return api; } private writeLibraryFunction(func: LibraryFunction) { let api: string = this.writeLibraryGlobal(func); api += this.writeFunctionLuaDocComment(func, func.realm); api += this.writeFunctionDeclaration(func, func.realm); return api; } private writeHookFunction(func: HookFunction) { return this.writeClassFunction(func); } private writePanel(panel: Panel) { return this.writeClass(panel.name, panel.parent); } private writePanelFunction(func: PanelFunction) { let api: string = ''; api += this.writeFunctionLuaDocComment(func, func.realm); api += this.writeFunctionDeclaration(func, func.realm, ':'); return api; } private writeEnum(_enum: Enum) { let api: string = ''; const isContainedInTable = _enum.items[0]?.key.includes('.') ?? false; api += `---@enum ${_enum.name}\n`; if (isContainedInTable) api += `local ${_enum.name} = {\n`; const writeItem = (key: string, item: typeof _enum.items[0]) => { if (isContainedInTable) { key = key.split('.')[1]; api += ` ${key} = ${item.value}, ` + (item.description ? `--[[ ${item.description} ]]` : '') + '\n'; } else { const comment = item.description ? `${putCommentBeforeEachLine(item.description, false)}\n` : ''; api += `${comment}${key} = ${item.value}\n`; } }; for (const item of _enum.items) writeItem(item.key, item); if (isContainedInTable) api += '}'; api += `\n\n`; return api; } private writeStruct(struct: Struct) { let fields: string = ''; for (const field of struct.fields) { fields += `---@field ${GluaApiWriter.safeName(field.name)} ${this.transformType(field.type)} ${removeNewlines(field.description!)}\n`; } return this.writeClass(struct.name, undefined, fields); } public writePages(pages: WikiPage[]) { let api: string = ''; for (const page of pages) { api += this.writePage(page); } return api; } private transformType(type: string) { if (type === 'vararg') return '...'; return type; } private writeFunctionLuaDocComment(func: Function, realm: Realm) {
let luaDocComment = `---[${realm.toUpperCase()}] ${putCommentBeforeEachLine(func.description!.trim())}\n`;
luaDocComment += `---\n---[(View on wiki)](${func.url})\n`; if (func.arguments) { func.arguments.forEach((arg, index) => { if (!arg.name) arg.name = arg.type; if (arg.type === 'vararg') arg.name = '...'; luaDocComment += `---@param ${GluaApiWriter.safeName(arg.name)}${arg.default !== undefined ? `?` : ''} ${this.transformType(arg.type)} ${putCommentBeforeEachLine(arg.description!)}\n`; }); } if (func.returns) { const returns = `---@return ${func.returns.map(ret => this.transformType(ret.type)).join(', ')}`; func.returns.forEach(ret => { const description = removeNewlines(ret.description ?? ''); if (func.returns!.length === 1) { luaDocComment += `${returns} #${description}\n`; return; } luaDocComment += `${returns} #${this.transformType(ret.type)} - ${description}\n`; }); } return luaDocComment; } private writeFunctionDeclaration(func: Function, realm: Realm, indexer: string = '.') { let declaration = `function ${func.parent ? `${func.parent}${indexer}` : ''}${GluaApiWriter.safeName(func.name)}(`; if (func.arguments) { declaration += func.arguments.map(arg => { if (arg.type === 'vararg') return '...'; return GluaApiWriter.safeName(arg.name!); }).join(', '); } declaration += ') end\n\n'; return declaration; } }
src/api-writer/glua-api-writer.ts
luttje-glua-api-snippets-9f40376
[ { "filename": "src/utils/string.ts", "retrieved_chunk": " */\nexport function putCommentBeforeEachLine(text: string, skipLineOne: boolean = true) {\n return text.split(/\\r?\\n/g).map((line, index) => {\n if (index === 0 && skipLineOne)\n return line;\n return `--- ${line}`;\n }).join('\\n');\n}\n/**\n * Makes a string safe for use as a file name", "score": 0.778713583946228 }, { "filename": "src/scrapers/wiki-page-markup-scraper.ts", "retrieved_chunk": " realm: $('realm:first').text() as Realm,\n arguments: arguments_,\n returns\n };\n if (isClassFunction) {\n return <ClassFunction> {\n ...base,\n type: 'classfunc'\n };\n } else if (isLibraryFunction) {", "score": 0.776549220085144 }, { "filename": "src/scrapers/wiki-page-markup-scraper.ts", "retrieved_chunk": "}\nexport function isEnum(page: WikiPage): page is Enum {\n return page.type === 'enum';\n}\nexport function isStruct(page: WikiPage): page is Struct {\n return page.type === 'struct';\n}\n/**\n * Scraper\n */", "score": 0.7412052154541016 }, { "filename": "src/scrapers/wiki-page-markup-scraper.ts", "retrieved_chunk": " if (base.parent === 'Global') {\n base.parent = '_G';\n (<LibraryFunction>base).dontDefineParent = true;\n }\n return <LibraryFunction> {\n ...base,\n type: 'libraryfunc'\n };\n } else if (isHookFunction) {\n return <HookFunction> {", "score": 0.740304708480835 }, { "filename": "src/cli-library-publisher.ts", "retrieved_chunk": " \"/**/\",\n \"continue\",\n ],\n \"Lua.diagnostics.disable\": [\n \"duplicate-set-field\", // Prevents complaining when a function exists twice in both the CLIENT and SERVER realm\n ],\n // TODO: runtime.path\n });\n fs.writeFileSync(path.join(options.output, 'config.json'), JSON.stringify(config, null, 2));\n const files = walk(options.input, (file, isDirectory) => isDirectory || (file.endsWith(`.lua`)));", "score": 0.7393749952316284 } ]
typescript
let luaDocComment = `---[${realm.toUpperCase()}] ${putCommentBeforeEachLine(func.description!.trim())}\n`;
import { ClassFunction, Enum, Function, HookFunction, LibraryFunction, Panel, PanelFunction, Realm, Struct, WikiPage, isPanel } from '../scrapers/wiki-page-markup-scraper.js'; import { putCommentBeforeEachLine, removeNewlines, safeFileName, toLowerCamelCase } from '../utils/string.js'; import { isClassFunction, isHookFunction, isLibraryFunction, isPanelFunction, isStruct, isEnum, } from '../scrapers/wiki-page-markup-scraper.js'; export const RESERVERD_KEYWORDS = new Set([ 'and', 'break', 'continue', 'do', 'else', 'elseif', 'end', 'false', 'for', 'function', 'goto', 'if', 'in', 'local', 'nil', 'not', 'or', 'repeat', 'return', 'then', 'true', 'until', 'while' ]); export class GluaApiWriter { private readonly writtenClasses: Set<string> = new Set(); private readonly writtenLibraryGlobals: Set<string> = new Set(); private readonly pageOverrides: Map<string, string> = new Map(); constructor() { } public static safeName(name: string) { if (name.includes('/')) name = name.replace(/\//g, ' or '); if (name.includes('=')) name = name.split('=')[0]; if (name.includes(' ')) name = toLowerCamelCase(name); // Remove any remaining characters not valid in a Lua variable/function name. name = name.replace(/[^A-Za-z\d_.]/g, ''); if (RESERVERD_KEYWORDS.has(name)) return `_${name}`; return name; } public addOverride(pageAddress: string, override: string) { this.pageOverrides.set(safeFileName(pageAddress, '.'), override); } public writePage(page: WikiPage) { const fileSafeAddress = safeFileName(page.address, '.'); if (this.pageOverrides.has(fileSafeAddress)) { let api = ''; if (isClassFunction(page)) api += this.writeClass(page.parent); else if (isLibraryFunction(page)) api += this.writeLibraryGlobal(page); api += this.pageOverrides.get(fileSafeAddress); return `${api}\n\n`; } else if (isClassFunction(page)) return this.writeClassFunction(page); else if (isLibraryFunction(page)) return this.writeLibraryFunction(page); else if (isHookFunction(page)) return this.writeHookFunction(page); else if (isPanel(page)) return this.writePanel(page); else if (isPanelFunction(page)) return this.writePanelFunction(page); else if (isEnum(page)) return this.writeEnum(page); else if (isStruct(page)) return this.writeStruct(page); } private writeClass(className: string, parent?: string, classFields: string = '') { let api: string = ''; if (!this.writtenClasses.has(className)) { const classOverride = `class.${className}`; if (this.pageOverrides.has(classOverride)) { api += this.pageOverrides.get(classOverride)!.replace(/\n$/g, '') + '\n\n'; api = api.replace('---{{CLASS_FIELDS}}\n', classFields); } else { api += `---@class ${className}`; if (parent) api += ` : ${parent}`; api += '\n'; api += classFields; api += `local ${className} = {}\n\n`; } this.writtenClasses.add(className); } return api; } private writeLibraryGlobal(func: LibraryFunction) { if (!func.dontDefineParent && !this.writtenLibraryGlobals.has(func.parent)) { const global = `${func.parent} = {}\n\n`; this.writtenLibraryGlobals.add(func.parent); return global; } return ''; } private writeClassFunction(func: ClassFunction) { let api: string = this.writeClass(func.parent); api += this.writeFunctionLuaDocComment(func, func.realm); api += this.writeFunctionDeclaration(func, func.realm, ':'); return api; } private writeLibraryFunction(func: LibraryFunction) { let api: string = this.writeLibraryGlobal(func); api += this.writeFunctionLuaDocComment(func, func.realm); api += this.writeFunctionDeclaration(func, func.realm); return api; } private writeHookFunction(func: HookFunction) { return this.writeClassFunction(func); } private writePanel(panel: Panel) { return this.writeClass(panel.name, panel.parent); } private writePanelFunction(func: PanelFunction) { let api: string = ''; api += this.writeFunctionLuaDocComment(func, func.realm); api += this.writeFunctionDeclaration(func, func.realm, ':'); return api; } private writeEnum(_enum: Enum) { let api: string = ''; const isContainedInTable = _enum.items[0]?.key.includes('.') ?? false; api += `---@enum ${_enum.name}\n`; if (isContainedInTable) api += `local ${_enum.name} = {\n`; const writeItem = (key: string, item: typeof _enum.items[0]) => { if (isContainedInTable) { key = key.split('.')[1]; api += ` ${key} = ${item.value}, ` + (item.description ? `--[[ ${item.description} ]]` : '') + '\n'; } else { const comment = item.description ? `${putCommentBeforeEachLine(item.description, false)}\n` : ''; api += `${comment}${key} = ${item.value}\n`; } }; for (const item of _enum.items) writeItem(item.key, item); if (isContainedInTable) api += '}'; api += `\n\n`; return api; } private writeStruct(struct: Struct) { let fields: string = ''; for (const field of struct.fields) { fields += `---@field ${GluaApiWriter.safeName(field.name)} ${this.transformType(field.type)} ${removeNewlines(field.description!)}\n`; } return this.writeClass(struct.name, undefined, fields); } public writePages(pages: WikiPage[]) { let api: string = ''; for (const page of pages) { api += this.writePage(page); } return api; } private transformType(type: string) { if (type === 'vararg') return '...'; return type; } private writeFunctionLuaDocComment(func: Function, realm: Realm) { let luaDocComment = `---[${realm.toUpperCase()}] ${putCommentBeforeEachLine(func.description!.trim())}\n`; luaDocComment += `---\n---[(View on wiki)](${func.url})\n`; if (func.arguments) { func.arguments
.forEach((arg, index) => {
if (!arg.name) arg.name = arg.type; if (arg.type === 'vararg') arg.name = '...'; luaDocComment += `---@param ${GluaApiWriter.safeName(arg.name)}${arg.default !== undefined ? `?` : ''} ${this.transformType(arg.type)} ${putCommentBeforeEachLine(arg.description!)}\n`; }); } if (func.returns) { const returns = `---@return ${func.returns.map(ret => this.transformType(ret.type)).join(', ')}`; func.returns.forEach(ret => { const description = removeNewlines(ret.description ?? ''); if (func.returns!.length === 1) { luaDocComment += `${returns} #${description}\n`; return; } luaDocComment += `${returns} #${this.transformType(ret.type)} - ${description}\n`; }); } return luaDocComment; } private writeFunctionDeclaration(func: Function, realm: Realm, indexer: string = '.') { let declaration = `function ${func.parent ? `${func.parent}${indexer}` : ''}${GluaApiWriter.safeName(func.name)}(`; if (func.arguments) { declaration += func.arguments.map(arg => { if (arg.type === 'vararg') return '...'; return GluaApiWriter.safeName(arg.name!); }).join(', '); } declaration += ') end\n\n'; return declaration; } }
src/api-writer/glua-api-writer.ts
luttje-glua-api-snippets-9f40376
[ { "filename": "src/scrapers/wiki-page-markup-scraper.ts", "retrieved_chunk": " } else if (isFunction) {\n const isClassFunction = mainElement.attr('type') === 'classfunc';\n const isLibraryFunction = mainElement.attr('type') === 'libraryfunc';\n const isHookFunction = mainElement.attr('type') === 'hook';\n const isPanelFunction = mainElement.attr('type') === 'panelfunc';\n const arguments_ = $('args arg').map(function() {\n const $el = $(this);\n const argument = <FunctionArgument> {\n name: $el.attr('name')!,\n type: $el.attr('type')!,", "score": 0.7287780046463013 }, { "filename": "src/cli-scraper.ts", "retrieved_chunk": " const options = program.opts();\n if (!options.url) {\n console.error('No URL provided');\n process.exit(1);\n }\n const baseDirectory = options.output.replace(/\\/$/, '');\n const customDirectory = options.customOverrides?.replace(/\\/$/, '') ?? null;\n const baseUrl = options.url.replace(/\\/$/, '');\n const pageListScraper = new WikiPageListScraper(`${baseUrl}/~pagelist?format=json`);\n const writer = new GluaApiWriter();", "score": 0.7262088060379028 }, { "filename": "src/cli-library-publisher.ts", "retrieved_chunk": " \"/**/\",\n \"continue\",\n ],\n \"Lua.diagnostics.disable\": [\n \"duplicate-set-field\", // Prevents complaining when a function exists twice in both the CLIENT and SERVER realm\n ],\n // TODO: runtime.path\n });\n fs.writeFileSync(path.join(options.output, 'config.json'), JSON.stringify(config, null, 2));\n const files = walk(options.input, (file, isDirectory) => isDirectory || (file.endsWith(`.lua`)));", "score": 0.7225207090377808 }, { "filename": "src/cli-scraper.ts", "retrieved_chunk": " const fileContent = fs.readFileSync(filePath, { encoding: 'utf-8' });\n const pageName = file.replace(/\\.lua$/, '');\n writer.addOverride(pageName, fileContent);\n }\n }\n const pageIndexes = await scrapeAndCollect(pageListScraper);\n for (const pageIndex of pageIndexes) {\n const pageMarkupScraper = new WikiPageMarkupScraper(`${baseUrl}/${pageIndex.address}?format=text`);\n pageMarkupScraper.on('scraped', (url, pageMarkups) => {\n if (pageMarkups.length === 0)", "score": 0.7219665050506592 }, { "filename": "src/cli-scraper.ts", "retrieved_chunk": " if (!fs.existsSync(`${moduleFile}.lua`))\n fs.writeFileSync(`${moduleFile}.lua`, '---@meta\\n\\n');\n if (!fs.existsSync(moduleFile))\n fs.mkdirSync(moduleFile, { recursive: true });\n fileName = fileName.replace(/[^a-z0-9]/gi, '_').toLowerCase();\n // Lua API\n fs.appendFileSync(path.join(baseDirectory, `${moduleName}.lua`), api);\n // JSON data\n const json = JSON.stringify(pageMarkups, null, 2);\n fs.writeFileSync(path.join(baseDirectory, moduleName, `${fileName}.json`), json);", "score": 0.7153493165969849 } ]
typescript
.forEach((arg, index) => {
import { Scrapeable, TraverseScraper } from './traverse-scraper.js'; import { ScrapeCallback } from './scraper.js'; import * as cheerio from 'cheerio'; import "reflect-metadata"; const tableColumnMetadataKey = Symbol("tableColumn"); export type TableColumnDefinition = { propertyKey: string | symbol, columnName: string, typeConverter: (value: string) => any }; export function tableColumn(columnName: string): PropertyDecorator { return (target: object, propertyKey: string | symbol) => { const existingColumns: TableColumnDefinition[] = Reflect.getMetadata(tableColumnMetadataKey, target) || []; const propertyType = Reflect.getMetadata("design:type", target, propertyKey); existingColumns.push({ propertyKey, columnName, typeConverter: (value: string) => { switch (propertyType) { case String: return value; case Number: return Number(value); case Boolean: return Boolean(value); default: return value; } } }); Reflect.defineMetadata(tableColumnMetadataKey, existingColumns, target); }; } export function getTableColumns(target: object): TableColumnDefinition[] { return Reflect.getMetadata(tableColumnMetadataKey, target) || []; } export class Row<T> { constructor(public data: T) { } } export class Table<T> implements Scrapeable { public url: string; public childUrls: Set<string> = new Set(); constructor(url: string, public rows: Row<T>[] = []) { this.url = url; } public addRow(row: Row<T>) { this.rows.push(row); } } export class TableScraper<T extends object>
extends TraverseScraper<Table<T>> {
constructor(baseUrl: string, private readonly factory: () => T) { super(baseUrl); } public getScrapeCallback(): ScrapeCallback<Table<T>> { return (response: Response, content: string): Table<T>[] => { const results: Table<T>[] = []; const $ = cheerio.load(content); const tables = $('table'); for (const table of tables) { const tableResult = this.fromTableElement($, table); if (tableResult) results.push(tableResult); } return results; }; } private fromTableElement($: cheerio.CheerioAPI, tableElement: cheerio.Element): Table<T> | null { const tableResult = new Table<T>(this.baseUrl); let headingRows = $(tableElement).find('thead > tr'); let shouldTrimHeadings = false; if (headingRows.length === 0) { headingRows = $(tableElement).find('tbody > tr:first-child'); shouldTrimHeadings = true; } let headings : cheerio.Element[] | undefined; if (headingRows.length > 0) headings = $(headingRows[0]).find('th').toArray(); if (!headings || headings.length === 0) throw new Error('No headings found in table'); let rows = $(tableElement).find('tbody > tr').toArray(); if (rows.length === 0) rows = $(tableElement).find('tr').toArray(); if (shouldTrimHeadings) rows = rows.slice(headingRows.length); let isEmpty = true; for (const row of rows) { const rowResult = this.fromRowElement($, row, headings); if (rowResult === null) continue; tableResult.addRow(rowResult); isEmpty = false; } if (isEmpty) return null; return tableResult; } private fromRowElement($: cheerio.CheerioAPI, rowElement: cheerio.Element, headings: cheerio.Element[]): Row<T> | null { const cells = $(rowElement).find('td').toArray(); const rowResult = this.factory(); const allTableColumns = getTableColumns(rowResult); let isEmpty = true; for (let i = 0; i < cells.length; i++) { const cell = cells[i]; const heading = headings[i]; if (!heading) continue; const headingText = $(heading).text(); if (!headingText) continue; let tableColumnDefinition = allTableColumns.find(column => column.columnName === headingText); if (!tableColumnDefinition) { const properties = Object.getOwnPropertyNames(rowResult); const propertyKey = properties.find(property => property.toLowerCase() === headingText.toLowerCase()); if (!propertyKey) continue; tableColumnDefinition = { propertyKey, columnName: headingText, typeConverter: (value: string) => value }; } const cellText = $(cell).text(); if (!cellText) continue; (rowResult as any)[tableColumnDefinition.propertyKey] = tableColumnDefinition.typeConverter(cellText); isEmpty = false; } if (isEmpty) return null; return new Row<T>(rowResult); } }
src/scrapers/table-scraper.ts
luttje-glua-api-snippets-9f40376
[ { "filename": "src/scrapers/traverse-scraper.ts", "retrieved_chunk": "import { Scraper, ScrapeCallback } from './scraper.js';\nexport interface Scrapeable {\n childUrls: Set<string>;\n}\nexport class TraverseScraper<T extends Scrapeable> extends Scraper<T> {\n protected readonly traversedUrls: Set<string> = new Set();\n protected childPageFilter?: (url: string) => boolean;\n public setChildPageFilter(filter: (url: string) => boolean): void {\n this.childPageFilter = filter;\n }", "score": 0.8482673764228821 }, { "filename": "src/scrapers/wiki-history-scraper.ts", "retrieved_chunk": " public history: WikiHistory[] = [];\n constructor(url: string, title: string) {\n super(url, title);\n }\n}\nexport class WikiHistoryPageScraper extends PageTraverseScraper<WikiHistoryPage> {\n constructor(baseUrl: string) {\n super(baseUrl, (url: string, title: string) => new WikiHistoryPage(url, title));\n }\n /**", "score": 0.8466936945915222 }, { "filename": "src/scrapers/page-traverse-scraper.ts", "retrieved_chunk": "import { Scrapeable, TraverseScraper } from './traverse-scraper.js';\nimport { decodeEntities } from './decode-entities.js';\nimport { ScrapeCallback } from './scraper.js';\nexport class Page implements Scrapeable {\n public url: string;\n public title: string;\n public childUrls: Set<string> = new Set();\n constructor(url: string, title: string) {\n this.url = url;\n this.title = title;", "score": 0.8289583921432495 }, { "filename": "src/scrapers/page-traverse-scraper.ts", "retrieved_chunk": " }\n}\nexport class PageTraverseScraper<T extends Page = Page> extends TraverseScraper<T> {\n private readonly factory: (url: string, title: string) => T;\n constructor(baseUrl: string, factory?: (url: string, title: string) => T) {\n super(baseUrl);\n this.factory = factory ?? ((url: string, title: string) => new Page(url, title) as T);\n }\n /**\n * Scrapes a page for its URL and title, and returns a list of child URLs", "score": 0.7994933128356934 }, { "filename": "src/scrapers/json-scraper.ts", "retrieved_chunk": " }\n public static makeScrapeCallback<T extends object = object>(): ScrapeCallback<T> {\n return (response: Response, content: string): T[] => {\n return JSON.parse(content);\n };\n }\n}", "score": 0.7930846214294434 } ]
typescript
extends TraverseScraper<Table<T>> {
import { ClassFunction, Enum, Function, HookFunction, LibraryFunction, Panel, PanelFunction, Realm, Struct, WikiPage, isPanel } from '../scrapers/wiki-page-markup-scraper.js'; import { putCommentBeforeEachLine, removeNewlines, safeFileName, toLowerCamelCase } from '../utils/string.js'; import { isClassFunction, isHookFunction, isLibraryFunction, isPanelFunction, isStruct, isEnum, } from '../scrapers/wiki-page-markup-scraper.js'; export const RESERVERD_KEYWORDS = new Set([ 'and', 'break', 'continue', 'do', 'else', 'elseif', 'end', 'false', 'for', 'function', 'goto', 'if', 'in', 'local', 'nil', 'not', 'or', 'repeat', 'return', 'then', 'true', 'until', 'while' ]); export class GluaApiWriter { private readonly writtenClasses: Set<string> = new Set(); private readonly writtenLibraryGlobals: Set<string> = new Set(); private readonly pageOverrides: Map<string, string> = new Map(); constructor() { } public static safeName(name: string) { if (name.includes('/')) name = name.replace(/\//g, ' or '); if (name.includes('=')) name = name.split('=')[0]; if (name.includes(' ')) name = toLowerCamelCase(name); // Remove any remaining characters not valid in a Lua variable/function name. name = name.replace(/[^A-Za-z\d_.]/g, ''); if (RESERVERD_KEYWORDS.has(name)) return `_${name}`; return name; } public addOverride(pageAddress: string, override: string) { this.pageOverrides.set(safeFileName(pageAddress, '.'), override); } public writePage(page: WikiPage) { const fileSafeAddress = safeFileName(page.address, '.'); if (this.pageOverrides.has(fileSafeAddress)) { let api = ''; if (isClassFunction(page)) api += this.writeClass(page.parent); else if (isLibraryFunction(page)) api += this.writeLibraryGlobal(page); api += this.pageOverrides.get(fileSafeAddress); return `${api}\n\n`; } else if (isClassFunction(page)) return this.writeClassFunction(page); else if (isLibraryFunction(page)) return this.writeLibraryFunction(page); else if (isHookFunction(page)) return this.writeHookFunction(page); else if (isPanel(page)) return this.writePanel(page); else if (isPanelFunction(page)) return this.writePanelFunction(page); else if (isEnum(page)) return this.writeEnum(page); else if (isStruct(page)) return this.writeStruct(page); } private writeClass(className: string, parent?: string, classFields: string = '') { let api: string = ''; if (!this.writtenClasses.has(className)) { const classOverride = `class.${className}`; if (this.pageOverrides.has(classOverride)) { api += this.pageOverrides.get(classOverride)!.replace(/\n$/g, '') + '\n\n'; api = api.replace('---{{CLASS_FIELDS}}\n', classFields); } else { api += `---@class ${className}`; if (parent) api += ` : ${parent}`; api += '\n'; api += classFields; api += `local ${className} = {}\n\n`; } this.writtenClasses.add(className); } return api; } private writeLibraryGlobal(func: LibraryFunction) { if (!func.dontDefineParent && !this.writtenLibraryGlobals.has(func.parent)) { const global = `${func.parent} = {}\n\n`; this.writtenLibraryGlobals.add(func.parent); return global; } return ''; } private writeClassFunction(func: ClassFunction) { let api: string
= this.writeClass(func.parent);
api += this.writeFunctionLuaDocComment(func, func.realm); api += this.writeFunctionDeclaration(func, func.realm, ':'); return api; } private writeLibraryFunction(func: LibraryFunction) { let api: string = this.writeLibraryGlobal(func); api += this.writeFunctionLuaDocComment(func, func.realm); api += this.writeFunctionDeclaration(func, func.realm); return api; } private writeHookFunction(func: HookFunction) { return this.writeClassFunction(func); } private writePanel(panel: Panel) { return this.writeClass(panel.name, panel.parent); } private writePanelFunction(func: PanelFunction) { let api: string = ''; api += this.writeFunctionLuaDocComment(func, func.realm); api += this.writeFunctionDeclaration(func, func.realm, ':'); return api; } private writeEnum(_enum: Enum) { let api: string = ''; const isContainedInTable = _enum.items[0]?.key.includes('.') ?? false; api += `---@enum ${_enum.name}\n`; if (isContainedInTable) api += `local ${_enum.name} = {\n`; const writeItem = (key: string, item: typeof _enum.items[0]) => { if (isContainedInTable) { key = key.split('.')[1]; api += ` ${key} = ${item.value}, ` + (item.description ? `--[[ ${item.description} ]]` : '') + '\n'; } else { const comment = item.description ? `${putCommentBeforeEachLine(item.description, false)}\n` : ''; api += `${comment}${key} = ${item.value}\n`; } }; for (const item of _enum.items) writeItem(item.key, item); if (isContainedInTable) api += '}'; api += `\n\n`; return api; } private writeStruct(struct: Struct) { let fields: string = ''; for (const field of struct.fields) { fields += `---@field ${GluaApiWriter.safeName(field.name)} ${this.transformType(field.type)} ${removeNewlines(field.description!)}\n`; } return this.writeClass(struct.name, undefined, fields); } public writePages(pages: WikiPage[]) { let api: string = ''; for (const page of pages) { api += this.writePage(page); } return api; } private transformType(type: string) { if (type === 'vararg') return '...'; return type; } private writeFunctionLuaDocComment(func: Function, realm: Realm) { let luaDocComment = `---[${realm.toUpperCase()}] ${putCommentBeforeEachLine(func.description!.trim())}\n`; luaDocComment += `---\n---[(View on wiki)](${func.url})\n`; if (func.arguments) { func.arguments.forEach((arg, index) => { if (!arg.name) arg.name = arg.type; if (arg.type === 'vararg') arg.name = '...'; luaDocComment += `---@param ${GluaApiWriter.safeName(arg.name)}${arg.default !== undefined ? `?` : ''} ${this.transformType(arg.type)} ${putCommentBeforeEachLine(arg.description!)}\n`; }); } if (func.returns) { const returns = `---@return ${func.returns.map(ret => this.transformType(ret.type)).join(', ')}`; func.returns.forEach(ret => { const description = removeNewlines(ret.description ?? ''); if (func.returns!.length === 1) { luaDocComment += `${returns} #${description}\n`; return; } luaDocComment += `${returns} #${this.transformType(ret.type)} - ${description}\n`; }); } return luaDocComment; } private writeFunctionDeclaration(func: Function, realm: Realm, indexer: string = '.') { let declaration = `function ${func.parent ? `${func.parent}${indexer}` : ''}${GluaApiWriter.safeName(func.name)}(`; if (func.arguments) { declaration += func.arguments.map(arg => { if (arg.type === 'vararg') return '...'; return GluaApiWriter.safeName(arg.name!); }).join(', '); } declaration += ') end\n\n'; return declaration; } }
src/api-writer/glua-api-writer.ts
luttje-glua-api-snippets-9f40376
[ { "filename": "src/scrapers/wiki-page-markup-scraper.ts", "retrieved_chunk": " if (base.parent === 'Global') {\n base.parent = '_G';\n (<LibraryFunction>base).dontDefineParent = true;\n }\n return <LibraryFunction> {\n ...base,\n type: 'libraryfunc'\n };\n } else if (isHookFunction) {\n return <HookFunction> {", "score": 0.757976770401001 }, { "filename": "src/scrapers/wiki-page-markup-scraper.ts", "retrieved_chunk": "export type FunctionReturn = WikiIdentifier & {};\nexport type Function = CommonWikiProperties & {\n parent: string;\n arguments?: FunctionArgument[];\n returns?: FunctionReturn[];\n};\nexport type ClassFunction = Function & {};\nexport type LibraryFunction = Function & {\n type: 'libraryfunc';\n dontDefineParent?: boolean;", "score": 0.7114426493644714 }, { "filename": "src/scrapers/wiki-page-markup-scraper.ts", "retrieved_chunk": " realm: $('realm:first').text() as Realm,\n arguments: arguments_,\n returns\n };\n if (isClassFunction) {\n return <ClassFunction> {\n ...base,\n type: 'classfunc'\n };\n } else if (isLibraryFunction) {", "score": 0.7068133354187012 }, { "filename": "src/cli-library-publisher.ts", "retrieved_chunk": " files.forEach((file) => {\n const relativePath = path.relative(options.input, file);\n const outputPath = path.join(options.output, libraryDirectory, relativePath);\n fs.copyFileSync(file, outputPath);\n });\n console.log(`Done building Library! It can be found @ ${options.output}`);\n}\nmain().catch((err) => {\n console.error(err);\n process.exit(1);", "score": 0.6990135908126831 }, { "filename": "src/cli-library-publisher.ts", "retrieved_chunk": " \"/**/\",\n \"continue\",\n ],\n \"Lua.diagnostics.disable\": [\n \"duplicate-set-field\", // Prevents complaining when a function exists twice in both the CLIENT and SERVER realm\n ],\n // TODO: runtime.path\n });\n fs.writeFileSync(path.join(options.output, 'config.json'), JSON.stringify(config, null, 2));\n const files = walk(options.input, (file, isDirectory) => isDirectory || (file.endsWith(`.lua`)));", "score": 0.6977910995483398 } ]
typescript
= this.writeClass(func.parent);
import { ScrapeCallback, Scraper } from './scraper.js'; import { deserializeXml } from '../utils/xml.js'; export type WikiFunctionType = 'panelfunc' | 'classfunc' | 'libraryfunc' | 'hook'; export type Realm = 'Menu' | 'Client' | 'Server' | 'Shared' | 'Client and menu'; export type CommonWikiProperties = { type: WikiFunctionType | 'enum' | 'struct' | 'panel'; address: string; name: string; description: string; realm: Realm; url: string; } export type WikiIdentifier = { name: string; type: string; description?: string; }; export type FunctionArgument = WikiIdentifier & { default?: string; }; export type FunctionReturn = WikiIdentifier & {}; export type Function = CommonWikiProperties & { parent: string; arguments?: FunctionArgument[]; returns?: FunctionReturn[]; }; export type ClassFunction = Function & {}; export type LibraryFunction = Function & { type: 'libraryfunc'; dontDefineParent?: boolean; }; export type HookFunction = Function & { type: 'hook'; isHook: 'yes'; }; export type PanelFunction = Function & { type: 'panelfunc'; isPanelFunction: 'yes'; }; export type EnumValue = { key: string; value: string; description: string; }; export type Enum = CommonWikiProperties & { type: 'enum'; items: EnumValue[]; }; export type StructField = { name: string; type: string; default?: any; description: string; }; export type Struct = CommonWikiProperties & { type: 'struct'; fields: StructField[]; }; export type Panel = CommonWikiProperties & { type: 'panel'; parent: string; }; export type WikiPage = ClassFunction | LibraryFunction | HookFunction | PanelFunction | Panel | Enum | Struct; /** * Guards */ export function isClassFunction(page: WikiPage): page is ClassFunction { return page.type === 'classfunc'; } export function isLibraryFunction(page: WikiPage): page is LibraryFunction { return page.type === 'libraryfunc'; } export function isHookFunction(page: WikiPage): page is HookFunction { return page.type === 'hook'; } export function isPanelFunction(page: WikiPage): page is PanelFunction { return page.type === 'panelfunc'; } export function isPanel(page: WikiPage): page is Panel { return page.type === 'panel'; } export function isEnum(page: WikiPage): page is Enum { return page.type === 'enum'; } export function isStruct(page: WikiPage): page is Struct { return page.type === 'struct'; } /** * Scraper */ export class WikiPageMarkupScraper extends Scraper<WikiPage> { /** * @param response The response from the page * @param content The content of the request * * @returns A list containing only the scraped page */ public getScrapeCallback(): ScrapeCallback<WikiPage> { return (response: Response, content: string): WikiPage[] => { const page
= deserializeXml<WikiPage | null>(content, ($) => {
const isEnum = $('enum').length > 0; const isStruct = $('structure').length > 0; const isFunction = $('function').length > 0; const isPanel = $('panel').length > 0; const mainElement = $(isEnum ? 'enum' : isStruct ? 'struct' : isPanel ? 'panel' : 'function'); const address = response.url.split('/').pop()!.split('?')[0]; if (isEnum) { const items = $('items item').map(function () { const $el = $(this); return <EnumValue>{ key: $el.attr('key')!, value: $el.attr('value')!, description: $el.text() }; }).get(); return <Enum>{ type: 'enum', name: address, address: address, description: $('description').text(), realm: $('realm').text() as Realm, items }; } else if (isStruct) { const fields = $('fields item').map(function () { const $el = $(this); return <StructField>{ name: $el.attr('name')!, type: $el.attr('type')!, default: $el.attr('default'), description: $el.text() }; }).get(); return <Struct>{ type: 'struct', name: address, address: address, description: $('description').text(), realm: $('realm').text() as Realm, fields }; } else if (isPanel) { return <Panel>{ type: 'panel', name: address, address: address, description: $('description').text(), realm: $('realm').text() as Realm, parent: $('parent').text() }; } else if (isFunction) { const isClassFunction = mainElement.attr('type') === 'classfunc'; const isLibraryFunction = mainElement.attr('type') === 'libraryfunc'; const isHookFunction = mainElement.attr('type') === 'hook'; const isPanelFunction = mainElement.attr('type') === 'panelfunc'; const arguments_ = $('args arg').map(function() { const $el = $(this); const argument = <FunctionArgument> { name: $el.attr('name')!, type: $el.attr('type')!, description: $el.text() }; if ($el.attr('default')) argument.default = $el.attr('default')!; return argument; }).get(); const returns = $('rets ret').map(function() { const $el = $(this); return <FunctionReturn> { name: $el.attr('name')!, type: $el.attr('type')!, description: $el.text() }; }).get(); const base = <Function> { type: mainElement.attr('type')!, parent: mainElement.attr('parent')!, name: mainElement.attr('name')!, address: address, description: $('description:first').text(), realm: $('realm:first').text() as Realm, arguments: arguments_, returns }; if (isClassFunction) { return <ClassFunction> { ...base, type: 'classfunc' }; } else if (isLibraryFunction) { if (base.parent === 'Global') { base.parent = '_G'; (<LibraryFunction>base).dontDefineParent = true; } return <LibraryFunction> { ...base, type: 'libraryfunc' }; } else if (isHookFunction) { return <HookFunction> { ...base, type: 'hook', isHook: 'yes' }; } else if (isPanelFunction) { return <PanelFunction> { ...base, type: 'panelfunc', isPanelFunction: 'yes' }; } } return null; }); if (!page) return []; page.url = response.url.replace(/\?format=text$/, ''); return [page]; }; } }
src/scrapers/wiki-page-markup-scraper.ts
luttje-glua-api-snippets-9f40376
[ { "filename": "src/scrapers/wiki-history-scraper.ts", "retrieved_chunk": " * Scrapes a wiki history page for information on wiki changes\n * \n * @param response The response from the page\n * @param content The content of the request\n * \n * @returns A list containing only the scraped page\n */\n public getScrapeCallback(): ScrapeCallback<WikiHistoryPage> {\n const baseScrapeCallback = super.getScrapeCallback();\n return async (response: Response, content: string): Promise<WikiHistoryPage[]> => {", "score": 0.9709066152572632 }, { "filename": "src/scrapers/page-traverse-scraper.ts", "retrieved_chunk": " * \n * @param response The response from the page\n * @param content The content of the request\n * \n * @returns A list containing only the scraped page\n */\n public getScrapeCallback(): ScrapeCallback<T> {\n return (response: Response, content: string): T[] => {\n const results: T[] = [];\n const url = response.url;", "score": 0.9698930382728577 }, { "filename": "src/scrapers/json-scraper.ts", "retrieved_chunk": "import { ScrapeCallback, Scraper } from './scraper.js';\nexport class JsonScraper<T extends object = object> extends Scraper<T> {\n /**\n * @param response The response from the page\n * @param content The content of the request\n * \n * @returns A list containing only the scraped page\n */\n public getScrapeCallback(): ScrapeCallback<T> {\n return JsonScraper.makeScrapeCallback<T>();", "score": 0.9037069082260132 }, { "filename": "src/scrapers/scraper.ts", "retrieved_chunk": " }\n public setRetryOptions(options: RequestInitWithRetry): void {\n this.retryOptions = options;\n }\n /**\n * Scrapes the base url and has the callback process the response\n */\n public async scrape(): Promise<void> {\n const callback = this.getScrapeCallback();\n await this.visitOne(this.baseUrl, callback);", "score": 0.867511510848999 }, { "filename": "src/scrapers/traverse-scraper.ts", "retrieved_chunk": " /**\n * Override scraping so we traverse all child URLs of the first scraped page\n */\n public async scrape(): Promise<void> {\n const callback = this.getScrapeCallback();\n await this.traverse(this.baseUrl, callback.bind(this));\n }\n protected getTraverseUrl(url: string): string | false {\n if (!url.startsWith(this.baseUrl))\n return false;", "score": 0.8536279797554016 } ]
typescript
= deserializeXml<WikiPage | null>(content, ($) => {
import { ClassFunction, Enum, Function, HookFunction, LibraryFunction, Panel, PanelFunction, Realm, Struct, WikiPage, isPanel } from '../scrapers/wiki-page-markup-scraper.js'; import { putCommentBeforeEachLine, removeNewlines, safeFileName, toLowerCamelCase } from '../utils/string.js'; import { isClassFunction, isHookFunction, isLibraryFunction, isPanelFunction, isStruct, isEnum, } from '../scrapers/wiki-page-markup-scraper.js'; export const RESERVERD_KEYWORDS = new Set([ 'and', 'break', 'continue', 'do', 'else', 'elseif', 'end', 'false', 'for', 'function', 'goto', 'if', 'in', 'local', 'nil', 'not', 'or', 'repeat', 'return', 'then', 'true', 'until', 'while' ]); export class GluaApiWriter { private readonly writtenClasses: Set<string> = new Set(); private readonly writtenLibraryGlobals: Set<string> = new Set(); private readonly pageOverrides: Map<string, string> = new Map(); constructor() { } public static safeName(name: string) { if (name.includes('/')) name = name.replace(/\//g, ' or '); if (name.includes('=')) name = name.split('=')[0]; if (name.includes(' ')) name
= toLowerCamelCase(name);
// Remove any remaining characters not valid in a Lua variable/function name. name = name.replace(/[^A-Za-z\d_.]/g, ''); if (RESERVERD_KEYWORDS.has(name)) return `_${name}`; return name; } public addOverride(pageAddress: string, override: string) { this.pageOverrides.set(safeFileName(pageAddress, '.'), override); } public writePage(page: WikiPage) { const fileSafeAddress = safeFileName(page.address, '.'); if (this.pageOverrides.has(fileSafeAddress)) { let api = ''; if (isClassFunction(page)) api += this.writeClass(page.parent); else if (isLibraryFunction(page)) api += this.writeLibraryGlobal(page); api += this.pageOverrides.get(fileSafeAddress); return `${api}\n\n`; } else if (isClassFunction(page)) return this.writeClassFunction(page); else if (isLibraryFunction(page)) return this.writeLibraryFunction(page); else if (isHookFunction(page)) return this.writeHookFunction(page); else if (isPanel(page)) return this.writePanel(page); else if (isPanelFunction(page)) return this.writePanelFunction(page); else if (isEnum(page)) return this.writeEnum(page); else if (isStruct(page)) return this.writeStruct(page); } private writeClass(className: string, parent?: string, classFields: string = '') { let api: string = ''; if (!this.writtenClasses.has(className)) { const classOverride = `class.${className}`; if (this.pageOverrides.has(classOverride)) { api += this.pageOverrides.get(classOverride)!.replace(/\n$/g, '') + '\n\n'; api = api.replace('---{{CLASS_FIELDS}}\n', classFields); } else { api += `---@class ${className}`; if (parent) api += ` : ${parent}`; api += '\n'; api += classFields; api += `local ${className} = {}\n\n`; } this.writtenClasses.add(className); } return api; } private writeLibraryGlobal(func: LibraryFunction) { if (!func.dontDefineParent && !this.writtenLibraryGlobals.has(func.parent)) { const global = `${func.parent} = {}\n\n`; this.writtenLibraryGlobals.add(func.parent); return global; } return ''; } private writeClassFunction(func: ClassFunction) { let api: string = this.writeClass(func.parent); api += this.writeFunctionLuaDocComment(func, func.realm); api += this.writeFunctionDeclaration(func, func.realm, ':'); return api; } private writeLibraryFunction(func: LibraryFunction) { let api: string = this.writeLibraryGlobal(func); api += this.writeFunctionLuaDocComment(func, func.realm); api += this.writeFunctionDeclaration(func, func.realm); return api; } private writeHookFunction(func: HookFunction) { return this.writeClassFunction(func); } private writePanel(panel: Panel) { return this.writeClass(panel.name, panel.parent); } private writePanelFunction(func: PanelFunction) { let api: string = ''; api += this.writeFunctionLuaDocComment(func, func.realm); api += this.writeFunctionDeclaration(func, func.realm, ':'); return api; } private writeEnum(_enum: Enum) { let api: string = ''; const isContainedInTable = _enum.items[0]?.key.includes('.') ?? false; api += `---@enum ${_enum.name}\n`; if (isContainedInTable) api += `local ${_enum.name} = {\n`; const writeItem = (key: string, item: typeof _enum.items[0]) => { if (isContainedInTable) { key = key.split('.')[1]; api += ` ${key} = ${item.value}, ` + (item.description ? `--[[ ${item.description} ]]` : '') + '\n'; } else { const comment = item.description ? `${putCommentBeforeEachLine(item.description, false)}\n` : ''; api += `${comment}${key} = ${item.value}\n`; } }; for (const item of _enum.items) writeItem(item.key, item); if (isContainedInTable) api += '}'; api += `\n\n`; return api; } private writeStruct(struct: Struct) { let fields: string = ''; for (const field of struct.fields) { fields += `---@field ${GluaApiWriter.safeName(field.name)} ${this.transformType(field.type)} ${removeNewlines(field.description!)}\n`; } return this.writeClass(struct.name, undefined, fields); } public writePages(pages: WikiPage[]) { let api: string = ''; for (const page of pages) { api += this.writePage(page); } return api; } private transformType(type: string) { if (type === 'vararg') return '...'; return type; } private writeFunctionLuaDocComment(func: Function, realm: Realm) { let luaDocComment = `---[${realm.toUpperCase()}] ${putCommentBeforeEachLine(func.description!.trim())}\n`; luaDocComment += `---\n---[(View on wiki)](${func.url})\n`; if (func.arguments) { func.arguments.forEach((arg, index) => { if (!arg.name) arg.name = arg.type; if (arg.type === 'vararg') arg.name = '...'; luaDocComment += `---@param ${GluaApiWriter.safeName(arg.name)}${arg.default !== undefined ? `?` : ''} ${this.transformType(arg.type)} ${putCommentBeforeEachLine(arg.description!)}\n`; }); } if (func.returns) { const returns = `---@return ${func.returns.map(ret => this.transformType(ret.type)).join(', ')}`; func.returns.forEach(ret => { const description = removeNewlines(ret.description ?? ''); if (func.returns!.length === 1) { luaDocComment += `${returns} #${description}\n`; return; } luaDocComment += `${returns} #${this.transformType(ret.type)} - ${description}\n`; }); } return luaDocComment; } private writeFunctionDeclaration(func: Function, realm: Realm, indexer: string = '.') { let declaration = `function ${func.parent ? `${func.parent}${indexer}` : ''}${GluaApiWriter.safeName(func.name)}(`; if (func.arguments) { declaration += func.arguments.map(arg => { if (arg.type === 'vararg') return '...'; return GluaApiWriter.safeName(arg.name!); }).join(', '); } declaration += ') end\n\n'; return declaration; } }
src/api-writer/glua-api-writer.ts
luttje-glua-api-snippets-9f40376
[ { "filename": "src/utils/filesystem.ts", "retrieved_chunk": " * @param windowsPath The Windows path to convert.\n * @returns The Unix path.\n */\nexport function convertWindowsToUnixPath(windowsPath: string) {\n let unixPath = windowsPath;\n unixPath = unixPath.replace(/^[A-Z]:/, (match) => match.toLowerCase());\n unixPath = unixPath.replace(/\\\\/g, '/');\n let colonIndex = unixPath.indexOf(':');\n if (colonIndex > -1)\n unixPath = unixPath.replace(/:/, '');", "score": 0.7717055082321167 }, { "filename": "src/utils/string.ts", "retrieved_chunk": "/**\n * Converts a string to lowerCamelCase \n * \n * @param str The string to convert\n * @returns The converted string\n */\nexport function toLowerCamelCase(str: string) {\n str = str.replace(/[_-]/g, ' ');\n return str.replace(/(?:^\\w|\\b\\w)/g, (letter, index) => {\n return index === 0 ? letter.toLowerCase() : letter.toUpperCase();", "score": 0.7683762907981873 }, { "filename": "src/cli-scraper.ts", "retrieved_chunk": " return;\n const api = writer.writePages(pageMarkups);\n let fileName = pageIndex.address;\n let moduleName = fileName;\n if (fileName.includes('.') || fileName.includes(':') || fileName.includes('/')) {\n [moduleName, fileName] = fileName.split(/[:.\\/]/, 2);\n }\n // Make sure modules like Entity and ENTITY are placed in the same file.\n moduleName = moduleName.toLowerCase();\n const moduleFile = path.join(baseDirectory, moduleName);", "score": 0.757469892501831 }, { "filename": "src/scrapers/traverse-scraper.ts", "retrieved_chunk": " if (url.endsWith('/'))\n url = url.substring(0, url.length - 1);\n if (url.includes('#'))\n url = url.substring(0, url.indexOf('#'));\n if (this.traversedUrls.has(url))\n return false;\n if (this.childPageFilter && !this.childPageFilter(url))\n return false;\n return url;\n }", "score": 0.7159745693206787 }, { "filename": "src/utils/filesystem.ts", "retrieved_chunk": "import archiver from 'archiver';\nimport path from 'path';\nimport fs from 'fs';\nexport function dateToFilename(date: Date) {\n return date.toISOString().replace(/:/g, '-')\n .slice(0, -5) // without .000Z\n .replace(/T/g, '_');\n}\nexport function walk(dir: string, filter?: (fileOrDirectory: string, isDirectory?: boolean) => boolean): string[] {\n const filelist: string[] = [];", "score": 0.6980887651443481 } ]
typescript
= toLowerCamelCase(name);
import { exec } from 'child_process'; import { GolemFile, GolemTarget, isGolemTarget } from './types'; import { ChatGPTMessage, ChatGPT_completion } from './chat_gpt'; import { readFile } from 'fs/promises'; import { dirname } from 'path'; import logger from './logger'; import { generateCacheKey, isCacheValid, saveOutputToCache, loadOutputFromCache, appendToGolemFile } from './utils'; import { writeFileSync} from 'fs'; // TODO 1: Check if prompt asks for additional targets. // TODO 2: Check if targets have other dependencies. // TODO 3: Saving properly (for example, it saves all of the previous context for imp task) // TODO 4: Use different files interface ExecutionContext { [key: string]: any; } const mainPrompt: ChatGPTMessage = { role: 'system', content: `You are an Agentic LLM assistant, designed only to produce code and helpful information. You may be asked to generate new targets. If the prompt given to you contains the phrase 'generate new targets', your response will be to generate a list of targets to help answer the prompt. The targets must be written as unnumbered items separated by lines starting with 'Target:'. The items in the list will not be arranged in any particular order. For example: Prompt: As an agentic LLM, generate new targets for the next iteration. Response: Target: Write a function to divide two numbers. Target: Create a class called Employee. Target: Write unit tests for the function GetPeopleInterests. It is not always the case that you will be asked to generate new targets. If the prompt does not contain the phrase 'generate new targets', then proceed to answer the prompt as truthfully as possible. For example: Prompt: What is capital of France? Response: Paris. Prompt: How many days are in the month of April? Response: 30 days. You are opinionated. If asked to provide a subjective answer, start by saying 'In my opinion' then answer the prompt. For example: Prompt: What is the best sport? Response: In my opinion, soccer. ` } export async function executeTarget(target: string, golemFile: GolemFile, golemFilePath: string, context: Map<string, any> = new Map()): Promise<void> {
const golemTarget = golemFile[target];
if (!golemTarget) { throw new Error(`Target "${target}" not found in Golem file.`); } console.log(`Executing target: ${target}`); if (golemTarget.dependencies) { console.log(`Dependencies for ${target}: ${golemTarget.dependencies}`); for (const dependency of golemTarget.dependencies) { if (dependency) { await executeTarget(dependency, golemFile, golemFilePath, context); } } } await executeAIChatWithCache(target, golemFile, golemFilePath, context); console.log(`Context after ${target} execution:`, context); } function executeCommand(command: string): Promise<void> { return new Promise((resolve, reject) => { exec(command, (error, stdout, stderr) => { if (error) { logger.error(`Error executing command: ${command}`); logger.error(stderr); reject(error); } else { logger.debug(stdout); resolve(); } }); }); } async function executeAIChatWithCache(target: string, golemFile: GolemFile, golemFilePath: string, context: Map<string, any>): Promise<void> { const golemFileToArray: any = []; for (const key in golemFile){ const val = golemFile[key as keyof typeof golemFile]; golemFileToArray.push(val); } const golemTarget = golemFile[target]; if (!golemTarget || !isGolemTarget(golemTarget)) { return; } const cacheKey = generateCacheKey(target, golemTarget.dependencies || [], [...golemFileToArray] || ''); if (isCacheValid(target, cacheKey)) { console.log("Returning Cached output"); const cachedOutput = loadOutputFromCache(target, cacheKey); context.set(target, cachedOutput); } else { await executeAIChat(target, golemFile, golemFilePath, context); saveOutputToCache(target, cacheKey, context); } } async function executeAIChat(target: string, golemFile: GolemFile, golemFilePath: string, context: Map<string, any>): Promise<void> { // ============== Setup start ==================================== const contextOfCurrentTarget: string[] = []; const allOutputs: {[key: string]: any} = {}; const golemTarget = golemFile[target]; console.log("gT", golemTarget); if (!golemTarget) { throw new Error(`Target "${target}" not found in Golem file.`); } if (!isGolemTarget(golemTarget)) { return; } if (!golemTarget.prompt && !golemTarget.model) { golemTarget.model = 'cat'; } let prompt = golemTarget.prompt ?? "{no prompt}"; if (isGolemTarget(golemTarget) && golemTarget.prompt) { prompt = golemTarget.prompt; const placeholderRegex = /{{\s*([\w\/.-]+)\s*}}/g; let match; while ((match = placeholderRegex.exec(prompt)) !== null) { const key = match[1]; if (context.has(key)) { prompt = prompt.replace(match[0], context.get(key)); } else { prompt = prompt.replace(match[0], ""); } } } else if (!golemTarget.prompt) { const defaultValues = new Map(context.entries()); context.set("default", Object.fromEntries(defaultValues)); return; } const model = golemTarget.model ?? 'gpt-3.5-turbo'; // ============== Setup end ==================================== if (model === 'cat') { const concatenatedOutput = golemTarget.dependencies.map(dep => context.get(dep)).join(''); context.set(target, concatenatedOutput); } else if (model == "gpt-3.5-turbo" || model == "gpt-3.5-turbo-0301" || model == "gpt-4-0314" || model == "gpt-4-32k") { if ("model" in golemTarget) { delete golemTarget.model; } // This gets the 'keys' (subtasks) of a target (task) const golemTargetKeys: string[] = Object.keys(golemTarget); // It starts from 1 as index 0 is dependencies. This can be changed if needed for (let i = 1; i < golemTargetKeys.length; i++){ // console.log("gTKi", golemTargetKeys[i]); const val: any = golemTarget[golemTargetKeys[i] as keyof typeof golemTarget]; // console.log("val", val); const previousContext: string | undefined = contextOfCurrentTarget[0] || ''; // Concat the previousContext (if undefined) to the current subtask (here, named val) const content = previousContext + val; // console.log("content", content); // This block of code replaces the {{}} placeholders in the string from the yaml file // with the output of the subtask or task it requires const replacedString = content.replace(/{{(.*?)}}/g, (match, p1) => { // Remove the curly braces from the placeholder const placeholder = p1.trim(); // Replace the placeholder with the corresponding value from the map return context.get(placeholder) || placeholder; }); // console.log("context", context); // console.log("replacedString", replacedString); const taskGenerationMessages: ChatGPTMessage[] = [ mainPrompt, { role: 'user', content: replacedString, }, ]; const response = await ChatGPT_completion(taskGenerationMessages, model, 0.7, 0.9); contextOfCurrentTarget.length = 0; //clear the previous context contextOfCurrentTarget.push(response); //append the new context to be used in the next iteration allOutputs[golemTargetKeys[i]] = response; const lines: string[] = response.split('\n'); // Extract the targets from the lines that start with "Target:" const targets: string[] = lines.filter((line: string) => line.startsWith("Target:")) .map((line: string) => line.slice(8)); let count = 1; targets.forEach((createdTarget: string) => { const targetName = target.concat("_target".concat(count.toString())); const newTarget: string = `\n${targetName}:\n dependencies: []\n prompt: ${createdTarget}`; appendToGolemFile(golemFilePath, newTarget); golemTargetKeys.push(targetName); golemTarget[targetName] = createdTarget; count += 1; }); if (golemTargetKeys.length === 2){ if (!response) { context.set(target, `Default value for ${target}`); } else { context.set(target, response); console.log(context); } } else if (golemTargetKeys.length > 2){ try { for (const key in allOutputs) { context.set(key, allOutputs[key]); } }catch (error: any) { logger.error(`Error generating AI response: ${error.message}`); } } } }else { throw new Error(`No such supported model ${model}`); } }
src/executor.ts
Confabulation-Corporation-golem-ac8b554
[ { "filename": "src/golem.ts", "retrieved_chunk": " 'Run the specified Golem file or the default Golem file if none is provided.',\n (yargs) => {\n yargs.positional('golemFile', {\n describe: 'Path to the Golem file',\n default: 'Golem.yaml',\n type: 'string',\n });\n },\n async (argv) => {\n try {", "score": 0.7857012748718262 }, { "filename": "src/parser.ts", "retrieved_chunk": "import * as yaml from 'js-yaml';\nimport { GolemFile } from './types';\nexport function parseGolemFile(content: string): GolemFile {\n try {\n const parsedContent = yaml.load(content) as GolemFile;\n // Update the parsing logic to handle the task_generation_prompt field\n return parsedContent;\n } catch (error: any) {\n throw new Error(`Error parsing Golem file: ${error.message}`);\n }", "score": 0.779218316078186 }, { "filename": "src/types.ts", "retrieved_chunk": "export interface GolemTarget {\n dependencies: string[];\n prompt: string;\n model?: string; // Add this line\n task_generation_prompt?: string; // Add this line\n [key: string]: string[] | string | undefined;\n}\nexport type GolemFile = {\n default: string[];\n} & {", "score": 0.7725016474723816 }, { "filename": "src/validator.ts", "retrieved_chunk": "import { GolemFile } from './types';\n// import { GolemFileError } from './errors';\nexport function validateGolemFile(golemFile: GolemFile): void {\n // Validate the Golem file structure and content\n // If any errors are found, throw a GolemFileError with a specific error message\n}", "score": 0.7719581127166748 }, { "filename": "src/chat_gpt.ts", "retrieved_chunk": " const waitTime = resetMs + Math.random() * 1000;\n logger.warn(\n `Rate limit or server error encountered (status: ${error.response.status}). Retrying in ${waitTime} ms...`\n );\n await new Promise((resolve) => setTimeout(resolve, waitTime));\n } else {\n throw error;\n }\n }\n }", "score": 0.7551758289337158 } ]
typescript
const golemTarget = golemFile[target];
import { exec } from 'child_process'; import { GolemFile, GolemTarget, isGolemTarget } from './types'; import { ChatGPTMessage, ChatGPT_completion } from './chat_gpt'; import { readFile } from 'fs/promises'; import { dirname } from 'path'; import logger from './logger'; import { generateCacheKey, isCacheValid, saveOutputToCache, loadOutputFromCache, appendToGolemFile } from './utils'; import { writeFileSync} from 'fs'; // TODO 1: Check if prompt asks for additional targets. // TODO 2: Check if targets have other dependencies. // TODO 3: Saving properly (for example, it saves all of the previous context for imp task) // TODO 4: Use different files interface ExecutionContext { [key: string]: any; } const mainPrompt: ChatGPTMessage = { role: 'system', content: `You are an Agentic LLM assistant, designed only to produce code and helpful information. You may be asked to generate new targets. If the prompt given to you contains the phrase 'generate new targets', your response will be to generate a list of targets to help answer the prompt. The targets must be written as unnumbered items separated by lines starting with 'Target:'. The items in the list will not be arranged in any particular order. For example: Prompt: As an agentic LLM, generate new targets for the next iteration. Response: Target: Write a function to divide two numbers. Target: Create a class called Employee. Target: Write unit tests for the function GetPeopleInterests. It is not always the case that you will be asked to generate new targets. If the prompt does not contain the phrase 'generate new targets', then proceed to answer the prompt as truthfully as possible. For example: Prompt: What is capital of France? Response: Paris. Prompt: How many days are in the month of April? Response: 30 days. You are opinionated. If asked to provide a subjective answer, start by saying 'In my opinion' then answer the prompt. For example: Prompt: What is the best sport? Response: In my opinion, soccer. ` } export async function executeTarget(target: string, golemFile: GolemFile, golemFilePath: string, context: Map<string, any> = new Map()): Promise<void> { const golemTarget = golemFile[target]; if (!golemTarget) { throw new Error(`Target "${target}" not found in Golem file.`); } console.log(`Executing target: ${target}`); if (golemTarget.dependencies) { console.log(`Dependencies for ${target}: ${golemTarget.dependencies}`); for (const dependency of golemTarget.dependencies) { if (dependency) { await executeTarget(dependency, golemFile, golemFilePath, context); } } } await executeAIChatWithCache(target, golemFile, golemFilePath, context); console.log(`Context after ${target} execution:`, context); } function executeCommand(command: string): Promise<void> { return new Promise((resolve, reject) => { exec(command, (error, stdout, stderr) => { if (error) { logger.error(`Error executing command: ${command}`); logger.error(stderr); reject(error); } else { logger.debug(stdout); resolve(); } }); }); } async function executeAIChatWithCache(target: string, golemFile: GolemFile, golemFilePath: string, context: Map<string, any>): Promise<void> { const golemFileToArray: any = []; for (const key in golemFile){ const val = golemFile[key as keyof typeof golemFile]; golemFileToArray.push(val); } const golemTarget = golemFile[target]; if (!golemTarget || !isGolemTarget(golemTarget)) { return; } const cacheKey = generateCacheKey(target, golemTarget.dependencies || [], [...golemFileToArray] || ''); if (isCacheValid(target, cacheKey)) { console.log("Returning Cached output"); const cachedOutput = loadOutputFromCache(target, cacheKey); context.set(target, cachedOutput); } else { await executeAIChat(target, golemFile, golemFilePath, context); saveOutputToCache(target, cacheKey, context); } } async function executeAIChat(target: string, golemFile: GolemFile, golemFilePath: string, context: Map<string, any>): Promise<void> { // ============== Setup start ==================================== const contextOfCurrentTarget: string[] = []; const allOutputs: {[key: string]: any} = {}; const golemTarget = golemFile[target]; console.log("gT", golemTarget); if (!golemTarget) { throw new Error(`Target "${target}" not found in Golem file.`); } if (!isGolemTarget(golemTarget)) { return; } if (!golemTarget.prompt && !golemTarget.model) { golemTarget.model = 'cat'; } let prompt = golemTarget.prompt ?? "{no prompt}"; if (isGolemTarget(golemTarget) && golemTarget.prompt) { prompt = golemTarget.prompt; const placeholderRegex = /{{\s*([\w\/.-]+)\s*}}/g; let match; while ((match = placeholderRegex.exec(prompt)) !== null) { const key = match[1]; if (context.has(key)) { prompt = prompt.replace(match[0], context.get(key)); } else { prompt = prompt.replace(match[0], ""); } } } else if (!golemTarget.prompt) { const defaultValues = new Map(context.entries()); context.set("default", Object.fromEntries(defaultValues)); return; } const model = golemTarget.model ?? 'gpt-3.5-turbo'; // ============== Setup end ==================================== if (model === 'cat') { const concatenatedOutput =
golemTarget.dependencies.map(dep => context.get(dep)).join('');
context.set(target, concatenatedOutput); } else if (model == "gpt-3.5-turbo" || model == "gpt-3.5-turbo-0301" || model == "gpt-4-0314" || model == "gpt-4-32k") { if ("model" in golemTarget) { delete golemTarget.model; } // This gets the 'keys' (subtasks) of a target (task) const golemTargetKeys: string[] = Object.keys(golemTarget); // It starts from 1 as index 0 is dependencies. This can be changed if needed for (let i = 1; i < golemTargetKeys.length; i++){ // console.log("gTKi", golemTargetKeys[i]); const val: any = golemTarget[golemTargetKeys[i] as keyof typeof golemTarget]; // console.log("val", val); const previousContext: string | undefined = contextOfCurrentTarget[0] || ''; // Concat the previousContext (if undefined) to the current subtask (here, named val) const content = previousContext + val; // console.log("content", content); // This block of code replaces the {{}} placeholders in the string from the yaml file // with the output of the subtask or task it requires const replacedString = content.replace(/{{(.*?)}}/g, (match, p1) => { // Remove the curly braces from the placeholder const placeholder = p1.trim(); // Replace the placeholder with the corresponding value from the map return context.get(placeholder) || placeholder; }); // console.log("context", context); // console.log("replacedString", replacedString); const taskGenerationMessages: ChatGPTMessage[] = [ mainPrompt, { role: 'user', content: replacedString, }, ]; const response = await ChatGPT_completion(taskGenerationMessages, model, 0.7, 0.9); contextOfCurrentTarget.length = 0; //clear the previous context contextOfCurrentTarget.push(response); //append the new context to be used in the next iteration allOutputs[golemTargetKeys[i]] = response; const lines: string[] = response.split('\n'); // Extract the targets from the lines that start with "Target:" const targets: string[] = lines.filter((line: string) => line.startsWith("Target:")) .map((line: string) => line.slice(8)); let count = 1; targets.forEach((createdTarget: string) => { const targetName = target.concat("_target".concat(count.toString())); const newTarget: string = `\n${targetName}:\n dependencies: []\n prompt: ${createdTarget}`; appendToGolemFile(golemFilePath, newTarget); golemTargetKeys.push(targetName); golemTarget[targetName] = createdTarget; count += 1; }); if (golemTargetKeys.length === 2){ if (!response) { context.set(target, `Default value for ${target}`); } else { context.set(target, response); console.log(context); } } else if (golemTargetKeys.length > 2){ try { for (const key in allOutputs) { context.set(key, allOutputs[key]); } }catch (error: any) { logger.error(`Error generating AI response: ${error.message}`); } } } }else { throw new Error(`No such supported model ${model}`); } }
src/executor.ts
Confabulation-Corporation-golem-ac8b554
[ { "filename": "src/dependencies.ts", "retrieved_chunk": "import { GolemFile, isGolemTarget } from './types';\nimport { GolemError } from './errors';\nexport function resolveDependencies(golemFile: GolemFile): string[] {\n const resolvedDependencies: string[] = [];\n if (!golemFile.default) {\n throw new GolemError(\"No default target specified\");\n }\n const defaultTarget = golemFile.default;\n if (isGolemTarget(defaultTarget)) {\n const defaultDependencies = defaultTarget.dependencies;", "score": 0.8000735640525818 }, { "filename": "src/parser.ts", "retrieved_chunk": "import * as yaml from 'js-yaml';\nimport { GolemFile } from './types';\nexport function parseGolemFile(content: string): GolemFile {\n try {\n const parsedContent = yaml.load(content) as GolemFile;\n // Update the parsing logic to handle the task_generation_prompt field\n return parsedContent;\n } catch (error: any) {\n throw new Error(`Error parsing Golem file: ${error.message}`);\n }", "score": 0.7466976046562195 }, { "filename": "src/utils.ts", "retrieved_chunk": " return join('.golem', `${target}_${cacheKey}_output.txt`);\n}\nexport function isCacheValid(target: string, cacheKey: string): boolean {\n const cachedOutputPath = getCachedOutputPath(target, cacheKey);\n return existsSync(cachedOutputPath);\n}\nexport function saveOutputToCache(target: string, cacheKey: string, context: Map<string, any>): void {\n const cachedOutputPath = getCachedOutputPath(target, cacheKey);\n const defaultMap = new Map();\n if (context.has(\"default\")) {", "score": 0.7415461540222168 }, { "filename": "src/golem.ts", "retrieved_chunk": " const golemFilePath = argv.golemFile as string;\n // console.log(golemFilePath);\n // Add this line to create the .golem/ directory\n createGolemCacheDir();\n // Read the Golem file content\n const golemFileContent = fs.readFileSync(golemFilePath, 'utf8');\n const golemFile = parseGolemFile(golemFileContent);\n console.log(golemFile);\n // Execute the default target with an empty context\n await executeTarget('default', golemFile, golemFilePath, new Map());", "score": 0.7357267141342163 }, { "filename": "src/types.ts", "retrieved_chunk": " [target: string]: GolemTarget | undefined;\n};\nexport function isGolemTarget(target: GolemTarget | string[] | undefined): target is GolemTarget {\n return target !== undefined && (target as GolemTarget).dependencies !== undefined;\n}", "score": 0.7089064121246338 } ]
typescript
golemTarget.dependencies.map(dep => context.get(dep)).join('');
import { Scrapeable, TraverseScraper } from './traverse-scraper.js'; import { decodeEntities } from './decode-entities.js'; import { ScrapeCallback } from './scraper.js'; export class Page implements Scrapeable { public url: string; public title: string; public childUrls: Set<string> = new Set(); constructor(url: string, title: string) { this.url = url; this.title = title; } } export class PageTraverseScraper<T extends Page = Page> extends TraverseScraper<T> { private readonly factory: (url: string, title: string) => T; constructor(baseUrl: string, factory?: (url: string, title: string) => T) { super(baseUrl); this.factory = factory ?? ((url: string, title: string) => new Page(url, title) as T); } /** * Scrapes a page for its URL and title, and returns a list of child URLs * * @param response The response from the page * @param content The content of the request * * @returns A list containing only the scraped page */ public getScrapeCallback(): ScrapeCallback<T> { return (response: Response, content: string): T[] => { const results: T[] = []; const url = response.url; const title = decodeEntities(content.match(/<title>(.*?)<\/title>/)?.[1] || ''); const page = this.factory(url, title); const links = content.match(/<a\s+(?:[^>]*?\s+)?href=(["'])([\s\S]*?)\1(?:[^>]*?\s+)?>(?:[\s\S]*?<\/a>)?/gi) ?.map(link => link.replace(/\n/g, '')) ?.map(link => link.match(/href=(["'])([\s\S]*?)\1/i)?.[2] || '') || []; for (let link of links) { link = decodeEntities(link); let absoluteUrl = link.startsWith('http') ? link : new URL(link, url).toString(); if (page.childUrls.has(absoluteUrl)) continue;
if (this.childPageFilter && !this.childPageFilter(absoluteUrl)) continue;
page.childUrls.add(absoluteUrl); } results.push(page); return results; }; } }
src/scrapers/page-traverse-scraper.ts
luttje-glua-api-snippets-9f40376
[ { "filename": "src/scrapers/traverse-scraper.ts", "retrieved_chunk": " if (url.endsWith('/'))\n url = url.substring(0, url.length - 1);\n if (url.includes('#'))\n url = url.substring(0, url.indexOf('#'));\n if (this.traversedUrls.has(url))\n return false;\n if (this.childPageFilter && !this.childPageFilter(url))\n return false;\n return url;\n }", "score": 0.7309136390686035 }, { "filename": "src/cli-scraper.ts", "retrieved_chunk": " const fileContent = fs.readFileSync(filePath, { encoding: 'utf-8' });\n const pageName = file.replace(/\\.lua$/, '');\n writer.addOverride(pageName, fileContent);\n }\n }\n const pageIndexes = await scrapeAndCollect(pageListScraper);\n for (const pageIndex of pageIndexes) {\n const pageMarkupScraper = new WikiPageMarkupScraper(`${baseUrl}/${pageIndex.address}?format=text`);\n pageMarkupScraper.on('scraped', (url, pageMarkups) => {\n if (pageMarkups.length === 0)", "score": 0.666100263595581 }, { "filename": "src/scrapers/wiki-history-scraper.ts", "retrieved_chunk": " parseInt(dateParts[0]) - 1, // Month\n parseInt(dateParts[1]), // Day\n parseInt(timeParts[0]) + (dateTimeParts[2] === 'PM' ? 12 : 0), // Hour\n parseInt(timeParts[1]), // Minute\n parseInt(timeParts[2]), // Second\n ),\n );\n const url = pageLinkAnchorElement.attr('href') || '';\n const change = $(pageLinkElement).text().replace($(pageLinkAnchorElement).text(), '').replace(/\\s+/g, ' ');\n page.history.push({", "score": 0.6621302366256714 }, { "filename": "src/scrapers/wiki-history-scraper.ts", "retrieved_chunk": " const pageLinkElement = $(changeElement).find('.address');\n const pageLinkAnchorElement = pageLinkElement.find('a');\n const user = $(changeElement).find('.user a').text();\n const rawDateTime = pageLinkAnchorElement.attr('title') || ''; // Always in 4/30/2023 2:13:46 AM format\n const dateTimeParts = rawDateTime.split(' ');\n const dateParts = dateTimeParts[0].split('/');\n const timeParts = dateTimeParts[1].split(':');\n const dateTime = new Date(\n Date.UTC(\n parseInt(dateParts[2]), // Year", "score": 0.6619858741760254 }, { "filename": "src/scrapers/wiki-page-markup-scraper.ts", "retrieved_chunk": " }\n }\n return null;\n });\n if (!page)\n return [];\n page.url = response.url.replace(/\\?format=text$/, '');\n return [page];\n };\n }", "score": 0.656593918800354 } ]
typescript
if (this.childPageFilter && !this.childPageFilter(absoluteUrl)) continue;
import { ClassFunction, Enum, Function, HookFunction, LibraryFunction, Panel, PanelFunction, Realm, Struct, WikiPage, isPanel } from '../scrapers/wiki-page-markup-scraper.js'; import { putCommentBeforeEachLine, removeNewlines, safeFileName, toLowerCamelCase } from '../utils/string.js'; import { isClassFunction, isHookFunction, isLibraryFunction, isPanelFunction, isStruct, isEnum, } from '../scrapers/wiki-page-markup-scraper.js'; export const RESERVERD_KEYWORDS = new Set([ 'and', 'break', 'continue', 'do', 'else', 'elseif', 'end', 'false', 'for', 'function', 'goto', 'if', 'in', 'local', 'nil', 'not', 'or', 'repeat', 'return', 'then', 'true', 'until', 'while' ]); export class GluaApiWriter { private readonly writtenClasses: Set<string> = new Set(); private readonly writtenLibraryGlobals: Set<string> = new Set(); private readonly pageOverrides: Map<string, string> = new Map(); constructor() { } public static safeName(name: string) { if (name.includes('/')) name = name.replace(/\//g, ' or '); if (name.includes('=')) name = name.split('=')[0]; if (name.includes(' ')) name = toLowerCamelCase(name); // Remove any remaining characters not valid in a Lua variable/function name. name = name.replace(/[^A-Za-z\d_.]/g, ''); if (RESERVERD_KEYWORDS.has(name)) return `_${name}`; return name; } public addOverride(pageAddress: string, override: string) { this.pageOverrides.set
(safeFileName(pageAddress, '.'), override);
} public writePage(page: WikiPage) { const fileSafeAddress = safeFileName(page.address, '.'); if (this.pageOverrides.has(fileSafeAddress)) { let api = ''; if (isClassFunction(page)) api += this.writeClass(page.parent); else if (isLibraryFunction(page)) api += this.writeLibraryGlobal(page); api += this.pageOverrides.get(fileSafeAddress); return `${api}\n\n`; } else if (isClassFunction(page)) return this.writeClassFunction(page); else if (isLibraryFunction(page)) return this.writeLibraryFunction(page); else if (isHookFunction(page)) return this.writeHookFunction(page); else if (isPanel(page)) return this.writePanel(page); else if (isPanelFunction(page)) return this.writePanelFunction(page); else if (isEnum(page)) return this.writeEnum(page); else if (isStruct(page)) return this.writeStruct(page); } private writeClass(className: string, parent?: string, classFields: string = '') { let api: string = ''; if (!this.writtenClasses.has(className)) { const classOverride = `class.${className}`; if (this.pageOverrides.has(classOverride)) { api += this.pageOverrides.get(classOverride)!.replace(/\n$/g, '') + '\n\n'; api = api.replace('---{{CLASS_FIELDS}}\n', classFields); } else { api += `---@class ${className}`; if (parent) api += ` : ${parent}`; api += '\n'; api += classFields; api += `local ${className} = {}\n\n`; } this.writtenClasses.add(className); } return api; } private writeLibraryGlobal(func: LibraryFunction) { if (!func.dontDefineParent && !this.writtenLibraryGlobals.has(func.parent)) { const global = `${func.parent} = {}\n\n`; this.writtenLibraryGlobals.add(func.parent); return global; } return ''; } private writeClassFunction(func: ClassFunction) { let api: string = this.writeClass(func.parent); api += this.writeFunctionLuaDocComment(func, func.realm); api += this.writeFunctionDeclaration(func, func.realm, ':'); return api; } private writeLibraryFunction(func: LibraryFunction) { let api: string = this.writeLibraryGlobal(func); api += this.writeFunctionLuaDocComment(func, func.realm); api += this.writeFunctionDeclaration(func, func.realm); return api; } private writeHookFunction(func: HookFunction) { return this.writeClassFunction(func); } private writePanel(panel: Panel) { return this.writeClass(panel.name, panel.parent); } private writePanelFunction(func: PanelFunction) { let api: string = ''; api += this.writeFunctionLuaDocComment(func, func.realm); api += this.writeFunctionDeclaration(func, func.realm, ':'); return api; } private writeEnum(_enum: Enum) { let api: string = ''; const isContainedInTable = _enum.items[0]?.key.includes('.') ?? false; api += `---@enum ${_enum.name}\n`; if (isContainedInTable) api += `local ${_enum.name} = {\n`; const writeItem = (key: string, item: typeof _enum.items[0]) => { if (isContainedInTable) { key = key.split('.')[1]; api += ` ${key} = ${item.value}, ` + (item.description ? `--[[ ${item.description} ]]` : '') + '\n'; } else { const comment = item.description ? `${putCommentBeforeEachLine(item.description, false)}\n` : ''; api += `${comment}${key} = ${item.value}\n`; } }; for (const item of _enum.items) writeItem(item.key, item); if (isContainedInTable) api += '}'; api += `\n\n`; return api; } private writeStruct(struct: Struct) { let fields: string = ''; for (const field of struct.fields) { fields += `---@field ${GluaApiWriter.safeName(field.name)} ${this.transformType(field.type)} ${removeNewlines(field.description!)}\n`; } return this.writeClass(struct.name, undefined, fields); } public writePages(pages: WikiPage[]) { let api: string = ''; for (const page of pages) { api += this.writePage(page); } return api; } private transformType(type: string) { if (type === 'vararg') return '...'; return type; } private writeFunctionLuaDocComment(func: Function, realm: Realm) { let luaDocComment = `---[${realm.toUpperCase()}] ${putCommentBeforeEachLine(func.description!.trim())}\n`; luaDocComment += `---\n---[(View on wiki)](${func.url})\n`; if (func.arguments) { func.arguments.forEach((arg, index) => { if (!arg.name) arg.name = arg.type; if (arg.type === 'vararg') arg.name = '...'; luaDocComment += `---@param ${GluaApiWriter.safeName(arg.name)}${arg.default !== undefined ? `?` : ''} ${this.transformType(arg.type)} ${putCommentBeforeEachLine(arg.description!)}\n`; }); } if (func.returns) { const returns = `---@return ${func.returns.map(ret => this.transformType(ret.type)).join(', ')}`; func.returns.forEach(ret => { const description = removeNewlines(ret.description ?? ''); if (func.returns!.length === 1) { luaDocComment += `${returns} #${description}\n`; return; } luaDocComment += `${returns} #${this.transformType(ret.type)} - ${description}\n`; }); } return luaDocComment; } private writeFunctionDeclaration(func: Function, realm: Realm, indexer: string = '.') { let declaration = `function ${func.parent ? `${func.parent}${indexer}` : ''}${GluaApiWriter.safeName(func.name)}(`; if (func.arguments) { declaration += func.arguments.map(arg => { if (arg.type === 'vararg') return '...'; return GluaApiWriter.safeName(arg.name!); }).join(', '); } declaration += ') end\n\n'; return declaration; } }
src/api-writer/glua-api-writer.ts
luttje-glua-api-snippets-9f40376
[ { "filename": "src/utils/string.ts", "retrieved_chunk": "/**\n * Converts a string to lowerCamelCase \n * \n * @param str The string to convert\n * @returns The converted string\n */\nexport function toLowerCamelCase(str: string) {\n str = str.replace(/[_-]/g, ' ');\n return str.replace(/(?:^\\w|\\b\\w)/g, (letter, index) => {\n return index === 0 ? letter.toLowerCase() : letter.toUpperCase();", "score": 0.7826969027519226 }, { "filename": "src/utils/string.ts", "retrieved_chunk": " * \n * @param str The string to make safe\n * @param replacement The string to replace unsafe characters with\n * @returns The safe string\n */\nexport function safeFileName(str: string, replacement: string = '_') {\n return str.replace(/[^a-z0-9_\\-\\. ]/gi, replacement);\n}", "score": 0.764003574848175 }, { "filename": "src/cli-scraper.ts", "retrieved_chunk": " return;\n const api = writer.writePages(pageMarkups);\n let fileName = pageIndex.address;\n let moduleName = fileName;\n if (fileName.includes('.') || fileName.includes(':') || fileName.includes('/')) {\n [moduleName, fileName] = fileName.split(/[:.\\/]/, 2);\n }\n // Make sure modules like Entity and ENTITY are placed in the same file.\n moduleName = moduleName.toLowerCase();\n const moduleFile = path.join(baseDirectory, moduleName);", "score": 0.7380574345588684 }, { "filename": "src/utils/string.ts", "retrieved_chunk": " */\nexport function putCommentBeforeEachLine(text: string, skipLineOne: boolean = true) {\n return text.split(/\\r?\\n/g).map((line, index) => {\n if (index === 0 && skipLineOne)\n return line;\n return `--- ${line}`;\n }).join('\\n');\n}\n/**\n * Makes a string safe for use as a file name", "score": 0.7261790037155151 }, { "filename": "src/utils/filesystem.ts", "retrieved_chunk": " * @param windowsPath The Windows path to convert.\n * @returns The Unix path.\n */\nexport function convertWindowsToUnixPath(windowsPath: string) {\n let unixPath = windowsPath;\n unixPath = unixPath.replace(/^[A-Z]:/, (match) => match.toLowerCase());\n unixPath = unixPath.replace(/\\\\/g, '/');\n let colonIndex = unixPath.indexOf(':');\n if (colonIndex > -1)\n unixPath = unixPath.replace(/:/, '');", "score": 0.7206954956054688 } ]
typescript
(safeFileName(pageAddress, '.'), override);
import { ClassFunction, Enum, Function, HookFunction, LibraryFunction, Panel, PanelFunction, Realm, Struct, WikiPage, isPanel } from '../scrapers/wiki-page-markup-scraper.js'; import { putCommentBeforeEachLine, removeNewlines, safeFileName, toLowerCamelCase } from '../utils/string.js'; import { isClassFunction, isHookFunction, isLibraryFunction, isPanelFunction, isStruct, isEnum, } from '../scrapers/wiki-page-markup-scraper.js'; export const RESERVERD_KEYWORDS = new Set([ 'and', 'break', 'continue', 'do', 'else', 'elseif', 'end', 'false', 'for', 'function', 'goto', 'if', 'in', 'local', 'nil', 'not', 'or', 'repeat', 'return', 'then', 'true', 'until', 'while' ]); export class GluaApiWriter { private readonly writtenClasses: Set<string> = new Set(); private readonly writtenLibraryGlobals: Set<string> = new Set(); private readonly pageOverrides: Map<string, string> = new Map(); constructor() { } public static safeName(name: string) { if (name.includes('/')) name = name.replace(/\//g, ' or '); if (name.includes('=')) name = name.split('=')[0]; if (name.includes(' ')) name = toLowerCamelCase(name); // Remove any remaining characters not valid in a Lua variable/function name. name = name.replace(/[^A-Za-z\d_.]/g, ''); if (RESERVERD_KEYWORDS.has(name)) return `_${name}`; return name; } public addOverride(pageAddress: string, override: string) { this.pageOverrides.set(safeFileName(pageAddress, '.'), override); } public writePage(page: WikiPage) { const fileSafeAddress = safeFileName(page.address, '.'); if (this.pageOverrides.has(fileSafeAddress)) { let api = ''; if (isClassFunction(page)) api += this.writeClass(page.parent); else if (isLibraryFunction(page)) api += this.writeLibraryGlobal(page); api += this.pageOverrides.get(fileSafeAddress); return `${api}\n\n`; } else if (isClassFunction(page)) return this.writeClassFunction(page); else if (isLibraryFunction(page)) return this.writeLibraryFunction(page); else if (isHookFunction(page)) return this.writeHookFunction(page); else if (isPanel(page)) return this.writePanel(page); else if (isPanelFunction(page)) return this.writePanelFunction(page); else if (isEnum(page)) return this.writeEnum(page); else if (isStruct(page)) return this.writeStruct(page); } private writeClass(className: string, parent?: string, classFields: string = '') { let api: string = ''; if (!this.writtenClasses.has(className)) { const classOverride = `class.${className}`; if (this.pageOverrides.has(classOverride)) { api += this.pageOverrides.get(classOverride)!.replace(/\n$/g, '') + '\n\n'; api = api.replace('---{{CLASS_FIELDS}}\n', classFields); } else { api += `---@class ${className}`; if (parent) api += ` : ${parent}`; api += '\n'; api += classFields; api += `local ${className} = {}\n\n`; } this.writtenClasses.add(className); } return api; } private writeLibraryGlobal(func: LibraryFunction) { if (!func.dontDefineParent && !this.writtenLibraryGlobals.has(func.parent)) { const global = `${func.parent} = {}\n\n`; this.writtenLibraryGlobals.add(func.parent); return global; } return ''; } private writeClassFunction(func: ClassFunction) { let api: string = this.writeClass(func.parent); api += this.writeFunctionLuaDocComment(func, func.realm); api += this.writeFunctionDeclaration(func, func.realm, ':'); return api; } private writeLibraryFunction(func: LibraryFunction) { let api: string = this.writeLibraryGlobal(func); api += this.writeFunctionLuaDocComment(func, func.realm); api += this.writeFunctionDeclaration(func, func.realm); return api; } private writeHookFunction(func: HookFunction) { return this.writeClassFunction(func); } private writePanel(panel: Panel) { return this.writeClass(panel.name, panel.parent); } private writePanelFunction(func: PanelFunction) { let api: string = ''; api += this.writeFunctionLuaDocComment(func, func.realm); api += this.writeFunctionDeclaration(func, func.realm, ':'); return api; } private writeEnum(_enum: Enum) { let api: string = ''; const isContainedInTable = _enum.items[0]?.key.includes('.') ?? false; api += `---@enum ${_enum.name}\n`; if (isContainedInTable) api += `local ${_enum.name} = {\n`; const writeItem = (key: string, item: typeof _enum.items[0]) => { if (isContainedInTable) { key = key.split('.')[1]; api += ` ${key} = ${item.value}, ` + (item.description ? `--[[ ${item.description} ]]` : '') + '\n'; } else { const comment = item.description ? `${putCommentBeforeEachLine(item.description, false)}\n` : ''; api += `${comment}${key} = ${item.value}\n`; } }; for (const item of _enum.items) writeItem(item.key, item); if (isContainedInTable) api += '}'; api += `\n\n`; return api; } private writeStruct(struct: Struct) { let fields: string = ''; for (const field of struct.fields) { fields += `---@field ${GluaApiWriter.safeName(field.name)} ${this.transformType(field.type)} ${removeNewlines(field.description!)}\n`; } return this.writeClass(struct.name, undefined, fields); } public writePages(pages: WikiPage[]) { let api: string = ''; for (const page of pages) { api += this.writePage(page); } return api; } private transformType(type: string) { if (type === 'vararg') return '...'; return type; } private writeFunctionLuaDocComment(func: Function, realm: Realm) { let luaDocComment = `---[${realm.toUpperCase()}] ${putCommentBeforeEachLine(func.description!.trim())}\n`; luaDocComment += `---\n---[(View on wiki)](${func.url})\n`; if (func.arguments) { func.arguments.forEach(
(arg, index) => {
if (!arg.name) arg.name = arg.type; if (arg.type === 'vararg') arg.name = '...'; luaDocComment += `---@param ${GluaApiWriter.safeName(arg.name)}${arg.default !== undefined ? `?` : ''} ${this.transformType(arg.type)} ${putCommentBeforeEachLine(arg.description!)}\n`; }); } if (func.returns) { const returns = `---@return ${func.returns.map(ret => this.transformType(ret.type)).join(', ')}`; func.returns.forEach(ret => { const description = removeNewlines(ret.description ?? ''); if (func.returns!.length === 1) { luaDocComment += `${returns} #${description}\n`; return; } luaDocComment += `${returns} #${this.transformType(ret.type)} - ${description}\n`; }); } return luaDocComment; } private writeFunctionDeclaration(func: Function, realm: Realm, indexer: string = '.') { let declaration = `function ${func.parent ? `${func.parent}${indexer}` : ''}${GluaApiWriter.safeName(func.name)}(`; if (func.arguments) { declaration += func.arguments.map(arg => { if (arg.type === 'vararg') return '...'; return GluaApiWriter.safeName(arg.name!); }).join(', '); } declaration += ') end\n\n'; return declaration; } }
src/api-writer/glua-api-writer.ts
luttje-glua-api-snippets-9f40376
[ { "filename": "src/scrapers/wiki-page-markup-scraper.ts", "retrieved_chunk": " } else if (isFunction) {\n const isClassFunction = mainElement.attr('type') === 'classfunc';\n const isLibraryFunction = mainElement.attr('type') === 'libraryfunc';\n const isHookFunction = mainElement.attr('type') === 'hook';\n const isPanelFunction = mainElement.attr('type') === 'panelfunc';\n const arguments_ = $('args arg').map(function() {\n const $el = $(this);\n const argument = <FunctionArgument> {\n name: $el.attr('name')!,\n type: $el.attr('type')!,", "score": 0.7354055047035217 }, { "filename": "src/cli-scraper.ts", "retrieved_chunk": " const options = program.opts();\n if (!options.url) {\n console.error('No URL provided');\n process.exit(1);\n }\n const baseDirectory = options.output.replace(/\\/$/, '');\n const customDirectory = options.customOverrides?.replace(/\\/$/, '') ?? null;\n const baseUrl = options.url.replace(/\\/$/, '');\n const pageListScraper = new WikiPageListScraper(`${baseUrl}/~pagelist?format=json`);\n const writer = new GluaApiWriter();", "score": 0.7261562943458557 }, { "filename": "src/cli-library-publisher.ts", "retrieved_chunk": " \"/**/\",\n \"continue\",\n ],\n \"Lua.diagnostics.disable\": [\n \"duplicate-set-field\", // Prevents complaining when a function exists twice in both the CLIENT and SERVER realm\n ],\n // TODO: runtime.path\n });\n fs.writeFileSync(path.join(options.output, 'config.json'), JSON.stringify(config, null, 2));\n const files = walk(options.input, (file, isDirectory) => isDirectory || (file.endsWith(`.lua`)));", "score": 0.7240710854530334 }, { "filename": "src/cli-scraper.ts", "retrieved_chunk": " const fileContent = fs.readFileSync(filePath, { encoding: 'utf-8' });\n const pageName = file.replace(/\\.lua$/, '');\n writer.addOverride(pageName, fileContent);\n }\n }\n const pageIndexes = await scrapeAndCollect(pageListScraper);\n for (const pageIndex of pageIndexes) {\n const pageMarkupScraper = new WikiPageMarkupScraper(`${baseUrl}/${pageIndex.address}?format=text`);\n pageMarkupScraper.on('scraped', (url, pageMarkups) => {\n if (pageMarkups.length === 0)", "score": 0.7225459814071655 }, { "filename": "src/cli-scraper.ts", "retrieved_chunk": " if (!fs.existsSync(`${moduleFile}.lua`))\n fs.writeFileSync(`${moduleFile}.lua`, '---@meta\\n\\n');\n if (!fs.existsSync(moduleFile))\n fs.mkdirSync(moduleFile, { recursive: true });\n fileName = fileName.replace(/[^a-z0-9]/gi, '_').toLowerCase();\n // Lua API\n fs.appendFileSync(path.join(baseDirectory, `${moduleName}.lua`), api);\n // JSON data\n const json = JSON.stringify(pageMarkups, null, 2);\n fs.writeFileSync(path.join(baseDirectory, moduleName, `${fileName}.json`), json);", "score": 0.7143888473510742 } ]
typescript
(arg, index) => {
import { Scraper, ScrapeCallback } from './scraper.js'; export interface Scrapeable { childUrls: Set<string>; } export class TraverseScraper<T extends Scrapeable> extends Scraper<T> { protected readonly traversedUrls: Set<string> = new Set(); protected childPageFilter?: (url: string) => boolean; public setChildPageFilter(filter: (url: string) => boolean): void { this.childPageFilter = filter; } /** * Override scraping so we traverse all child URLs of the first scraped page */ public async scrape(): Promise<void> { const callback = this.getScrapeCallback(); await this.traverse(this.baseUrl, callback.bind(this)); } protected getTraverseUrl(url: string): string | false { if (!url.startsWith(this.baseUrl)) return false; if (url.endsWith('/')) url = url.substring(0, url.length - 1); if (url.includes('#')) url = url.substring(0, url.indexOf('#')); if (this.traversedUrls.has(url)) return false; if (this.childPageFilter && !this.childPageFilter(url)) return false; return url; } public async traverse(url: string, callback?: ScrapeCallback<T>): Promise<void> { if (!callback) callback = this.getScrapeCallback(); const urlsToTraverse: string[] = [url]; while (urlsToTraverse.length > 0) { let currentUrl = urlsToTraverse.shift()!; let url = this.getTraverseUrl(currentUrl); if (!url) continue; const currentResults =
await this.visitOne(url, callback);
this.traversedUrls.add(url); for (const result of currentResults) { for (const childUrl of result.childUrls) { const traverseUrl = this.getTraverseUrl(childUrl); if (traverseUrl && !urlsToTraverse.includes(traverseUrl)) urlsToTraverse.push(traverseUrl); } } } } }
src/scrapers/traverse-scraper.ts
luttje-glua-api-snippets-9f40376
[ { "filename": "src/scrapers/scraper.ts", "retrieved_chunk": " }\n public async visitOne(url: string, callback?: ScrapeCallback<T>): Promise<T[]> {\n if (!callback)\n callback = this.getScrapeCallback();\n if (!!process.env.VERBOSE_LOGGING)\n console.debug(`Scraping ${url}...`);\n this.emit('beforescrape', url);\n let response;\n let content;\n try {", "score": 0.8158850073814392 }, { "filename": "src/scrapers/scraper.ts", "retrieved_chunk": " }\n public setRetryOptions(options: RequestInitWithRetry): void {\n this.retryOptions = options;\n }\n /**\n * Scrapes the base url and has the callback process the response\n */\n public async scrape(): Promise<void> {\n const callback = this.getScrapeCallback();\n await this.visitOne(this.baseUrl, callback);", "score": 0.7911128401756287 }, { "filename": "src/scrapers/table-scraper.ts", "retrieved_chunk": " constructor(baseUrl: string, private readonly factory: () => T) {\n super(baseUrl);\n }\n public getScrapeCallback(): ScrapeCallback<Table<T>> {\n return (response: Response, content: string): Table<T>[] => {\n const results: Table<T>[] = [];\n const $ = cheerio.load(content);\n const tables = $('table');\n for (const table of tables) {\n const tableResult = this.fromTableElement($, table);", "score": 0.7586851119995117 }, { "filename": "src/api-writer/glua-api-writer.ts", "retrieved_chunk": " }\n public writePages(pages: WikiPage[]) {\n let api: string = '';\n for (const page of pages) {\n api += this.writePage(page);\n }\n return api;\n }\n private transformType(type: string) {\n if (type === 'vararg')", "score": 0.746157169342041 }, { "filename": "src/utils/filesystem.ts", "retrieved_chunk": " const traverse = (currentDir: string) => {\n const files = fs.readdirSync(currentDir);\n for (const file of files) {\n const filepath = path.join(currentDir, file);\n const stat = fs.statSync(filepath);\n if (stat.isDirectory()) {\n if (!filter || filter(filepath, true))\n traverse(filepath);\n } else {\n if (!filter || filter(filepath, false))", "score": 0.7455390691757202 } ]
typescript
await this.visitOne(url, callback);
import { Configuration, OpenAIApi } from 'openai'; import logger from './logger'; export interface ChatGPTMessage { role: 'system' | 'user' | 'assistant'; content: string; } // My environment variable is saving the open ai api key as OPENAI_API_KEY not OPENAI_TOKEN. Commented for pull request const OPENAI_TOKEN = process.env.OPENAI_API_KEY; // const OPENAI_TOKEN = process.env.OPENAI_TOKEN; export async function ChatGPT_completion( messages: ChatGPTMessage[], model: "gpt-3.5-turbo" | "gpt-3.5-turbo-0301" | "gpt-4-0314" | "gpt-4-32k", temperature: number = 0.7, top_p: number = 0.9, maxRetries: number = 3 ): Promise<string> { const config = new Configuration({ apiKey: OPENAI_TOKEN, }); const openai = new OpenAIApi(config); for (let i = 0; i < maxRetries; i++) { try { const completion = await openai.createChatCompletion({ model: model, messages: messages, }); return (completion.data!.choices[0]!.message?.content || "").trim(); } catch (error: any) { if (error.response && (error.response.status === 429 || (error.response.status >= 500 && error.response.status < 600))) { const resetMs = parseInt(error.response.headers['x-ratelimit-reset-requests']) || 1000; const waitTime = resetMs + Math.random() * 1000; logger
.warn( `Rate limit or server error encountered (status: ${error.response.status}). Retrying in ${waitTime} ms...` );
await new Promise((resolve) => setTimeout(resolve, waitTime)); } else { throw error; } } } throw new Error('Max retries reached. Request failed.'); }
src/chat_gpt.ts
Confabulation-Corporation-golem-ac8b554
[ { "filename": "src/executor.ts", "retrieved_chunk": " if (error) {\n logger.error(`Error executing command: ${command}`);\n logger.error(stderr);\n reject(error);\n } else {\n logger.debug(stdout);\n resolve();\n }\n });\n });", "score": 0.6899679899215698 }, { "filename": "src/executor.ts", "retrieved_chunk": " },\n ];\n const response = await ChatGPT_completion(taskGenerationMessages, model, 0.7, 0.9);\n contextOfCurrentTarget.length = 0; //clear the previous context\n contextOfCurrentTarget.push(response); //append the new context to be used in the next iteration\n allOutputs[golemTargetKeys[i]] = response;\n const lines: string[] = response.split('\\n');\n // Extract the targets from the lines that start with \"Target:\"\n const targets: string[] = lines.filter((line: string) => line.startsWith(\"Target:\"))\n .map((line: string) => line.slice(8));", "score": 0.659462571144104 }, { "filename": "src/golem.ts", "retrieved_chunk": " } catch (error: any) {\n logger.error(`Error: ${error.message}`);\n }\n }\n )\n .demandCommand(1, 'You must provide a valid command.')\n .help()\n .alias('h', 'help')\n .strict().argv;", "score": 0.6567826867103577 }, { "filename": "src/executor.ts", "retrieved_chunk": " context.set(key, allOutputs[key]);\n }\n }catch (error: any) {\n logger.error(`Error generating AI response: ${error.message}`);\n } \n }\n }\n }else {\n throw new Error(`No such supported model ${model}`);\n }", "score": 0.6564939022064209 }, { "filename": "src/parser.ts", "retrieved_chunk": "import * as yaml from 'js-yaml';\nimport { GolemFile } from './types';\nexport function parseGolemFile(content: string): GolemFile {\n try {\n const parsedContent = yaml.load(content) as GolemFile;\n // Update the parsing logic to handle the task_generation_prompt field\n return parsedContent;\n } catch (error: any) {\n throw new Error(`Error parsing Golem file: ${error.message}`);\n }", "score": 0.6562998294830322 } ]
typescript
.warn( `Rate limit or server error encountered (status: ${error.response.status}). Retrying in ${waitTime} ms...` );
import { Scrapeable, TraverseScraper } from './traverse-scraper.js'; import { ScrapeCallback } from './scraper.js'; import * as cheerio from 'cheerio'; import "reflect-metadata"; const tableColumnMetadataKey = Symbol("tableColumn"); export type TableColumnDefinition = { propertyKey: string | symbol, columnName: string, typeConverter: (value: string) => any }; export function tableColumn(columnName: string): PropertyDecorator { return (target: object, propertyKey: string | symbol) => { const existingColumns: TableColumnDefinition[] = Reflect.getMetadata(tableColumnMetadataKey, target) || []; const propertyType = Reflect.getMetadata("design:type", target, propertyKey); existingColumns.push({ propertyKey, columnName, typeConverter: (value: string) => { switch (propertyType) { case String: return value; case Number: return Number(value); case Boolean: return Boolean(value); default: return value; } } }); Reflect.defineMetadata(tableColumnMetadataKey, existingColumns, target); }; } export function getTableColumns(target: object): TableColumnDefinition[] { return Reflect.getMetadata(tableColumnMetadataKey, target) || []; } export class Row<T> { constructor(public data: T) { } } export class Table<T> implements Scrapeable { public url: string; public childUrls: Set<string> = new Set(); constructor(url: string, public rows: Row<T>[] = []) { this.url = url; } public addRow(row: Row<T>) { this.rows.push(row); } } export class TableScraper<T extends object> extends TraverseScraper<Table<T>> { constructor(baseUrl: string, private readonly factory: () => T) { super(baseUrl); }
public getScrapeCallback(): ScrapeCallback<Table<T>> {
return (response: Response, content: string): Table<T>[] => { const results: Table<T>[] = []; const $ = cheerio.load(content); const tables = $('table'); for (const table of tables) { const tableResult = this.fromTableElement($, table); if (tableResult) results.push(tableResult); } return results; }; } private fromTableElement($: cheerio.CheerioAPI, tableElement: cheerio.Element): Table<T> | null { const tableResult = new Table<T>(this.baseUrl); let headingRows = $(tableElement).find('thead > tr'); let shouldTrimHeadings = false; if (headingRows.length === 0) { headingRows = $(tableElement).find('tbody > tr:first-child'); shouldTrimHeadings = true; } let headings : cheerio.Element[] | undefined; if (headingRows.length > 0) headings = $(headingRows[0]).find('th').toArray(); if (!headings || headings.length === 0) throw new Error('No headings found in table'); let rows = $(tableElement).find('tbody > tr').toArray(); if (rows.length === 0) rows = $(tableElement).find('tr').toArray(); if (shouldTrimHeadings) rows = rows.slice(headingRows.length); let isEmpty = true; for (const row of rows) { const rowResult = this.fromRowElement($, row, headings); if (rowResult === null) continue; tableResult.addRow(rowResult); isEmpty = false; } if (isEmpty) return null; return tableResult; } private fromRowElement($: cheerio.CheerioAPI, rowElement: cheerio.Element, headings: cheerio.Element[]): Row<T> | null { const cells = $(rowElement).find('td').toArray(); const rowResult = this.factory(); const allTableColumns = getTableColumns(rowResult); let isEmpty = true; for (let i = 0; i < cells.length; i++) { const cell = cells[i]; const heading = headings[i]; if (!heading) continue; const headingText = $(heading).text(); if (!headingText) continue; let tableColumnDefinition = allTableColumns.find(column => column.columnName === headingText); if (!tableColumnDefinition) { const properties = Object.getOwnPropertyNames(rowResult); const propertyKey = properties.find(property => property.toLowerCase() === headingText.toLowerCase()); if (!propertyKey) continue; tableColumnDefinition = { propertyKey, columnName: headingText, typeConverter: (value: string) => value }; } const cellText = $(cell).text(); if (!cellText) continue; (rowResult as any)[tableColumnDefinition.propertyKey] = tableColumnDefinition.typeConverter(cellText); isEmpty = false; } if (isEmpty) return null; return new Row<T>(rowResult); } }
src/scrapers/table-scraper.ts
luttje-glua-api-snippets-9f40376
[ { "filename": "src/scrapers/traverse-scraper.ts", "retrieved_chunk": "import { Scraper, ScrapeCallback } from './scraper.js';\nexport interface Scrapeable {\n childUrls: Set<string>;\n}\nexport class TraverseScraper<T extends Scrapeable> extends Scraper<T> {\n protected readonly traversedUrls: Set<string> = new Set();\n protected childPageFilter?: (url: string) => boolean;\n public setChildPageFilter(filter: (url: string) => boolean): void {\n this.childPageFilter = filter;\n }", "score": 0.8957411646842957 }, { "filename": "src/scrapers/scraper.ts", "retrieved_chunk": "export class Scraper<T extends ScrapeResult> extends TypedEventEmitter<ScraperEvents<T>> {\n protected retryOptions: RequestInitWithRetry = {};\n constructor(\n protected readonly baseUrl: string,\n protected readonly scrapeCallback?: ScrapeCallback<T>\n ) { \n super();\n }\n public getScrapeCallback(): ScrapeCallback<T> {\n return this.scrapeCallback || ((_: Response, __: string): T[] => []);", "score": 0.866360068321228 }, { "filename": "src/scrapers/page-traverse-scraper.ts", "retrieved_chunk": " }\n}\nexport class PageTraverseScraper<T extends Page = Page> extends TraverseScraper<T> {\n private readonly factory: (url: string, title: string) => T;\n constructor(baseUrl: string, factory?: (url: string, title: string) => T) {\n super(baseUrl);\n this.factory = factory ?? ((url: string, title: string) => new Page(url, title) as T);\n }\n /**\n * Scrapes a page for its URL and title, and returns a list of child URLs", "score": 0.8584944009780884 }, { "filename": "src/scrapers/wiki-history-scraper.ts", "retrieved_chunk": " public history: WikiHistory[] = [];\n constructor(url: string, title: string) {\n super(url, title);\n }\n}\nexport class WikiHistoryPageScraper extends PageTraverseScraper<WikiHistoryPage> {\n constructor(baseUrl: string) {\n super(baseUrl, (url: string, title: string) => new WikiHistoryPage(url, title));\n }\n /**", "score": 0.8572498559951782 }, { "filename": "src/scrapers/page-traverse-scraper.ts", "retrieved_chunk": "import { Scrapeable, TraverseScraper } from './traverse-scraper.js';\nimport { decodeEntities } from './decode-entities.js';\nimport { ScrapeCallback } from './scraper.js';\nexport class Page implements Scrapeable {\n public url: string;\n public title: string;\n public childUrls: Set<string> = new Set();\n constructor(url: string, title: string) {\n this.url = url;\n this.title = title;", "score": 0.8379364609718323 } ]
typescript
public getScrapeCallback(): ScrapeCallback<Table<T>> {
import { ScrapeCallback, Scraper } from './scraper.js'; import { deserializeXml } from '../utils/xml.js'; export type WikiFunctionType = 'panelfunc' | 'classfunc' | 'libraryfunc' | 'hook'; export type Realm = 'Menu' | 'Client' | 'Server' | 'Shared' | 'Client and menu'; export type CommonWikiProperties = { type: WikiFunctionType | 'enum' | 'struct' | 'panel'; address: string; name: string; description: string; realm: Realm; url: string; } export type WikiIdentifier = { name: string; type: string; description?: string; }; export type FunctionArgument = WikiIdentifier & { default?: string; }; export type FunctionReturn = WikiIdentifier & {}; export type Function = CommonWikiProperties & { parent: string; arguments?: FunctionArgument[]; returns?: FunctionReturn[]; }; export type ClassFunction = Function & {}; export type LibraryFunction = Function & { type: 'libraryfunc'; dontDefineParent?: boolean; }; export type HookFunction = Function & { type: 'hook'; isHook: 'yes'; }; export type PanelFunction = Function & { type: 'panelfunc'; isPanelFunction: 'yes'; }; export type EnumValue = { key: string; value: string; description: string; }; export type Enum = CommonWikiProperties & { type: 'enum'; items: EnumValue[]; }; export type StructField = { name: string; type: string; default?: any; description: string; }; export type Struct = CommonWikiProperties & { type: 'struct'; fields: StructField[]; }; export type Panel = CommonWikiProperties & { type: 'panel'; parent: string; }; export type WikiPage = ClassFunction | LibraryFunction | HookFunction | PanelFunction | Panel | Enum | Struct; /** * Guards */ export function isClassFunction(page: WikiPage): page is ClassFunction { return page.type === 'classfunc'; } export function isLibraryFunction(page: WikiPage): page is LibraryFunction { return page.type === 'libraryfunc'; } export function isHookFunction(page: WikiPage): page is HookFunction { return page.type === 'hook'; } export function isPanelFunction(page: WikiPage): page is PanelFunction { return page.type === 'panelfunc'; } export function isPanel(page: WikiPage): page is Panel { return page.type === 'panel'; } export function isEnum(page: WikiPage): page is Enum { return page.type === 'enum'; } export function isStruct(page: WikiPage): page is Struct { return page.type === 'struct'; } /** * Scraper */ export class WikiPageMarkupScraper extends Scraper<WikiPage> { /** * @param response The response from the page * @param content The content of the request * * @returns A list containing only the scraped page */ public getScrapeCallback(): ScrapeCallback<WikiPage> { return (response: Response, content: string): WikiPage[] => {
const page = deserializeXml<WikiPage | null>(content, ($) => {
const isEnum = $('enum').length > 0; const isStruct = $('structure').length > 0; const isFunction = $('function').length > 0; const isPanel = $('panel').length > 0; const mainElement = $(isEnum ? 'enum' : isStruct ? 'struct' : isPanel ? 'panel' : 'function'); const address = response.url.split('/').pop()!.split('?')[0]; if (isEnum) { const items = $('items item').map(function () { const $el = $(this); return <EnumValue>{ key: $el.attr('key')!, value: $el.attr('value')!, description: $el.text() }; }).get(); return <Enum>{ type: 'enum', name: address, address: address, description: $('description').text(), realm: $('realm').text() as Realm, items }; } else if (isStruct) { const fields = $('fields item').map(function () { const $el = $(this); return <StructField>{ name: $el.attr('name')!, type: $el.attr('type')!, default: $el.attr('default'), description: $el.text() }; }).get(); return <Struct>{ type: 'struct', name: address, address: address, description: $('description').text(), realm: $('realm').text() as Realm, fields }; } else if (isPanel) { return <Panel>{ type: 'panel', name: address, address: address, description: $('description').text(), realm: $('realm').text() as Realm, parent: $('parent').text() }; } else if (isFunction) { const isClassFunction = mainElement.attr('type') === 'classfunc'; const isLibraryFunction = mainElement.attr('type') === 'libraryfunc'; const isHookFunction = mainElement.attr('type') === 'hook'; const isPanelFunction = mainElement.attr('type') === 'panelfunc'; const arguments_ = $('args arg').map(function() { const $el = $(this); const argument = <FunctionArgument> { name: $el.attr('name')!, type: $el.attr('type')!, description: $el.text() }; if ($el.attr('default')) argument.default = $el.attr('default')!; return argument; }).get(); const returns = $('rets ret').map(function() { const $el = $(this); return <FunctionReturn> { name: $el.attr('name')!, type: $el.attr('type')!, description: $el.text() }; }).get(); const base = <Function> { type: mainElement.attr('type')!, parent: mainElement.attr('parent')!, name: mainElement.attr('name')!, address: address, description: $('description:first').text(), realm: $('realm:first').text() as Realm, arguments: arguments_, returns }; if (isClassFunction) { return <ClassFunction> { ...base, type: 'classfunc' }; } else if (isLibraryFunction) { if (base.parent === 'Global') { base.parent = '_G'; (<LibraryFunction>base).dontDefineParent = true; } return <LibraryFunction> { ...base, type: 'libraryfunc' }; } else if (isHookFunction) { return <HookFunction> { ...base, type: 'hook', isHook: 'yes' }; } else if (isPanelFunction) { return <PanelFunction> { ...base, type: 'panelfunc', isPanelFunction: 'yes' }; } } return null; }); if (!page) return []; page.url = response.url.replace(/\?format=text$/, ''); return [page]; }; } }
src/scrapers/wiki-page-markup-scraper.ts
luttje-glua-api-snippets-9f40376
[ { "filename": "src/scrapers/wiki-history-scraper.ts", "retrieved_chunk": " * Scrapes a wiki history page for information on wiki changes\n * \n * @param response The response from the page\n * @param content The content of the request\n * \n * @returns A list containing only the scraped page\n */\n public getScrapeCallback(): ScrapeCallback<WikiHistoryPage> {\n const baseScrapeCallback = super.getScrapeCallback();\n return async (response: Response, content: string): Promise<WikiHistoryPage[]> => {", "score": 0.9537699222564697 }, { "filename": "src/scrapers/page-traverse-scraper.ts", "retrieved_chunk": " * \n * @param response The response from the page\n * @param content The content of the request\n * \n * @returns A list containing only the scraped page\n */\n public getScrapeCallback(): ScrapeCallback<T> {\n return (response: Response, content: string): T[] => {\n const results: T[] = [];\n const url = response.url;", "score": 0.9390761256217957 }, { "filename": "src/scrapers/json-scraper.ts", "retrieved_chunk": "import { ScrapeCallback, Scraper } from './scraper.js';\nexport class JsonScraper<T extends object = object> extends Scraper<T> {\n /**\n * @param response The response from the page\n * @param content The content of the request\n * \n * @returns A list containing only the scraped page\n */\n public getScrapeCallback(): ScrapeCallback<T> {\n return JsonScraper.makeScrapeCallback<T>();", "score": 0.9210429191589355 }, { "filename": "src/scrapers/scraper.ts", "retrieved_chunk": " }\n public setRetryOptions(options: RequestInitWithRetry): void {\n this.retryOptions = options;\n }\n /**\n * Scrapes the base url and has the callback process the response\n */\n public async scrape(): Promise<void> {\n const callback = this.getScrapeCallback();\n await this.visitOne(this.baseUrl, callback);", "score": 0.8757731318473816 }, { "filename": "src/scrapers/traverse-scraper.ts", "retrieved_chunk": " /**\n * Override scraping so we traverse all child URLs of the first scraped page\n */\n public async scrape(): Promise<void> {\n const callback = this.getScrapeCallback();\n await this.traverse(this.baseUrl, callback.bind(this));\n }\n protected getTraverseUrl(url: string): string | false {\n if (!url.startsWith(this.baseUrl))\n return false;", "score": 0.8680242300033569 } ]
typescript
const page = deserializeXml<WikiPage | null>(content, ($) => {
import { ClassFunction, Enum, Function, HookFunction, LibraryFunction, Panel, PanelFunction, Realm, Struct, WikiPage, isPanel } from '../scrapers/wiki-page-markup-scraper.js'; import { putCommentBeforeEachLine, removeNewlines, safeFileName, toLowerCamelCase } from '../utils/string.js'; import { isClassFunction, isHookFunction, isLibraryFunction, isPanelFunction, isStruct, isEnum, } from '../scrapers/wiki-page-markup-scraper.js'; export const RESERVERD_KEYWORDS = new Set([ 'and', 'break', 'continue', 'do', 'else', 'elseif', 'end', 'false', 'for', 'function', 'goto', 'if', 'in', 'local', 'nil', 'not', 'or', 'repeat', 'return', 'then', 'true', 'until', 'while' ]); export class GluaApiWriter { private readonly writtenClasses: Set<string> = new Set(); private readonly writtenLibraryGlobals: Set<string> = new Set(); private readonly pageOverrides: Map<string, string> = new Map(); constructor() { } public static safeName(name: string) { if (name.includes('/')) name = name.replace(/\//g, ' or '); if (name.includes('=')) name = name.split('=')[0]; if (name.includes(' ')) name = toLowerCamelCase(name); // Remove any remaining characters not valid in a Lua variable/function name. name = name.replace(/[^A-Za-z\d_.]/g, ''); if (RESERVERD_KEYWORDS.has(name)) return `_${name}`; return name; } public addOverride(pageAddress: string, override: string) { this.pageOverrides.set(safeFileName(pageAddress, '.'), override); } public writePage(page: WikiPage) { const fileSafeAddress = safeFileName(page.address, '.'); if (this.pageOverrides.has(fileSafeAddress)) { let api = ''; if (isClassFunction(page)) api += this.writeClass(page.parent); else if (isLibraryFunction(page)) api += this.writeLibraryGlobal(page); api += this.pageOverrides.get(fileSafeAddress); return `${api}\n\n`; } else if (isClassFunction(page)) return this.writeClassFunction(page); else if (isLibraryFunction(page)) return this.writeLibraryFunction(page); else if (isHookFunction(page)) return this.writeHookFunction(page); else
if (isPanel(page)) return this.writePanel(page);
else if (isPanelFunction(page)) return this.writePanelFunction(page); else if (isEnum(page)) return this.writeEnum(page); else if (isStruct(page)) return this.writeStruct(page); } private writeClass(className: string, parent?: string, classFields: string = '') { let api: string = ''; if (!this.writtenClasses.has(className)) { const classOverride = `class.${className}`; if (this.pageOverrides.has(classOverride)) { api += this.pageOverrides.get(classOverride)!.replace(/\n$/g, '') + '\n\n'; api = api.replace('---{{CLASS_FIELDS}}\n', classFields); } else { api += `---@class ${className}`; if (parent) api += ` : ${parent}`; api += '\n'; api += classFields; api += `local ${className} = {}\n\n`; } this.writtenClasses.add(className); } return api; } private writeLibraryGlobal(func: LibraryFunction) { if (!func.dontDefineParent && !this.writtenLibraryGlobals.has(func.parent)) { const global = `${func.parent} = {}\n\n`; this.writtenLibraryGlobals.add(func.parent); return global; } return ''; } private writeClassFunction(func: ClassFunction) { let api: string = this.writeClass(func.parent); api += this.writeFunctionLuaDocComment(func, func.realm); api += this.writeFunctionDeclaration(func, func.realm, ':'); return api; } private writeLibraryFunction(func: LibraryFunction) { let api: string = this.writeLibraryGlobal(func); api += this.writeFunctionLuaDocComment(func, func.realm); api += this.writeFunctionDeclaration(func, func.realm); return api; } private writeHookFunction(func: HookFunction) { return this.writeClassFunction(func); } private writePanel(panel: Panel) { return this.writeClass(panel.name, panel.parent); } private writePanelFunction(func: PanelFunction) { let api: string = ''; api += this.writeFunctionLuaDocComment(func, func.realm); api += this.writeFunctionDeclaration(func, func.realm, ':'); return api; } private writeEnum(_enum: Enum) { let api: string = ''; const isContainedInTable = _enum.items[0]?.key.includes('.') ?? false; api += `---@enum ${_enum.name}\n`; if (isContainedInTable) api += `local ${_enum.name} = {\n`; const writeItem = (key: string, item: typeof _enum.items[0]) => { if (isContainedInTable) { key = key.split('.')[1]; api += ` ${key} = ${item.value}, ` + (item.description ? `--[[ ${item.description} ]]` : '') + '\n'; } else { const comment = item.description ? `${putCommentBeforeEachLine(item.description, false)}\n` : ''; api += `${comment}${key} = ${item.value}\n`; } }; for (const item of _enum.items) writeItem(item.key, item); if (isContainedInTable) api += '}'; api += `\n\n`; return api; } private writeStruct(struct: Struct) { let fields: string = ''; for (const field of struct.fields) { fields += `---@field ${GluaApiWriter.safeName(field.name)} ${this.transformType(field.type)} ${removeNewlines(field.description!)}\n`; } return this.writeClass(struct.name, undefined, fields); } public writePages(pages: WikiPage[]) { let api: string = ''; for (const page of pages) { api += this.writePage(page); } return api; } private transformType(type: string) { if (type === 'vararg') return '...'; return type; } private writeFunctionLuaDocComment(func: Function, realm: Realm) { let luaDocComment = `---[${realm.toUpperCase()}] ${putCommentBeforeEachLine(func.description!.trim())}\n`; luaDocComment += `---\n---[(View on wiki)](${func.url})\n`; if (func.arguments) { func.arguments.forEach((arg, index) => { if (!arg.name) arg.name = arg.type; if (arg.type === 'vararg') arg.name = '...'; luaDocComment += `---@param ${GluaApiWriter.safeName(arg.name)}${arg.default !== undefined ? `?` : ''} ${this.transformType(arg.type)} ${putCommentBeforeEachLine(arg.description!)}\n`; }); } if (func.returns) { const returns = `---@return ${func.returns.map(ret => this.transformType(ret.type)).join(', ')}`; func.returns.forEach(ret => { const description = removeNewlines(ret.description ?? ''); if (func.returns!.length === 1) { luaDocComment += `${returns} #${description}\n`; return; } luaDocComment += `${returns} #${this.transformType(ret.type)} - ${description}\n`; }); } return luaDocComment; } private writeFunctionDeclaration(func: Function, realm: Realm, indexer: string = '.') { let declaration = `function ${func.parent ? `${func.parent}${indexer}` : ''}${GluaApiWriter.safeName(func.name)}(`; if (func.arguments) { declaration += func.arguments.map(arg => { if (arg.type === 'vararg') return '...'; return GluaApiWriter.safeName(arg.name!); }).join(', '); } declaration += ') end\n\n'; return declaration; } }
src/api-writer/glua-api-writer.ts
luttje-glua-api-snippets-9f40376
[ { "filename": "src/scrapers/wiki-page-markup-scraper.ts", "retrieved_chunk": " return page.type === 'libraryfunc';\n}\nexport function isHookFunction(page: WikiPage): page is HookFunction {\n return page.type === 'hook';\n}\nexport function isPanelFunction(page: WikiPage): page is PanelFunction {\n return page.type === 'panelfunc';\n}\nexport function isPanel(page: WikiPage): page is Panel {\n return page.type === 'panel';", "score": 0.7822843194007874 }, { "filename": "src/scrapers/wiki-page-markup-scraper.ts", "retrieved_chunk": " parent: string;\n};\nexport type WikiPage = ClassFunction | LibraryFunction | HookFunction | PanelFunction | Panel | Enum | Struct;\n/**\n * Guards\n */\nexport function isClassFunction(page: WikiPage): page is ClassFunction {\n return page.type === 'classfunc';\n}\nexport function isLibraryFunction(page: WikiPage): page is LibraryFunction {", "score": 0.7528990507125854 }, { "filename": "src/scrapers/wiki-page-markup-scraper.ts", "retrieved_chunk": "}\nexport function isEnum(page: WikiPage): page is Enum {\n return page.type === 'enum';\n}\nexport function isStruct(page: WikiPage): page is Struct {\n return page.type === 'struct';\n}\n/**\n * Scraper\n */", "score": 0.7013881206512451 }, { "filename": "src/scrapers/wiki-page-markup-scraper.ts", "retrieved_chunk": " ...base,\n type: 'hook',\n isHook: 'yes'\n };\n } else if (isPanelFunction) {\n return <PanelFunction> {\n ...base,\n type: 'panelfunc',\n isPanelFunction: 'yes'\n };", "score": 0.6975387334823608 }, { "filename": "src/scrapers/wiki-page-markup-scraper.ts", "retrieved_chunk": " realm: $('realm:first').text() as Realm,\n arguments: arguments_,\n returns\n };\n if (isClassFunction) {\n return <ClassFunction> {\n ...base,\n type: 'classfunc'\n };\n } else if (isLibraryFunction) {", "score": 0.6943919658660889 } ]
typescript
if (isPanel(page)) return this.writePanel(page);
import { ScrapeCallback, Scraper } from './scraper.js'; import { deserializeXml } from '../utils/xml.js'; export type WikiFunctionType = 'panelfunc' | 'classfunc' | 'libraryfunc' | 'hook'; export type Realm = 'Menu' | 'Client' | 'Server' | 'Shared' | 'Client and menu'; export type CommonWikiProperties = { type: WikiFunctionType | 'enum' | 'struct' | 'panel'; address: string; name: string; description: string; realm: Realm; url: string; } export type WikiIdentifier = { name: string; type: string; description?: string; }; export type FunctionArgument = WikiIdentifier & { default?: string; }; export type FunctionReturn = WikiIdentifier & {}; export type Function = CommonWikiProperties & { parent: string; arguments?: FunctionArgument[]; returns?: FunctionReturn[]; }; export type ClassFunction = Function & {}; export type LibraryFunction = Function & { type: 'libraryfunc'; dontDefineParent?: boolean; }; export type HookFunction = Function & { type: 'hook'; isHook: 'yes'; }; export type PanelFunction = Function & { type: 'panelfunc'; isPanelFunction: 'yes'; }; export type EnumValue = { key: string; value: string; description: string; }; export type Enum = CommonWikiProperties & { type: 'enum'; items: EnumValue[]; }; export type StructField = { name: string; type: string; default?: any; description: string; }; export type Struct = CommonWikiProperties & { type: 'struct'; fields: StructField[]; }; export type Panel = CommonWikiProperties & { type: 'panel'; parent: string; }; export type WikiPage = ClassFunction | LibraryFunction | HookFunction | PanelFunction | Panel | Enum | Struct; /** * Guards */ export function isClassFunction(page: WikiPage): page is ClassFunction { return page.type === 'classfunc'; } export function isLibraryFunction(page: WikiPage): page is LibraryFunction { return page.type === 'libraryfunc'; } export function isHookFunction(page: WikiPage): page is HookFunction { return page.type === 'hook'; } export function isPanelFunction(page: WikiPage): page is PanelFunction { return page.type === 'panelfunc'; } export function isPanel(page: WikiPage): page is Panel { return page.type === 'panel'; } export function isEnum(page: WikiPage): page is Enum { return page.type === 'enum'; } export function isStruct(page: WikiPage): page is Struct { return page.type === 'struct'; } /** * Scraper */ export class WikiPageMarkupScraper extends Scraper<WikiPage> { /** * @param response The response from the page * @param content The content of the request * * @returns A list containing only the scraped page */ public getScrapeCallback()
: ScrapeCallback<WikiPage> {
return (response: Response, content: string): WikiPage[] => { const page = deserializeXml<WikiPage | null>(content, ($) => { const isEnum = $('enum').length > 0; const isStruct = $('structure').length > 0; const isFunction = $('function').length > 0; const isPanel = $('panel').length > 0; const mainElement = $(isEnum ? 'enum' : isStruct ? 'struct' : isPanel ? 'panel' : 'function'); const address = response.url.split('/').pop()!.split('?')[0]; if (isEnum) { const items = $('items item').map(function () { const $el = $(this); return <EnumValue>{ key: $el.attr('key')!, value: $el.attr('value')!, description: $el.text() }; }).get(); return <Enum>{ type: 'enum', name: address, address: address, description: $('description').text(), realm: $('realm').text() as Realm, items }; } else if (isStruct) { const fields = $('fields item').map(function () { const $el = $(this); return <StructField>{ name: $el.attr('name')!, type: $el.attr('type')!, default: $el.attr('default'), description: $el.text() }; }).get(); return <Struct>{ type: 'struct', name: address, address: address, description: $('description').text(), realm: $('realm').text() as Realm, fields }; } else if (isPanel) { return <Panel>{ type: 'panel', name: address, address: address, description: $('description').text(), realm: $('realm').text() as Realm, parent: $('parent').text() }; } else if (isFunction) { const isClassFunction = mainElement.attr('type') === 'classfunc'; const isLibraryFunction = mainElement.attr('type') === 'libraryfunc'; const isHookFunction = mainElement.attr('type') === 'hook'; const isPanelFunction = mainElement.attr('type') === 'panelfunc'; const arguments_ = $('args arg').map(function() { const $el = $(this); const argument = <FunctionArgument> { name: $el.attr('name')!, type: $el.attr('type')!, description: $el.text() }; if ($el.attr('default')) argument.default = $el.attr('default')!; return argument; }).get(); const returns = $('rets ret').map(function() { const $el = $(this); return <FunctionReturn> { name: $el.attr('name')!, type: $el.attr('type')!, description: $el.text() }; }).get(); const base = <Function> { type: mainElement.attr('type')!, parent: mainElement.attr('parent')!, name: mainElement.attr('name')!, address: address, description: $('description:first').text(), realm: $('realm:first').text() as Realm, arguments: arguments_, returns }; if (isClassFunction) { return <ClassFunction> { ...base, type: 'classfunc' }; } else if (isLibraryFunction) { if (base.parent === 'Global') { base.parent = '_G'; (<LibraryFunction>base).dontDefineParent = true; } return <LibraryFunction> { ...base, type: 'libraryfunc' }; } else if (isHookFunction) { return <HookFunction> { ...base, type: 'hook', isHook: 'yes' }; } else if (isPanelFunction) { return <PanelFunction> { ...base, type: 'panelfunc', isPanelFunction: 'yes' }; } } return null; }); if (!page) return []; page.url = response.url.replace(/\?format=text$/, ''); return [page]; }; } }
src/scrapers/wiki-page-markup-scraper.ts
luttje-glua-api-snippets-9f40376
[ { "filename": "src/scrapers/json-scraper.ts", "retrieved_chunk": "import { ScrapeCallback, Scraper } from './scraper.js';\nexport class JsonScraper<T extends object = object> extends Scraper<T> {\n /**\n * @param response The response from the page\n * @param content The content of the request\n * \n * @returns A list containing only the scraped page\n */\n public getScrapeCallback(): ScrapeCallback<T> {\n return JsonScraper.makeScrapeCallback<T>();", "score": 0.951534628868103 }, { "filename": "src/scrapers/wiki-history-scraper.ts", "retrieved_chunk": " * Scrapes a wiki history page for information on wiki changes\n * \n * @param response The response from the page\n * @param content The content of the request\n * \n * @returns A list containing only the scraped page\n */\n public getScrapeCallback(): ScrapeCallback<WikiHistoryPage> {\n const baseScrapeCallback = super.getScrapeCallback();\n return async (response: Response, content: string): Promise<WikiHistoryPage[]> => {", "score": 0.939723551273346 }, { "filename": "src/scrapers/page-traverse-scraper.ts", "retrieved_chunk": " * \n * @param response The response from the page\n * @param content The content of the request\n * \n * @returns A list containing only the scraped page\n */\n public getScrapeCallback(): ScrapeCallback<T> {\n return (response: Response, content: string): T[] => {\n const results: T[] = [];\n const url = response.url;", "score": 0.9313417077064514 }, { "filename": "src/scrapers/scraper.ts", "retrieved_chunk": " }\n public setRetryOptions(options: RequestInitWithRetry): void {\n this.retryOptions = options;\n }\n /**\n * Scrapes the base url and has the callback process the response\n */\n public async scrape(): Promise<void> {\n const callback = this.getScrapeCallback();\n await this.visitOne(this.baseUrl, callback);", "score": 0.8595654964447021 }, { "filename": "src/scrapers/page-traverse-scraper.ts", "retrieved_chunk": " }\n}\nexport class PageTraverseScraper<T extends Page = Page> extends TraverseScraper<T> {\n private readonly factory: (url: string, title: string) => T;\n constructor(baseUrl: string, factory?: (url: string, title: string) => T) {\n super(baseUrl);\n this.factory = factory ?? ((url: string, title: string) => new Page(url, title) as T);\n }\n /**\n * Scrapes a page for its URL and title, and returns a list of child URLs", "score": 0.8573983311653137 } ]
typescript
: ScrapeCallback<WikiPage> {
import { ScrapeCallback, Scraper } from './scraper.js'; import { deserializeXml } from '../utils/xml.js'; export type WikiFunctionType = 'panelfunc' | 'classfunc' | 'libraryfunc' | 'hook'; export type Realm = 'Menu' | 'Client' | 'Server' | 'Shared' | 'Client and menu'; export type CommonWikiProperties = { type: WikiFunctionType | 'enum' | 'struct' | 'panel'; address: string; name: string; description: string; realm: Realm; url: string; } export type WikiIdentifier = { name: string; type: string; description?: string; }; export type FunctionArgument = WikiIdentifier & { default?: string; }; export type FunctionReturn = WikiIdentifier & {}; export type Function = CommonWikiProperties & { parent: string; arguments?: FunctionArgument[]; returns?: FunctionReturn[]; }; export type ClassFunction = Function & {}; export type LibraryFunction = Function & { type: 'libraryfunc'; dontDefineParent?: boolean; }; export type HookFunction = Function & { type: 'hook'; isHook: 'yes'; }; export type PanelFunction = Function & { type: 'panelfunc'; isPanelFunction: 'yes'; }; export type EnumValue = { key: string; value: string; description: string; }; export type Enum = CommonWikiProperties & { type: 'enum'; items: EnumValue[]; }; export type StructField = { name: string; type: string; default?: any; description: string; }; export type Struct = CommonWikiProperties & { type: 'struct'; fields: StructField[]; }; export type Panel = CommonWikiProperties & { type: 'panel'; parent: string; }; export type WikiPage = ClassFunction | LibraryFunction | HookFunction | PanelFunction | Panel | Enum | Struct; /** * Guards */ export function isClassFunction(page: WikiPage): page is ClassFunction { return page.type === 'classfunc'; } export function isLibraryFunction(page: WikiPage): page is LibraryFunction { return page.type === 'libraryfunc'; } export function isHookFunction(page: WikiPage): page is HookFunction { return page.type === 'hook'; } export function isPanelFunction(page: WikiPage): page is PanelFunction { return page.type === 'panelfunc'; } export function isPanel(page: WikiPage): page is Panel { return page.type === 'panel'; } export function isEnum(page: WikiPage): page is Enum { return page.type === 'enum'; } export function isStruct(page: WikiPage): page is Struct { return page.type === 'struct'; } /** * Scraper */ export class WikiPageMarkupScraper extends Scraper<WikiPage> { /** * @param response The response from the page * @param content The content of the request * * @returns A list containing only the scraped page */ public getScrapeCallback(): ScrapeCallback<WikiPage> { return (response: Response, content: string): WikiPage[] => { const page = deserializeXml<WikiPage | null>(content, ($) => { const isEnum = $('enum').length > 0; const isStruct = $('structure').length > 0; const isFunction = $('function').length > 0; const isPanel = $('panel').length > 0; const mainElement = $(isEnum ? 'enum' : isStruct ? 'struct' : isPanel ? 'panel' : 'function'); const address = response.url.split('/').pop()!.split('?')[0]; if (isEnum) { const items = $('items item').map(function () {
const $el = $(this);
return <EnumValue>{ key: $el.attr('key')!, value: $el.attr('value')!, description: $el.text() }; }).get(); return <Enum>{ type: 'enum', name: address, address: address, description: $('description').text(), realm: $('realm').text() as Realm, items }; } else if (isStruct) { const fields = $('fields item').map(function () { const $el = $(this); return <StructField>{ name: $el.attr('name')!, type: $el.attr('type')!, default: $el.attr('default'), description: $el.text() }; }).get(); return <Struct>{ type: 'struct', name: address, address: address, description: $('description').text(), realm: $('realm').text() as Realm, fields }; } else if (isPanel) { return <Panel>{ type: 'panel', name: address, address: address, description: $('description').text(), realm: $('realm').text() as Realm, parent: $('parent').text() }; } else if (isFunction) { const isClassFunction = mainElement.attr('type') === 'classfunc'; const isLibraryFunction = mainElement.attr('type') === 'libraryfunc'; const isHookFunction = mainElement.attr('type') === 'hook'; const isPanelFunction = mainElement.attr('type') === 'panelfunc'; const arguments_ = $('args arg').map(function() { const $el = $(this); const argument = <FunctionArgument> { name: $el.attr('name')!, type: $el.attr('type')!, description: $el.text() }; if ($el.attr('default')) argument.default = $el.attr('default')!; return argument; }).get(); const returns = $('rets ret').map(function() { const $el = $(this); return <FunctionReturn> { name: $el.attr('name')!, type: $el.attr('type')!, description: $el.text() }; }).get(); const base = <Function> { type: mainElement.attr('type')!, parent: mainElement.attr('parent')!, name: mainElement.attr('name')!, address: address, description: $('description:first').text(), realm: $('realm:first').text() as Realm, arguments: arguments_, returns }; if (isClassFunction) { return <ClassFunction> { ...base, type: 'classfunc' }; } else if (isLibraryFunction) { if (base.parent === 'Global') { base.parent = '_G'; (<LibraryFunction>base).dontDefineParent = true; } return <LibraryFunction> { ...base, type: 'libraryfunc' }; } else if (isHookFunction) { return <HookFunction> { ...base, type: 'hook', isHook: 'yes' }; } else if (isPanelFunction) { return <PanelFunction> { ...base, type: 'panelfunc', isPanelFunction: 'yes' }; } } return null; }); if (!page) return []; page.url = response.url.replace(/\?format=text$/, ''); return [page]; }; } }
src/scrapers/wiki-page-markup-scraper.ts
luttje-glua-api-snippets-9f40376
[ { "filename": "src/scrapers/wiki-history-scraper.ts", "retrieved_chunk": " const pages = await baseScrapeCallback(response, content);\n if (pages.length === 0)\n return [];\n // There is only one page per response\n const page = pages[0];\n const $ = cheerio.load(content);\n const changeElements = $('table.changelist > tbody > .entry');\n if (!changeElements)\n return [page];\n for (const changeElement of changeElements) {", "score": 0.7713262438774109 }, { "filename": "src/scrapers/table-scraper.ts", "retrieved_chunk": " if (!tableColumnDefinition) {\n const properties = Object.getOwnPropertyNames(rowResult);\n const propertyKey = properties.find(property => property.toLowerCase() === headingText.toLowerCase());\n if (!propertyKey)\n continue;\n tableColumnDefinition = {\n propertyKey,\n columnName: headingText,\n typeConverter: (value: string) => value\n };", "score": 0.7546112537384033 }, { "filename": "src/api-writer/glua-api-writer.ts", "retrieved_chunk": " }\n public writePages(pages: WikiPage[]) {\n let api: string = '';\n for (const page of pages) {\n api += this.writePage(page);\n }\n return api;\n }\n private transformType(type: string) {\n if (type === 'vararg')", "score": 0.7545831203460693 }, { "filename": "src/scrapers/table-scraper.ts", "retrieved_chunk": " constructor(baseUrl: string, private readonly factory: () => T) {\n super(baseUrl);\n }\n public getScrapeCallback(): ScrapeCallback<Table<T>> {\n return (response: Response, content: string): Table<T>[] => {\n const results: Table<T>[] = [];\n const $ = cheerio.load(content);\n const tables = $('table');\n for (const table of tables) {\n const tableResult = this.fromTableElement($, table);", "score": 0.749082088470459 }, { "filename": "src/scrapers/table-scraper.ts", "retrieved_chunk": " let isEmpty = true;\n for (let i = 0; i < cells.length; i++) {\n const cell = cells[i];\n const heading = headings[i];\n if (!heading)\n continue;\n const headingText = $(heading).text();\n if (!headingText)\n continue;\n let tableColumnDefinition = allTableColumns.find(column => column.columnName === headingText);", "score": 0.7483569383621216 } ]
typescript
const $el = $(this);
import { Scrapeable, TraverseScraper } from './traverse-scraper.js'; import { ScrapeCallback } from './scraper.js'; import * as cheerio from 'cheerio'; import "reflect-metadata"; const tableColumnMetadataKey = Symbol("tableColumn"); export type TableColumnDefinition = { propertyKey: string | symbol, columnName: string, typeConverter: (value: string) => any }; export function tableColumn(columnName: string): PropertyDecorator { return (target: object, propertyKey: string | symbol) => { const existingColumns: TableColumnDefinition[] = Reflect.getMetadata(tableColumnMetadataKey, target) || []; const propertyType = Reflect.getMetadata("design:type", target, propertyKey); existingColumns.push({ propertyKey, columnName, typeConverter: (value: string) => { switch (propertyType) { case String: return value; case Number: return Number(value); case Boolean: return Boolean(value); default: return value; } } }); Reflect.defineMetadata(tableColumnMetadataKey, existingColumns, target); }; } export function getTableColumns(target: object): TableColumnDefinition[] { return Reflect.getMetadata(tableColumnMetadataKey, target) || []; } export class Row<T> { constructor(public data: T) { } } export class Table<T> implements Scrapeable { public url: string; public childUrls: Set<string> = new Set(); constructor(url: string, public rows: Row<T>[] = []) { this.url = url; } public addRow(row: Row<T>) { this.rows.push(row); } } export class TableScraper<T extends object> extends TraverseScraper<Table<T>> { constructor(baseUrl: string, private readonly factory: () => T) { super(baseUrl); } public getScrapeCallback(): ScrapeCallback<Table<T>> { return (response: Response, content: string): Table<T>[] => { const results: Table<T>[] = []; const $ = cheerio.load(content); const tables = $('table'); for (const table of tables) { const tableResult = this.fromTableElement($, table); if (tableResult) results.push(tableResult); } return results; }; } private fromTableElement($: cheerio.CheerioAPI, tableElement: cheerio.Element): Table<T> | null {
const tableResult = new Table<T>(this.baseUrl);
let headingRows = $(tableElement).find('thead > tr'); let shouldTrimHeadings = false; if (headingRows.length === 0) { headingRows = $(tableElement).find('tbody > tr:first-child'); shouldTrimHeadings = true; } let headings : cheerio.Element[] | undefined; if (headingRows.length > 0) headings = $(headingRows[0]).find('th').toArray(); if (!headings || headings.length === 0) throw new Error('No headings found in table'); let rows = $(tableElement).find('tbody > tr').toArray(); if (rows.length === 0) rows = $(tableElement).find('tr').toArray(); if (shouldTrimHeadings) rows = rows.slice(headingRows.length); let isEmpty = true; for (const row of rows) { const rowResult = this.fromRowElement($, row, headings); if (rowResult === null) continue; tableResult.addRow(rowResult); isEmpty = false; } if (isEmpty) return null; return tableResult; } private fromRowElement($: cheerio.CheerioAPI, rowElement: cheerio.Element, headings: cheerio.Element[]): Row<T> | null { const cells = $(rowElement).find('td').toArray(); const rowResult = this.factory(); const allTableColumns = getTableColumns(rowResult); let isEmpty = true; for (let i = 0; i < cells.length; i++) { const cell = cells[i]; const heading = headings[i]; if (!heading) continue; const headingText = $(heading).text(); if (!headingText) continue; let tableColumnDefinition = allTableColumns.find(column => column.columnName === headingText); if (!tableColumnDefinition) { const properties = Object.getOwnPropertyNames(rowResult); const propertyKey = properties.find(property => property.toLowerCase() === headingText.toLowerCase()); if (!propertyKey) continue; tableColumnDefinition = { propertyKey, columnName: headingText, typeConverter: (value: string) => value }; } const cellText = $(cell).text(); if (!cellText) continue; (rowResult as any)[tableColumnDefinition.propertyKey] = tableColumnDefinition.typeConverter(cellText); isEmpty = false; } if (isEmpty) return null; return new Row<T>(rowResult); } }
src/scrapers/table-scraper.ts
luttje-glua-api-snippets-9f40376
[ { "filename": "src/scrapers/json-scraper.ts", "retrieved_chunk": " }\n public static makeScrapeCallback<T extends object = object>(): ScrapeCallback<T> {\n return (response: Response, content: string): T[] => {\n return JSON.parse(content);\n };\n }\n}", "score": 0.8056704998016357 }, { "filename": "src/utils/xml.ts", "retrieved_chunk": "import * as cheerio from 'cheerio';\nexport function deserializeXml<T extends object | null>(xml: string, deserializer: ($: cheerio.CheerioAPI) => T): T {\n const $ = cheerio.load(xml, { xmlMode: true });\n return deserializer($);\n}", "score": 0.7872604131698608 }, { "filename": "src/scrapers/collector.ts", "retrieved_chunk": "import { Scraper, ScrapeResult } from \"./scraper.js\";\nexport async function scrapeAndCollect<T extends ScrapeResult>(scraper: Scraper<T>) {\n const collected: T[] = [];\n scraper.on(\"scraped\", (url: string, results: T[]) => {\n collected.push(...results);\n });\n await scraper.scrape();\n return collected;\n}", "score": 0.7648149728775024 }, { "filename": "src/scrapers/scraper.ts", "retrieved_chunk": " }\n public setRetryOptions(options: RequestInitWithRetry): void {\n this.retryOptions = options;\n }\n /**\n * Scrapes the base url and has the callback process the response\n */\n public async scrape(): Promise<void> {\n const callback = this.getScrapeCallback();\n await this.visitOne(this.baseUrl, callback);", "score": 0.759046733379364 }, { "filename": "src/scrapers/wiki-history-scraper.ts", "retrieved_chunk": " const pages = await baseScrapeCallback(response, content);\n if (pages.length === 0)\n return [];\n // There is only one page per response\n const page = pages[0];\n const $ = cheerio.load(content);\n const changeElements = $('table.changelist > tbody > .entry');\n if (!changeElements)\n return [page];\n for (const changeElement of changeElements) {", "score": 0.7583590745925903 } ]
typescript
const tableResult = new Table<T>(this.baseUrl);
import { ScrapeCallback, Scraper } from './scraper.js'; import { deserializeXml } from '../utils/xml.js'; export type WikiFunctionType = 'panelfunc' | 'classfunc' | 'libraryfunc' | 'hook'; export type Realm = 'Menu' | 'Client' | 'Server' | 'Shared' | 'Client and menu'; export type CommonWikiProperties = { type: WikiFunctionType | 'enum' | 'struct' | 'panel'; address: string; name: string; description: string; realm: Realm; url: string; } export type WikiIdentifier = { name: string; type: string; description?: string; }; export type FunctionArgument = WikiIdentifier & { default?: string; }; export type FunctionReturn = WikiIdentifier & {}; export type Function = CommonWikiProperties & { parent: string; arguments?: FunctionArgument[]; returns?: FunctionReturn[]; }; export type ClassFunction = Function & {}; export type LibraryFunction = Function & { type: 'libraryfunc'; dontDefineParent?: boolean; }; export type HookFunction = Function & { type: 'hook'; isHook: 'yes'; }; export type PanelFunction = Function & { type: 'panelfunc'; isPanelFunction: 'yes'; }; export type EnumValue = { key: string; value: string; description: string; }; export type Enum = CommonWikiProperties & { type: 'enum'; items: EnumValue[]; }; export type StructField = { name: string; type: string; default?: any; description: string; }; export type Struct = CommonWikiProperties & { type: 'struct'; fields: StructField[]; }; export type Panel = CommonWikiProperties & { type: 'panel'; parent: string; }; export type WikiPage = ClassFunction | LibraryFunction | HookFunction | PanelFunction | Panel | Enum | Struct; /** * Guards */ export function isClassFunction(page: WikiPage): page is ClassFunction { return page.type === 'classfunc'; } export function isLibraryFunction(page: WikiPage): page is LibraryFunction { return page.type === 'libraryfunc'; } export function isHookFunction(page: WikiPage): page is HookFunction { return page.type === 'hook'; } export function isPanelFunction(page: WikiPage): page is PanelFunction { return page.type === 'panelfunc'; } export function isPanel(page: WikiPage): page is Panel { return page.type === 'panel'; } export function isEnum(page: WikiPage): page is Enum { return page.type === 'enum'; } export function isStruct(page: WikiPage): page is Struct { return page.type === 'struct'; } /** * Scraper */ export class WikiPageMarkupScraper extends
Scraper<WikiPage> {
/** * @param response The response from the page * @param content The content of the request * * @returns A list containing only the scraped page */ public getScrapeCallback(): ScrapeCallback<WikiPage> { return (response: Response, content: string): WikiPage[] => { const page = deserializeXml<WikiPage | null>(content, ($) => { const isEnum = $('enum').length > 0; const isStruct = $('structure').length > 0; const isFunction = $('function').length > 0; const isPanel = $('panel').length > 0; const mainElement = $(isEnum ? 'enum' : isStruct ? 'struct' : isPanel ? 'panel' : 'function'); const address = response.url.split('/').pop()!.split('?')[0]; if (isEnum) { const items = $('items item').map(function () { const $el = $(this); return <EnumValue>{ key: $el.attr('key')!, value: $el.attr('value')!, description: $el.text() }; }).get(); return <Enum>{ type: 'enum', name: address, address: address, description: $('description').text(), realm: $('realm').text() as Realm, items }; } else if (isStruct) { const fields = $('fields item').map(function () { const $el = $(this); return <StructField>{ name: $el.attr('name')!, type: $el.attr('type')!, default: $el.attr('default'), description: $el.text() }; }).get(); return <Struct>{ type: 'struct', name: address, address: address, description: $('description').text(), realm: $('realm').text() as Realm, fields }; } else if (isPanel) { return <Panel>{ type: 'panel', name: address, address: address, description: $('description').text(), realm: $('realm').text() as Realm, parent: $('parent').text() }; } else if (isFunction) { const isClassFunction = mainElement.attr('type') === 'classfunc'; const isLibraryFunction = mainElement.attr('type') === 'libraryfunc'; const isHookFunction = mainElement.attr('type') === 'hook'; const isPanelFunction = mainElement.attr('type') === 'panelfunc'; const arguments_ = $('args arg').map(function() { const $el = $(this); const argument = <FunctionArgument> { name: $el.attr('name')!, type: $el.attr('type')!, description: $el.text() }; if ($el.attr('default')) argument.default = $el.attr('default')!; return argument; }).get(); const returns = $('rets ret').map(function() { const $el = $(this); return <FunctionReturn> { name: $el.attr('name')!, type: $el.attr('type')!, description: $el.text() }; }).get(); const base = <Function> { type: mainElement.attr('type')!, parent: mainElement.attr('parent')!, name: mainElement.attr('name')!, address: address, description: $('description:first').text(), realm: $('realm:first').text() as Realm, arguments: arguments_, returns }; if (isClassFunction) { return <ClassFunction> { ...base, type: 'classfunc' }; } else if (isLibraryFunction) { if (base.parent === 'Global') { base.parent = '_G'; (<LibraryFunction>base).dontDefineParent = true; } return <LibraryFunction> { ...base, type: 'libraryfunc' }; } else if (isHookFunction) { return <HookFunction> { ...base, type: 'hook', isHook: 'yes' }; } else if (isPanelFunction) { return <PanelFunction> { ...base, type: 'panelfunc', isPanelFunction: 'yes' }; } } return null; }); if (!page) return []; page.url = response.url.replace(/\?format=text$/, ''); return [page]; }; } }
src/scrapers/wiki-page-markup-scraper.ts
luttje-glua-api-snippets-9f40376
[ { "filename": "src/scrapers/wiki-page-list-scraper.ts", "retrieved_chunk": "import { JsonScraper } from './json-scraper.js';\nexport type WikiPageIndexObject = {\n address: string;\n updateCount: number;\n viewCount: number;\n}\nexport class WikiPageListScraper extends JsonScraper<WikiPageIndexObject> {}", "score": 0.835433840751648 }, { "filename": "src/scrapers/wiki-history-scraper.ts", "retrieved_chunk": " public history: WikiHistory[] = [];\n constructor(url: string, title: string) {\n super(url, title);\n }\n}\nexport class WikiHistoryPageScraper extends PageTraverseScraper<WikiHistoryPage> {\n constructor(baseUrl: string) {\n super(baseUrl, (url: string, title: string) => new WikiHistoryPage(url, title));\n }\n /**", "score": 0.8266817927360535 }, { "filename": "src/scrapers/traverse-scraper.ts", "retrieved_chunk": "import { Scraper, ScrapeCallback } from './scraper.js';\nexport interface Scrapeable {\n childUrls: Set<string>;\n}\nexport class TraverseScraper<T extends Scrapeable> extends Scraper<T> {\n protected readonly traversedUrls: Set<string> = new Set();\n protected childPageFilter?: (url: string) => boolean;\n public setChildPageFilter(filter: (url: string) => boolean): void {\n this.childPageFilter = filter;\n }", "score": 0.8079580068588257 }, { "filename": "src/scrapers/page-traverse-scraper.ts", "retrieved_chunk": "import { Scrapeable, TraverseScraper } from './traverse-scraper.js';\nimport { decodeEntities } from './decode-entities.js';\nimport { ScrapeCallback } from './scraper.js';\nexport class Page implements Scrapeable {\n public url: string;\n public title: string;\n public childUrls: Set<string> = new Set();\n constructor(url: string, title: string) {\n this.url = url;\n this.title = title;", "score": 0.7899196147918701 }, { "filename": "src/scrapers/page-traverse-scraper.ts", "retrieved_chunk": " }\n}\nexport class PageTraverseScraper<T extends Page = Page> extends TraverseScraper<T> {\n private readonly factory: (url: string, title: string) => T;\n constructor(baseUrl: string, factory?: (url: string, title: string) => T) {\n super(baseUrl);\n this.factory = factory ?? ((url: string, title: string) => new Page(url, title) as T);\n }\n /**\n * Scrapes a page for its URL and title, and returns a list of child URLs", "score": 0.7759169936180115 } ]
typescript
Scraper<WikiPage> {
import { exec } from 'child_process'; import { GolemFile, GolemTarget, isGolemTarget } from './types'; import { ChatGPTMessage, ChatGPT_completion } from './chat_gpt'; import { readFile } from 'fs/promises'; import { dirname } from 'path'; import logger from './logger'; import { generateCacheKey, isCacheValid, saveOutputToCache, loadOutputFromCache, appendToGolemFile } from './utils'; import { writeFileSync} from 'fs'; // TODO 1: Check if prompt asks for additional targets. // TODO 2: Check if targets have other dependencies. // TODO 3: Saving properly (for example, it saves all of the previous context for imp task) // TODO 4: Use different files interface ExecutionContext { [key: string]: any; } const mainPrompt: ChatGPTMessage = { role: 'system', content: `You are an Agentic LLM assistant, designed only to produce code and helpful information. You may be asked to generate new targets. If the prompt given to you contains the phrase 'generate new targets', your response will be to generate a list of targets to help answer the prompt. The targets must be written as unnumbered items separated by lines starting with 'Target:'. The items in the list will not be arranged in any particular order. For example: Prompt: As an agentic LLM, generate new targets for the next iteration. Response: Target: Write a function to divide two numbers. Target: Create a class called Employee. Target: Write unit tests for the function GetPeopleInterests. It is not always the case that you will be asked to generate new targets. If the prompt does not contain the phrase 'generate new targets', then proceed to answer the prompt as truthfully as possible. For example: Prompt: What is capital of France? Response: Paris. Prompt: How many days are in the month of April? Response: 30 days. You are opinionated. If asked to provide a subjective answer, start by saying 'In my opinion' then answer the prompt. For example: Prompt: What is the best sport? Response: In my opinion, soccer. ` } export async function executeTarget(target: string, golemFile: GolemFile, golemFilePath: string, context: Map<string, any> = new Map()): Promise<void> { const golemTarget = golemFile[target]; if (!golemTarget) { throw new Error(`Target "${target}" not found in Golem file.`); } console.log(`Executing target: ${target}`); if (golemTarget.dependencies) { console.log(`Dependencies for ${target}: ${golemTarget.dependencies}`); for (const dependency of golemTarget.dependencies) { if (dependency) { await executeTarget(dependency, golemFile, golemFilePath, context); } } } await executeAIChatWithCache(target, golemFile, golemFilePath, context); console.log(`Context after ${target} execution:`, context); } function executeCommand(command: string): Promise<void> { return new Promise((resolve, reject) => { exec(command, (error, stdout, stderr) => { if (error) { logger.error(`Error executing command: ${command}`); logger.error(stderr); reject(error); } else { logger.debug(stdout); resolve(); } }); }); } async function executeAIChatWithCache(target: string, golemFile: GolemFile, golemFilePath: string, context: Map<string, any>): Promise<void> { const golemFileToArray: any = []; for (const key in golemFile){ const val = golemFile[key as keyof typeof golemFile]; golemFileToArray.push(val); } const golemTarget = golemFile[target]; if (!golemTarget || !isGolemTarget(golemTarget)) { return; } const cacheKey = generateCacheKey(target, golemTarget.dependencies || [], [...golemFileToArray] || ''); if (isCacheValid(target, cacheKey)) { console.log("Returning Cached output"); const cachedOutput = loadOutputFromCache(target, cacheKey); context.set(target, cachedOutput); } else { await executeAIChat(target, golemFile, golemFilePath, context); saveOutputToCache(target, cacheKey, context); } } async function executeAIChat(target: string, golemFile: GolemFile, golemFilePath: string, context: Map<string, any>): Promise<void> { // ============== Setup start ==================================== const contextOfCurrentTarget: string[] = []; const allOutputs: {[key: string]: any} = {}; const golemTarget = golemFile[target]; console.log("gT", golemTarget); if (!golemTarget) { throw new Error(`Target "${target}" not found in Golem file.`); } if (!isGolemTarget(golemTarget)) { return; } if (!golemTarget.prompt && !golemTarget.model) { golemTarget.model = 'cat'; } let prompt = golemTarget.prompt ?? "{no prompt}"; if (isGolemTarget(golemTarget) && golemTarget.prompt) { prompt = golemTarget.prompt; const placeholderRegex = /{{\s*([\w\/.-]+)\s*}}/g; let match; while ((match = placeholderRegex.exec(prompt)) !== null) { const key = match[1]; if (context.has(key)) { prompt = prompt.replace(match[0], context.get(key)); } else { prompt = prompt.replace(match[0], ""); } } } else if (!golemTarget.prompt) { const defaultValues = new Map(context.entries()); context.set("default", Object.fromEntries(defaultValues)); return; } const model = golemTarget.model ?? 'gpt-3.5-turbo'; // ============== Setup end ==================================== if (model === 'cat') { const concatenatedOutput = golemTarget.dependencies.map(dep => context.get(dep)).join(''); context.set(target, concatenatedOutput); } else if (model == "gpt-3.5-turbo" || model == "gpt-3.5-turbo-0301" || model == "gpt-4-0314" || model == "gpt-4-32k") { if ("model" in golemTarget) { delete golemTarget.model; } // This gets the 'keys' (subtasks) of a target (task) const golemTargetKeys: string[] = Object.keys(golemTarget); // It starts from 1 as index 0 is dependencies. This can be changed if needed for (let i = 1; i < golemTargetKeys.length; i++){ // console.log("gTKi", golemTargetKeys[i]); const val: any = golemTarget[golemTargetKeys[i] as keyof typeof golemTarget]; // console.log("val", val); const previousContext: string | undefined = contextOfCurrentTarget[0] || ''; // Concat the previousContext (if undefined) to the current subtask (here, named val) const content = previousContext + val; // console.log("content", content); // This block of code replaces the {{}} placeholders in the string from the yaml file // with the output of the subtask or task it requires const replacedString = content.replace(/{{(.*?)}}/g, (match, p1) => { // Remove the curly braces from the placeholder const placeholder = p1.trim(); // Replace the placeholder with the corresponding value from the map return context.get(placeholder) || placeholder; }); // console.log("context", context); // console.log("replacedString", replacedString); const taskGenerationMessages: ChatGPTMessage[] = [ mainPrompt, { role: 'user', content: replacedString, }, ]; const response =
await ChatGPT_completion(taskGenerationMessages, model, 0.7, 0.9);
contextOfCurrentTarget.length = 0; //clear the previous context contextOfCurrentTarget.push(response); //append the new context to be used in the next iteration allOutputs[golemTargetKeys[i]] = response; const lines: string[] = response.split('\n'); // Extract the targets from the lines that start with "Target:" const targets: string[] = lines.filter((line: string) => line.startsWith("Target:")) .map((line: string) => line.slice(8)); let count = 1; targets.forEach((createdTarget: string) => { const targetName = target.concat("_target".concat(count.toString())); const newTarget: string = `\n${targetName}:\n dependencies: []\n prompt: ${createdTarget}`; appendToGolemFile(golemFilePath, newTarget); golemTargetKeys.push(targetName); golemTarget[targetName] = createdTarget; count += 1; }); if (golemTargetKeys.length === 2){ if (!response) { context.set(target, `Default value for ${target}`); } else { context.set(target, response); console.log(context); } } else if (golemTargetKeys.length > 2){ try { for (const key in allOutputs) { context.set(key, allOutputs[key]); } }catch (error: any) { logger.error(`Error generating AI response: ${error.message}`); } } } }else { throw new Error(`No such supported model ${model}`); } }
src/executor.ts
Confabulation-Corporation-golem-ac8b554
[ { "filename": "src/golem.ts", "retrieved_chunk": " 'Run the specified Golem file or the default Golem file if none is provided.',\n (yargs) => {\n yargs.positional('golemFile', {\n describe: 'Path to the Golem file',\n default: 'Golem.yaml',\n type: 'string',\n });\n },\n async (argv) => {\n try {", "score": 0.74351966381073 }, { "filename": "src/parser.ts", "retrieved_chunk": "import * as yaml from 'js-yaml';\nimport { GolemFile } from './types';\nexport function parseGolemFile(content: string): GolemFile {\n try {\n const parsedContent = yaml.load(content) as GolemFile;\n // Update the parsing logic to handle the task_generation_prompt field\n return parsedContent;\n } catch (error: any) {\n throw new Error(`Error parsing Golem file: ${error.message}`);\n }", "score": 0.7411850690841675 }, { "filename": "src/chat_gpt.ts", "retrieved_chunk": " const waitTime = resetMs + Math.random() * 1000;\n logger.warn(\n `Rate limit or server error encountered (status: ${error.response.status}). Retrying in ${waitTime} ms...`\n );\n await new Promise((resolve) => setTimeout(resolve, waitTime));\n } else {\n throw error;\n }\n }\n }", "score": 0.7379626035690308 }, { "filename": "src/types.ts", "retrieved_chunk": "export interface GolemTarget {\n dependencies: string[];\n prompt: string;\n model?: string; // Add this line\n task_generation_prompt?: string; // Add this line\n [key: string]: string[] | string | undefined;\n}\nexport type GolemFile = {\n default: string[];\n} & {", "score": 0.7351481914520264 }, { "filename": "src/chat_gpt.ts", "retrieved_chunk": " for (let i = 0; i < maxRetries; i++) {\n try {\n const completion = await openai.createChatCompletion({\n model: model,\n messages: messages,\n });\n return (completion.data!.choices[0]!.message?.content || \"\").trim();\n } catch (error: any) {\n if (error.response && (error.response.status === 429 || (error.response.status >= 500 && error.response.status < 600))) {\n const resetMs = parseInt(error.response.headers['x-ratelimit-reset-requests']) || 1000;", "score": 0.707182765007019 } ]
typescript
await ChatGPT_completion(taskGenerationMessages, model, 0.7, 0.9);
import { ClassFunction, Enum, Function, HookFunction, LibraryFunction, Panel, PanelFunction, Realm, Struct, WikiPage, isPanel } from '../scrapers/wiki-page-markup-scraper.js'; import { putCommentBeforeEachLine, removeNewlines, safeFileName, toLowerCamelCase } from '../utils/string.js'; import { isClassFunction, isHookFunction, isLibraryFunction, isPanelFunction, isStruct, isEnum, } from '../scrapers/wiki-page-markup-scraper.js'; export const RESERVERD_KEYWORDS = new Set([ 'and', 'break', 'continue', 'do', 'else', 'elseif', 'end', 'false', 'for', 'function', 'goto', 'if', 'in', 'local', 'nil', 'not', 'or', 'repeat', 'return', 'then', 'true', 'until', 'while' ]); export class GluaApiWriter { private readonly writtenClasses: Set<string> = new Set(); private readonly writtenLibraryGlobals: Set<string> = new Set(); private readonly pageOverrides: Map<string, string> = new Map(); constructor() { } public static safeName(name: string) { if (name.includes('/')) name = name.replace(/\//g, ' or '); if (name.includes('=')) name = name.split('=')[0]; if (name.includes(' ')) name = toLowerCamelCase(name); // Remove any remaining characters not valid in a Lua variable/function name. name = name.replace(/[^A-Za-z\d_.]/g, ''); if (RESERVERD_KEYWORDS.has(name)) return `_${name}`; return name; } public addOverride(pageAddress: string, override: string) { this.pageOverrides.set(safeFileName(pageAddress, '.'), override); } public writePage(page: WikiPage) { const fileSafeAddress = safeFileName(page.address, '.'); if (this.pageOverrides.has(fileSafeAddress)) { let api = ''; if (isClassFunction(page)) api += this.writeClass(page.parent); else if (isLibraryFunction(page)) api += this.writeLibraryGlobal(page); api += this.pageOverrides.get(fileSafeAddress); return `${api}\n\n`; } else if (isClassFunction(page)) return this.writeClassFunction(page); else if (isLibraryFunction(page)) return this.writeLibraryFunction(page); else if (isHookFunction(page)) return this.writeHookFunction(page); else if (isPanel(page)) return this.writePanel(page); else if (isPanelFunction(page)) return this.writePanelFunction(page); else if (isEnum(page)) return this.writeEnum(page); else if (isStruct(page)) return this.writeStruct(page); } private writeClass(className: string, parent?: string, classFields: string = '') { let api: string = ''; if (!this.writtenClasses.has(className)) { const classOverride = `class.${className}`; if (this.pageOverrides.has(classOverride)) { api += this.pageOverrides.get(classOverride)!.replace(/\n$/g, '') + '\n\n'; api = api.replace('---{{CLASS_FIELDS}}\n', classFields); } else { api += `---@class ${className}`; if (parent) api += ` : ${parent}`; api += '\n'; api += classFields; api += `local ${className} = {}\n\n`; } this.writtenClasses.add(className); } return api; } private writeLibraryGlobal(func: LibraryFunction) { if (!func.dontDefineParent && !this.writtenLibraryGlobals.has(func.parent)) { const global = `${func.parent} = {}\n\n`; this.writtenLibraryGlobals.add(func.parent); return global; } return ''; } private writeClassFunction(func: ClassFunction) { let api: string = this.writeClass(func.parent); api += this.writeFunctionLuaDocComment(func, func.realm); api += this.writeFunctionDeclaration(func, func.realm, ':'); return api; } private writeLibraryFunction(func: LibraryFunction) { let api: string = this.writeLibraryGlobal(func); api += this.writeFunctionLuaDocComment(func, func.realm); api += this.writeFunctionDeclaration(func, func.realm); return api; } private writeHookFunction(func: HookFunction) { return this.writeClassFunction(func); } private writePanel(panel: Panel) { return this.writeClass(panel.name, panel.parent); } private writePanelFunction(func: PanelFunction) { let api: string = ''; api += this.writeFunctionLuaDocComment(func, func.realm); api += this.writeFunctionDeclaration(func, func.realm, ':'); return api; } private writeEnum(_enum: Enum) { let api: string = '';
const isContainedInTable = _enum.items[0]?.key.includes('.') ?? false;
api += `---@enum ${_enum.name}\n`; if (isContainedInTable) api += `local ${_enum.name} = {\n`; const writeItem = (key: string, item: typeof _enum.items[0]) => { if (isContainedInTable) { key = key.split('.')[1]; api += ` ${key} = ${item.value}, ` + (item.description ? `--[[ ${item.description} ]]` : '') + '\n'; } else { const comment = item.description ? `${putCommentBeforeEachLine(item.description, false)}\n` : ''; api += `${comment}${key} = ${item.value}\n`; } }; for (const item of _enum.items) writeItem(item.key, item); if (isContainedInTable) api += '}'; api += `\n\n`; return api; } private writeStruct(struct: Struct) { let fields: string = ''; for (const field of struct.fields) { fields += `---@field ${GluaApiWriter.safeName(field.name)} ${this.transformType(field.type)} ${removeNewlines(field.description!)}\n`; } return this.writeClass(struct.name, undefined, fields); } public writePages(pages: WikiPage[]) { let api: string = ''; for (const page of pages) { api += this.writePage(page); } return api; } private transformType(type: string) { if (type === 'vararg') return '...'; return type; } private writeFunctionLuaDocComment(func: Function, realm: Realm) { let luaDocComment = `---[${realm.toUpperCase()}] ${putCommentBeforeEachLine(func.description!.trim())}\n`; luaDocComment += `---\n---[(View on wiki)](${func.url})\n`; if (func.arguments) { func.arguments.forEach((arg, index) => { if (!arg.name) arg.name = arg.type; if (arg.type === 'vararg') arg.name = '...'; luaDocComment += `---@param ${GluaApiWriter.safeName(arg.name)}${arg.default !== undefined ? `?` : ''} ${this.transformType(arg.type)} ${putCommentBeforeEachLine(arg.description!)}\n`; }); } if (func.returns) { const returns = `---@return ${func.returns.map(ret => this.transformType(ret.type)).join(', ')}`; func.returns.forEach(ret => { const description = removeNewlines(ret.description ?? ''); if (func.returns!.length === 1) { luaDocComment += `${returns} #${description}\n`; return; } luaDocComment += `${returns} #${this.transformType(ret.type)} - ${description}\n`; }); } return luaDocComment; } private writeFunctionDeclaration(func: Function, realm: Realm, indexer: string = '.') { let declaration = `function ${func.parent ? `${func.parent}${indexer}` : ''}${GluaApiWriter.safeName(func.name)}(`; if (func.arguments) { declaration += func.arguments.map(arg => { if (arg.type === 'vararg') return '...'; return GluaApiWriter.safeName(arg.name!); }).join(', '); } declaration += ') end\n\n'; return declaration; } }
src/api-writer/glua-api-writer.ts
luttje-glua-api-snippets-9f40376
[ { "filename": "src/scrapers/wiki-page-markup-scraper.ts", "retrieved_chunk": " const isEnum = $('enum').length > 0;\n const isStruct = $('structure').length > 0;\n const isFunction = $('function').length > 0;\n const isPanel = $('panel').length > 0;\n const mainElement = $(isEnum ? 'enum' : isStruct ? 'struct' : isPanel ? 'panel' : 'function');\n const address = response.url.split('/').pop()!.split('?')[0];\n if (isEnum) {\n const items = $('items item').map(function () {\n const $el = $(this);\n return <EnumValue>{", "score": 0.7658983469009399 }, { "filename": "src/scrapers/wiki-page-markup-scraper.ts", "retrieved_chunk": "}\nexport function isEnum(page: WikiPage): page is Enum {\n return page.type === 'enum';\n}\nexport function isStruct(page: WikiPage): page is Struct {\n return page.type === 'struct';\n}\n/**\n * Scraper\n */", "score": 0.7543460726737976 }, { "filename": "src/scrapers/wiki-page-markup-scraper.ts", "retrieved_chunk": " parent: string;\n};\nexport type WikiPage = ClassFunction | LibraryFunction | HookFunction | PanelFunction | Panel | Enum | Struct;\n/**\n * Guards\n */\nexport function isClassFunction(page: WikiPage): page is ClassFunction {\n return page.type === 'classfunc';\n}\nexport function isLibraryFunction(page: WikiPage): page is LibraryFunction {", "score": 0.7525875568389893 }, { "filename": "src/scrapers/wiki-page-markup-scraper.ts", "retrieved_chunk": " realm: $('realm:first').text() as Realm,\n arguments: arguments_,\n returns\n };\n if (isClassFunction) {\n return <ClassFunction> {\n ...base,\n type: 'classfunc'\n };\n } else if (isLibraryFunction) {", "score": 0.7509799003601074 }, { "filename": "src/scrapers/table-scraper.ts", "retrieved_chunk": " constructor(baseUrl: string, private readonly factory: () => T) {\n super(baseUrl);\n }\n public getScrapeCallback(): ScrapeCallback<Table<T>> {\n return (response: Response, content: string): Table<T>[] => {\n const results: Table<T>[] = [];\n const $ = cheerio.load(content);\n const tables = $('table');\n for (const table of tables) {\n const tableResult = this.fromTableElement($, table);", "score": 0.7482763528823853 } ]
typescript
const isContainedInTable = _enum.items[0]?.key.includes('.') ?? false;
import { ScrapeCallback, Scraper } from './scraper.js'; import { deserializeXml } from '../utils/xml.js'; export type WikiFunctionType = 'panelfunc' | 'classfunc' | 'libraryfunc' | 'hook'; export type Realm = 'Menu' | 'Client' | 'Server' | 'Shared' | 'Client and menu'; export type CommonWikiProperties = { type: WikiFunctionType | 'enum' | 'struct' | 'panel'; address: string; name: string; description: string; realm: Realm; url: string; } export type WikiIdentifier = { name: string; type: string; description?: string; }; export type FunctionArgument = WikiIdentifier & { default?: string; }; export type FunctionReturn = WikiIdentifier & {}; export type Function = CommonWikiProperties & { parent: string; arguments?: FunctionArgument[]; returns?: FunctionReturn[]; }; export type ClassFunction = Function & {}; export type LibraryFunction = Function & { type: 'libraryfunc'; dontDefineParent?: boolean; }; export type HookFunction = Function & { type: 'hook'; isHook: 'yes'; }; export type PanelFunction = Function & { type: 'panelfunc'; isPanelFunction: 'yes'; }; export type EnumValue = { key: string; value: string; description: string; }; export type Enum = CommonWikiProperties & { type: 'enum'; items: EnumValue[]; }; export type StructField = { name: string; type: string; default?: any; description: string; }; export type Struct = CommonWikiProperties & { type: 'struct'; fields: StructField[]; }; export type Panel = CommonWikiProperties & { type: 'panel'; parent: string; }; export type WikiPage = ClassFunction | LibraryFunction | HookFunction | PanelFunction | Panel | Enum | Struct; /** * Guards */ export function isClassFunction(page: WikiPage): page is ClassFunction { return page.type === 'classfunc'; } export function isLibraryFunction(page: WikiPage): page is LibraryFunction { return page.type === 'libraryfunc'; } export function isHookFunction(page: WikiPage): page is HookFunction { return page.type === 'hook'; } export function isPanelFunction(page: WikiPage): page is PanelFunction { return page.type === 'panelfunc'; } export function isPanel(page: WikiPage): page is Panel { return page.type === 'panel'; } export function isEnum(page: WikiPage): page is Enum { return page.type === 'enum'; } export function isStruct(page: WikiPage): page is Struct { return page.type === 'struct'; } /** * Scraper */ export
class WikiPageMarkupScraper extends Scraper<WikiPage> {
/** * @param response The response from the page * @param content The content of the request * * @returns A list containing only the scraped page */ public getScrapeCallback(): ScrapeCallback<WikiPage> { return (response: Response, content: string): WikiPage[] => { const page = deserializeXml<WikiPage | null>(content, ($) => { const isEnum = $('enum').length > 0; const isStruct = $('structure').length > 0; const isFunction = $('function').length > 0; const isPanel = $('panel').length > 0; const mainElement = $(isEnum ? 'enum' : isStruct ? 'struct' : isPanel ? 'panel' : 'function'); const address = response.url.split('/').pop()!.split('?')[0]; if (isEnum) { const items = $('items item').map(function () { const $el = $(this); return <EnumValue>{ key: $el.attr('key')!, value: $el.attr('value')!, description: $el.text() }; }).get(); return <Enum>{ type: 'enum', name: address, address: address, description: $('description').text(), realm: $('realm').text() as Realm, items }; } else if (isStruct) { const fields = $('fields item').map(function () { const $el = $(this); return <StructField>{ name: $el.attr('name')!, type: $el.attr('type')!, default: $el.attr('default'), description: $el.text() }; }).get(); return <Struct>{ type: 'struct', name: address, address: address, description: $('description').text(), realm: $('realm').text() as Realm, fields }; } else if (isPanel) { return <Panel>{ type: 'panel', name: address, address: address, description: $('description').text(), realm: $('realm').text() as Realm, parent: $('parent').text() }; } else if (isFunction) { const isClassFunction = mainElement.attr('type') === 'classfunc'; const isLibraryFunction = mainElement.attr('type') === 'libraryfunc'; const isHookFunction = mainElement.attr('type') === 'hook'; const isPanelFunction = mainElement.attr('type') === 'panelfunc'; const arguments_ = $('args arg').map(function() { const $el = $(this); const argument = <FunctionArgument> { name: $el.attr('name')!, type: $el.attr('type')!, description: $el.text() }; if ($el.attr('default')) argument.default = $el.attr('default')!; return argument; }).get(); const returns = $('rets ret').map(function() { const $el = $(this); return <FunctionReturn> { name: $el.attr('name')!, type: $el.attr('type')!, description: $el.text() }; }).get(); const base = <Function> { type: mainElement.attr('type')!, parent: mainElement.attr('parent')!, name: mainElement.attr('name')!, address: address, description: $('description:first').text(), realm: $('realm:first').text() as Realm, arguments: arguments_, returns }; if (isClassFunction) { return <ClassFunction> { ...base, type: 'classfunc' }; } else if (isLibraryFunction) { if (base.parent === 'Global') { base.parent = '_G'; (<LibraryFunction>base).dontDefineParent = true; } return <LibraryFunction> { ...base, type: 'libraryfunc' }; } else if (isHookFunction) { return <HookFunction> { ...base, type: 'hook', isHook: 'yes' }; } else if (isPanelFunction) { return <PanelFunction> { ...base, type: 'panelfunc', isPanelFunction: 'yes' }; } } return null; }); if (!page) return []; page.url = response.url.replace(/\?format=text$/, ''); return [page]; }; } }
src/scrapers/wiki-page-markup-scraper.ts
luttje-glua-api-snippets-9f40376
[ { "filename": "src/scrapers/wiki-page-list-scraper.ts", "retrieved_chunk": "import { JsonScraper } from './json-scraper.js';\nexport type WikiPageIndexObject = {\n address: string;\n updateCount: number;\n viewCount: number;\n}\nexport class WikiPageListScraper extends JsonScraper<WikiPageIndexObject> {}", "score": 0.8367279767990112 }, { "filename": "src/scrapers/wiki-history-scraper.ts", "retrieved_chunk": " public history: WikiHistory[] = [];\n constructor(url: string, title: string) {\n super(url, title);\n }\n}\nexport class WikiHistoryPageScraper extends PageTraverseScraper<WikiHistoryPage> {\n constructor(baseUrl: string) {\n super(baseUrl, (url: string, title: string) => new WikiHistoryPage(url, title));\n }\n /**", "score": 0.8298835754394531 }, { "filename": "src/scrapers/traverse-scraper.ts", "retrieved_chunk": "import { Scraper, ScrapeCallback } from './scraper.js';\nexport interface Scrapeable {\n childUrls: Set<string>;\n}\nexport class TraverseScraper<T extends Scrapeable> extends Scraper<T> {\n protected readonly traversedUrls: Set<string> = new Set();\n protected childPageFilter?: (url: string) => boolean;\n public setChildPageFilter(filter: (url: string) => boolean): void {\n this.childPageFilter = filter;\n }", "score": 0.8075284361839294 }, { "filename": "src/scrapers/page-traverse-scraper.ts", "retrieved_chunk": "import { Scrapeable, TraverseScraper } from './traverse-scraper.js';\nimport { decodeEntities } from './decode-entities.js';\nimport { ScrapeCallback } from './scraper.js';\nexport class Page implements Scrapeable {\n public url: string;\n public title: string;\n public childUrls: Set<string> = new Set();\n constructor(url: string, title: string) {\n this.url = url;\n this.title = title;", "score": 0.7902951836585999 }, { "filename": "src/scrapers/page-traverse-scraper.ts", "retrieved_chunk": " }\n}\nexport class PageTraverseScraper<T extends Page = Page> extends TraverseScraper<T> {\n private readonly factory: (url: string, title: string) => T;\n constructor(baseUrl: string, factory?: (url: string, title: string) => T) {\n super(baseUrl);\n this.factory = factory ?? ((url: string, title: string) => new Page(url, title) as T);\n }\n /**\n * Scrapes a page for its URL and title, and returns a list of child URLs", "score": 0.7811760902404785 } ]
typescript
class WikiPageMarkupScraper extends Scraper<WikiPage> {
import { ScrapeCallback, Scraper } from './scraper.js'; import { deserializeXml } from '../utils/xml.js'; export type WikiFunctionType = 'panelfunc' | 'classfunc' | 'libraryfunc' | 'hook'; export type Realm = 'Menu' | 'Client' | 'Server' | 'Shared' | 'Client and menu'; export type CommonWikiProperties = { type: WikiFunctionType | 'enum' | 'struct' | 'panel'; address: string; name: string; description: string; realm: Realm; url: string; } export type WikiIdentifier = { name: string; type: string; description?: string; }; export type FunctionArgument = WikiIdentifier & { default?: string; }; export type FunctionReturn = WikiIdentifier & {}; export type Function = CommonWikiProperties & { parent: string; arguments?: FunctionArgument[]; returns?: FunctionReturn[]; }; export type ClassFunction = Function & {}; export type LibraryFunction = Function & { type: 'libraryfunc'; dontDefineParent?: boolean; }; export type HookFunction = Function & { type: 'hook'; isHook: 'yes'; }; export type PanelFunction = Function & { type: 'panelfunc'; isPanelFunction: 'yes'; }; export type EnumValue = { key: string; value: string; description: string; }; export type Enum = CommonWikiProperties & { type: 'enum'; items: EnumValue[]; }; export type StructField = { name: string; type: string; default?: any; description: string; }; export type Struct = CommonWikiProperties & { type: 'struct'; fields: StructField[]; }; export type Panel = CommonWikiProperties & { type: 'panel'; parent: string; }; export type WikiPage = ClassFunction | LibraryFunction | HookFunction | PanelFunction | Panel | Enum | Struct; /** * Guards */ export function isClassFunction(page: WikiPage): page is ClassFunction { return page.type === 'classfunc'; } export function isLibraryFunction(page: WikiPage): page is LibraryFunction { return page.type === 'libraryfunc'; } export function isHookFunction(page: WikiPage): page is HookFunction { return page.type === 'hook'; } export function isPanelFunction(page: WikiPage): page is PanelFunction { return page.type === 'panelfunc'; } export function isPanel(page: WikiPage): page is Panel { return page.type === 'panel'; } export function isEnum(page: WikiPage): page is Enum { return page.type === 'enum'; } export function isStruct(page: WikiPage): page is Struct { return page.type === 'struct'; } /** * Scraper */ export class WikiPageMarkupScraper extends Scraper<WikiPage> { /** * @param response The response from the page * @param content The content of the request * * @returns A list containing only the scraped page */
public getScrapeCallback(): ScrapeCallback<WikiPage> {
return (response: Response, content: string): WikiPage[] => { const page = deserializeXml<WikiPage | null>(content, ($) => { const isEnum = $('enum').length > 0; const isStruct = $('structure').length > 0; const isFunction = $('function').length > 0; const isPanel = $('panel').length > 0; const mainElement = $(isEnum ? 'enum' : isStruct ? 'struct' : isPanel ? 'panel' : 'function'); const address = response.url.split('/').pop()!.split('?')[0]; if (isEnum) { const items = $('items item').map(function () { const $el = $(this); return <EnumValue>{ key: $el.attr('key')!, value: $el.attr('value')!, description: $el.text() }; }).get(); return <Enum>{ type: 'enum', name: address, address: address, description: $('description').text(), realm: $('realm').text() as Realm, items }; } else if (isStruct) { const fields = $('fields item').map(function () { const $el = $(this); return <StructField>{ name: $el.attr('name')!, type: $el.attr('type')!, default: $el.attr('default'), description: $el.text() }; }).get(); return <Struct>{ type: 'struct', name: address, address: address, description: $('description').text(), realm: $('realm').text() as Realm, fields }; } else if (isPanel) { return <Panel>{ type: 'panel', name: address, address: address, description: $('description').text(), realm: $('realm').text() as Realm, parent: $('parent').text() }; } else if (isFunction) { const isClassFunction = mainElement.attr('type') === 'classfunc'; const isLibraryFunction = mainElement.attr('type') === 'libraryfunc'; const isHookFunction = mainElement.attr('type') === 'hook'; const isPanelFunction = mainElement.attr('type') === 'panelfunc'; const arguments_ = $('args arg').map(function() { const $el = $(this); const argument = <FunctionArgument> { name: $el.attr('name')!, type: $el.attr('type')!, description: $el.text() }; if ($el.attr('default')) argument.default = $el.attr('default')!; return argument; }).get(); const returns = $('rets ret').map(function() { const $el = $(this); return <FunctionReturn> { name: $el.attr('name')!, type: $el.attr('type')!, description: $el.text() }; }).get(); const base = <Function> { type: mainElement.attr('type')!, parent: mainElement.attr('parent')!, name: mainElement.attr('name')!, address: address, description: $('description:first').text(), realm: $('realm:first').text() as Realm, arguments: arguments_, returns }; if (isClassFunction) { return <ClassFunction> { ...base, type: 'classfunc' }; } else if (isLibraryFunction) { if (base.parent === 'Global') { base.parent = '_G'; (<LibraryFunction>base).dontDefineParent = true; } return <LibraryFunction> { ...base, type: 'libraryfunc' }; } else if (isHookFunction) { return <HookFunction> { ...base, type: 'hook', isHook: 'yes' }; } else if (isPanelFunction) { return <PanelFunction> { ...base, type: 'panelfunc', isPanelFunction: 'yes' }; } } return null; }); if (!page) return []; page.url = response.url.replace(/\?format=text$/, ''); return [page]; }; } }
src/scrapers/wiki-page-markup-scraper.ts
luttje-glua-api-snippets-9f40376
[ { "filename": "src/scrapers/json-scraper.ts", "retrieved_chunk": "import { ScrapeCallback, Scraper } from './scraper.js';\nexport class JsonScraper<T extends object = object> extends Scraper<T> {\n /**\n * @param response The response from the page\n * @param content The content of the request\n * \n * @returns A list containing only the scraped page\n */\n public getScrapeCallback(): ScrapeCallback<T> {\n return JsonScraper.makeScrapeCallback<T>();", "score": 0.95790696144104 }, { "filename": "src/scrapers/wiki-history-scraper.ts", "retrieved_chunk": " * Scrapes a wiki history page for information on wiki changes\n * \n * @param response The response from the page\n * @param content The content of the request\n * \n * @returns A list containing only the scraped page\n */\n public getScrapeCallback(): ScrapeCallback<WikiHistoryPage> {\n const baseScrapeCallback = super.getScrapeCallback();\n return async (response: Response, content: string): Promise<WikiHistoryPage[]> => {", "score": 0.9418620467185974 }, { "filename": "src/scrapers/page-traverse-scraper.ts", "retrieved_chunk": " * \n * @param response The response from the page\n * @param content The content of the request\n * \n * @returns A list containing only the scraped page\n */\n public getScrapeCallback(): ScrapeCallback<T> {\n return (response: Response, content: string): T[] => {\n const results: T[] = [];\n const url = response.url;", "score": 0.9270909428596497 }, { "filename": "src/scrapers/scraper.ts", "retrieved_chunk": " }\n public setRetryOptions(options: RequestInitWithRetry): void {\n this.retryOptions = options;\n }\n /**\n * Scrapes the base url and has the callback process the response\n */\n public async scrape(): Promise<void> {\n const callback = this.getScrapeCallback();\n await this.visitOne(this.baseUrl, callback);", "score": 0.8639323711395264 }, { "filename": "src/scrapers/page-traverse-scraper.ts", "retrieved_chunk": " }\n}\nexport class PageTraverseScraper<T extends Page = Page> extends TraverseScraper<T> {\n private readonly factory: (url: string, title: string) => T;\n constructor(baseUrl: string, factory?: (url: string, title: string) => T) {\n super(baseUrl);\n this.factory = factory ?? ((url: string, title: string) => new Page(url, title) as T);\n }\n /**\n * Scrapes a page for its URL and title, and returns a list of child URLs", "score": 0.8605747222900391 } ]
typescript
public getScrapeCallback(): ScrapeCallback<WikiPage> {
import { ClassFunction, Enum, Function, HookFunction, LibraryFunction, Panel, PanelFunction, Realm, Struct, WikiPage, isPanel } from '../scrapers/wiki-page-markup-scraper.js'; import { putCommentBeforeEachLine, removeNewlines, safeFileName, toLowerCamelCase } from '../utils/string.js'; import { isClassFunction, isHookFunction, isLibraryFunction, isPanelFunction, isStruct, isEnum, } from '../scrapers/wiki-page-markup-scraper.js'; export const RESERVERD_KEYWORDS = new Set([ 'and', 'break', 'continue', 'do', 'else', 'elseif', 'end', 'false', 'for', 'function', 'goto', 'if', 'in', 'local', 'nil', 'not', 'or', 'repeat', 'return', 'then', 'true', 'until', 'while' ]); export class GluaApiWriter { private readonly writtenClasses: Set<string> = new Set(); private readonly writtenLibraryGlobals: Set<string> = new Set(); private readonly pageOverrides: Map<string, string> = new Map(); constructor() { } public static safeName(name: string) { if (name.includes('/')) name = name.replace(/\//g, ' or '); if (name.includes('=')) name = name.split('=')[0]; if (name.includes(' ')) name = toLowerCamelCase(name); // Remove any remaining characters not valid in a Lua variable/function name. name = name.replace(/[^A-Za-z\d_.]/g, ''); if (RESERVERD_KEYWORDS.has(name)) return `_${name}`; return name; } public addOverride(pageAddress: string, override: string) { this.pageOverrides.set(safeFileName(pageAddress, '.'), override); } public writePage(page: WikiPage) { const fileSafeAddress = safeFileName(page.address, '.'); if (this.pageOverrides.has(fileSafeAddress)) { let api = ''; if (isClassFunction(page)) api += this.writeClass(page.parent); else if (isLibraryFunction(page)) api += this.writeLibraryGlobal(page); api += this.pageOverrides.get(fileSafeAddress); return `${api}\n\n`; } else if (isClassFunction(page)) return this.writeClassFunction(page); else if (isLibraryFunction(page)) return this.writeLibraryFunction(page); else if (isHookFunction(page)) return this.writeHookFunction(page); else if (isPanel(page)) return this.writePanel(page); else if (isPanelFunction(page)) return this.writePanelFunction(page); else if (isEnum(page)) return this.writeEnum(page); else if (isStruct(page)) return this.writeStruct(page); } private writeClass(className: string, parent?: string, classFields: string = '') { let api: string = ''; if (!this.writtenClasses.has(className)) { const classOverride = `class.${className}`; if (this.pageOverrides.has(classOverride)) { api += this.pageOverrides.get(classOverride)!.replace(/\n$/g, '') + '\n\n'; api = api.replace('---{{CLASS_FIELDS}}\n', classFields); } else { api += `---@class ${className}`; if (parent) api += ` : ${parent}`; api += '\n'; api += classFields; api += `local ${className} = {}\n\n`; } this.writtenClasses.add(className); } return api; } private writeLibraryGlobal(func: LibraryFunction) { if (!func.dontDefineParent && !this.writtenLibraryGlobals.has(func.parent)) { const global = `${func.parent} = {}\n\n`; this.writtenLibraryGlobals.add(func.parent); return global; } return ''; } private writeClassFunction(func: ClassFunction) { let api: string = this.writeClass(func.parent);
api += this.writeFunctionLuaDocComment(func, func.realm);
api += this.writeFunctionDeclaration(func, func.realm, ':'); return api; } private writeLibraryFunction(func: LibraryFunction) { let api: string = this.writeLibraryGlobal(func); api += this.writeFunctionLuaDocComment(func, func.realm); api += this.writeFunctionDeclaration(func, func.realm); return api; } private writeHookFunction(func: HookFunction) { return this.writeClassFunction(func); } private writePanel(panel: Panel) { return this.writeClass(panel.name, panel.parent); } private writePanelFunction(func: PanelFunction) { let api: string = ''; api += this.writeFunctionLuaDocComment(func, func.realm); api += this.writeFunctionDeclaration(func, func.realm, ':'); return api; } private writeEnum(_enum: Enum) { let api: string = ''; const isContainedInTable = _enum.items[0]?.key.includes('.') ?? false; api += `---@enum ${_enum.name}\n`; if (isContainedInTable) api += `local ${_enum.name} = {\n`; const writeItem = (key: string, item: typeof _enum.items[0]) => { if (isContainedInTable) { key = key.split('.')[1]; api += ` ${key} = ${item.value}, ` + (item.description ? `--[[ ${item.description} ]]` : '') + '\n'; } else { const comment = item.description ? `${putCommentBeforeEachLine(item.description, false)}\n` : ''; api += `${comment}${key} = ${item.value}\n`; } }; for (const item of _enum.items) writeItem(item.key, item); if (isContainedInTable) api += '}'; api += `\n\n`; return api; } private writeStruct(struct: Struct) { let fields: string = ''; for (const field of struct.fields) { fields += `---@field ${GluaApiWriter.safeName(field.name)} ${this.transformType(field.type)} ${removeNewlines(field.description!)}\n`; } return this.writeClass(struct.name, undefined, fields); } public writePages(pages: WikiPage[]) { let api: string = ''; for (const page of pages) { api += this.writePage(page); } return api; } private transformType(type: string) { if (type === 'vararg') return '...'; return type; } private writeFunctionLuaDocComment(func: Function, realm: Realm) { let luaDocComment = `---[${realm.toUpperCase()}] ${putCommentBeforeEachLine(func.description!.trim())}\n`; luaDocComment += `---\n---[(View on wiki)](${func.url})\n`; if (func.arguments) { func.arguments.forEach((arg, index) => { if (!arg.name) arg.name = arg.type; if (arg.type === 'vararg') arg.name = '...'; luaDocComment += `---@param ${GluaApiWriter.safeName(arg.name)}${arg.default !== undefined ? `?` : ''} ${this.transformType(arg.type)} ${putCommentBeforeEachLine(arg.description!)}\n`; }); } if (func.returns) { const returns = `---@return ${func.returns.map(ret => this.transformType(ret.type)).join(', ')}`; func.returns.forEach(ret => { const description = removeNewlines(ret.description ?? ''); if (func.returns!.length === 1) { luaDocComment += `${returns} #${description}\n`; return; } luaDocComment += `${returns} #${this.transformType(ret.type)} - ${description}\n`; }); } return luaDocComment; } private writeFunctionDeclaration(func: Function, realm: Realm, indexer: string = '.') { let declaration = `function ${func.parent ? `${func.parent}${indexer}` : ''}${GluaApiWriter.safeName(func.name)}(`; if (func.arguments) { declaration += func.arguments.map(arg => { if (arg.type === 'vararg') return '...'; return GluaApiWriter.safeName(arg.name!); }).join(', '); } declaration += ') end\n\n'; return declaration; } }
src/api-writer/glua-api-writer.ts
luttje-glua-api-snippets-9f40376
[ { "filename": "src/scrapers/wiki-page-markup-scraper.ts", "retrieved_chunk": " if (base.parent === 'Global') {\n base.parent = '_G';\n (<LibraryFunction>base).dontDefineParent = true;\n }\n return <LibraryFunction> {\n ...base,\n type: 'libraryfunc'\n };\n } else if (isHookFunction) {\n return <HookFunction> {", "score": 0.7440177202224731 }, { "filename": "src/scrapers/wiki-page-markup-scraper.ts", "retrieved_chunk": " realm: $('realm:first').text() as Realm,\n arguments: arguments_,\n returns\n };\n if (isClassFunction) {\n return <ClassFunction> {\n ...base,\n type: 'classfunc'\n };\n } else if (isLibraryFunction) {", "score": 0.7069450616836548 }, { "filename": "src/scrapers/wiki-page-markup-scraper.ts", "retrieved_chunk": "export type FunctionReturn = WikiIdentifier & {};\nexport type Function = CommonWikiProperties & {\n parent: string;\n arguments?: FunctionArgument[];\n returns?: FunctionReturn[];\n};\nexport type ClassFunction = Function & {};\nexport type LibraryFunction = Function & {\n type: 'libraryfunc';\n dontDefineParent?: boolean;", "score": 0.7067883610725403 }, { "filename": "src/scrapers/wiki-page-markup-scraper.ts", "retrieved_chunk": " } else if (isFunction) {\n const isClassFunction = mainElement.attr('type') === 'classfunc';\n const isLibraryFunction = mainElement.attr('type') === 'libraryfunc';\n const isHookFunction = mainElement.attr('type') === 'hook';\n const isPanelFunction = mainElement.attr('type') === 'panelfunc';\n const arguments_ = $('args arg').map(function() {\n const $el = $(this);\n const argument = <FunctionArgument> {\n name: $el.attr('name')!,\n type: $el.attr('type')!,", "score": 0.7008678913116455 }, { "filename": "src/cli-library-publisher.ts", "retrieved_chunk": " \"/**/\",\n \"continue\",\n ],\n \"Lua.diagnostics.disable\": [\n \"duplicate-set-field\", // Prevents complaining when a function exists twice in both the CLIENT and SERVER realm\n ],\n // TODO: runtime.path\n });\n fs.writeFileSync(path.join(options.output, 'config.json'), JSON.stringify(config, null, 2));\n const files = walk(options.input, (file, isDirectory) => isDirectory || (file.endsWith(`.lua`)));", "score": 0.7007328271865845 } ]
typescript
api += this.writeFunctionLuaDocComment(func, func.realm);
import { ClassFunction, Enum, Function, HookFunction, LibraryFunction, Panel, PanelFunction, Realm, Struct, WikiPage, isPanel } from '../scrapers/wiki-page-markup-scraper.js'; import { putCommentBeforeEachLine, removeNewlines, safeFileName, toLowerCamelCase } from '../utils/string.js'; import { isClassFunction, isHookFunction, isLibraryFunction, isPanelFunction, isStruct, isEnum, } from '../scrapers/wiki-page-markup-scraper.js'; export const RESERVERD_KEYWORDS = new Set([ 'and', 'break', 'continue', 'do', 'else', 'elseif', 'end', 'false', 'for', 'function', 'goto', 'if', 'in', 'local', 'nil', 'not', 'or', 'repeat', 'return', 'then', 'true', 'until', 'while' ]); export class GluaApiWriter { private readonly writtenClasses: Set<string> = new Set(); private readonly writtenLibraryGlobals: Set<string> = new Set(); private readonly pageOverrides: Map<string, string> = new Map(); constructor() { } public static safeName(name: string) { if (name.includes('/')) name = name.replace(/\//g, ' or '); if (name.includes('=')) name = name.split('=')[0]; if (name.includes(' ')) name = toLowerCamelCase(name); // Remove any remaining characters not valid in a Lua variable/function name. name = name.replace(/[^A-Za-z\d_.]/g, ''); if (RESERVERD_KEYWORDS.has(name)) return `_${name}`; return name; } public addOverride(pageAddress: string, override: string) { this.pageOverrides.set(safeFileName(pageAddress, '.'), override); } public writePage(page: WikiPage) { const fileSafeAddress = safeFileName(page.address, '.'); if (this.pageOverrides.has(fileSafeAddress)) { let api = ''; if (isClassFunction(page)) api += this.writeClass(page.parent); else if (isLibraryFunction(page)) api += this.writeLibraryGlobal(page); api += this.pageOverrides.get(fileSafeAddress); return `${api}\n\n`; } else if (isClassFunction(page)) return this.writeClassFunction(page); else if (isLibraryFunction(page)) return this.writeLibraryFunction(page); else if (isHookFunction(page)) return this.writeHookFunction(page); else if (isPanel(page)) return this.writePanel(page); else if (isPanelFunction(page)) return this.writePanelFunction(page); else if (isEnum(page)) return this.writeEnum(page); else if (isStruct(page)) return this.writeStruct(page); } private writeClass(className: string, parent?: string, classFields: string = '') { let api: string = ''; if (!this.writtenClasses.has(className)) { const classOverride = `class.${className}`; if (this.pageOverrides.has(classOverride)) { api += this.pageOverrides.get(classOverride)!.replace(/\n$/g, '') + '\n\n'; api = api.replace('---{{CLASS_FIELDS}}\n', classFields); } else { api += `---@class ${className}`; if (parent) api += ` : ${parent}`; api += '\n'; api += classFields; api += `local ${className} = {}\n\n`; } this.writtenClasses.add(className); } return api; } private writeLibraryGlobal(func: LibraryFunction) { if (!func.dontDefineParent && !this.writtenLibraryGlobals.has(func.parent)) { const global = `${func.parent} = {}\n\n`; this.writtenLibraryGlobals.add(func.parent); return global; } return ''; } private writeClassFunction(func: ClassFunction) { let api: string = this.writeClass(func.parent); api += this.writeFunctionLuaDocComment(func, func.realm); api += this.writeFunctionDeclaration(func, func.realm, ':'); return api; } private writeLibraryFunction(func: LibraryFunction) { let api: string = this.writeLibraryGlobal(func); api += this.writeFunctionLuaDocComment(func, func.realm); api += this.writeFunctionDeclaration(func, func.realm); return api; } private writeHookFunction(func: HookFunction) { return this.writeClassFunction(func); } private writePanel(panel: Panel) { return this.writeClass(panel.name, panel.parent); } private writePanelFunction(func: PanelFunction) { let api: string = ''; api += this.writeFunctionLuaDocComment(func, func.realm); api += this.writeFunctionDeclaration(func, func.realm, ':'); return api; } private writeEnum(_enum: Enum) { let api: string = ''; const isContainedInTable = _enum.items[0]?.key.includes('.') ?? false; api += `---@enum ${_enum.name}\n`; if (isContainedInTable) api += `local ${_enum.name} = {\n`; const writeItem = (key: string, item: typeof _enum.items[0]) => { if (isContainedInTable) { key = key.split('.')[1]; api += ` ${key} = ${item.value}, ` + (item.description ? `--[[ ${item.description} ]]` : '') + '\n'; } else { const comment = item.description ? `${putCommentBeforeEachLine(item.description, false)}\n` : ''; api += `${comment}${key} = ${item.value}\n`; } }; for (const item of _enum.items) writeItem(item.key, item); if (isContainedInTable) api += '}'; api += `\n\n`; return api; } private writeStruct(struct: Struct) { let fields: string = ''; for (const field of struct.fields) { fields += `---@field ${GluaApiWriter.safeName(field.name)} ${this.transformType(field.type)} ${removeNewlines(field.description!)}\n`; } return this.writeClass(struct.name, undefined, fields); } public writePages(pages: WikiPage[]) { let api: string = ''; for (const page of pages) { api += this.writePage(page); } return api; } private transformType(type: string) { if (type === 'vararg') return '...'; return type; } private writeFunctionLuaDocComment(func: Function, realm: Realm) { let luaDocComment = `---[${realm.toUpperCase()}] ${putCommentBeforeEachLine(func.description!.trim())}\n`; luaDocComment += `---\n---[(View on wiki)](${func.url})\n`; if (func.arguments) { func.arguments.forEach((arg, index) => { if (!arg.name) arg.name = arg.type; if (arg.type === 'vararg') arg.name = '...'; luaDocComment += `---@param ${GluaApiWriter.safeName(arg.name)}${arg.default !== undefined ? `?` : ''} ${this.transformType(arg.type)} ${putCommentBeforeEachLine(arg.description!)}\n`; }); } if (func.returns) { const returns = `---@return ${func.returns
.map(ret => this.transformType(ret.type)).join(', ')}`;
func.returns.forEach(ret => { const description = removeNewlines(ret.description ?? ''); if (func.returns!.length === 1) { luaDocComment += `${returns} #${description}\n`; return; } luaDocComment += `${returns} #${this.transformType(ret.type)} - ${description}\n`; }); } return luaDocComment; } private writeFunctionDeclaration(func: Function, realm: Realm, indexer: string = '.') { let declaration = `function ${func.parent ? `${func.parent}${indexer}` : ''}${GluaApiWriter.safeName(func.name)}(`; if (func.arguments) { declaration += func.arguments.map(arg => { if (arg.type === 'vararg') return '...'; return GluaApiWriter.safeName(arg.name!); }).join(', '); } declaration += ') end\n\n'; return declaration; } }
src/api-writer/glua-api-writer.ts
luttje-glua-api-snippets-9f40376
[ { "filename": "src/scrapers/wiki-page-markup-scraper.ts", "retrieved_chunk": " description: $el.text()\n };\n if ($el.attr('default'))\n argument.default = $el.attr('default')!;\n return argument;\n }).get();\n const returns = $('rets ret').map(function() {\n const $el = $(this);\n return <FunctionReturn> {\n name: $el.attr('name')!,", "score": 0.7548352479934692 }, { "filename": "src/scrapers/wiki-page-markup-scraper.ts", "retrieved_chunk": " } else if (isFunction) {\n const isClassFunction = mainElement.attr('type') === 'classfunc';\n const isLibraryFunction = mainElement.attr('type') === 'libraryfunc';\n const isHookFunction = mainElement.attr('type') === 'hook';\n const isPanelFunction = mainElement.attr('type') === 'panelfunc';\n const arguments_ = $('args arg').map(function() {\n const $el = $(this);\n const argument = <FunctionArgument> {\n name: $el.attr('name')!,\n type: $el.attr('type')!,", "score": 0.7193783521652222 }, { "filename": "src/scrapers/wiki-page-markup-scraper.ts", "retrieved_chunk": " type: $el.attr('type')!,\n description: $el.text()\n };\n }).get();\n const base = <Function> {\n type: mainElement.attr('type')!,\n parent: mainElement.attr('parent')!,\n name: mainElement.attr('name')!,\n address: address,\n description: $('description:first').text(),", "score": 0.665595531463623 }, { "filename": "src/cli-scraper.ts", "retrieved_chunk": " if (!fs.existsSync(`${moduleFile}.lua`))\n fs.writeFileSync(`${moduleFile}.lua`, '---@meta\\n\\n');\n if (!fs.existsSync(moduleFile))\n fs.mkdirSync(moduleFile, { recursive: true });\n fileName = fileName.replace(/[^a-z0-9]/gi, '_').toLowerCase();\n // Lua API\n fs.appendFileSync(path.join(baseDirectory, `${moduleName}.lua`), api);\n // JSON data\n const json = JSON.stringify(pageMarkups, null, 2);\n fs.writeFileSync(path.join(baseDirectory, moduleName, `${fileName}.json`), json);", "score": 0.6418931484222412 }, { "filename": "src/scrapers/wiki-page-markup-scraper.ts", "retrieved_chunk": " realm: $('realm').text() as Realm,\n items\n };\n } else if (isStruct) {\n const fields = $('fields item').map(function () {\n const $el = $(this);\n return <StructField>{\n name: $el.attr('name')!,\n type: $el.attr('type')!,\n default: $el.attr('default'),", "score": 0.6354852914810181 } ]
typescript
.map(ret => this.transformType(ret.type)).join(', ')}`;
import { Scraper, ScrapeCallback } from './scraper.js'; export interface Scrapeable { childUrls: Set<string>; } export class TraverseScraper<T extends Scrapeable> extends Scraper<T> { protected readonly traversedUrls: Set<string> = new Set(); protected childPageFilter?: (url: string) => boolean; public setChildPageFilter(filter: (url: string) => boolean): void { this.childPageFilter = filter; } /** * Override scraping so we traverse all child URLs of the first scraped page */ public async scrape(): Promise<void> { const callback = this.getScrapeCallback(); await this.traverse(this.baseUrl, callback.bind(this)); } protected getTraverseUrl(url: string): string | false { if (!url.startsWith(this.baseUrl)) return false; if (url.endsWith('/')) url = url.substring(0, url.length - 1); if (url.includes('#')) url = url.substring(0, url.indexOf('#')); if (this.traversedUrls.has(url)) return false; if (this.childPageFilter && !this.childPageFilter(url)) return false; return url; } public async traverse
(url: string, callback?: ScrapeCallback<T>): Promise<void> {
if (!callback) callback = this.getScrapeCallback(); const urlsToTraverse: string[] = [url]; while (urlsToTraverse.length > 0) { let currentUrl = urlsToTraverse.shift()!; let url = this.getTraverseUrl(currentUrl); if (!url) continue; const currentResults = await this.visitOne(url, callback); this.traversedUrls.add(url); for (const result of currentResults) { for (const childUrl of result.childUrls) { const traverseUrl = this.getTraverseUrl(childUrl); if (traverseUrl && !urlsToTraverse.includes(traverseUrl)) urlsToTraverse.push(traverseUrl); } } } } }
src/scrapers/traverse-scraper.ts
luttje-glua-api-snippets-9f40376
[ { "filename": "src/scrapers/scraper.ts", "retrieved_chunk": " }\n public async visitOne(url: string, callback?: ScrapeCallback<T>): Promise<T[]> {\n if (!callback)\n callback = this.getScrapeCallback();\n if (!!process.env.VERBOSE_LOGGING)\n console.debug(`Scraping ${url}...`);\n this.emit('beforescrape', url);\n let response;\n let content;\n try {", "score": 0.8091728687286377 }, { "filename": "src/scrapers/page-traverse-scraper.ts", "retrieved_chunk": " if (this.childPageFilter && !this.childPageFilter(absoluteUrl))\n continue;\n page.childUrls.add(absoluteUrl);\n }\n results.push(page);\n return results;\n };\n }\n}", "score": 0.7722347974777222 }, { "filename": "src/scrapers/scraper.ts", "retrieved_chunk": " response = await fetch(url, this.retryOptions);\n content = await response.text();\n } catch (e) {\n console.warn(`Error fetching ${url}: ${e}`);\n return [];\n }\n const scrapedResults = await callback(response, content);\n this.emit('scraped', url, scrapedResults);\n return scrapedResults;\n }", "score": 0.7554550170898438 }, { "filename": "src/scrapers/page-traverse-scraper.ts", "retrieved_chunk": "import { Scrapeable, TraverseScraper } from './traverse-scraper.js';\nimport { decodeEntities } from './decode-entities.js';\nimport { ScrapeCallback } from './scraper.js';\nexport class Page implements Scrapeable {\n public url: string;\n public title: string;\n public childUrls: Set<string> = new Set();\n constructor(url: string, title: string) {\n this.url = url;\n this.title = title;", "score": 0.7493695020675659 }, { "filename": "src/scrapers/wiki-history-scraper.ts", "retrieved_chunk": " public history: WikiHistory[] = [];\n constructor(url: string, title: string) {\n super(url, title);\n }\n}\nexport class WikiHistoryPageScraper extends PageTraverseScraper<WikiHistoryPage> {\n constructor(baseUrl: string) {\n super(baseUrl, (url: string, title: string) => new WikiHistoryPage(url, title));\n }\n /**", "score": 0.7314642667770386 } ]
typescript
(url: string, callback?: ScrapeCallback<T>): Promise<void> {
import { Scrapeable, TraverseScraper } from './traverse-scraper.js'; import { ScrapeCallback } from './scraper.js'; import * as cheerio from 'cheerio'; import "reflect-metadata"; const tableColumnMetadataKey = Symbol("tableColumn"); export type TableColumnDefinition = { propertyKey: string | symbol, columnName: string, typeConverter: (value: string) => any }; export function tableColumn(columnName: string): PropertyDecorator { return (target: object, propertyKey: string | symbol) => { const existingColumns: TableColumnDefinition[] = Reflect.getMetadata(tableColumnMetadataKey, target) || []; const propertyType = Reflect.getMetadata("design:type", target, propertyKey); existingColumns.push({ propertyKey, columnName, typeConverter: (value: string) => { switch (propertyType) { case String: return value; case Number: return Number(value); case Boolean: return Boolean(value); default: return value; } } }); Reflect.defineMetadata(tableColumnMetadataKey, existingColumns, target); }; } export function getTableColumns(target: object): TableColumnDefinition[] { return Reflect.getMetadata(tableColumnMetadataKey, target) || []; } export class Row<T> { constructor(public data: T) { } } export class Table<T> implements Scrapeable { public url: string; public childUrls: Set<string> = new Set(); constructor(url: string, public rows: Row<T>[] = []) { this.url = url; } public addRow(row: Row<T>) { this.rows.push(row); } } export class TableScraper<T
extends object> extends TraverseScraper<Table<T>> {
constructor(baseUrl: string, private readonly factory: () => T) { super(baseUrl); } public getScrapeCallback(): ScrapeCallback<Table<T>> { return (response: Response, content: string): Table<T>[] => { const results: Table<T>[] = []; const $ = cheerio.load(content); const tables = $('table'); for (const table of tables) { const tableResult = this.fromTableElement($, table); if (tableResult) results.push(tableResult); } return results; }; } private fromTableElement($: cheerio.CheerioAPI, tableElement: cheerio.Element): Table<T> | null { const tableResult = new Table<T>(this.baseUrl); let headingRows = $(tableElement).find('thead > tr'); let shouldTrimHeadings = false; if (headingRows.length === 0) { headingRows = $(tableElement).find('tbody > tr:first-child'); shouldTrimHeadings = true; } let headings : cheerio.Element[] | undefined; if (headingRows.length > 0) headings = $(headingRows[0]).find('th').toArray(); if (!headings || headings.length === 0) throw new Error('No headings found in table'); let rows = $(tableElement).find('tbody > tr').toArray(); if (rows.length === 0) rows = $(tableElement).find('tr').toArray(); if (shouldTrimHeadings) rows = rows.slice(headingRows.length); let isEmpty = true; for (const row of rows) { const rowResult = this.fromRowElement($, row, headings); if (rowResult === null) continue; tableResult.addRow(rowResult); isEmpty = false; } if (isEmpty) return null; return tableResult; } private fromRowElement($: cheerio.CheerioAPI, rowElement: cheerio.Element, headings: cheerio.Element[]): Row<T> | null { const cells = $(rowElement).find('td').toArray(); const rowResult = this.factory(); const allTableColumns = getTableColumns(rowResult); let isEmpty = true; for (let i = 0; i < cells.length; i++) { const cell = cells[i]; const heading = headings[i]; if (!heading) continue; const headingText = $(heading).text(); if (!headingText) continue; let tableColumnDefinition = allTableColumns.find(column => column.columnName === headingText); if (!tableColumnDefinition) { const properties = Object.getOwnPropertyNames(rowResult); const propertyKey = properties.find(property => property.toLowerCase() === headingText.toLowerCase()); if (!propertyKey) continue; tableColumnDefinition = { propertyKey, columnName: headingText, typeConverter: (value: string) => value }; } const cellText = $(cell).text(); if (!cellText) continue; (rowResult as any)[tableColumnDefinition.propertyKey] = tableColumnDefinition.typeConverter(cellText); isEmpty = false; } if (isEmpty) return null; return new Row<T>(rowResult); } }
src/scrapers/table-scraper.ts
luttje-glua-api-snippets-9f40376
[ { "filename": "src/scrapers/traverse-scraper.ts", "retrieved_chunk": "import { Scraper, ScrapeCallback } from './scraper.js';\nexport interface Scrapeable {\n childUrls: Set<string>;\n}\nexport class TraverseScraper<T extends Scrapeable> extends Scraper<T> {\n protected readonly traversedUrls: Set<string> = new Set();\n protected childPageFilter?: (url: string) => boolean;\n public setChildPageFilter(filter: (url: string) => boolean): void {\n this.childPageFilter = filter;\n }", "score": 0.8481215834617615 }, { "filename": "src/scrapers/wiki-history-scraper.ts", "retrieved_chunk": " public history: WikiHistory[] = [];\n constructor(url: string, title: string) {\n super(url, title);\n }\n}\nexport class WikiHistoryPageScraper extends PageTraverseScraper<WikiHistoryPage> {\n constructor(baseUrl: string) {\n super(baseUrl, (url: string, title: string) => new WikiHistoryPage(url, title));\n }\n /**", "score": 0.8459899425506592 }, { "filename": "src/scrapers/page-traverse-scraper.ts", "retrieved_chunk": "import { Scrapeable, TraverseScraper } from './traverse-scraper.js';\nimport { decodeEntities } from './decode-entities.js';\nimport { ScrapeCallback } from './scraper.js';\nexport class Page implements Scrapeable {\n public url: string;\n public title: string;\n public childUrls: Set<string> = new Set();\n constructor(url: string, title: string) {\n this.url = url;\n this.title = title;", "score": 0.826526403427124 }, { "filename": "src/scrapers/page-traverse-scraper.ts", "retrieved_chunk": " }\n}\nexport class PageTraverseScraper<T extends Page = Page> extends TraverseScraper<T> {\n private readonly factory: (url: string, title: string) => T;\n constructor(baseUrl: string, factory?: (url: string, title: string) => T) {\n super(baseUrl);\n this.factory = factory ?? ((url: string, title: string) => new Page(url, title) as T);\n }\n /**\n * Scrapes a page for its URL and title, and returns a list of child URLs", "score": 0.7972016930580139 }, { "filename": "src/scrapers/json-scraper.ts", "retrieved_chunk": " }\n public static makeScrapeCallback<T extends object = object>(): ScrapeCallback<T> {\n return (response: Response, content: string): T[] => {\n return JSON.parse(content);\n };\n }\n}", "score": 0.7941375970840454 } ]
typescript
extends object> extends TraverseScraper<Table<T>> {
import { Scraper, ScrapeCallback } from './scraper.js'; export interface Scrapeable { childUrls: Set<string>; } export class TraverseScraper<T extends Scrapeable> extends Scraper<T> { protected readonly traversedUrls: Set<string> = new Set(); protected childPageFilter?: (url: string) => boolean; public setChildPageFilter(filter: (url: string) => boolean): void { this.childPageFilter = filter; } /** * Override scraping so we traverse all child URLs of the first scraped page */ public async scrape(): Promise<void> { const callback = this.getScrapeCallback(); await this.traverse(this.baseUrl, callback.bind(this)); } protected getTraverseUrl(url: string): string | false { if (!url.startsWith(this.baseUrl)) return false; if (url.endsWith('/')) url = url.substring(0, url.length - 1); if (url.includes('#')) url = url.substring(0, url.indexOf('#')); if (this.traversedUrls.has(url)) return false; if (this.childPageFilter && !this.childPageFilter(url)) return false; return url; } public async traverse(url: string, callback?: ScrapeCallback<T>): Promise<void> { if (!callback) callback = this.getScrapeCallback(); const urlsToTraverse: string[] = [url]; while (urlsToTraverse.length > 0) { let currentUrl = urlsToTraverse.shift()!; let url = this.getTraverseUrl(currentUrl); if (!url) continue; const currentResults
= await this.visitOne(url, callback);
this.traversedUrls.add(url); for (const result of currentResults) { for (const childUrl of result.childUrls) { const traverseUrl = this.getTraverseUrl(childUrl); if (traverseUrl && !urlsToTraverse.includes(traverseUrl)) urlsToTraverse.push(traverseUrl); } } } } }
src/scrapers/traverse-scraper.ts
luttje-glua-api-snippets-9f40376
[ { "filename": "src/scrapers/scraper.ts", "retrieved_chunk": " }\n public async visitOne(url: string, callback?: ScrapeCallback<T>): Promise<T[]> {\n if (!callback)\n callback = this.getScrapeCallback();\n if (!!process.env.VERBOSE_LOGGING)\n console.debug(`Scraping ${url}...`);\n this.emit('beforescrape', url);\n let response;\n let content;\n try {", "score": 0.8195067644119263 }, { "filename": "src/scrapers/scraper.ts", "retrieved_chunk": " }\n public setRetryOptions(options: RequestInitWithRetry): void {\n this.retryOptions = options;\n }\n /**\n * Scrapes the base url and has the callback process the response\n */\n public async scrape(): Promise<void> {\n const callback = this.getScrapeCallback();\n await this.visitOne(this.baseUrl, callback);", "score": 0.7920185327529907 }, { "filename": "src/scrapers/table-scraper.ts", "retrieved_chunk": " constructor(baseUrl: string, private readonly factory: () => T) {\n super(baseUrl);\n }\n public getScrapeCallback(): ScrapeCallback<Table<T>> {\n return (response: Response, content: string): Table<T>[] => {\n const results: Table<T>[] = [];\n const $ = cheerio.load(content);\n const tables = $('table');\n for (const table of tables) {\n const tableResult = this.fromTableElement($, table);", "score": 0.7602852582931519 }, { "filename": "src/utils/filesystem.ts", "retrieved_chunk": " const traverse = (currentDir: string) => {\n const files = fs.readdirSync(currentDir);\n for (const file of files) {\n const filepath = path.join(currentDir, file);\n const stat = fs.statSync(filepath);\n if (stat.isDirectory()) {\n if (!filter || filter(filepath, true))\n traverse(filepath);\n } else {\n if (!filter || filter(filepath, false))", "score": 0.7512810230255127 }, { "filename": "src/api-writer/glua-api-writer.ts", "retrieved_chunk": " }\n public writePages(pages: WikiPage[]) {\n let api: string = '';\n for (const page of pages) {\n api += this.writePage(page);\n }\n return api;\n }\n private transformType(type: string) {\n if (type === 'vararg')", "score": 0.7485184073448181 } ]
typescript
= await this.visitOne(url, callback);
import { ScrapeCallback, Scraper } from './scraper.js'; import { deserializeXml } from '../utils/xml.js'; export type WikiFunctionType = 'panelfunc' | 'classfunc' | 'libraryfunc' | 'hook'; export type Realm = 'Menu' | 'Client' | 'Server' | 'Shared' | 'Client and menu'; export type CommonWikiProperties = { type: WikiFunctionType | 'enum' | 'struct' | 'panel'; address: string; name: string; description: string; realm: Realm; url: string; } export type WikiIdentifier = { name: string; type: string; description?: string; }; export type FunctionArgument = WikiIdentifier & { default?: string; }; export type FunctionReturn = WikiIdentifier & {}; export type Function = CommonWikiProperties & { parent: string; arguments?: FunctionArgument[]; returns?: FunctionReturn[]; }; export type ClassFunction = Function & {}; export type LibraryFunction = Function & { type: 'libraryfunc'; dontDefineParent?: boolean; }; export type HookFunction = Function & { type: 'hook'; isHook: 'yes'; }; export type PanelFunction = Function & { type: 'panelfunc'; isPanelFunction: 'yes'; }; export type EnumValue = { key: string; value: string; description: string; }; export type Enum = CommonWikiProperties & { type: 'enum'; items: EnumValue[]; }; export type StructField = { name: string; type: string; default?: any; description: string; }; export type Struct = CommonWikiProperties & { type: 'struct'; fields: StructField[]; }; export type Panel = CommonWikiProperties & { type: 'panel'; parent: string; }; export type WikiPage = ClassFunction | LibraryFunction | HookFunction | PanelFunction | Panel | Enum | Struct; /** * Guards */ export function isClassFunction(page: WikiPage): page is ClassFunction { return page.type === 'classfunc'; } export function isLibraryFunction(page: WikiPage): page is LibraryFunction { return page.type === 'libraryfunc'; } export function isHookFunction(page: WikiPage): page is HookFunction { return page.type === 'hook'; } export function isPanelFunction(page: WikiPage): page is PanelFunction { return page.type === 'panelfunc'; } export function isPanel(page: WikiPage): page is Panel { return page.type === 'panel'; } export function isEnum(page: WikiPage): page is Enum { return page.type === 'enum'; } export function isStruct(page: WikiPage): page is Struct { return page.type === 'struct'; } /** * Scraper */
export class WikiPageMarkupScraper extends Scraper<WikiPage> {
/** * @param response The response from the page * @param content The content of the request * * @returns A list containing only the scraped page */ public getScrapeCallback(): ScrapeCallback<WikiPage> { return (response: Response, content: string): WikiPage[] => { const page = deserializeXml<WikiPage | null>(content, ($) => { const isEnum = $('enum').length > 0; const isStruct = $('structure').length > 0; const isFunction = $('function').length > 0; const isPanel = $('panel').length > 0; const mainElement = $(isEnum ? 'enum' : isStruct ? 'struct' : isPanel ? 'panel' : 'function'); const address = response.url.split('/').pop()!.split('?')[0]; if (isEnum) { const items = $('items item').map(function () { const $el = $(this); return <EnumValue>{ key: $el.attr('key')!, value: $el.attr('value')!, description: $el.text() }; }).get(); return <Enum>{ type: 'enum', name: address, address: address, description: $('description').text(), realm: $('realm').text() as Realm, items }; } else if (isStruct) { const fields = $('fields item').map(function () { const $el = $(this); return <StructField>{ name: $el.attr('name')!, type: $el.attr('type')!, default: $el.attr('default'), description: $el.text() }; }).get(); return <Struct>{ type: 'struct', name: address, address: address, description: $('description').text(), realm: $('realm').text() as Realm, fields }; } else if (isPanel) { return <Panel>{ type: 'panel', name: address, address: address, description: $('description').text(), realm: $('realm').text() as Realm, parent: $('parent').text() }; } else if (isFunction) { const isClassFunction = mainElement.attr('type') === 'classfunc'; const isLibraryFunction = mainElement.attr('type') === 'libraryfunc'; const isHookFunction = mainElement.attr('type') === 'hook'; const isPanelFunction = mainElement.attr('type') === 'panelfunc'; const arguments_ = $('args arg').map(function() { const $el = $(this); const argument = <FunctionArgument> { name: $el.attr('name')!, type: $el.attr('type')!, description: $el.text() }; if ($el.attr('default')) argument.default = $el.attr('default')!; return argument; }).get(); const returns = $('rets ret').map(function() { const $el = $(this); return <FunctionReturn> { name: $el.attr('name')!, type: $el.attr('type')!, description: $el.text() }; }).get(); const base = <Function> { type: mainElement.attr('type')!, parent: mainElement.attr('parent')!, name: mainElement.attr('name')!, address: address, description: $('description:first').text(), realm: $('realm:first').text() as Realm, arguments: arguments_, returns }; if (isClassFunction) { return <ClassFunction> { ...base, type: 'classfunc' }; } else if (isLibraryFunction) { if (base.parent === 'Global') { base.parent = '_G'; (<LibraryFunction>base).dontDefineParent = true; } return <LibraryFunction> { ...base, type: 'libraryfunc' }; } else if (isHookFunction) { return <HookFunction> { ...base, type: 'hook', isHook: 'yes' }; } else if (isPanelFunction) { return <PanelFunction> { ...base, type: 'panelfunc', isPanelFunction: 'yes' }; } } return null; }); if (!page) return []; page.url = response.url.replace(/\?format=text$/, ''); return [page]; }; } }
src/scrapers/wiki-page-markup-scraper.ts
luttje-glua-api-snippets-9f40376
[ { "filename": "src/scrapers/wiki-history-scraper.ts", "retrieved_chunk": " public history: WikiHistory[] = [];\n constructor(url: string, title: string) {\n super(url, title);\n }\n}\nexport class WikiHistoryPageScraper extends PageTraverseScraper<WikiHistoryPage> {\n constructor(baseUrl: string) {\n super(baseUrl, (url: string, title: string) => new WikiHistoryPage(url, title));\n }\n /**", "score": 0.8149247169494629 }, { "filename": "src/scrapers/wiki-page-list-scraper.ts", "retrieved_chunk": "import { JsonScraper } from './json-scraper.js';\nexport type WikiPageIndexObject = {\n address: string;\n updateCount: number;\n viewCount: number;\n}\nexport class WikiPageListScraper extends JsonScraper<WikiPageIndexObject> {}", "score": 0.8078637719154358 }, { "filename": "src/scrapers/traverse-scraper.ts", "retrieved_chunk": "import { Scraper, ScrapeCallback } from './scraper.js';\nexport interface Scrapeable {\n childUrls: Set<string>;\n}\nexport class TraverseScraper<T extends Scrapeable> extends Scraper<T> {\n protected readonly traversedUrls: Set<string> = new Set();\n protected childPageFilter?: (url: string) => boolean;\n public setChildPageFilter(filter: (url: string) => boolean): void {\n this.childPageFilter = filter;\n }", "score": 0.7941708564758301 }, { "filename": "src/api-writer/glua-api-writer.ts", "retrieved_chunk": " }\n public writePages(pages: WikiPage[]) {\n let api: string = '';\n for (const page of pages) {\n api += this.writePage(page);\n }\n return api;\n }\n private transformType(type: string) {\n if (type === 'vararg')", "score": 0.7751210927963257 }, { "filename": "src/scrapers/page-traverse-scraper.ts", "retrieved_chunk": "import { Scrapeable, TraverseScraper } from './traverse-scraper.js';\nimport { decodeEntities } from './decode-entities.js';\nimport { ScrapeCallback } from './scraper.js';\nexport class Page implements Scrapeable {\n public url: string;\n public title: string;\n public childUrls: Set<string> = new Set();\n constructor(url: string, title: string) {\n this.url = url;\n this.title = title;", "score": 0.7747376561164856 } ]
typescript
export class WikiPageMarkupScraper extends Scraper<WikiPage> {
import { ClassFunction, Enum, Function, HookFunction, LibraryFunction, Panel, PanelFunction, Realm, Struct, WikiPage, isPanel } from '../scrapers/wiki-page-markup-scraper.js'; import { putCommentBeforeEachLine, removeNewlines, safeFileName, toLowerCamelCase } from '../utils/string.js'; import { isClassFunction, isHookFunction, isLibraryFunction, isPanelFunction, isStruct, isEnum, } from '../scrapers/wiki-page-markup-scraper.js'; export const RESERVERD_KEYWORDS = new Set([ 'and', 'break', 'continue', 'do', 'else', 'elseif', 'end', 'false', 'for', 'function', 'goto', 'if', 'in', 'local', 'nil', 'not', 'or', 'repeat', 'return', 'then', 'true', 'until', 'while' ]); export class GluaApiWriter { private readonly writtenClasses: Set<string> = new Set(); private readonly writtenLibraryGlobals: Set<string> = new Set(); private readonly pageOverrides: Map<string, string> = new Map(); constructor() { } public static safeName(name: string) { if (name.includes('/')) name = name.replace(/\//g, ' or '); if (name.includes('=')) name = name.split('=')[0]; if (name.includes(' ')) name = toLowerCamelCase(name); // Remove any remaining characters not valid in a Lua variable/function name. name = name.replace(/[^A-Za-z\d_.]/g, ''); if (RESERVERD_KEYWORDS.has(name)) return `_${name}`; return name; } public addOverride(pageAddress: string, override: string) { this.pageOverrides.set(safeFileName(pageAddress, '.'), override); } public writePage(page: WikiPage) { const fileSafeAddress = safeFileName(page.address, '.'); if (this.pageOverrides.has(fileSafeAddress)) { let api = ''; if (isClassFunction(page)) api += this.writeClass(page.parent); else if (isLibraryFunction(page)) api += this.writeLibraryGlobal(page); api += this.pageOverrides.get(fileSafeAddress); return `${api}\n\n`; } else if (isClassFunction(page)) return this.writeClassFunction(page); else if (isLibraryFunction(page)) return this.writeLibraryFunction(page); else if (isHookFunction(page)) return this.writeHookFunction(page); else if (isPanel(page)) return this.writePanel(page); else if (isPanelFunction(page)) return this.writePanelFunction(page); else if (isEnum(page)) return this.writeEnum(page); else if (isStruct(page)) return this.writeStruct(page); } private writeClass(className: string, parent?: string, classFields: string = '') { let api: string = ''; if (!this.writtenClasses.has(className)) { const classOverride = `class.${className}`; if (this.pageOverrides.has(classOverride)) { api += this.pageOverrides.get(classOverride)!.replace(/\n$/g, '') + '\n\n'; api = api.replace('---{{CLASS_FIELDS}}\n', classFields); } else { api += `---@class ${className}`; if (parent) api += ` : ${parent}`; api += '\n'; api += classFields; api += `local ${className} = {}\n\n`; } this.writtenClasses.add(className); } return api; } private writeLibraryGlobal(func: LibraryFunction) { if (!func.dontDefineParent && !this.writtenLibraryGlobals.has(func.parent)) { const global = `${func.parent} = {}\n\n`; this.writtenLibraryGlobals.add(func.parent); return global; } return ''; } private writeClassFunction(func: ClassFunction) { let api: string = this.writeClass(func.parent); api += this.writeFunctionLuaDocComment(func, func.realm); api += this.writeFunctionDeclaration(func, func.realm, ':'); return api; } private writeLibraryFunction(func: LibraryFunction) { let api: string = this.writeLibraryGlobal(func); api += this.writeFunctionLuaDocComment(func, func.realm); api += this.writeFunctionDeclaration(func, func.realm); return api; } private writeHookFunction(func: HookFunction) { return this.writeClassFunction(func); } private writePanel(panel: Panel) { return this.writeClass(panel.name, panel.parent); } private writePanelFunction(func: PanelFunction) { let api: string = ''; api += this.writeFunctionLuaDocComment(func, func.realm); api += this.writeFunctionDeclaration(func, func.realm, ':'); return api; } private writeEnum(_enum: Enum) { let api: string = ''; const isContainedInTable = _enum.items[0]?.key.includes('.') ?? false; api += `---@enum ${_enum.name}\n`; if (isContainedInTable) api += `local ${_enum.name} = {\n`; const writeItem = (key: string, item: typeof _enum.items[0]) => { if (isContainedInTable) { key = key.split('.')[1]; api += ` ${key} = ${item.value}, ` + (item.description ? `--[[ ${item.description} ]]` : '') + '\n'; } else {
const comment = item.description ? `${putCommentBeforeEachLine(item.description, false)}\n` : '';
api += `${comment}${key} = ${item.value}\n`; } }; for (const item of _enum.items) writeItem(item.key, item); if (isContainedInTable) api += '}'; api += `\n\n`; return api; } private writeStruct(struct: Struct) { let fields: string = ''; for (const field of struct.fields) { fields += `---@field ${GluaApiWriter.safeName(field.name)} ${this.transformType(field.type)} ${removeNewlines(field.description!)}\n`; } return this.writeClass(struct.name, undefined, fields); } public writePages(pages: WikiPage[]) { let api: string = ''; for (const page of pages) { api += this.writePage(page); } return api; } private transformType(type: string) { if (type === 'vararg') return '...'; return type; } private writeFunctionLuaDocComment(func: Function, realm: Realm) { let luaDocComment = `---[${realm.toUpperCase()}] ${putCommentBeforeEachLine(func.description!.trim())}\n`; luaDocComment += `---\n---[(View on wiki)](${func.url})\n`; if (func.arguments) { func.arguments.forEach((arg, index) => { if (!arg.name) arg.name = arg.type; if (arg.type === 'vararg') arg.name = '...'; luaDocComment += `---@param ${GluaApiWriter.safeName(arg.name)}${arg.default !== undefined ? `?` : ''} ${this.transformType(arg.type)} ${putCommentBeforeEachLine(arg.description!)}\n`; }); } if (func.returns) { const returns = `---@return ${func.returns.map(ret => this.transformType(ret.type)).join(', ')}`; func.returns.forEach(ret => { const description = removeNewlines(ret.description ?? ''); if (func.returns!.length === 1) { luaDocComment += `${returns} #${description}\n`; return; } luaDocComment += `${returns} #${this.transformType(ret.type)} - ${description}\n`; }); } return luaDocComment; } private writeFunctionDeclaration(func: Function, realm: Realm, indexer: string = '.') { let declaration = `function ${func.parent ? `${func.parent}${indexer}` : ''}${GluaApiWriter.safeName(func.name)}(`; if (func.arguments) { declaration += func.arguments.map(arg => { if (arg.type === 'vararg') return '...'; return GluaApiWriter.safeName(arg.name!); }).join(', '); } declaration += ') end\n\n'; return declaration; } }
src/api-writer/glua-api-writer.ts
luttje-glua-api-snippets-9f40376
[ { "filename": "src/scrapers/table-scraper.ts", "retrieved_chunk": " if (!tableColumnDefinition) {\n const properties = Object.getOwnPropertyNames(rowResult);\n const propertyKey = properties.find(property => property.toLowerCase() === headingText.toLowerCase());\n if (!propertyKey)\n continue;\n tableColumnDefinition = {\n propertyKey,\n columnName: headingText,\n typeConverter: (value: string) => value\n };", "score": 0.7296280860900879 }, { "filename": "src/utils/string.ts", "retrieved_chunk": " */\nexport function putCommentBeforeEachLine(text: string, skipLineOne: boolean = true) {\n return text.split(/\\r?\\n/g).map((line, index) => {\n if (index === 0 && skipLineOne)\n return line;\n return `--- ${line}`;\n }).join('\\n');\n}\n/**\n * Makes a string safe for use as a file name", "score": 0.7234004735946655 }, { "filename": "src/scrapers/wiki-page-markup-scraper.ts", "retrieved_chunk": " const isEnum = $('enum').length > 0;\n const isStruct = $('structure').length > 0;\n const isFunction = $('function').length > 0;\n const isPanel = $('panel').length > 0;\n const mainElement = $(isEnum ? 'enum' : isStruct ? 'struct' : isPanel ? 'panel' : 'function');\n const address = response.url.split('/').pop()!.split('?')[0];\n if (isEnum) {\n const items = $('items item').map(function () {\n const $el = $(this);\n return <EnumValue>{", "score": 0.7219483852386475 }, { "filename": "src/scrapers/wiki-page-markup-scraper.ts", "retrieved_chunk": " realm: $('realm').text() as Realm,\n items\n };\n } else if (isStruct) {\n const fields = $('fields item').map(function () {\n const $el = $(this);\n return <StructField>{\n name: $el.attr('name')!,\n type: $el.attr('type')!,\n default: $el.attr('default'),", "score": 0.7077571153640747 }, { "filename": "src/scrapers/table-scraper.ts", "retrieved_chunk": "export function tableColumn(columnName: string): PropertyDecorator {\n return (target: object, propertyKey: string | symbol) => {\n const existingColumns: TableColumnDefinition[] = Reflect.getMetadata(tableColumnMetadataKey, target) || [];\n const propertyType = Reflect.getMetadata(\"design:type\", target, propertyKey);\n existingColumns.push({\n propertyKey,\n columnName,\n typeConverter: (value: string) => {\n switch (propertyType) {\n case String:", "score": 0.7048025131225586 } ]
typescript
const comment = item.description ? `${putCommentBeforeEachLine(item.description, false)}\n` : '';
import { ScrapeCallback, Scraper } from './scraper.js'; import { deserializeXml } from '../utils/xml.js'; export type WikiFunctionType = 'panelfunc' | 'classfunc' | 'libraryfunc' | 'hook'; export type Realm = 'Menu' | 'Client' | 'Server' | 'Shared' | 'Client and menu'; export type CommonWikiProperties = { type: WikiFunctionType | 'enum' | 'struct' | 'panel'; address: string; name: string; description: string; realm: Realm; url: string; } export type WikiIdentifier = { name: string; type: string; description?: string; }; export type FunctionArgument = WikiIdentifier & { default?: string; }; export type FunctionReturn = WikiIdentifier & {}; export type Function = CommonWikiProperties & { parent: string; arguments?: FunctionArgument[]; returns?: FunctionReturn[]; }; export type ClassFunction = Function & {}; export type LibraryFunction = Function & { type: 'libraryfunc'; dontDefineParent?: boolean; }; export type HookFunction = Function & { type: 'hook'; isHook: 'yes'; }; export type PanelFunction = Function & { type: 'panelfunc'; isPanelFunction: 'yes'; }; export type EnumValue = { key: string; value: string; description: string; }; export type Enum = CommonWikiProperties & { type: 'enum'; items: EnumValue[]; }; export type StructField = { name: string; type: string; default?: any; description: string; }; export type Struct = CommonWikiProperties & { type: 'struct'; fields: StructField[]; }; export type Panel = CommonWikiProperties & { type: 'panel'; parent: string; }; export type WikiPage = ClassFunction | LibraryFunction | HookFunction | PanelFunction | Panel | Enum | Struct; /** * Guards */ export function isClassFunction(page: WikiPage): page is ClassFunction { return page.type === 'classfunc'; } export function isLibraryFunction(page: WikiPage): page is LibraryFunction { return page.type === 'libraryfunc'; } export function isHookFunction(page: WikiPage): page is HookFunction { return page.type === 'hook'; } export function isPanelFunction(page: WikiPage): page is PanelFunction { return page.type === 'panelfunc'; } export function isPanel(page: WikiPage): page is Panel { return page.type === 'panel'; } export function isEnum(page: WikiPage): page is Enum { return page.type === 'enum'; } export function isStruct(page: WikiPage): page is Struct { return page.type === 'struct'; } /** * Scraper */ export class WikiPageMarkupScraper extends Scraper<WikiPage> { /** * @param response The response from the page * @param content The content of the request * * @returns A list containing only the scraped page */ public getScrapeCallback(): ScrapeCallback<WikiPage> { return (response: Response, content: string): WikiPage[] => { const page = deserializeXml<WikiPage | null>(content
, ($) => {
const isEnum = $('enum').length > 0; const isStruct = $('structure').length > 0; const isFunction = $('function').length > 0; const isPanel = $('panel').length > 0; const mainElement = $(isEnum ? 'enum' : isStruct ? 'struct' : isPanel ? 'panel' : 'function'); const address = response.url.split('/').pop()!.split('?')[0]; if (isEnum) { const items = $('items item').map(function () { const $el = $(this); return <EnumValue>{ key: $el.attr('key')!, value: $el.attr('value')!, description: $el.text() }; }).get(); return <Enum>{ type: 'enum', name: address, address: address, description: $('description').text(), realm: $('realm').text() as Realm, items }; } else if (isStruct) { const fields = $('fields item').map(function () { const $el = $(this); return <StructField>{ name: $el.attr('name')!, type: $el.attr('type')!, default: $el.attr('default'), description: $el.text() }; }).get(); return <Struct>{ type: 'struct', name: address, address: address, description: $('description').text(), realm: $('realm').text() as Realm, fields }; } else if (isPanel) { return <Panel>{ type: 'panel', name: address, address: address, description: $('description').text(), realm: $('realm').text() as Realm, parent: $('parent').text() }; } else if (isFunction) { const isClassFunction = mainElement.attr('type') === 'classfunc'; const isLibraryFunction = mainElement.attr('type') === 'libraryfunc'; const isHookFunction = mainElement.attr('type') === 'hook'; const isPanelFunction = mainElement.attr('type') === 'panelfunc'; const arguments_ = $('args arg').map(function() { const $el = $(this); const argument = <FunctionArgument> { name: $el.attr('name')!, type: $el.attr('type')!, description: $el.text() }; if ($el.attr('default')) argument.default = $el.attr('default')!; return argument; }).get(); const returns = $('rets ret').map(function() { const $el = $(this); return <FunctionReturn> { name: $el.attr('name')!, type: $el.attr('type')!, description: $el.text() }; }).get(); const base = <Function> { type: mainElement.attr('type')!, parent: mainElement.attr('parent')!, name: mainElement.attr('name')!, address: address, description: $('description:first').text(), realm: $('realm:first').text() as Realm, arguments: arguments_, returns }; if (isClassFunction) { return <ClassFunction> { ...base, type: 'classfunc' }; } else if (isLibraryFunction) { if (base.parent === 'Global') { base.parent = '_G'; (<LibraryFunction>base).dontDefineParent = true; } return <LibraryFunction> { ...base, type: 'libraryfunc' }; } else if (isHookFunction) { return <HookFunction> { ...base, type: 'hook', isHook: 'yes' }; } else if (isPanelFunction) { return <PanelFunction> { ...base, type: 'panelfunc', isPanelFunction: 'yes' }; } } return null; }); if (!page) return []; page.url = response.url.replace(/\?format=text$/, ''); return [page]; }; } }
src/scrapers/wiki-page-markup-scraper.ts
luttje-glua-api-snippets-9f40376
[ { "filename": "src/scrapers/wiki-history-scraper.ts", "retrieved_chunk": " * Scrapes a wiki history page for information on wiki changes\n * \n * @param response The response from the page\n * @param content The content of the request\n * \n * @returns A list containing only the scraped page\n */\n public getScrapeCallback(): ScrapeCallback<WikiHistoryPage> {\n const baseScrapeCallback = super.getScrapeCallback();\n return async (response: Response, content: string): Promise<WikiHistoryPage[]> => {", "score": 0.970303475856781 }, { "filename": "src/scrapers/page-traverse-scraper.ts", "retrieved_chunk": " * \n * @param response The response from the page\n * @param content The content of the request\n * \n * @returns A list containing only the scraped page\n */\n public getScrapeCallback(): ScrapeCallback<T> {\n return (response: Response, content: string): T[] => {\n const results: T[] = [];\n const url = response.url;", "score": 0.968256950378418 }, { "filename": "src/scrapers/json-scraper.ts", "retrieved_chunk": "import { ScrapeCallback, Scraper } from './scraper.js';\nexport class JsonScraper<T extends object = object> extends Scraper<T> {\n /**\n * @param response The response from the page\n * @param content The content of the request\n * \n * @returns A list containing only the scraped page\n */\n public getScrapeCallback(): ScrapeCallback<T> {\n return JsonScraper.makeScrapeCallback<T>();", "score": 0.9040359258651733 }, { "filename": "src/scrapers/scraper.ts", "retrieved_chunk": " }\n public setRetryOptions(options: RequestInitWithRetry): void {\n this.retryOptions = options;\n }\n /**\n * Scrapes the base url and has the callback process the response\n */\n public async scrape(): Promise<void> {\n const callback = this.getScrapeCallback();\n await this.visitOne(this.baseUrl, callback);", "score": 0.8676002621650696 }, { "filename": "src/scrapers/traverse-scraper.ts", "retrieved_chunk": " /**\n * Override scraping so we traverse all child URLs of the first scraped page\n */\n public async scrape(): Promise<void> {\n const callback = this.getScrapeCallback();\n await this.traverse(this.baseUrl, callback.bind(this));\n }\n protected getTraverseUrl(url: string): string | false {\n if (!url.startsWith(this.baseUrl))\n return false;", "score": 0.85345059633255 } ]
typescript
, ($) => {
import { Close, Login, PersonAdd } from '@mui/icons-material' import { Alert, Avatar, Badge, Box, Button, IconButton, List, ListItem, ListItemAvatar, ListItemSecondaryAction, ListItemText, Tooltip, styled, } from '@mui/material' import { useEffect, useState } from 'react' import browser, { Tabs } from 'webextension-polyfill' import accountService, { Account } from '../../services/account' import cookie from '../../services/cookie' import rule from '../../services/rule' import { isGitHubUrl, isNormalGitHubUrl, removeAccount } from '../../shared' const StyledBadge = styled(Badge)(({ theme }) => ({ '& .MuiBadge-badge': { backgroundColor: '#44b700', color: '#44b700', boxShadow: `0 0 0 2px ${theme.palette.background.paper}`, '&::after': { position: 'absolute', top: 0, left: 0, width: '100%', height: '100%', borderRadius: '50%', animation: 'ripple 1.2s infinite ease-in-out', border: '1px solid currentColor', content: '""', }, }, '@keyframes ripple': { '0%': { transform: 'scale(.8)', opacity: 1, }, '100%': { transform: 'scale(2.4)', opacity: 0, }, }, })) function GitHubAvatar({ account }: { account: Account }) { const { name, active } = account const avatarUrl = account.avatarUrl ?? `https://github.com/${name}.png?size=100` const avatar = <Avatar src={avatarUrl} /> if (active) { return ( <StyledBadge overlap="circular" anchorOrigin={{ vertical: 'bottom', horizontal: 'right' }} variant="dot" > {avatar} </StyledBadge> ) } return avatar } async function getCurrentTab(): Promise<Tabs.Tab | undefined> { const queryOptions = { active: true, lastFocusedWindow: true } // `tab` will either be a `tabs.Tab` instance or `undefined`. const [tab] = await browser.tabs.query(queryOptions) return tab } export default function Accounts() { const [accounts, setAccounts] = useState<Account[]>([]) useEffect(() => { accountService.getAll().then(setAccounts) }, []) async function handleLogin() { await cookie.clear() const tab = await getCurrentTab() const rules = await rule.getAll() if (isNormalGitHubUrl(tab?.url, rules)) { await browser.tabs.update(tab?.id!, { url: `https://github.com/login?return_to=${encodeURIComponent(tab?.url ?? '')}`, }) } else if (isGitHubUrl(tab?.url)) { await browser.tabs.update(tab?.id!, { url: 'https://github.com/login' }) } else { await browser.tabs.create({ url: 'https://github.com/login' }) } window.close() } async function handleSwitch(username: string) { await accountService.switchTo(username) const tab = await getCurrentTab() const rules = await rule.getAll() // If the current tab is a normal GitHub page, reload it. if (isNormalGitHubUrl(tab?.url, rules)) { await browser.tabs.reload(tab?.id!) } else if (isGitHubUrl(tab?.url)) { await browser.tabs.update(tab?.id!, { url: 'https://github.com' }) } else { await browser.tabs.create({ url: 'https://github.com' }) } window.close() } async function handleRemove(accountName: string) { await
removeAccount(accountName) setAccounts(accounts.filter((account) => account.name !== accountName)) }
return ( <Box> <Alert severity="info" sx={{ mb: 2 }}> You can manage your logged in accounts here. </Alert> <Box sx={{ mb: 1 }}> <List dense disablePadding> {accounts.map((account, i) => ( <ListItem key={account.name} disableGutters divider={i !== accounts.length - 1}> <ListItemAvatar> <GitHubAvatar account={account} /> </ListItemAvatar> <ListItemText primary={account.name} secondary={account.expiresAt && `Expires at ${account.expiresAt.toLocaleString()}`} /> <ListItemSecondaryAction> <Tooltip title={`Switch to ${account.name}`}> <span> <IconButton color="primary" disabled={account.active} onClick={() => handleSwitch(account.name)} > <Login /> </IconButton> </span> </Tooltip> <Tooltip title={`Remove ${account.name}`} onClick={() => handleRemove(account.name)} > <IconButton color="warning"> <Close /> </IconButton> </Tooltip> </ListItemSecondaryAction> </ListItem> ))} </List> </Box> <Button variant="contained" sx={{ textTransform: 'none' }} startIcon={<PersonAdd />} onClick={handleLogin} > Login Another Account </Button> </Box> ) }
src/popup/components/Accounts.tsx
yuezk-github-account-switcher-36b3c11
[ { "filename": "src/shared.ts", "retrieved_chunk": " return false\n }\n if (urlMatchesAnyRule(url, rules)) {\n return false\n }\n return true\n}\nexport async function removeAccount(account: string) {\n await browser.runtime.sendMessage({ type: 'removeAccount', account })\n}", "score": 0.8514324426651001 }, { "filename": "src/services/account.ts", "retrieved_chunk": " })\n }\n if (cookies.length) {\n setBadgeText(accountName.slice(0, 2))\n } else {\n setBadgeText('...')\n }\n}\nasync function remove(accountName: string) {\n await storage.update<Accounts>('accounts', (accounts) => {", "score": 0.8504708409309387 }, { "filename": "src/background/index.ts", "retrieved_chunk": " }\n await setBadgeText(account.slice(0, 2))\n}\nasync function removeAccount(accountName: string) {\n await accountService.remove(accountName)\n await updateDynamicRequestRules()\n}\nasync function buildCookieValue(accountName: string): Promise<string | null> {\n const account = await accountService.find(accountName)\n const cookies = account?.cookies || []", "score": 0.835167407989502 }, { "filename": "src/services/account.ts", "retrieved_chunk": "async function find(accountName: string): Promise<Account | undefined> {\n const accounts = await getAll()\n return accounts.find((account) => account.name === accountName)\n}\nasync function upsert(accountName: string, cookies: Cookie[]) {\n await storage.update<Accounts>('accounts', (accounts = {}) => {\n accounts[accountName] = cookies\n return accounts\n })\n}", "score": 0.823745608329773 }, { "filename": "src/services/account.ts", "retrieved_chunk": " if (!accounts) {\n return\n }\n delete accounts[accountName]\n return accounts\n })\n}\nasync function saveAvatar(accountName: string, avatarUrl: string) {\n await storage.update<Record<string, string>>('avatars', (avatars = {}) => {\n avatars[accountName] = avatarUrl", "score": 0.8177542090415955 } ]
typescript
removeAccount(accountName) setAccounts(accounts.filter((account) => account.name !== accountName)) }
import browser from 'webextension-polyfill' import { isNormalGitHubUrl, removeAccount } from '../shared' import { ClearCookiesMessage, GetAccountsMessage, GetAccountsResponse, GetAutoSwitchRulesMessage, GetAutoSwitchRulesResponse, } from '../types' import './index.css' // Script that will be injected in the main page import { createElement } from './createElement' import injectedScript from './injected?script&module' import { ACCOUNT_ITEM_CLASS, ACCOUNT_REMOVE_CLASS, ADD_ACCOUNT_BUTTON_ID, createAccountItem, createAddAccountLink, createDivider } from './ui' async function addSwitchUserMenu(logoutForm: HTMLFormElement) { const currentAccount = document.querySelector<HTMLMetaElement>('meta[name="user-login"]')?.content if (!currentAccount) { console.info('no current account found') return } if (!document.getElementById(ADD_ACCOUNT_BUTTON_ID)) { // Add the "Add another account" menu item and a divider const fragment = createElement('fragment', { children: [ createAddAccountLink(), createDivider(), ], }) // Insert the elements before the logoutForm logoutForm.parentElement?.insertBefore(fragment, logoutForm) } const res: GetAccountsResponse = await browser.runtime.sendMessage({ type: 'getAccounts', } as GetAccountsMessage) if (!res?.success) { return } const { data: accounts } = res const addAccountButton = document.getElementById(ADD_ACCOUNT_BUTTON_ID)! for (const account of accounts) { if (account === currentAccount) { continue }
const accountId = `${ACCOUNT_ITEM_CLASS}-${account}` if (!document.getElementById(accountId) && addAccountButton) {
const accountWrapper = createAccountItem(account) addAccountButton.parentElement?.insertBefore(accountWrapper, addAccountButton) } } } async function getAutoSwitchRules() { const res: GetAutoSwitchRulesResponse = await browser.runtime.sendMessage({ type: 'getAutoSwitchRules', } as GetAutoSwitchRulesMessage) return res?.success ? res.data : [] } async function addAccount() { await browser.runtime.sendMessage({ type: 'clearCookies' } as ClearCookiesMessage) const autoSwitchRules = await getAutoSwitchRules() window.location.href = isNormalGitHubUrl(window.location.href, autoSwitchRules) ? `/login?return_to=${encodeURIComponent(window.location.href)}` : '/login' } async function switchAccount(account: string) { await browser.runtime.sendMessage({ type: 'switchAccount', account }) const autoSwitchRules = await getAutoSwitchRules() if (isNormalGitHubUrl(window.location.href, autoSwitchRules)) { window.location.reload() } else { window.location.href = '/' } } function injectScript() { const script = document.createElement('script') script.src = browser.runtime.getURL(injectedScript) script.type = 'module' document.head.prepend(script) } function ready(fn: () => void) { if (document.readyState !== 'loading') { fn() return } document.addEventListener('DOMContentLoaded', fn) } function watchDom() { new MutationObserver((mutations) => { for (const mutation of mutations) { const isOpen = mutation.type === 'attributes' && mutation.attributeName === 'open' && mutation.target instanceof HTMLElement && mutation.target.hasAttribute('open') if (isOpen || (mutation.type === 'childList' && mutation.target instanceof HTMLElement)) { // Find the logout form on GitHub page or Gist page const logoutForm = mutation.target.querySelector<HTMLFormElement>( '.js-loggout-form, #user-links .logout-form, user-drawer-side-panel nav-list .ActionListItem:last-child', ) if (logoutForm) { addSwitchUserMenu(logoutForm) } } } }).observe(document.documentElement, { childList: true, subtree: true, attributes: true, }) } async function init() { injectScript() ready(watchDom) document.addEventListener('click', (event) => { const target = event.target as HTMLElement if (target.closest(`.${ADD_ACCOUNT_BUTTON_ID}`)) { // add another account event.preventDefault() addAccount() } else if (target.closest(`.${ACCOUNT_ITEM_CLASS}`)) { // switch to account const closestTarget = target.closest(`.${ACCOUNT_ITEM_CLASS}`) as HTMLElement const { account } = closestTarget.dataset switchAccount(account!) } else if (target.closest(`.${ACCOUNT_REMOVE_CLASS}`)) { // remove account const btn = target.closest(`.${ACCOUNT_REMOVE_CLASS}`) as HTMLElement const { account } = btn.dataset removeAccount(account!).then(() => { btn.parentElement?.remove() }) } }) } init()
src/content/index.ts
yuezk-github-account-switcher-36b3c11
[ { "filename": "src/content/ui.ts", "retrieved_chunk": " ]\n })\n },\n createAccountItem(account: string) {\n const accountId = `${ACCOUNT_ITEM_CLASS}-${account}`\n return createElement('li', {\n id: accountId,\n class: 'ActionListItem',\n children: [\n createElement('button', {", "score": 0.8486868739128113 }, { "filename": "src/content/ui.ts", "retrieved_chunk": " class: `dropdown-item ${ADD_ACCOUNT_BUTTON_ID}`,\n children: 'Add another account'\n })\n },\n createAccountItem(account: string) {\n const accountId = `${ACCOUNT_ITEM_CLASS}-${account}`\n return createElement('div', {\n id: accountId,\n class: 'gh-account-switcher__account-wrapper',\n children: [", "score": 0.838904619216919 }, { "filename": "src/background/index.ts", "retrieved_chunk": " const autoSwitchRules = await ruleService.getAll()\n for (const [index, rule] of autoSwitchRules.entries()) {\n const cookieValue = await buildCookieValue(rule.account)\n if (!cookieValue) {\n continue\n }\n requestRules.push({\n id: index + 1,\n priority: 1,\n action: {", "score": 0.8034858703613281 }, { "filename": "src/services/account.ts", "retrieved_chunk": "async function switchTo(accountName: string) {\n await cookie.clear()\n const account = await find(accountName)\n const cookies = account?.cookies || []\n for (const cookie of cookies) {\n const { hostOnly, domain, session, ...rest } = cookie\n await browser.cookies.set({\n url: 'https://github.com',\n domain: hostOnly ? undefined : domain,\n ...rest,", "score": 0.7999029159545898 }, { "filename": "src/popup/components/Accounts.tsx", "retrieved_chunk": " }\n window.close()\n }\n async function handleSwitch(username: string) {\n await accountService.switchTo(username)\n const tab = await getCurrentTab()\n const rules = await rule.getAll()\n // If the current tab is a normal GitHub page, reload it.\n if (isNormalGitHubUrl(tab?.url, rules)) {\n await browser.tabs.reload(tab?.id!)", "score": 0.79519122838974 } ]
typescript
const accountId = `${ACCOUNT_ITEM_CLASS}-${account}` if (!document.getElementById(accountId) && addAccountButton) {
import { createElement, createRemoveIcon } from './createElement' export const ADD_ACCOUNT_BUTTON_ID = 'gh-account-switcher__add-account' export const ACCOUNT_ITEM_CLASS = 'gh-account-switcher__account' export const ACCOUNT_REMOVE_CLASS = 'gh-account-switcher__account-remove' function isNewLook() { return document.querySelector('.AppHeader-user') !== null } function uiLook() { return isNewLook() ? newLook : classicLook } const classicLook = { createDivider() { return createElement('div', { class: 'dropdown-divider' }) }, createAddAccountLink() { return createElement('a', { id: ADD_ACCOUNT_BUTTON_ID, href: '/login', class: `dropdown-item ${ADD_ACCOUNT_BUTTON_ID}`, children: 'Add another account' }) }, createAccountItem(account: string) { const accountId = `${ACCOUNT_ITEM_CLASS}-${account}` return createElement('div', { id: accountId, class: 'gh-account-switcher__account-wrapper', children: [ createElement('button', { 'data-account': account, class: `dropdown-item btn-link ${ACCOUNT_ITEM_CLASS}`, role: 'menuitem', children: [ 'Switch to ', createElement('b', { children: account }), ], }), createElement('button', { title: 'Remove account', class: `btn-link ${ACCOUNT_REMOVE_CLASS}`, 'data-account': account, children:
createRemoveIcon(), }), ] }) }
} const newLook = { createDivider() { return createElement('li', { class: 'ActionList-sectionDivider' }) }, createAddAccountLink() { return createElement('li', { id: ADD_ACCOUNT_BUTTON_ID, class: 'ActionListItem', children: [ createElement('a', { class: `ActionListContent ${ADD_ACCOUNT_BUTTON_ID}`, href: '/login', children: [ createElement('span', { class: 'ActionListItem-label', children: 'Add another account' }) ] }) ] }) }, createAccountItem(account: string) { const accountId = `${ACCOUNT_ITEM_CLASS}-${account}` return createElement('li', { id: accountId, class: 'ActionListItem', children: [ createElement('button', { 'data-account': account, class: `ActionListContent ${ACCOUNT_ITEM_CLASS}`, children: [ createElement('span', { class: 'ActionListItem-label', children: [ 'Switch to ', createElement('b', { children: account }), ] }) ] }), createElement('button', { title: 'Remove account', 'data-account': account, class: `btn-link color-fg-danger ${ACCOUNT_REMOVE_CLASS}`, children: createRemoveIcon(), }) ] }) } } export function createDivider() { const look = uiLook() return look.createDivider(); } export function createAddAccountLink() { const look = uiLook() return look.createAddAccountLink(); } export function createAccountItem(account: string) { const look = uiLook() return look.createAccountItem(account); }
src/content/ui.ts
yuezk-github-account-switcher-36b3c11
[ { "filename": "src/content/index.ts", "retrieved_chunk": " if (!document.getElementById(ADD_ACCOUNT_BUTTON_ID)) {\n // Add the \"Add another account\" menu item and a divider\n const fragment = createElement('fragment', {\n children: [\n createAddAccountLink(),\n createDivider(),\n ],\n })\n // Insert the elements before the logoutForm\n logoutForm.parentElement?.insertBefore(fragment, logoutForm)", "score": 0.75373375415802 }, { "filename": "src/popup/components/AutoSwitchRules.tsx", "retrieved_chunk": " startIcon={<AddCircle />}\n onClick={startAdding}\n disabled={isAdding}\n sx={{ textTransform: 'none' }}\n >\n Add a Rule\n </Button>\n </Box>\n )\n}", "score": 0.7315146923065186 }, { "filename": "src/content/index.ts", "retrieved_chunk": "// Script that will be injected in the main page\nimport { createElement } from './createElement'\nimport injectedScript from './injected?script&module'\nimport { ACCOUNT_ITEM_CLASS, ACCOUNT_REMOVE_CLASS, ADD_ACCOUNT_BUTTON_ID, createAccountItem, createAddAccountLink, createDivider } from './ui'\nasync function addSwitchUserMenu(logoutForm: HTMLFormElement) {\n const currentAccount = document.querySelector<HTMLMetaElement>('meta[name=\"user-login\"]')?.content\n if (!currentAccount) {\n console.info('no current account found')\n return\n }", "score": 0.7314094305038452 }, { "filename": "src/popup/components/Header.tsx", "retrieved_chunk": " <Container\n component=\"header\"\n sx={{\n py: 1,\n borderBottom: 1,\n borderBottomColor: 'divider',\n display: 'flex',\n alignItems: 'center',\n }}\n >", "score": 0.7225637435913086 }, { "filename": "src/content/index.ts", "retrieved_chunk": " const closestTarget = target.closest(`.${ACCOUNT_ITEM_CLASS}`) as HTMLElement\n const { account } = closestTarget.dataset\n switchAccount(account!)\n } else if (target.closest(`.${ACCOUNT_REMOVE_CLASS}`)) {\n // remove account\n const btn = target.closest(`.${ACCOUNT_REMOVE_CLASS}`) as HTMLElement\n const { account } = btn.dataset\n removeAccount(account!).then(() => {\n btn.parentElement?.remove()\n })", "score": 0.7219845652580261 } ]
typescript
createRemoveIcon(), }), ] }) }
import { Close, Login, PersonAdd } from '@mui/icons-material' import { Alert, Avatar, Badge, Box, Button, IconButton, List, ListItem, ListItemAvatar, ListItemSecondaryAction, ListItemText, Tooltip, styled, } from '@mui/material' import { useEffect, useState } from 'react' import browser, { Tabs } from 'webextension-polyfill' import accountService, { Account } from '../../services/account' import cookie from '../../services/cookie' import rule from '../../services/rule' import { isGitHubUrl, isNormalGitHubUrl, removeAccount } from '../../shared' const StyledBadge = styled(Badge)(({ theme }) => ({ '& .MuiBadge-badge': { backgroundColor: '#44b700', color: '#44b700', boxShadow: `0 0 0 2px ${theme.palette.background.paper}`, '&::after': { position: 'absolute', top: 0, left: 0, width: '100%', height: '100%', borderRadius: '50%', animation: 'ripple 1.2s infinite ease-in-out', border: '1px solid currentColor', content: '""', }, }, '@keyframes ripple': { '0%': { transform: 'scale(.8)', opacity: 1, }, '100%': { transform: 'scale(2.4)', opacity: 0, }, }, })) function GitHubAvatar({ account }: { account: Account }) { const { name, active } = account const avatarUrl = account.avatarUrl ?? `https://github.com/${name}.png?size=100` const avatar = <Avatar src={avatarUrl} /> if (active) { return ( <StyledBadge overlap="circular" anchorOrigin={{ vertical: 'bottom', horizontal: 'right' }} variant="dot" > {avatar} </StyledBadge> ) } return avatar } async function getCurrentTab(): Promise<Tabs.Tab | undefined> { const queryOptions = { active: true, lastFocusedWindow: true } // `tab` will either be a `tabs.Tab` instance or `undefined`. const [tab] = await browser.tabs.query(queryOptions) return tab } export default function Accounts() { const [accounts, setAccounts] = useState<Account[]>([]) useEffect(() => { accountService.getAll().then(setAccounts) }, []) async function handleLogin() { await cookie.clear() const tab = await getCurrentTab() const rules = await rule.getAll() if (isNormalGitHubUrl(tab?.url, rules)) { await browser.tabs.update(tab?.id!, { url: `https://github.com/login?return_to=${encodeURIComponent(tab?.url ?? '')}`, }) } else if (
isGitHubUrl(tab?.url)) {
await browser.tabs.update(tab?.id!, { url: 'https://github.com/login' }) } else { await browser.tabs.create({ url: 'https://github.com/login' }) } window.close() } async function handleSwitch(username: string) { await accountService.switchTo(username) const tab = await getCurrentTab() const rules = await rule.getAll() // If the current tab is a normal GitHub page, reload it. if (isNormalGitHubUrl(tab?.url, rules)) { await browser.tabs.reload(tab?.id!) } else if (isGitHubUrl(tab?.url)) { await browser.tabs.update(tab?.id!, { url: 'https://github.com' }) } else { await browser.tabs.create({ url: 'https://github.com' }) } window.close() } async function handleRemove(accountName: string) { await removeAccount(accountName) setAccounts(accounts.filter((account) => account.name !== accountName)) } return ( <Box> <Alert severity="info" sx={{ mb: 2 }}> You can manage your logged in accounts here. </Alert> <Box sx={{ mb: 1 }}> <List dense disablePadding> {accounts.map((account, i) => ( <ListItem key={account.name} disableGutters divider={i !== accounts.length - 1}> <ListItemAvatar> <GitHubAvatar account={account} /> </ListItemAvatar> <ListItemText primary={account.name} secondary={account.expiresAt && `Expires at ${account.expiresAt.toLocaleString()}`} /> <ListItemSecondaryAction> <Tooltip title={`Switch to ${account.name}`}> <span> <IconButton color="primary" disabled={account.active} onClick={() => handleSwitch(account.name)} > <Login /> </IconButton> </span> </Tooltip> <Tooltip title={`Remove ${account.name}`} onClick={() => handleRemove(account.name)} > <IconButton color="warning"> <Close /> </IconButton> </Tooltip> </ListItemSecondaryAction> </ListItem> ))} </List> </Box> <Button variant="contained" sx={{ textTransform: 'none' }} startIcon={<PersonAdd />} onClick={handleLogin} > Login Another Account </Button> </Box> ) }
src/popup/components/Accounts.tsx
yuezk-github-account-switcher-36b3c11
[ { "filename": "src/content/index.ts", "retrieved_chunk": " ? `/login?return_to=${encodeURIComponent(window.location.href)}`\n : '/login'\n}\nasync function switchAccount(account: string) {\n await browser.runtime.sendMessage({ type: 'switchAccount', account })\n const autoSwitchRules = await getAutoSwitchRules()\n if (isNormalGitHubUrl(window.location.href, autoSwitchRules)) {\n window.location.reload()\n } else {\n window.location.href = '/'", "score": 0.8391712307929993 }, { "filename": "src/content/injected.ts", "retrieved_chunk": " return url.href\n }\n}\nfunction patchUrl(oldUrl: string | URL) {\n const account = document.querySelector<HTMLMetaElement>('meta[name=\"user-login\"]')?.content\n if (!account) {\n return oldUrl\n }\n const newUrl = new URL(oldUrl, window.location.origin)\n newUrl.searchParams.append(ACCOUNT_PARAM, account)", "score": 0.7791121006011963 }, { "filename": "src/content/index.ts", "retrieved_chunk": "async function getAutoSwitchRules() {\n const res: GetAutoSwitchRulesResponse = await browser.runtime.sendMessage({\n type: 'getAutoSwitchRules',\n } as GetAutoSwitchRulesMessage)\n return res?.success ? res.data : []\n}\nasync function addAccount() {\n await browser.runtime.sendMessage({ type: 'clearCookies' } as ClearCookiesMessage)\n const autoSwitchRules = await getAutoSwitchRules()\n window.location.href = isNormalGitHubUrl(window.location.href, autoSwitchRules)", "score": 0.7707926034927368 }, { "filename": "src/background/index.ts", "retrieved_chunk": " if (!account) {\n return\n }\n await accountService.upsert(account, await cookie.getAll())\n const accounts = await accountService.getAll()\n console.info('synced accounts', accounts)\n await updateDynamicRequestRules()\n const res = await fetch(`https://github.com/${account}.png?size=100`)\n if (res.status === 200) {\n accountService.saveAvatar(account, res.url)", "score": 0.760456383228302 }, { "filename": "src/services/account.ts", "retrieved_chunk": "async function switchTo(accountName: string) {\n await cookie.clear()\n const account = await find(accountName)\n const cookies = account?.cookies || []\n for (const cookie of cookies) {\n const { hostOnly, domain, session, ...rest } = cookie\n await browser.cookies.set({\n url: 'https://github.com',\n domain: hostOnly ? undefined : domain,\n ...rest,", "score": 0.7554945945739746 } ]
typescript
isGitHubUrl(tab?.url)) {
import browser from 'webextension-polyfill' import { isNormalGitHubUrl, removeAccount } from '../shared' import { ClearCookiesMessage, GetAccountsMessage, GetAccountsResponse, GetAutoSwitchRulesMessage, GetAutoSwitchRulesResponse, } from '../types' import './index.css' // Script that will be injected in the main page import { createElement } from './createElement' import injectedScript from './injected?script&module' import { ACCOUNT_ITEM_CLASS, ACCOUNT_REMOVE_CLASS, ADD_ACCOUNT_BUTTON_ID, createAccountItem, createAddAccountLink, createDivider } from './ui' async function addSwitchUserMenu(logoutForm: HTMLFormElement) { const currentAccount = document.querySelector<HTMLMetaElement>('meta[name="user-login"]')?.content if (!currentAccount) { console.info('no current account found') return } if (!document.getElementById(ADD_ACCOUNT_BUTTON_ID)) { // Add the "Add another account" menu item and a divider const fragment = createElement('fragment', { children: [ createAddAccountLink(), createDivider(), ], }) // Insert the elements before the logoutForm logoutForm.parentElement?.insertBefore(fragment, logoutForm) } const res: GetAccountsResponse = await browser.runtime.sendMessage({ type: 'getAccounts', } as GetAccountsMessage) if (!res?.success) { return } const { data: accounts } = res const addAccountButton = document.getElementById(ADD_ACCOUNT_BUTTON_ID)! for (const account of accounts) { if (account === currentAccount) { continue } const accountId = `${ACCOUNT_ITEM_CLASS}-${account}` if (!document.getElementById(accountId) && addAccountButton) { const accountWrapper = createAccountItem(account) addAccountButton.parentElement?.insertBefore(accountWrapper, addAccountButton) } } } async function getAutoSwitchRules() { const res: GetAutoSwitchRulesResponse = await browser.runtime.sendMessage({ type: 'getAutoSwitchRules', } as GetAutoSwitchRulesMessage) return res?.success ? res.data : [] } async function addAccount() { await browser.runtime.sendMessage({ type: 'clearCookies' } as ClearCookiesMessage) const autoSwitchRules = await getAutoSwitchRules() window.location.href = isNormalGitHubUrl(window.location.href, autoSwitchRules) ? `/login?return_to=${encodeURIComponent(window.location.href)}` : '/login' } async function switchAccount(account: string) { await browser.runtime.sendMessage({ type: 'switchAccount', account }) const autoSwitchRules = await getAutoSwitchRules() if (isNormalGitHubUrl(window.location.href, autoSwitchRules)) { window.location.reload() } else { window.location.href = '/' } } function injectScript() { const script = document.createElement('script') script.src = browser.runtime.
getURL(injectedScript) script.type = 'module' document.head.prepend(script) }
function ready(fn: () => void) { if (document.readyState !== 'loading') { fn() return } document.addEventListener('DOMContentLoaded', fn) } function watchDom() { new MutationObserver((mutations) => { for (const mutation of mutations) { const isOpen = mutation.type === 'attributes' && mutation.attributeName === 'open' && mutation.target instanceof HTMLElement && mutation.target.hasAttribute('open') if (isOpen || (mutation.type === 'childList' && mutation.target instanceof HTMLElement)) { // Find the logout form on GitHub page or Gist page const logoutForm = mutation.target.querySelector<HTMLFormElement>( '.js-loggout-form, #user-links .logout-form, user-drawer-side-panel nav-list .ActionListItem:last-child', ) if (logoutForm) { addSwitchUserMenu(logoutForm) } } } }).observe(document.documentElement, { childList: true, subtree: true, attributes: true, }) } async function init() { injectScript() ready(watchDom) document.addEventListener('click', (event) => { const target = event.target as HTMLElement if (target.closest(`.${ADD_ACCOUNT_BUTTON_ID}`)) { // add another account event.preventDefault() addAccount() } else if (target.closest(`.${ACCOUNT_ITEM_CLASS}`)) { // switch to account const closestTarget = target.closest(`.${ACCOUNT_ITEM_CLASS}`) as HTMLElement const { account } = closestTarget.dataset switchAccount(account!) } else if (target.closest(`.${ACCOUNT_REMOVE_CLASS}`)) { // remove account const btn = target.closest(`.${ACCOUNT_REMOVE_CLASS}`) as HTMLElement const { account } = btn.dataset removeAccount(account!).then(() => { btn.parentElement?.remove() }) } }) } init()
src/content/index.ts
yuezk-github-account-switcher-36b3c11
[ { "filename": "src/content/injected.ts", "retrieved_chunk": " return url.href\n }\n}\nfunction patchUrl(oldUrl: string | URL) {\n const account = document.querySelector<HTMLMetaElement>('meta[name=\"user-login\"]')?.content\n if (!account) {\n return oldUrl\n }\n const newUrl = new URL(oldUrl, window.location.origin)\n newUrl.searchParams.append(ACCOUNT_PARAM, account)", "score": 0.7471394538879395 }, { "filename": "src/background/index.ts", "retrieved_chunk": " listenMessage()\n if (!browser.declarativeNetRequest) {\n interceptRequests()\n }\n /*\n chrome.declarativeNetRequest.onRuleMatchedDebug.addListener((info) => {\n console.info('onRuleMatchedDebug', info)\n })*/\n}\ninit()", "score": 0.7120770215988159 }, { "filename": "src/content/createElement.ts", "retrieved_chunk": " for (const child of childrenArray) {\n if (typeof child === 'undefined') {\n continue\n }\n if (typeof child === 'string') {\n parent.appendChild(document.createTextNode(child))\n } else {\n parent.appendChild(child)\n }\n }", "score": 0.6804302930831909 }, { "filename": "src/services/cookie.ts", "retrieved_chunk": "import browser from 'webextension-polyfill'\nconst COOKIE_URL = 'https://github.com'\nasync function get(name: string) {\n return browser.cookies.get({ url: COOKIE_URL, name })\n}\nasync function getAll() {\n return browser.cookies.getAll({ url: COOKIE_URL })\n}\nasync function clear() {\n const cookies = await getAll()", "score": 0.6756041049957275 }, { "filename": "src/shared.ts", "retrieved_chunk": " return false\n }\n if (urlMatchesAnyRule(url, rules)) {\n return false\n }\n return true\n}\nexport async function removeAccount(account: string) {\n await browser.runtime.sendMessage({ type: 'removeAccount', account })\n}", "score": 0.6730749607086182 } ]
typescript
getURL(injectedScript) script.type = 'module' document.head.prepend(script) }
import browser, { DeclarativeNetRequest } from 'webextension-polyfill' import accountService from '../services/account' import { setBadgeText } from '../services/badge' import cookie from '../services/cookie' import ruleService from '../services/rule' import { RequestMessage, Response } from '../types' const RESOURCE_TYPES: DeclarativeNetRequest.ResourceType[] = [ 'main_frame', 'sub_frame', 'csp_report', 'websocket', 'xmlhttprequest', ] async function syncAccounts() { const usernameCookie = await cookie.get('dotcom_user') const sessionCookie = await cookie.get('user_session') if (!usernameCookie || !sessionCookie) { return } const { value: account } = usernameCookie if (!account) { return } await accountService.upsert(account, await cookie.getAll()) const accounts = await accountService.getAll() console.info('synced accounts', accounts) await updateDynamicRequestRules() const res = await fetch(`https://github.com/${account}.png?size=100`) if (res.status === 200) { accountService.saveAvatar(account, res.url) } await setBadgeText(account.slice(0, 2)) } async function removeAccount(accountName: string) { await accountService.remove(accountName) await updateDynamicRequestRules() } async function buildCookieValue(accountName: string): Promise<string | null> { const account = await accountService.find(accountName) const cookies = account?.cookies || [] if (!cookies.length) { return null } return cookies .map((cookie) => `${cookie.name}=${cookie.value}`) .concat(`__account__=${accountName}`) .join('; ') } async function buildAddRules(): Promise<DeclarativeNetRequest.Rule[]> { const requestRules: DeclarativeNetRequest.Rule[] = [] const autoSwitchRules = await ruleService.getAll() for (const [index, rule] of autoSwitchRules.entries()) { const cookieValue = await buildCookieValue(rule.account) if (!cookieValue) { continue } requestRules.push({ id: index + 1, priority: 1, action: { type: 'modifyHeaders', requestHeaders: [ { header: 'Cookie', operation: 'set', value: cookieValue, }, ], }, condition: { regexFilter: `${rule.urlPattern}|__account__=${rule.account}`, resourceTypes: RESOURCE_TYPES, }, }) } return requestRules } async function updateDynamicRequestRules() { if (!browser.declarativeNetRequest) { return } const existingRules = await browser.declarativeNetRequest.getDynamicRules() const removeRuleIds = existingRules.map((rule) => rule.id) const addRules = await buildAddRules() await browser.declarativeNetRequest.updateDynamicRules({ removeRuleIds, addRules, }) const rules = await browser.declarativeNetRequest.getDynamicRules() console.info('Current dynamic rules:', rules) } // Watch the requests, if the main_frame url matches any of the auto switch rules, switch to the account function watchAutoSwitchRequests() { browser.webRequest.onBeforeRequest.addListener( (details) => { ruleService.getAll().then((autoSwitchRules) => { for (const rule of autoSwitchRules) { if (new RegExp(rule.urlPattern).test(details.url)) { console.info('onBeforeRequest: found an auto switch rule for url', details.url, rule) return accountService.switchTo(rule.account) } } }) }, { urls: ['https://github.com/*'], types: ['main_frame'], }, ) } function watchCookies() { browser.cookies.onChanged.addListener(async (changeInfo) => { const { cookie, removed } = changeInfo // Ignore other cookies if (cookie.name !== 'dotcom_user') { return } if (removed) { if (cookie.name === 'dotcom_user') { console.info('dotcom_user cookie removed') await setBadgeText('...') } return } console.info('New dotcom_user cookie', cookie.value) await syncAccounts() }) }
function handleMessage(message: RequestMessage) {
const { type } = message switch (type) { case 'getAccounts': return accountService.getAllNames() case 'switchAccount': return accountService.switchTo(message.account) case 'removeAccount': return removeAccount(message.account) case 'clearCookies': return cookie.clear() case 'getAutoSwitchRules': return ruleService.getAll() } } function listenMessage() { browser.runtime.onMessage.addListener( async (request: RequestMessage, _sender): Promise<Response<unknown>> => { try { const data = await handleMessage(request) return { success: true, data } } catch (error: unknown) { return { success: false, error: error as Error } } }, ) } function interceptRequests() { browser.webRequest.onBeforeSendHeaders.addListener( async (details) => { if (!details.requestHeaders) { return { requestHeaders: details.requestHeaders } } const autoSwitchRules = await ruleService.getAll() for (const rule of autoSwitchRules) { const urlPattern = `${rule.urlPattern}|__account__=${rule.account}` if (new RegExp(urlPattern).test(details.url)) { const cookieValue = await buildCookieValue(rule.account) if (cookieValue) { for (const header of details.requestHeaders) { if (header.name.toLowerCase() === 'cookie') { header.value = cookieValue } } } console.info('interceptRequests: found an auto switch rule for url', details.url, rule) return { requestHeaders: details.requestHeaders } } } return { requestHeaders: details.requestHeaders } }, { urls: ['https://github.com/*'], types: RESOURCE_TYPES, }, ['blocking', 'requestHeaders'], ) } async function init() { await syncAccounts() watchAutoSwitchRequests() watchCookies() listenMessage() if (!browser.declarativeNetRequest) { interceptRequests() } /* chrome.declarativeNetRequest.onRuleMatchedDebug.addListener((info) => { console.info('onRuleMatchedDebug', info) })*/ } init()
src/background/index.ts
yuezk-github-account-switcher-36b3c11
[ { "filename": "src/services/account.ts", "retrieved_chunk": " })\n }\n if (cookies.length) {\n setBadgeText(accountName.slice(0, 2))\n } else {\n setBadgeText('...')\n }\n}\nasync function remove(accountName: string) {\n await storage.update<Accounts>('accounts', (accounts) => {", "score": 0.8359730243682861 }, { "filename": "src/shared.ts", "retrieved_chunk": " return false\n }\n if (urlMatchesAnyRule(url, rules)) {\n return false\n }\n return true\n}\nexport async function removeAccount(account: string) {\n await browser.runtime.sendMessage({ type: 'removeAccount', account })\n}", "score": 0.7956112623214722 }, { "filename": "src/services/account.ts", "retrieved_chunk": " expiresAt: userSessionCookie?.expirationDate\n ? new Date(userSessionCookie.expirationDate * 1000)\n : undefined,\n }\n })\n}\nasync function getAllNames(): Promise<string[]> {\n const accounts = await getAll()\n return accounts.map(({ name }) => name)\n}", "score": 0.7798260450363159 }, { "filename": "src/services/account.ts", "retrieved_chunk": " if (!accounts) {\n return\n }\n delete accounts[accountName]\n return accounts\n })\n}\nasync function saveAvatar(accountName: string, avatarUrl: string) {\n await storage.update<Record<string, string>>('avatars', (avatars = {}) => {\n avatars[accountName] = avatarUrl", "score": 0.7728585004806519 }, { "filename": "src/services/cookie.ts", "retrieved_chunk": " for (const cookie of cookies) {\n await browser.cookies.remove({ url: COOKIE_URL, name: cookie.name })\n }\n}\nexport default {\n get,\n getAll,\n clear,\n}", "score": 0.7700473070144653 } ]
typescript
function handleMessage(message: RequestMessage) {
import browser from 'webextension-polyfill' import { isNormalGitHubUrl, removeAccount } from '../shared' import { ClearCookiesMessage, GetAccountsMessage, GetAccountsResponse, GetAutoSwitchRulesMessage, GetAutoSwitchRulesResponse, } from '../types' import './index.css' // Script that will be injected in the main page import { createElement } from './createElement' import injectedScript from './injected?script&module' import { ACCOUNT_ITEM_CLASS, ACCOUNT_REMOVE_CLASS, ADD_ACCOUNT_BUTTON_ID, createAccountItem, createAddAccountLink, createDivider } from './ui' async function addSwitchUserMenu(logoutForm: HTMLFormElement) { const currentAccount = document.querySelector<HTMLMetaElement>('meta[name="user-login"]')?.content if (!currentAccount) { console.info('no current account found') return } if (!document.getElementById(ADD_ACCOUNT_BUTTON_ID)) { // Add the "Add another account" menu item and a divider const fragment = createElement('fragment', { children: [ createAddAccountLink(), createDivider(), ], }) // Insert the elements before the logoutForm logoutForm.parentElement?.insertBefore(fragment, logoutForm) } const res: GetAccountsResponse = await browser.runtime.sendMessage({ type: 'getAccounts', } as GetAccountsMessage) if (!res?.success) { return } const { data: accounts } = res const addAccountButton = document.getElementById(ADD_ACCOUNT_BUTTON_ID)! for (const account of accounts) { if (account === currentAccount) { continue } const accountId = `${ACCOUNT_ITEM_CLASS}-${account}` if (!document.getElementById(accountId) && addAccountButton) {
const accountWrapper = createAccountItem(account) addAccountButton.parentElement?.insertBefore(accountWrapper, addAccountButton) }
} } async function getAutoSwitchRules() { const res: GetAutoSwitchRulesResponse = await browser.runtime.sendMessage({ type: 'getAutoSwitchRules', } as GetAutoSwitchRulesMessage) return res?.success ? res.data : [] } async function addAccount() { await browser.runtime.sendMessage({ type: 'clearCookies' } as ClearCookiesMessage) const autoSwitchRules = await getAutoSwitchRules() window.location.href = isNormalGitHubUrl(window.location.href, autoSwitchRules) ? `/login?return_to=${encodeURIComponent(window.location.href)}` : '/login' } async function switchAccount(account: string) { await browser.runtime.sendMessage({ type: 'switchAccount', account }) const autoSwitchRules = await getAutoSwitchRules() if (isNormalGitHubUrl(window.location.href, autoSwitchRules)) { window.location.reload() } else { window.location.href = '/' } } function injectScript() { const script = document.createElement('script') script.src = browser.runtime.getURL(injectedScript) script.type = 'module' document.head.prepend(script) } function ready(fn: () => void) { if (document.readyState !== 'loading') { fn() return } document.addEventListener('DOMContentLoaded', fn) } function watchDom() { new MutationObserver((mutations) => { for (const mutation of mutations) { const isOpen = mutation.type === 'attributes' && mutation.attributeName === 'open' && mutation.target instanceof HTMLElement && mutation.target.hasAttribute('open') if (isOpen || (mutation.type === 'childList' && mutation.target instanceof HTMLElement)) { // Find the logout form on GitHub page or Gist page const logoutForm = mutation.target.querySelector<HTMLFormElement>( '.js-loggout-form, #user-links .logout-form, user-drawer-side-panel nav-list .ActionListItem:last-child', ) if (logoutForm) { addSwitchUserMenu(logoutForm) } } } }).observe(document.documentElement, { childList: true, subtree: true, attributes: true, }) } async function init() { injectScript() ready(watchDom) document.addEventListener('click', (event) => { const target = event.target as HTMLElement if (target.closest(`.${ADD_ACCOUNT_BUTTON_ID}`)) { // add another account event.preventDefault() addAccount() } else if (target.closest(`.${ACCOUNT_ITEM_CLASS}`)) { // switch to account const closestTarget = target.closest(`.${ACCOUNT_ITEM_CLASS}`) as HTMLElement const { account } = closestTarget.dataset switchAccount(account!) } else if (target.closest(`.${ACCOUNT_REMOVE_CLASS}`)) { // remove account const btn = target.closest(`.${ACCOUNT_REMOVE_CLASS}`) as HTMLElement const { account } = btn.dataset removeAccount(account!).then(() => { btn.parentElement?.remove() }) } }) } init()
src/content/index.ts
yuezk-github-account-switcher-36b3c11
[ { "filename": "src/content/ui.ts", "retrieved_chunk": " class: `dropdown-item ${ADD_ACCOUNT_BUTTON_ID}`,\n children: 'Add another account'\n })\n },\n createAccountItem(account: string) {\n const accountId = `${ACCOUNT_ITEM_CLASS}-${account}`\n return createElement('div', {\n id: accountId,\n class: 'gh-account-switcher__account-wrapper',\n children: [", "score": 0.807283878326416 }, { "filename": "src/content/ui.ts", "retrieved_chunk": " ]\n })\n },\n createAccountItem(account: string) {\n const accountId = `${ACCOUNT_ITEM_CLASS}-${account}`\n return createElement('li', {\n id: accountId,\n class: 'ActionListItem',\n children: [\n createElement('button', {", "score": 0.8030588626861572 }, { "filename": "src/content/ui.ts", "retrieved_chunk": "const classicLook = {\n createDivider() {\n return createElement('div', {\n class: 'dropdown-divider'\n })\n },\n createAddAccountLink() {\n return createElement('a', {\n id: ADD_ACCOUNT_BUTTON_ID,\n href: '/login',", "score": 0.762166440486908 }, { "filename": "src/popup/components/Accounts.tsx", "retrieved_chunk": " }\n window.close()\n }\n async function handleSwitch(username: string) {\n await accountService.switchTo(username)\n const tab = await getCurrentTab()\n const rules = await rule.getAll()\n // If the current tab is a normal GitHub page, reload it.\n if (isNormalGitHubUrl(tab?.url, rules)) {\n await browser.tabs.reload(tab?.id!)", "score": 0.742740273475647 }, { "filename": "src/content/ui.ts", "retrieved_chunk": " createDivider() {\n return createElement('li', {\n class: 'ActionList-sectionDivider'\n })\n },\n createAddAccountLink() {\n return createElement('li', {\n id: ADD_ACCOUNT_BUTTON_ID,\n class: 'ActionListItem',\n children: [", "score": 0.7359248399734497 } ]
typescript
const accountWrapper = createAccountItem(account) addAccountButton.parentElement?.insertBefore(accountWrapper, addAccountButton) }
import browser from 'webextension-polyfill' import { isNormalGitHubUrl, removeAccount } from '../shared' import { ClearCookiesMessage, GetAccountsMessage, GetAccountsResponse, GetAutoSwitchRulesMessage, GetAutoSwitchRulesResponse, } from '../types' import './index.css' // Script that will be injected in the main page import { createElement } from './createElement' import injectedScript from './injected?script&module' import { ACCOUNT_ITEM_CLASS, ACCOUNT_REMOVE_CLASS, ADD_ACCOUNT_BUTTON_ID, createAccountItem, createAddAccountLink, createDivider } from './ui' async function addSwitchUserMenu(logoutForm: HTMLFormElement) { const currentAccount = document.querySelector<HTMLMetaElement>('meta[name="user-login"]')?.content if (!currentAccount) { console.info('no current account found') return } if (!document.getElementById(ADD_ACCOUNT_BUTTON_ID)) { // Add the "Add another account" menu item and a divider const fragment = createElement('fragment', { children: [ createAddAccountLink(), createDivider(), ], }) // Insert the elements before the logoutForm logoutForm.parentElement?.insertBefore(fragment, logoutForm) } const res: GetAccountsResponse = await browser.runtime.sendMessage({ type: 'getAccounts', } as GetAccountsMessage) if (!res?.success) { return } const { data: accounts } = res const addAccountButton = document.getElementById(ADD_ACCOUNT_BUTTON_ID)! for (const account of accounts) { if (account === currentAccount) { continue } const accountId = `${ACCOUNT_ITEM_CLASS}-${account}` if (!document.getElementById(accountId) && addAccountButton) { const accountWrapper = createAccountItem(account) addAccountButton.parentElement?.insertBefore(accountWrapper, addAccountButton) } } } async function getAutoSwitchRules() { const res: GetAutoSwitchRulesResponse = await browser.runtime.sendMessage({ type: 'getAutoSwitchRules', } as GetAutoSwitchRulesMessage) return res?.success ? res.data : [] } async function addAccount() { await browser.runtime.sendMessage({ type: 'clearCookies' } as ClearCookiesMessage) const autoSwitchRules = await getAutoSwitchRules() window.location.href = isNormalGitHubUrl(window.location.href, autoSwitchRules) ? `/login?return_to=${encodeURIComponent(window.location.href)}` : '/login' } async function switchAccount(account: string) { await browser.runtime.sendMessage({ type: 'switchAccount', account }) const autoSwitchRules = await getAutoSwitchRules() if (isNormalGitHubUrl(window.location.href, autoSwitchRules)) { window.location.reload() } else { window.location.href = '/' } } function injectScript() { const script = document.createElement('script') script.src = browser.runtime.getURL(injectedScript) script.type = 'module' document.head.prepend(script) } function ready(fn: () => void) { if (document.readyState !== 'loading') { fn() return } document.addEventListener('DOMContentLoaded', fn) } function watchDom() { new MutationObserver((mutations) => { for (const mutation of mutations) { const isOpen = mutation.type === 'attributes' && mutation.attributeName === 'open' && mutation.target instanceof HTMLElement && mutation.target.hasAttribute('open') if (isOpen || (mutation.type === 'childList' && mutation.target instanceof HTMLElement)) { // Find the logout form on GitHub page or Gist page const logoutForm = mutation.target.querySelector<HTMLFormElement>( '.js-loggout-form, #user-links .logout-form, user-drawer-side-panel nav-list .ActionListItem:last-child', ) if (logoutForm) { addSwitchUserMenu(logoutForm) } } } }).observe(document.documentElement, { childList: true, subtree: true, attributes: true, }) } async function init() { injectScript() ready(watchDom) document.addEventListener('click', (event) => { const target = event.target as HTMLElement if (target.closest(`.${ADD_ACCOUNT_BUTTON_ID}`)) { // add another account event.preventDefault() addAccount() } else if (target.closest(`.${ACCOUNT_ITEM_CLASS}`)) { // switch to account const closestTarget = target.closest(`.${ACCOUNT_ITEM_CLASS}`) as HTMLElement const { account } = closestTarget.dataset switchAccount(account!) }
else if (target.closest(`.${ACCOUNT_REMOVE_CLASS}`)) {
// remove account const btn = target.closest(`.${ACCOUNT_REMOVE_CLASS}`) as HTMLElement const { account } = btn.dataset removeAccount(account!).then(() => { btn.parentElement?.remove() }) } }) } init()
src/content/index.ts
yuezk-github-account-switcher-36b3c11
[ { "filename": "src/content/ui.ts", "retrieved_chunk": " class: `dropdown-item ${ADD_ACCOUNT_BUTTON_ID}`,\n children: 'Add another account'\n })\n },\n createAccountItem(account: string) {\n const accountId = `${ACCOUNT_ITEM_CLASS}-${account}`\n return createElement('div', {\n id: accountId,\n class: 'gh-account-switcher__account-wrapper',\n children: [", "score": 0.8006688356399536 }, { "filename": "src/content/ui.ts", "retrieved_chunk": " ]\n })\n },\n createAccountItem(account: string) {\n const accountId = `${ACCOUNT_ITEM_CLASS}-${account}`\n return createElement('li', {\n id: accountId,\n class: 'ActionListItem',\n children: [\n createElement('button', {", "score": 0.7696648836135864 }, { "filename": "src/content/ui.ts", "retrieved_chunk": "const classicLook = {\n createDivider() {\n return createElement('div', {\n class: 'dropdown-divider'\n })\n },\n createAddAccountLink() {\n return createElement('a', {\n id: ADD_ACCOUNT_BUTTON_ID,\n href: '/login',", "score": 0.7448519468307495 }, { "filename": "src/content/injected.ts", "retrieved_chunk": " return url.href\n }\n}\nfunction patchUrl(oldUrl: string | URL) {\n const account = document.querySelector<HTMLMetaElement>('meta[name=\"user-login\"]')?.content\n if (!account) {\n return oldUrl\n }\n const newUrl = new URL(oldUrl, window.location.origin)\n newUrl.searchParams.append(ACCOUNT_PARAM, account)", "score": 0.7387101650238037 }, { "filename": "src/content/ui.ts", "retrieved_chunk": " createDivider() {\n return createElement('li', {\n class: 'ActionList-sectionDivider'\n })\n },\n createAddAccountLink() {\n return createElement('li', {\n id: ADD_ACCOUNT_BUTTON_ID,\n class: 'ActionListItem',\n children: [", "score": 0.7286558151245117 } ]
typescript
else if (target.closest(`.${ACCOUNT_REMOVE_CLASS}`)) {
import browser, { DeclarativeNetRequest } from 'webextension-polyfill' import accountService from '../services/account' import { setBadgeText } from '../services/badge' import cookie from '../services/cookie' import ruleService from '../services/rule' import { RequestMessage, Response } from '../types' const RESOURCE_TYPES: DeclarativeNetRequest.ResourceType[] = [ 'main_frame', 'sub_frame', 'csp_report', 'websocket', 'xmlhttprequest', ] async function syncAccounts() { const usernameCookie = await cookie.get('dotcom_user') const sessionCookie = await cookie.get('user_session') if (!usernameCookie || !sessionCookie) { return } const { value: account } = usernameCookie if (!account) { return } await accountService.upsert(account, await cookie.getAll()) const accounts = await accountService.getAll() console.info('synced accounts', accounts) await updateDynamicRequestRules() const res = await fetch(`https://github.com/${account}.png?size=100`) if (res.status === 200) { accountService.saveAvatar(account, res.url) } await setBadgeText(account.slice(0, 2)) } async function removeAccount(accountName: string) { await accountService.remove(accountName) await updateDynamicRequestRules() } async function buildCookieValue(accountName: string): Promise<string | null> { const account = await accountService.find(accountName) const cookies = account?.cookies || [] if (!cookies.length) { return null } return cookies .map((cookie) => `${cookie.name}=${cookie.value}`) .concat(`__account__=${accountName}`) .join('; ') } async function buildAddRules(): Promise<DeclarativeNetRequest.Rule[]> { const requestRules: DeclarativeNetRequest.Rule[] = [] const autoSwitchRules = await ruleService.getAll() for (const [index, rule] of autoSwitchRules.entries()) { const cookieValue = await buildCookieValue(rule.account) if (!cookieValue) { continue } requestRules.push({ id: index + 1, priority: 1, action: { type: 'modifyHeaders', requestHeaders: [ { header: 'Cookie', operation: 'set', value: cookieValue, }, ], }, condition: { regexFilter: `${rule.urlPattern}|__account__=${rule.account}`, resourceTypes: RESOURCE_TYPES, }, }) } return requestRules } async function updateDynamicRequestRules() { if (!browser.declarativeNetRequest) { return } const existingRules = await browser.declarativeNetRequest.getDynamicRules() const removeRuleIds = existingRules.map((rule) => rule.id) const addRules = await buildAddRules() await browser.declarativeNetRequest.updateDynamicRules({ removeRuleIds, addRules, }) const rules = await browser.declarativeNetRequest.getDynamicRules() console.info('Current dynamic rules:', rules) } // Watch the requests, if the main_frame url matches any of the auto switch rules, switch to the account function watchAutoSwitchRequests() { browser.webRequest.onBeforeRequest.addListener( (details) => { ruleService.getAll().then((autoSwitchRules) => { for (const rule of autoSwitchRules) { if (new RegExp(rule.urlPattern).test(details.url)) { console.info('onBeforeRequest: found an auto switch rule for url', details.url, rule) return accountService.switchTo(rule.account) } } }) }, { urls: ['https://github.com/*'], types: ['main_frame'], }, ) } function watchCookies() { browser.cookies.onChanged.addListener(async (changeInfo) => { const { cookie, removed } = changeInfo // Ignore other cookies if (cookie.name !== 'dotcom_user') { return } if (removed) { if (cookie.name === 'dotcom_user') { console.info('dotcom_user cookie removed') await setBadgeText('...') } return } console.info('New dotcom_user cookie', cookie.value) await syncAccounts() }) } function handleMessage(message: RequestMessage) { const { type } = message switch (type) { case 'getAccounts': return accountService.getAllNames() case 'switchAccount': return accountService.switchTo(message.account) case 'removeAccount': return removeAccount(message.account) case 'clearCookies': return cookie.clear() case 'getAutoSwitchRules': return ruleService.getAll() } } function listenMessage() { browser.runtime.onMessage.addListener(
async (request: RequestMessage, _sender): Promise<Response<unknown>> => {
try { const data = await handleMessage(request) return { success: true, data } } catch (error: unknown) { return { success: false, error: error as Error } } }, ) } function interceptRequests() { browser.webRequest.onBeforeSendHeaders.addListener( async (details) => { if (!details.requestHeaders) { return { requestHeaders: details.requestHeaders } } const autoSwitchRules = await ruleService.getAll() for (const rule of autoSwitchRules) { const urlPattern = `${rule.urlPattern}|__account__=${rule.account}` if (new RegExp(urlPattern).test(details.url)) { const cookieValue = await buildCookieValue(rule.account) if (cookieValue) { for (const header of details.requestHeaders) { if (header.name.toLowerCase() === 'cookie') { header.value = cookieValue } } } console.info('interceptRequests: found an auto switch rule for url', details.url, rule) return { requestHeaders: details.requestHeaders } } } return { requestHeaders: details.requestHeaders } }, { urls: ['https://github.com/*'], types: RESOURCE_TYPES, }, ['blocking', 'requestHeaders'], ) } async function init() { await syncAccounts() watchAutoSwitchRequests() watchCookies() listenMessage() if (!browser.declarativeNetRequest) { interceptRequests() } /* chrome.declarativeNetRequest.onRuleMatchedDebug.addListener((info) => { console.info('onRuleMatchedDebug', info) })*/ } init()
src/background/index.ts
yuezk-github-account-switcher-36b3c11
[ { "filename": "src/content/index.ts", "retrieved_chunk": "async function getAutoSwitchRules() {\n const res: GetAutoSwitchRulesResponse = await browser.runtime.sendMessage({\n type: 'getAutoSwitchRules',\n } as GetAutoSwitchRulesMessage)\n return res?.success ? res.data : []\n}\nasync function addAccount() {\n await browser.runtime.sendMessage({ type: 'clearCookies' } as ClearCookiesMessage)\n const autoSwitchRules = await getAutoSwitchRules()\n window.location.href = isNormalGitHubUrl(window.location.href, autoSwitchRules)", "score": 0.81614089012146 }, { "filename": "src/shared.ts", "retrieved_chunk": " return false\n }\n if (urlMatchesAnyRule(url, rules)) {\n return false\n }\n return true\n}\nexport async function removeAccount(account: string) {\n await browser.runtime.sendMessage({ type: 'removeAccount', account })\n}", "score": 0.808086633682251 }, { "filename": "src/popup/components/Accounts.tsx", "retrieved_chunk": " const [tab] = await browser.tabs.query(queryOptions)\n return tab\n}\nexport default function Accounts() {\n const [accounts, setAccounts] = useState<Account[]>([])\n useEffect(() => {\n accountService.getAll().then(setAccounts)\n }, [])\n async function handleLogin() {\n await cookie.clear()", "score": 0.7955923080444336 }, { "filename": "src/services/account.ts", "retrieved_chunk": "async function find(accountName: string): Promise<Account | undefined> {\n const accounts = await getAll()\n return accounts.find((account) => account.name === accountName)\n}\nasync function upsert(accountName: string, cookies: Cookie[]) {\n await storage.update<Accounts>('accounts', (accounts = {}) => {\n accounts[accountName] = cookies\n return accounts\n })\n}", "score": 0.7763735055923462 }, { "filename": "src/services/account.ts", "retrieved_chunk": " })\n }\n if (cookies.length) {\n setBadgeText(accountName.slice(0, 2))\n } else {\n setBadgeText('...')\n }\n}\nasync function remove(accountName: string) {\n await storage.update<Accounts>('accounts', (accounts) => {", "score": 0.7740974426269531 } ]
typescript
async (request: RequestMessage, _sender): Promise<Response<unknown>> => {
import browser, { DeclarativeNetRequest } from 'webextension-polyfill' import accountService from '../services/account' import { setBadgeText } from '../services/badge' import cookie from '../services/cookie' import ruleService from '../services/rule' import { RequestMessage, Response } from '../types' const RESOURCE_TYPES: DeclarativeNetRequest.ResourceType[] = [ 'main_frame', 'sub_frame', 'csp_report', 'websocket', 'xmlhttprequest', ] async function syncAccounts() { const usernameCookie = await cookie.get('dotcom_user') const sessionCookie = await cookie.get('user_session') if (!usernameCookie || !sessionCookie) { return } const { value: account } = usernameCookie if (!account) { return } await accountService.upsert(account, await cookie.getAll()) const accounts = await accountService.getAll() console.info('synced accounts', accounts) await updateDynamicRequestRules() const res = await fetch(`https://github.com/${account}.png?size=100`) if (res.status === 200) { accountService.saveAvatar(account, res.url) } await setBadgeText(account.slice(0, 2)) } async function removeAccount(accountName: string) { await accountService.remove(accountName) await updateDynamicRequestRules() } async function buildCookieValue(accountName: string): Promise<string | null> { const account = await accountService.find(accountName) const cookies = account?.cookies || [] if (!cookies.length) { return null } return cookies .map((cookie) => `${cookie.name}=${cookie.value}`) .concat(`__account__=${accountName}`) .join('; ') } async function buildAddRules(): Promise<DeclarativeNetRequest.Rule[]> { const requestRules: DeclarativeNetRequest.Rule[] = [] const autoSwitchRules =
await ruleService.getAll() for (const [index, rule] of autoSwitchRules.entries()) {
const cookieValue = await buildCookieValue(rule.account) if (!cookieValue) { continue } requestRules.push({ id: index + 1, priority: 1, action: { type: 'modifyHeaders', requestHeaders: [ { header: 'Cookie', operation: 'set', value: cookieValue, }, ], }, condition: { regexFilter: `${rule.urlPattern}|__account__=${rule.account}`, resourceTypes: RESOURCE_TYPES, }, }) } return requestRules } async function updateDynamicRequestRules() { if (!browser.declarativeNetRequest) { return } const existingRules = await browser.declarativeNetRequest.getDynamicRules() const removeRuleIds = existingRules.map((rule) => rule.id) const addRules = await buildAddRules() await browser.declarativeNetRequest.updateDynamicRules({ removeRuleIds, addRules, }) const rules = await browser.declarativeNetRequest.getDynamicRules() console.info('Current dynamic rules:', rules) } // Watch the requests, if the main_frame url matches any of the auto switch rules, switch to the account function watchAutoSwitchRequests() { browser.webRequest.onBeforeRequest.addListener( (details) => { ruleService.getAll().then((autoSwitchRules) => { for (const rule of autoSwitchRules) { if (new RegExp(rule.urlPattern).test(details.url)) { console.info('onBeforeRequest: found an auto switch rule for url', details.url, rule) return accountService.switchTo(rule.account) } } }) }, { urls: ['https://github.com/*'], types: ['main_frame'], }, ) } function watchCookies() { browser.cookies.onChanged.addListener(async (changeInfo) => { const { cookie, removed } = changeInfo // Ignore other cookies if (cookie.name !== 'dotcom_user') { return } if (removed) { if (cookie.name === 'dotcom_user') { console.info('dotcom_user cookie removed') await setBadgeText('...') } return } console.info('New dotcom_user cookie', cookie.value) await syncAccounts() }) } function handleMessage(message: RequestMessage) { const { type } = message switch (type) { case 'getAccounts': return accountService.getAllNames() case 'switchAccount': return accountService.switchTo(message.account) case 'removeAccount': return removeAccount(message.account) case 'clearCookies': return cookie.clear() case 'getAutoSwitchRules': return ruleService.getAll() } } function listenMessage() { browser.runtime.onMessage.addListener( async (request: RequestMessage, _sender): Promise<Response<unknown>> => { try { const data = await handleMessage(request) return { success: true, data } } catch (error: unknown) { return { success: false, error: error as Error } } }, ) } function interceptRequests() { browser.webRequest.onBeforeSendHeaders.addListener( async (details) => { if (!details.requestHeaders) { return { requestHeaders: details.requestHeaders } } const autoSwitchRules = await ruleService.getAll() for (const rule of autoSwitchRules) { const urlPattern = `${rule.urlPattern}|__account__=${rule.account}` if (new RegExp(urlPattern).test(details.url)) { const cookieValue = await buildCookieValue(rule.account) if (cookieValue) { for (const header of details.requestHeaders) { if (header.name.toLowerCase() === 'cookie') { header.value = cookieValue } } } console.info('interceptRequests: found an auto switch rule for url', details.url, rule) return { requestHeaders: details.requestHeaders } } } return { requestHeaders: details.requestHeaders } }, { urls: ['https://github.com/*'], types: RESOURCE_TYPES, }, ['blocking', 'requestHeaders'], ) } async function init() { await syncAccounts() watchAutoSwitchRequests() watchCookies() listenMessage() if (!browser.declarativeNetRequest) { interceptRequests() } /* chrome.declarativeNetRequest.onRuleMatchedDebug.addListener((info) => { console.info('onRuleMatchedDebug', info) })*/ } init()
src/background/index.ts
yuezk-github-account-switcher-36b3c11
[ { "filename": "src/content/index.ts", "retrieved_chunk": "async function getAutoSwitchRules() {\n const res: GetAutoSwitchRulesResponse = await browser.runtime.sendMessage({\n type: 'getAutoSwitchRules',\n } as GetAutoSwitchRulesMessage)\n return res?.success ? res.data : []\n}\nasync function addAccount() {\n await browser.runtime.sendMessage({ type: 'clearCookies' } as ClearCookiesMessage)\n const autoSwitchRules = await getAutoSwitchRules()\n window.location.href = isNormalGitHubUrl(window.location.href, autoSwitchRules)", "score": 0.8014524579048157 }, { "filename": "src/services/rule.ts", "retrieved_chunk": "import storage from './storage'\nexport type Rule = {\n id: number\n urlPattern: string\n account: string\n}\nasync function getAll(): Promise<Rule[]> {\n const rules = await storage.get<Rule[]>('rules')\n return rules || []\n}", "score": 0.7885582447052002 }, { "filename": "src/services/rule.ts", "retrieved_chunk": "async function add(rule: Rule) {\n await storage.update<Rule[]>('rules', (rules = []) => {\n return [...rules, rule]\n })\n}\nasync function update(rule: Rule) {\n await storage.update<Rule[]>('rules', (rules = []) => {\n return rules.map((r) => (r.id === rule.id ? rule : r))\n })\n}", "score": 0.7836419343948364 }, { "filename": "src/services/account.ts", "retrieved_chunk": " expiresAt: userSessionCookie?.expirationDate\n ? new Date(userSessionCookie.expirationDate * 1000)\n : undefined,\n }\n })\n}\nasync function getAllNames(): Promise<string[]> {\n const accounts = await getAll()\n return accounts.map(({ name }) => name)\n}", "score": 0.7835155725479126 }, { "filename": "src/services/rule.ts", "retrieved_chunk": "async function remove(id: number) {\n await storage.update<Rule[]>('rules', (rules = []) => {\n return rules.filter((rule) => rule.id !== id)\n })\n}\nexport default {\n getAll,\n add,\n update,\n remove,", "score": 0.7790406942367554 } ]
typescript
await ruleService.getAll() for (const [index, rule] of autoSwitchRules.entries()) {
import { Close, Login, PersonAdd } from '@mui/icons-material' import { Alert, Avatar, Badge, Box, Button, IconButton, List, ListItem, ListItemAvatar, ListItemSecondaryAction, ListItemText, Tooltip, styled, } from '@mui/material' import { useEffect, useState } from 'react' import browser, { Tabs } from 'webextension-polyfill' import accountService, { Account } from '../../services/account' import cookie from '../../services/cookie' import rule from '../../services/rule' import { isGitHubUrl, isNormalGitHubUrl, removeAccount } from '../../shared' const StyledBadge = styled(Badge)(({ theme }) => ({ '& .MuiBadge-badge': { backgroundColor: '#44b700', color: '#44b700', boxShadow: `0 0 0 2px ${theme.palette.background.paper}`, '&::after': { position: 'absolute', top: 0, left: 0, width: '100%', height: '100%', borderRadius: '50%', animation: 'ripple 1.2s infinite ease-in-out', border: '1px solid currentColor', content: '""', }, }, '@keyframes ripple': { '0%': { transform: 'scale(.8)', opacity: 1, }, '100%': { transform: 'scale(2.4)', opacity: 0, }, }, })) function GitHubAvatar({ account }: { account: Account }) { const { name, active } = account const avatarUrl = account.avatarUrl ?? `https://github.com/${name}.png?size=100` const avatar = <Avatar src={avatarUrl} /> if (active) { return ( <StyledBadge overlap="circular" anchorOrigin={{ vertical: 'bottom', horizontal: 'right' }} variant="dot" > {avatar} </StyledBadge> ) } return avatar } async function getCurrentTab(): Promise<Tabs.Tab | undefined> { const queryOptions = { active: true, lastFocusedWindow: true } // `tab` will either be a `tabs.Tab` instance or `undefined`. const [tab] = await browser.tabs.query(queryOptions) return tab } export default function Accounts() { const [accounts, setAccounts] = useState<Account[]>([]) useEffect(() => { accountService.getAll().then(setAccounts) }, []) async function handleLogin() { await cookie.clear() const tab = await getCurrentTab()
const rules = await rule.getAll() if (isNormalGitHubUrl(tab?.url, rules)) {
await browser.tabs.update(tab?.id!, { url: `https://github.com/login?return_to=${encodeURIComponent(tab?.url ?? '')}`, }) } else if (isGitHubUrl(tab?.url)) { await browser.tabs.update(tab?.id!, { url: 'https://github.com/login' }) } else { await browser.tabs.create({ url: 'https://github.com/login' }) } window.close() } async function handleSwitch(username: string) { await accountService.switchTo(username) const tab = await getCurrentTab() const rules = await rule.getAll() // If the current tab is a normal GitHub page, reload it. if (isNormalGitHubUrl(tab?.url, rules)) { await browser.tabs.reload(tab?.id!) } else if (isGitHubUrl(tab?.url)) { await browser.tabs.update(tab?.id!, { url: 'https://github.com' }) } else { await browser.tabs.create({ url: 'https://github.com' }) } window.close() } async function handleRemove(accountName: string) { await removeAccount(accountName) setAccounts(accounts.filter((account) => account.name !== accountName)) } return ( <Box> <Alert severity="info" sx={{ mb: 2 }}> You can manage your logged in accounts here. </Alert> <Box sx={{ mb: 1 }}> <List dense disablePadding> {accounts.map((account, i) => ( <ListItem key={account.name} disableGutters divider={i !== accounts.length - 1}> <ListItemAvatar> <GitHubAvatar account={account} /> </ListItemAvatar> <ListItemText primary={account.name} secondary={account.expiresAt && `Expires at ${account.expiresAt.toLocaleString()}`} /> <ListItemSecondaryAction> <Tooltip title={`Switch to ${account.name}`}> <span> <IconButton color="primary" disabled={account.active} onClick={() => handleSwitch(account.name)} > <Login /> </IconButton> </span> </Tooltip> <Tooltip title={`Remove ${account.name}`} onClick={() => handleRemove(account.name)} > <IconButton color="warning"> <Close /> </IconButton> </Tooltip> </ListItemSecondaryAction> </ListItem> ))} </List> </Box> <Button variant="contained" sx={{ textTransform: 'none' }} startIcon={<PersonAdd />} onClick={handleLogin} > Login Another Account </Button> </Box> ) }
src/popup/components/Accounts.tsx
yuezk-github-account-switcher-36b3c11
[ { "filename": "src/services/account.ts", "retrieved_chunk": "async function find(accountName: string): Promise<Account | undefined> {\n const accounts = await getAll()\n return accounts.find((account) => account.name === accountName)\n}\nasync function upsert(accountName: string, cookies: Cookie[]) {\n await storage.update<Accounts>('accounts', (accounts = {}) => {\n accounts[accountName] = cookies\n return accounts\n })\n}", "score": 0.8495569229125977 }, { "filename": "src/services/account.ts", "retrieved_chunk": " expiresAt?: Date\n}\ntype Accounts = Record<string, Cookie[]>\nasync function getAll(): Promise<Account[]> {\n const accounts = await storage.get<Accounts>('accounts')\n if (!accounts) {\n return []\n }\n const currentAccount = await browser.cookies.get({\n url: 'https://github.com',", "score": 0.8427497148513794 }, { "filename": "src/background/index.ts", "retrieved_chunk": " }\n await setBadgeText(account.slice(0, 2))\n}\nasync function removeAccount(accountName: string) {\n await accountService.remove(accountName)\n await updateDynamicRequestRules()\n}\nasync function buildCookieValue(accountName: string): Promise<string | null> {\n const account = await accountService.find(accountName)\n const cookies = account?.cookies || []", "score": 0.8371801972389221 }, { "filename": "src/services/account.ts", "retrieved_chunk": "async function switchTo(accountName: string) {\n await cookie.clear()\n const account = await find(accountName)\n const cookies = account?.cookies || []\n for (const cookie of cookies) {\n const { hostOnly, domain, session, ...rest } = cookie\n await browser.cookies.set({\n url: 'https://github.com',\n domain: hostOnly ? undefined : domain,\n ...rest,", "score": 0.827121376991272 }, { "filename": "src/content/index.ts", "retrieved_chunk": "async function getAutoSwitchRules() {\n const res: GetAutoSwitchRulesResponse = await browser.runtime.sendMessage({\n type: 'getAutoSwitchRules',\n } as GetAutoSwitchRulesMessage)\n return res?.success ? res.data : []\n}\nasync function addAccount() {\n await browser.runtime.sendMessage({ type: 'clearCookies' } as ClearCookiesMessage)\n const autoSwitchRules = await getAutoSwitchRules()\n window.location.href = isNormalGitHubUrl(window.location.href, autoSwitchRules)", "score": 0.8195394277572632 } ]
typescript
const rules = await rule.getAll() if (isNormalGitHubUrl(tab?.url, rules)) {
import browser, { DeclarativeNetRequest } from 'webextension-polyfill' import accountService from '../services/account' import { setBadgeText } from '../services/badge' import cookie from '../services/cookie' import ruleService from '../services/rule' import { RequestMessage, Response } from '../types' const RESOURCE_TYPES: DeclarativeNetRequest.ResourceType[] = [ 'main_frame', 'sub_frame', 'csp_report', 'websocket', 'xmlhttprequest', ] async function syncAccounts() { const usernameCookie = await cookie.get('dotcom_user') const sessionCookie = await cookie.get('user_session') if (!usernameCookie || !sessionCookie) { return } const { value: account } = usernameCookie if (!account) { return } await accountService.upsert(account, await cookie.getAll()) const accounts = await accountService.getAll() console.info('synced accounts', accounts) await updateDynamicRequestRules() const res = await fetch(`https://github.com/${account}.png?size=100`) if (res.status === 200) { accountService.saveAvatar(account, res.url) } await setBadgeText(account.slice(0, 2)) } async function removeAccount(accountName: string) { await accountService.remove(accountName) await updateDynamicRequestRules() } async function buildCookieValue(accountName: string): Promise<string | null> {
const account = await accountService.find(accountName) const cookies = account?.cookies || [] if (!cookies.length) {
return null } return cookies .map((cookie) => `${cookie.name}=${cookie.value}`) .concat(`__account__=${accountName}`) .join('; ') } async function buildAddRules(): Promise<DeclarativeNetRequest.Rule[]> { const requestRules: DeclarativeNetRequest.Rule[] = [] const autoSwitchRules = await ruleService.getAll() for (const [index, rule] of autoSwitchRules.entries()) { const cookieValue = await buildCookieValue(rule.account) if (!cookieValue) { continue } requestRules.push({ id: index + 1, priority: 1, action: { type: 'modifyHeaders', requestHeaders: [ { header: 'Cookie', operation: 'set', value: cookieValue, }, ], }, condition: { regexFilter: `${rule.urlPattern}|__account__=${rule.account}`, resourceTypes: RESOURCE_TYPES, }, }) } return requestRules } async function updateDynamicRequestRules() { if (!browser.declarativeNetRequest) { return } const existingRules = await browser.declarativeNetRequest.getDynamicRules() const removeRuleIds = existingRules.map((rule) => rule.id) const addRules = await buildAddRules() await browser.declarativeNetRequest.updateDynamicRules({ removeRuleIds, addRules, }) const rules = await browser.declarativeNetRequest.getDynamicRules() console.info('Current dynamic rules:', rules) } // Watch the requests, if the main_frame url matches any of the auto switch rules, switch to the account function watchAutoSwitchRequests() { browser.webRequest.onBeforeRequest.addListener( (details) => { ruleService.getAll().then((autoSwitchRules) => { for (const rule of autoSwitchRules) { if (new RegExp(rule.urlPattern).test(details.url)) { console.info('onBeforeRequest: found an auto switch rule for url', details.url, rule) return accountService.switchTo(rule.account) } } }) }, { urls: ['https://github.com/*'], types: ['main_frame'], }, ) } function watchCookies() { browser.cookies.onChanged.addListener(async (changeInfo) => { const { cookie, removed } = changeInfo // Ignore other cookies if (cookie.name !== 'dotcom_user') { return } if (removed) { if (cookie.name === 'dotcom_user') { console.info('dotcom_user cookie removed') await setBadgeText('...') } return } console.info('New dotcom_user cookie', cookie.value) await syncAccounts() }) } function handleMessage(message: RequestMessage) { const { type } = message switch (type) { case 'getAccounts': return accountService.getAllNames() case 'switchAccount': return accountService.switchTo(message.account) case 'removeAccount': return removeAccount(message.account) case 'clearCookies': return cookie.clear() case 'getAutoSwitchRules': return ruleService.getAll() } } function listenMessage() { browser.runtime.onMessage.addListener( async (request: RequestMessage, _sender): Promise<Response<unknown>> => { try { const data = await handleMessage(request) return { success: true, data } } catch (error: unknown) { return { success: false, error: error as Error } } }, ) } function interceptRequests() { browser.webRequest.onBeforeSendHeaders.addListener( async (details) => { if (!details.requestHeaders) { return { requestHeaders: details.requestHeaders } } const autoSwitchRules = await ruleService.getAll() for (const rule of autoSwitchRules) { const urlPattern = `${rule.urlPattern}|__account__=${rule.account}` if (new RegExp(urlPattern).test(details.url)) { const cookieValue = await buildCookieValue(rule.account) if (cookieValue) { for (const header of details.requestHeaders) { if (header.name.toLowerCase() === 'cookie') { header.value = cookieValue } } } console.info('interceptRequests: found an auto switch rule for url', details.url, rule) return { requestHeaders: details.requestHeaders } } } return { requestHeaders: details.requestHeaders } }, { urls: ['https://github.com/*'], types: RESOURCE_TYPES, }, ['blocking', 'requestHeaders'], ) } async function init() { await syncAccounts() watchAutoSwitchRequests() watchCookies() listenMessage() if (!browser.declarativeNetRequest) { interceptRequests() } /* chrome.declarativeNetRequest.onRuleMatchedDebug.addListener((info) => { console.info('onRuleMatchedDebug', info) })*/ } init()
src/background/index.ts
yuezk-github-account-switcher-36b3c11
[ { "filename": "src/services/account.ts", "retrieved_chunk": "async function find(accountName: string): Promise<Account | undefined> {\n const accounts = await getAll()\n return accounts.find((account) => account.name === accountName)\n}\nasync function upsert(accountName: string, cookies: Cookie[]) {\n await storage.update<Accounts>('accounts', (accounts = {}) => {\n accounts[accountName] = cookies\n return accounts\n })\n}", "score": 0.8951032161712646 }, { "filename": "src/services/account.ts", "retrieved_chunk": " expiresAt?: Date\n}\ntype Accounts = Record<string, Cookie[]>\nasync function getAll(): Promise<Account[]> {\n const accounts = await storage.get<Accounts>('accounts')\n if (!accounts) {\n return []\n }\n const currentAccount = await browser.cookies.get({\n url: 'https://github.com',", "score": 0.8674815893173218 }, { "filename": "src/services/account.ts", "retrieved_chunk": " })\n }\n if (cookies.length) {\n setBadgeText(accountName.slice(0, 2))\n } else {\n setBadgeText('...')\n }\n}\nasync function remove(accountName: string) {\n await storage.update<Accounts>('accounts', (accounts) => {", "score": 0.8521215915679932 }, { "filename": "src/services/account.ts", "retrieved_chunk": " if (!accounts) {\n return\n }\n delete accounts[accountName]\n return accounts\n })\n}\nasync function saveAvatar(accountName: string, avatarUrl: string) {\n await storage.update<Record<string, string>>('avatars', (avatars = {}) => {\n avatars[accountName] = avatarUrl", "score": 0.8478456139564514 }, { "filename": "src/services/account.ts", "retrieved_chunk": " expiresAt: userSessionCookie?.expirationDate\n ? new Date(userSessionCookie.expirationDate * 1000)\n : undefined,\n }\n })\n}\nasync function getAllNames(): Promise<string[]> {\n const accounts = await getAll()\n return accounts.map(({ name }) => name)\n}", "score": 0.8457773923873901 } ]
typescript
const account = await accountService.find(accountName) const cookies = account?.cookies || [] if (!cookies.length) {
import { Close, Login, PersonAdd } from '@mui/icons-material' import { Alert, Avatar, Badge, Box, Button, IconButton, List, ListItem, ListItemAvatar, ListItemSecondaryAction, ListItemText, Tooltip, styled, } from '@mui/material' import { useEffect, useState } from 'react' import browser, { Tabs } from 'webextension-polyfill' import accountService, { Account } from '../../services/account' import cookie from '../../services/cookie' import rule from '../../services/rule' import { isGitHubUrl, isNormalGitHubUrl, removeAccount } from '../../shared' const StyledBadge = styled(Badge)(({ theme }) => ({ '& .MuiBadge-badge': { backgroundColor: '#44b700', color: '#44b700', boxShadow: `0 0 0 2px ${theme.palette.background.paper}`, '&::after': { position: 'absolute', top: 0, left: 0, width: '100%', height: '100%', borderRadius: '50%', animation: 'ripple 1.2s infinite ease-in-out', border: '1px solid currentColor', content: '""', }, }, '@keyframes ripple': { '0%': { transform: 'scale(.8)', opacity: 1, }, '100%': { transform: 'scale(2.4)', opacity: 0, }, }, })) function GitHubAvatar({ account }: { account: Account }) { const { name, active } = account const avatarUrl = account.avatarUrl ?? `https://github.com/${name}.png?size=100` const avatar = <Avatar src={avatarUrl} /> if (active) { return ( <StyledBadge overlap="circular" anchorOrigin={{ vertical: 'bottom', horizontal: 'right' }} variant="dot" > {avatar} </StyledBadge> ) } return avatar } async function getCurrentTab(): Promise<Tabs.Tab | undefined> { const queryOptions = { active: true, lastFocusedWindow: true } // `tab` will either be a `tabs.Tab` instance or `undefined`. const [tab] = await browser.tabs.query(queryOptions) return tab } export default function Accounts() { const [accounts, setAccounts] = useState<Account[]>([]) useEffect(() => { accountService.getAll().then(setAccounts) }, []) async function handleLogin() { await cookie.clear() const tab = await getCurrentTab() const rules = await rule.getAll()
if (isNormalGitHubUrl(tab?.url, rules)) {
await browser.tabs.update(tab?.id!, { url: `https://github.com/login?return_to=${encodeURIComponent(tab?.url ?? '')}`, }) } else if (isGitHubUrl(tab?.url)) { await browser.tabs.update(tab?.id!, { url: 'https://github.com/login' }) } else { await browser.tabs.create({ url: 'https://github.com/login' }) } window.close() } async function handleSwitch(username: string) { await accountService.switchTo(username) const tab = await getCurrentTab() const rules = await rule.getAll() // If the current tab is a normal GitHub page, reload it. if (isNormalGitHubUrl(tab?.url, rules)) { await browser.tabs.reload(tab?.id!) } else if (isGitHubUrl(tab?.url)) { await browser.tabs.update(tab?.id!, { url: 'https://github.com' }) } else { await browser.tabs.create({ url: 'https://github.com' }) } window.close() } async function handleRemove(accountName: string) { await removeAccount(accountName) setAccounts(accounts.filter((account) => account.name !== accountName)) } return ( <Box> <Alert severity="info" sx={{ mb: 2 }}> You can manage your logged in accounts here. </Alert> <Box sx={{ mb: 1 }}> <List dense disablePadding> {accounts.map((account, i) => ( <ListItem key={account.name} disableGutters divider={i !== accounts.length - 1}> <ListItemAvatar> <GitHubAvatar account={account} /> </ListItemAvatar> <ListItemText primary={account.name} secondary={account.expiresAt && `Expires at ${account.expiresAt.toLocaleString()}`} /> <ListItemSecondaryAction> <Tooltip title={`Switch to ${account.name}`}> <span> <IconButton color="primary" disabled={account.active} onClick={() => handleSwitch(account.name)} > <Login /> </IconButton> </span> </Tooltip> <Tooltip title={`Remove ${account.name}`} onClick={() => handleRemove(account.name)} > <IconButton color="warning"> <Close /> </IconButton> </Tooltip> </ListItemSecondaryAction> </ListItem> ))} </List> </Box> <Button variant="contained" sx={{ textTransform: 'none' }} startIcon={<PersonAdd />} onClick={handleLogin} > Login Another Account </Button> </Box> ) }
src/popup/components/Accounts.tsx
yuezk-github-account-switcher-36b3c11
[ { "filename": "src/services/account.ts", "retrieved_chunk": "async function find(accountName: string): Promise<Account | undefined> {\n const accounts = await getAll()\n return accounts.find((account) => account.name === accountName)\n}\nasync function upsert(accountName: string, cookies: Cookie[]) {\n await storage.update<Accounts>('accounts', (accounts = {}) => {\n accounts[accountName] = cookies\n return accounts\n })\n}", "score": 0.8495569229125977 }, { "filename": "src/services/account.ts", "retrieved_chunk": " expiresAt?: Date\n}\ntype Accounts = Record<string, Cookie[]>\nasync function getAll(): Promise<Account[]> {\n const accounts = await storage.get<Accounts>('accounts')\n if (!accounts) {\n return []\n }\n const currentAccount = await browser.cookies.get({\n url: 'https://github.com',", "score": 0.8427497148513794 }, { "filename": "src/background/index.ts", "retrieved_chunk": " }\n await setBadgeText(account.slice(0, 2))\n}\nasync function removeAccount(accountName: string) {\n await accountService.remove(accountName)\n await updateDynamicRequestRules()\n}\nasync function buildCookieValue(accountName: string): Promise<string | null> {\n const account = await accountService.find(accountName)\n const cookies = account?.cookies || []", "score": 0.8371801972389221 }, { "filename": "src/services/account.ts", "retrieved_chunk": "async function switchTo(accountName: string) {\n await cookie.clear()\n const account = await find(accountName)\n const cookies = account?.cookies || []\n for (const cookie of cookies) {\n const { hostOnly, domain, session, ...rest } = cookie\n await browser.cookies.set({\n url: 'https://github.com',\n domain: hostOnly ? undefined : domain,\n ...rest,", "score": 0.827121376991272 }, { "filename": "src/content/index.ts", "retrieved_chunk": "async function getAutoSwitchRules() {\n const res: GetAutoSwitchRulesResponse = await browser.runtime.sendMessage({\n type: 'getAutoSwitchRules',\n } as GetAutoSwitchRulesMessage)\n return res?.success ? res.data : []\n}\nasync function addAccount() {\n await browser.runtime.sendMessage({ type: 'clearCookies' } as ClearCookiesMessage)\n const autoSwitchRules = await getAutoSwitchRules()\n window.location.href = isNormalGitHubUrl(window.location.href, autoSwitchRules)", "score": 0.8195394277572632 } ]
typescript
if (isNormalGitHubUrl(tab?.url, rules)) {
import browser, { DeclarativeNetRequest } from 'webextension-polyfill' import accountService from '../services/account' import { setBadgeText } from '../services/badge' import cookie from '../services/cookie' import ruleService from '../services/rule' import { RequestMessage, Response } from '../types' const RESOURCE_TYPES: DeclarativeNetRequest.ResourceType[] = [ 'main_frame', 'sub_frame', 'csp_report', 'websocket', 'xmlhttprequest', ] async function syncAccounts() { const usernameCookie = await cookie.get('dotcom_user') const sessionCookie = await cookie.get('user_session') if (!usernameCookie || !sessionCookie) { return } const { value: account } = usernameCookie if (!account) { return } await accountService.upsert(account, await cookie.getAll()) const accounts = await accountService.getAll() console.info('synced accounts', accounts) await updateDynamicRequestRules() const res = await fetch(`https://github.com/${account}.png?size=100`) if (res.status === 200) { accountService.saveAvatar(account, res.url) } await setBadgeText(account.slice(0, 2)) } async function removeAccount(accountName: string) { await accountService.remove(accountName) await updateDynamicRequestRules() } async function buildCookieValue(accountName: string): Promise<string | null> { const account = await accountService.find(accountName) const cookies = account?.cookies || [] if (!cookies.length) { return null } return cookies .map((cookie) => `${cookie.name}=${cookie.value}`) .concat(`__account__=${accountName}`) .join('; ') } async function buildAddRules(): Promise<DeclarativeNetRequest.Rule[]> { const requestRules: DeclarativeNetRequest.Rule[] = []
const autoSwitchRules = await ruleService.getAll() for (const [index, rule] of autoSwitchRules.entries()) {
const cookieValue = await buildCookieValue(rule.account) if (!cookieValue) { continue } requestRules.push({ id: index + 1, priority: 1, action: { type: 'modifyHeaders', requestHeaders: [ { header: 'Cookie', operation: 'set', value: cookieValue, }, ], }, condition: { regexFilter: `${rule.urlPattern}|__account__=${rule.account}`, resourceTypes: RESOURCE_TYPES, }, }) } return requestRules } async function updateDynamicRequestRules() { if (!browser.declarativeNetRequest) { return } const existingRules = await browser.declarativeNetRequest.getDynamicRules() const removeRuleIds = existingRules.map((rule) => rule.id) const addRules = await buildAddRules() await browser.declarativeNetRequest.updateDynamicRules({ removeRuleIds, addRules, }) const rules = await browser.declarativeNetRequest.getDynamicRules() console.info('Current dynamic rules:', rules) } // Watch the requests, if the main_frame url matches any of the auto switch rules, switch to the account function watchAutoSwitchRequests() { browser.webRequest.onBeforeRequest.addListener( (details) => { ruleService.getAll().then((autoSwitchRules) => { for (const rule of autoSwitchRules) { if (new RegExp(rule.urlPattern).test(details.url)) { console.info('onBeforeRequest: found an auto switch rule for url', details.url, rule) return accountService.switchTo(rule.account) } } }) }, { urls: ['https://github.com/*'], types: ['main_frame'], }, ) } function watchCookies() { browser.cookies.onChanged.addListener(async (changeInfo) => { const { cookie, removed } = changeInfo // Ignore other cookies if (cookie.name !== 'dotcom_user') { return } if (removed) { if (cookie.name === 'dotcom_user') { console.info('dotcom_user cookie removed') await setBadgeText('...') } return } console.info('New dotcom_user cookie', cookie.value) await syncAccounts() }) } function handleMessage(message: RequestMessage) { const { type } = message switch (type) { case 'getAccounts': return accountService.getAllNames() case 'switchAccount': return accountService.switchTo(message.account) case 'removeAccount': return removeAccount(message.account) case 'clearCookies': return cookie.clear() case 'getAutoSwitchRules': return ruleService.getAll() } } function listenMessage() { browser.runtime.onMessage.addListener( async (request: RequestMessage, _sender): Promise<Response<unknown>> => { try { const data = await handleMessage(request) return { success: true, data } } catch (error: unknown) { return { success: false, error: error as Error } } }, ) } function interceptRequests() { browser.webRequest.onBeforeSendHeaders.addListener( async (details) => { if (!details.requestHeaders) { return { requestHeaders: details.requestHeaders } } const autoSwitchRules = await ruleService.getAll() for (const rule of autoSwitchRules) { const urlPattern = `${rule.urlPattern}|__account__=${rule.account}` if (new RegExp(urlPattern).test(details.url)) { const cookieValue = await buildCookieValue(rule.account) if (cookieValue) { for (const header of details.requestHeaders) { if (header.name.toLowerCase() === 'cookie') { header.value = cookieValue } } } console.info('interceptRequests: found an auto switch rule for url', details.url, rule) return { requestHeaders: details.requestHeaders } } } return { requestHeaders: details.requestHeaders } }, { urls: ['https://github.com/*'], types: RESOURCE_TYPES, }, ['blocking', 'requestHeaders'], ) } async function init() { await syncAccounts() watchAutoSwitchRequests() watchCookies() listenMessage() if (!browser.declarativeNetRequest) { interceptRequests() } /* chrome.declarativeNetRequest.onRuleMatchedDebug.addListener((info) => { console.info('onRuleMatchedDebug', info) })*/ } init()
src/background/index.ts
yuezk-github-account-switcher-36b3c11
[ { "filename": "src/content/index.ts", "retrieved_chunk": "async function getAutoSwitchRules() {\n const res: GetAutoSwitchRulesResponse = await browser.runtime.sendMessage({\n type: 'getAutoSwitchRules',\n } as GetAutoSwitchRulesMessage)\n return res?.success ? res.data : []\n}\nasync function addAccount() {\n await browser.runtime.sendMessage({ type: 'clearCookies' } as ClearCookiesMessage)\n const autoSwitchRules = await getAutoSwitchRules()\n window.location.href = isNormalGitHubUrl(window.location.href, autoSwitchRules)", "score": 0.8078904151916504 }, { "filename": "src/services/account.ts", "retrieved_chunk": " expiresAt: userSessionCookie?.expirationDate\n ? new Date(userSessionCookie.expirationDate * 1000)\n : undefined,\n }\n })\n}\nasync function getAllNames(): Promise<string[]> {\n const accounts = await getAll()\n return accounts.map(({ name }) => name)\n}", "score": 0.7874419689178467 }, { "filename": "src/services/rule.ts", "retrieved_chunk": "import storage from './storage'\nexport type Rule = {\n id: number\n urlPattern: string\n account: string\n}\nasync function getAll(): Promise<Rule[]> {\n const rules = await storage.get<Rule[]>('rules')\n return rules || []\n}", "score": 0.7869577407836914 }, { "filename": "src/services/account.ts", "retrieved_chunk": "async function find(accountName: string): Promise<Account | undefined> {\n const accounts = await getAll()\n return accounts.find((account) => account.name === accountName)\n}\nasync function upsert(accountName: string, cookies: Cookie[]) {\n await storage.update<Accounts>('accounts', (accounts = {}) => {\n accounts[accountName] = cookies\n return accounts\n })\n}", "score": 0.7813613414764404 }, { "filename": "src/services/rule.ts", "retrieved_chunk": "async function add(rule: Rule) {\n await storage.update<Rule[]>('rules', (rules = []) => {\n return [...rules, rule]\n })\n}\nasync function update(rule: Rule) {\n await storage.update<Rule[]>('rules', (rules = []) => {\n return rules.map((r) => (r.id === rule.id ? rule : r))\n })\n}", "score": 0.7799407839775085 } ]
typescript
const autoSwitchRules = await ruleService.getAll() for (const [index, rule] of autoSwitchRules.entries()) {
import browser, { DeclarativeNetRequest } from 'webextension-polyfill' import accountService from '../services/account' import { setBadgeText } from '../services/badge' import cookie from '../services/cookie' import ruleService from '../services/rule' import { RequestMessage, Response } from '../types' const RESOURCE_TYPES: DeclarativeNetRequest.ResourceType[] = [ 'main_frame', 'sub_frame', 'csp_report', 'websocket', 'xmlhttprequest', ] async function syncAccounts() { const usernameCookie = await cookie.get('dotcom_user') const sessionCookie = await cookie.get('user_session') if (!usernameCookie || !sessionCookie) { return } const { value: account } = usernameCookie if (!account) { return } await accountService.upsert(account, await cookie.getAll()) const accounts = await accountService.getAll() console.info('synced accounts', accounts) await updateDynamicRequestRules() const res = await fetch(`https://github.com/${account}.png?size=100`) if (res.status === 200) { accountService.saveAvatar(account, res.url) } await setBadgeText(account.slice(0, 2)) } async function removeAccount(accountName: string) { await accountService.remove(accountName) await updateDynamicRequestRules() } async function buildCookieValue(accountName: string): Promise<string | null> { const account = await accountService.find(accountName) const cookies = account?.cookies || [] if (!cookies.length) { return null } return cookies .map((cookie) => `${cookie.name}=${cookie.value}`) .concat(`__account__=${accountName}`) .join('; ') } async function buildAddRules(): Promise<DeclarativeNetRequest.Rule[]> { const requestRules: DeclarativeNetRequest.Rule[] = [] const autoSwitchRules = await ruleService.getAll() for (const [index, rule] of autoSwitchRules.entries()) { const cookieValue = await buildCookieValue(rule.account) if (!cookieValue) { continue } requestRules.push({ id: index + 1, priority: 1, action: { type: 'modifyHeaders', requestHeaders: [ { header: 'Cookie', operation: 'set', value: cookieValue, }, ], }, condition: { regexFilter: `${rule.urlPattern}|__account__=${rule.account}`, resourceTypes: RESOURCE_TYPES, }, }) } return requestRules } async function updateDynamicRequestRules() { if (!browser.declarativeNetRequest) { return } const existingRules = await browser.declarativeNetRequest.getDynamicRules() const removeRuleIds = existingRules.map((rule) => rule.id) const addRules = await buildAddRules() await browser.declarativeNetRequest.updateDynamicRules({ removeRuleIds, addRules, }) const rules = await browser.declarativeNetRequest.getDynamicRules() console.info('Current dynamic rules:', rules) } // Watch the requests, if the main_frame url matches any of the auto switch rules, switch to the account function watchAutoSwitchRequests() { browser.webRequest.onBeforeRequest.addListener( (details) => {
ruleService.getAll().then((autoSwitchRules) => {
for (const rule of autoSwitchRules) { if (new RegExp(rule.urlPattern).test(details.url)) { console.info('onBeforeRequest: found an auto switch rule for url', details.url, rule) return accountService.switchTo(rule.account) } } }) }, { urls: ['https://github.com/*'], types: ['main_frame'], }, ) } function watchCookies() { browser.cookies.onChanged.addListener(async (changeInfo) => { const { cookie, removed } = changeInfo // Ignore other cookies if (cookie.name !== 'dotcom_user') { return } if (removed) { if (cookie.name === 'dotcom_user') { console.info('dotcom_user cookie removed') await setBadgeText('...') } return } console.info('New dotcom_user cookie', cookie.value) await syncAccounts() }) } function handleMessage(message: RequestMessage) { const { type } = message switch (type) { case 'getAccounts': return accountService.getAllNames() case 'switchAccount': return accountService.switchTo(message.account) case 'removeAccount': return removeAccount(message.account) case 'clearCookies': return cookie.clear() case 'getAutoSwitchRules': return ruleService.getAll() } } function listenMessage() { browser.runtime.onMessage.addListener( async (request: RequestMessage, _sender): Promise<Response<unknown>> => { try { const data = await handleMessage(request) return { success: true, data } } catch (error: unknown) { return { success: false, error: error as Error } } }, ) } function interceptRequests() { browser.webRequest.onBeforeSendHeaders.addListener( async (details) => { if (!details.requestHeaders) { return { requestHeaders: details.requestHeaders } } const autoSwitchRules = await ruleService.getAll() for (const rule of autoSwitchRules) { const urlPattern = `${rule.urlPattern}|__account__=${rule.account}` if (new RegExp(urlPattern).test(details.url)) { const cookieValue = await buildCookieValue(rule.account) if (cookieValue) { for (const header of details.requestHeaders) { if (header.name.toLowerCase() === 'cookie') { header.value = cookieValue } } } console.info('interceptRequests: found an auto switch rule for url', details.url, rule) return { requestHeaders: details.requestHeaders } } } return { requestHeaders: details.requestHeaders } }, { urls: ['https://github.com/*'], types: RESOURCE_TYPES, }, ['blocking', 'requestHeaders'], ) } async function init() { await syncAccounts() watchAutoSwitchRequests() watchCookies() listenMessage() if (!browser.declarativeNetRequest) { interceptRequests() } /* chrome.declarativeNetRequest.onRuleMatchedDebug.addListener((info) => { console.info('onRuleMatchedDebug', info) })*/ } init()
src/background/index.ts
yuezk-github-account-switcher-36b3c11
[ { "filename": "src/popup/components/Accounts.tsx", "retrieved_chunk": " }\n window.close()\n }\n async function handleSwitch(username: string) {\n await accountService.switchTo(username)\n const tab = await getCurrentTab()\n const rules = await rule.getAll()\n // If the current tab is a normal GitHub page, reload it.\n if (isNormalGitHubUrl(tab?.url, rules)) {\n await browser.tabs.reload(tab?.id!)", "score": 0.8089733123779297 }, { "filename": "src/content/index.ts", "retrieved_chunk": "async function getAutoSwitchRules() {\n const res: GetAutoSwitchRulesResponse = await browser.runtime.sendMessage({\n type: 'getAutoSwitchRules',\n } as GetAutoSwitchRulesMessage)\n return res?.success ? res.data : []\n}\nasync function addAccount() {\n await browser.runtime.sendMessage({ type: 'clearCookies' } as ClearCookiesMessage)\n const autoSwitchRules = await getAutoSwitchRules()\n window.location.href = isNormalGitHubUrl(window.location.href, autoSwitchRules)", "score": 0.8071062564849854 }, { "filename": "src/popup/components/AutoSwitchRules.tsx", "retrieved_chunk": " }, [])\n function startAdding() {\n setIsAdding(true)\n }\n function stopAdding() {\n setIsAdding(false)\n }\n async function addRule(rule: Rule) {\n await ruleService.add(rule)\n setRules(await ruleService.getAll())", "score": 0.7514855861663818 }, { "filename": "src/shared.ts", "retrieved_chunk": " return false\n }\n if (urlMatchesAnyRule(url, rules)) {\n return false\n }\n return true\n}\nexport async function removeAccount(account: string) {\n await browser.runtime.sendMessage({ type: 'removeAccount', account })\n}", "score": 0.7486791610717773 }, { "filename": "src/content/index.ts", "retrieved_chunk": " ? `/login?return_to=${encodeURIComponent(window.location.href)}`\n : '/login'\n}\nasync function switchAccount(account: string) {\n await browser.runtime.sendMessage({ type: 'switchAccount', account })\n const autoSwitchRules = await getAutoSwitchRules()\n if (isNormalGitHubUrl(window.location.href, autoSwitchRules)) {\n window.location.reload()\n } else {\n window.location.href = '/'", "score": 0.7484891414642334 } ]
typescript
ruleService.getAll().then((autoSwitchRules) => {
import { Close, Login, PersonAdd } from '@mui/icons-material' import { Alert, Avatar, Badge, Box, Button, IconButton, List, ListItem, ListItemAvatar, ListItemSecondaryAction, ListItemText, Tooltip, styled, } from '@mui/material' import { useEffect, useState } from 'react' import browser, { Tabs } from 'webextension-polyfill' import accountService, { Account } from '../../services/account' import cookie from '../../services/cookie' import rule from '../../services/rule' import { isGitHubUrl, isNormalGitHubUrl, removeAccount } from '../../shared' const StyledBadge = styled(Badge)(({ theme }) => ({ '& .MuiBadge-badge': { backgroundColor: '#44b700', color: '#44b700', boxShadow: `0 0 0 2px ${theme.palette.background.paper}`, '&::after': { position: 'absolute', top: 0, left: 0, width: '100%', height: '100%', borderRadius: '50%', animation: 'ripple 1.2s infinite ease-in-out', border: '1px solid currentColor', content: '""', }, }, '@keyframes ripple': { '0%': { transform: 'scale(.8)', opacity: 1, }, '100%': { transform: 'scale(2.4)', opacity: 0, }, }, }))
function GitHubAvatar({ account }: { account: Account }) {
const { name, active } = account const avatarUrl = account.avatarUrl ?? `https://github.com/${name}.png?size=100` const avatar = <Avatar src={avatarUrl} /> if (active) { return ( <StyledBadge overlap="circular" anchorOrigin={{ vertical: 'bottom', horizontal: 'right' }} variant="dot" > {avatar} </StyledBadge> ) } return avatar } async function getCurrentTab(): Promise<Tabs.Tab | undefined> { const queryOptions = { active: true, lastFocusedWindow: true } // `tab` will either be a `tabs.Tab` instance or `undefined`. const [tab] = await browser.tabs.query(queryOptions) return tab } export default function Accounts() { const [accounts, setAccounts] = useState<Account[]>([]) useEffect(() => { accountService.getAll().then(setAccounts) }, []) async function handleLogin() { await cookie.clear() const tab = await getCurrentTab() const rules = await rule.getAll() if (isNormalGitHubUrl(tab?.url, rules)) { await browser.tabs.update(tab?.id!, { url: `https://github.com/login?return_to=${encodeURIComponent(tab?.url ?? '')}`, }) } else if (isGitHubUrl(tab?.url)) { await browser.tabs.update(tab?.id!, { url: 'https://github.com/login' }) } else { await browser.tabs.create({ url: 'https://github.com/login' }) } window.close() } async function handleSwitch(username: string) { await accountService.switchTo(username) const tab = await getCurrentTab() const rules = await rule.getAll() // If the current tab is a normal GitHub page, reload it. if (isNormalGitHubUrl(tab?.url, rules)) { await browser.tabs.reload(tab?.id!) } else if (isGitHubUrl(tab?.url)) { await browser.tabs.update(tab?.id!, { url: 'https://github.com' }) } else { await browser.tabs.create({ url: 'https://github.com' }) } window.close() } async function handleRemove(accountName: string) { await removeAccount(accountName) setAccounts(accounts.filter((account) => account.name !== accountName)) } return ( <Box> <Alert severity="info" sx={{ mb: 2 }}> You can manage your logged in accounts here. </Alert> <Box sx={{ mb: 1 }}> <List dense disablePadding> {accounts.map((account, i) => ( <ListItem key={account.name} disableGutters divider={i !== accounts.length - 1}> <ListItemAvatar> <GitHubAvatar account={account} /> </ListItemAvatar> <ListItemText primary={account.name} secondary={account.expiresAt && `Expires at ${account.expiresAt.toLocaleString()}`} /> <ListItemSecondaryAction> <Tooltip title={`Switch to ${account.name}`}> <span> <IconButton color="primary" disabled={account.active} onClick={() => handleSwitch(account.name)} > <Login /> </IconButton> </span> </Tooltip> <Tooltip title={`Remove ${account.name}`} onClick={() => handleRemove(account.name)} > <IconButton color="warning"> <Close /> </IconButton> </Tooltip> </ListItemSecondaryAction> </ListItem> ))} </List> </Box> <Button variant="contained" sx={{ textTransform: 'none' }} startIcon={<PersonAdd />} onClick={handleLogin} > Login Another Account </Button> </Box> ) }
src/popup/components/Accounts.tsx
yuezk-github-account-switcher-36b3c11
[ { "filename": "src/background/index.ts", "retrieved_chunk": " type: 'modifyHeaders',\n requestHeaders: [\n {\n header: 'Cookie',\n operation: 'set',\n value: cookieValue,\n },\n ],\n },\n condition: {", "score": 0.7834771871566772 }, { "filename": "src/popup/components/RuleItem.tsx", "retrieved_chunk": " initialValue?: Rule\n mode?: 'view' | 'edit'\n onDone: (rule: Rule) => void\n onDelete: (rule: Rule) => void\n}\nexport default function RuleItem(props: Props) {\n const { initialValue, mode, onDone, onDelete } = props\n const [rule, setRule] = useState<Rule>(\n initialValue ?? { id: Date.now(), urlPattern: '', account: '' },\n )", "score": 0.7659688591957092 }, { "filename": "src/popup/components/Header.tsx", "retrieved_chunk": " variant=\"square\"\n className={active ? 'active' : ''}\n onClick={handleClick}\n sx={{\n mr: 2,\n width: 32,\n height: 32,\n transform: 'rotate(0turn)',\n transition: 'transform 0.5s ease-in-out',\n '&.active': {", "score": 0.7611556649208069 }, { "filename": "src/content/ui.ts", "retrieved_chunk": "const classicLook = {\n createDivider() {\n return createElement('div', {\n class: 'dropdown-divider'\n })\n },\n createAddAccountLink() {\n return createElement('a', {\n id: ADD_ACCOUNT_BUTTON_ID,\n href: '/login',", "score": 0.7565377950668335 }, { "filename": "src/popup/components/RuleItem.tsx", "retrieved_chunk": " return {\n valid: false,\n message: 'Invalid account',\n }\n }\n return {\n valid: true,\n }\n}\ntype Props = {", "score": 0.7557714581489563 } ]
typescript
function GitHubAvatar({ account }: { account: Account }) {
import { AddCircle } from '@mui/icons-material' import { Alert, Box, Button, Link } from '@mui/material' import { useEffect, useState } from 'react' import ruleService, { Rule } from '../../services/rule' import RuleItem from './RuleItem' export default function AutoSwitchRules() { const [rules, setRules] = useState<Rule[]>([]) const [isAdding, setIsAdding] = useState(false) useEffect(() => { ruleService.getAll().then(setRules) }, []) function startAdding() { setIsAdding(true) } function stopAdding() { setIsAdding(false) } async function addRule(rule: Rule) { await ruleService.add(rule) setRules(await ruleService.getAll()) stopAdding() } async function updateRule(rule: Rule) { await ruleService.update(rule) setRules(await ruleService.getAll()) } async function removeRule(rule: Rule) { await ruleService.remove(rule.id) setRules(await ruleService.getAll()) } return ( <Box> <Alert severity="info" sx={{ mb: 2 }}> When the request URL path matches the regular expression, the account will be switched to the specified account automatically,{' '} <Link href="https://github.com/yuezk/github-account-switcher#auto-switching" target="_blank" > see help </Link> . </Alert> <Box display="flex" flexDirection="column" gap={1} sx={{ '& > :last-child': { mb: 2, }, }} > {rules.map((rule) => ( <
RuleItem key={rule.id} initialValue={rule} onDone={updateRule} onDelete={removeRule} /> ))}
{isAdding && <RuleItem mode="edit" onDone={addRule} onDelete={stopAdding} />} </Box> <Button variant="contained" startIcon={<AddCircle />} onClick={startAdding} disabled={isAdding} sx={{ textTransform: 'none' }} > Add a Rule </Button> </Box> ) }
src/popup/components/AutoSwitchRules.tsx
yuezk-github-account-switcher-36b3c11
[ { "filename": "src/popup/components/Settings.tsx", "retrieved_chunk": " setValue(newValue)\n }\n return (\n <TabContext value={value}>\n <Box sx={{ borderBottom: 1, borderColor: 'divider' }}>\n <TabList onChange={handleChange}>\n <Tab\n icon={<People />}\n iconPosition=\"start\"\n label=\"Accounts\"", "score": 0.7882442474365234 }, { "filename": "src/popup/components/RuleItem.tsx", "retrieved_chunk": " </IconButton>\n </Tooltip>\n )}\n {isEditing && (\n <Tooltip title=\"Done\">\n <IconButton size=\"small\" color=\"primary\" onClick={handleDone}>\n <Done />\n </IconButton>\n </Tooltip>\n )}", "score": 0.7782979011535645 }, { "filename": "src/popup/components/Accounts.tsx", "retrieved_chunk": " }\n return (\n <Box>\n <Alert severity=\"info\" sx={{ mb: 2 }}>\n You can manage your logged in accounts here.\n </Alert>\n <Box sx={{ mb: 1 }}>\n <List dense disablePadding>\n {accounts.map((account, i) => (\n <ListItem key={account.name} disableGutters divider={i !== accounts.length - 1}>", "score": 0.7775441408157349 }, { "filename": "src/content/ui.ts", "retrieved_chunk": " createElement('a', {\n class: `ActionListContent ${ADD_ACCOUNT_BUTTON_ID}`,\n href: '/login',\n children: [\n createElement('span', {\n class: 'ActionListItem-label',\n children: 'Add another account'\n })\n ]\n })", "score": 0.7568843364715576 }, { "filename": "src/popup/components/Accounts.tsx", "retrieved_chunk": " </List>\n </Box>\n <Button\n variant=\"contained\"\n sx={{ textTransform: 'none' }}\n startIcon={<PersonAdd />}\n onClick={handleLogin}\n >\n Login Another Account\n </Button>", "score": 0.7557052373886108 } ]
typescript
RuleItem key={rule.id} initialValue={rule} onDone={updateRule} onDelete={removeRule} /> ))}
import browser, { DeclarativeNetRequest } from 'webextension-polyfill' import accountService from '../services/account' import { setBadgeText } from '../services/badge' import cookie from '../services/cookie' import ruleService from '../services/rule' import { RequestMessage, Response } from '../types' const RESOURCE_TYPES: DeclarativeNetRequest.ResourceType[] = [ 'main_frame', 'sub_frame', 'csp_report', 'websocket', 'xmlhttprequest', ] async function syncAccounts() { const usernameCookie = await cookie.get('dotcom_user') const sessionCookie = await cookie.get('user_session') if (!usernameCookie || !sessionCookie) { return } const { value: account } = usernameCookie if (!account) { return } await accountService.upsert(account, await cookie.getAll()) const accounts = await accountService.getAll() console.info('synced accounts', accounts) await updateDynamicRequestRules() const res = await fetch(`https://github.com/${account}.png?size=100`) if (res.status === 200) { accountService.saveAvatar(account, res.url) } await setBadgeText(account.slice(0, 2)) } async function removeAccount(accountName: string) { await accountService.remove(accountName) await updateDynamicRequestRules() } async function buildCookieValue(accountName: string): Promise<string | null> { const account = await accountService.find(accountName) const cookies = account?.cookies || [] if (!cookies.length) { return null } return cookies .map((cookie) => `${cookie.name}=${cookie.value}`) .concat(`__account__=${accountName}`) .join('; ') } async function buildAddRules(): Promise<DeclarativeNetRequest.Rule[]> { const requestRules: DeclarativeNetRequest.Rule[] = [] const autoSwitchRules = await ruleService.getAll() for (const [index, rule] of autoSwitchRules.entries()) { const cookieValue = await buildCookieValue(rule.account) if (!cookieValue) { continue } requestRules.push({ id: index + 1, priority: 1, action: { type: 'modifyHeaders', requestHeaders: [ { header: 'Cookie', operation: 'set', value: cookieValue, }, ], }, condition: { regexFilter: `${rule.urlPattern}|__account__=${rule.account}`, resourceTypes: RESOURCE_TYPES, }, }) } return requestRules } async function updateDynamicRequestRules() { if (!browser.declarativeNetRequest) { return } const existingRules = await browser.declarativeNetRequest.getDynamicRules() const removeRuleIds = existingRules.map((rule) => rule.id) const addRules = await buildAddRules() await browser.declarativeNetRequest.updateDynamicRules({ removeRuleIds, addRules, }) const rules = await browser.declarativeNetRequest.getDynamicRules() console.info('Current dynamic rules:', rules) } // Watch the requests, if the main_frame url matches any of the auto switch rules, switch to the account function watchAutoSwitchRequests() { browser.webRequest.onBeforeRequest.addListener( (details) => { ruleService.getAll().then((autoSwitchRules) => { for (const rule of autoSwitchRules) { if (new RegExp(rule.urlPattern).test(details.url)) { console.info('onBeforeRequest: found an auto switch rule for url', details.url, rule) return accountService.switchTo(rule.account) } } }) }, { urls: ['https://github.com/*'], types: ['main_frame'], }, ) } function watchCookies() { browser.cookies.onChanged.addListener(async (changeInfo) => { const { cookie, removed } = changeInfo // Ignore other cookies if (cookie.name !== 'dotcom_user') { return } if (removed) { if (cookie.name === 'dotcom_user') { console.info('dotcom_user cookie removed') await setBadgeText('...') } return } console.info('New dotcom_user cookie', cookie.value) await syncAccounts() }) } function handleMessage(message: RequestMessage) {
const { type } = message switch (type) {
case 'getAccounts': return accountService.getAllNames() case 'switchAccount': return accountService.switchTo(message.account) case 'removeAccount': return removeAccount(message.account) case 'clearCookies': return cookie.clear() case 'getAutoSwitchRules': return ruleService.getAll() } } function listenMessage() { browser.runtime.onMessage.addListener( async (request: RequestMessage, _sender): Promise<Response<unknown>> => { try { const data = await handleMessage(request) return { success: true, data } } catch (error: unknown) { return { success: false, error: error as Error } } }, ) } function interceptRequests() { browser.webRequest.onBeforeSendHeaders.addListener( async (details) => { if (!details.requestHeaders) { return { requestHeaders: details.requestHeaders } } const autoSwitchRules = await ruleService.getAll() for (const rule of autoSwitchRules) { const urlPattern = `${rule.urlPattern}|__account__=${rule.account}` if (new RegExp(urlPattern).test(details.url)) { const cookieValue = await buildCookieValue(rule.account) if (cookieValue) { for (const header of details.requestHeaders) { if (header.name.toLowerCase() === 'cookie') { header.value = cookieValue } } } console.info('interceptRequests: found an auto switch rule for url', details.url, rule) return { requestHeaders: details.requestHeaders } } } return { requestHeaders: details.requestHeaders } }, { urls: ['https://github.com/*'], types: RESOURCE_TYPES, }, ['blocking', 'requestHeaders'], ) } async function init() { await syncAccounts() watchAutoSwitchRequests() watchCookies() listenMessage() if (!browser.declarativeNetRequest) { interceptRequests() } /* chrome.declarativeNetRequest.onRuleMatchedDebug.addListener((info) => { console.info('onRuleMatchedDebug', info) })*/ } init()
src/background/index.ts
yuezk-github-account-switcher-36b3c11
[ { "filename": "src/services/account.ts", "retrieved_chunk": " expiresAt: userSessionCookie?.expirationDate\n ? new Date(userSessionCookie.expirationDate * 1000)\n : undefined,\n }\n })\n}\nasync function getAllNames(): Promise<string[]> {\n const accounts = await getAll()\n return accounts.map(({ name }) => name)\n}", "score": 0.8467893600463867 }, { "filename": "src/content/index.ts", "retrieved_chunk": " }\n const res: GetAccountsResponse = await browser.runtime.sendMessage({\n type: 'getAccounts',\n } as GetAccountsMessage)\n if (!res?.success) {\n return\n }\n const { data: accounts } = res\n const addAccountButton = document.getElementById(ADD_ACCOUNT_BUTTON_ID)!\n for (const account of accounts) {", "score": 0.8445641994476318 }, { "filename": "src/shared.ts", "retrieved_chunk": " return false\n }\n if (urlMatchesAnyRule(url, rules)) {\n return false\n }\n return true\n}\nexport async function removeAccount(account: string) {\n await browser.runtime.sendMessage({ type: 'removeAccount', account })\n}", "score": 0.8256258964538574 }, { "filename": "src/services/account.ts", "retrieved_chunk": "async function switchTo(accountName: string) {\n await cookie.clear()\n const account = await find(accountName)\n const cookies = account?.cookies || []\n for (const cookie of cookies) {\n const { hostOnly, domain, session, ...rest } = cookie\n await browser.cookies.set({\n url: 'https://github.com',\n domain: hostOnly ? undefined : domain,\n ...rest,", "score": 0.8133566379547119 }, { "filename": "src/services/account.ts", "retrieved_chunk": "async function find(accountName: string): Promise<Account | undefined> {\n const accounts = await getAll()\n return accounts.find((account) => account.name === accountName)\n}\nasync function upsert(accountName: string, cookies: Cookie[]) {\n await storage.update<Accounts>('accounts', (accounts = {}) => {\n accounts[accountName] = cookies\n return accounts\n })\n}", "score": 0.8129168748855591 } ]
typescript
const { type } = message switch (type) {
import browser from 'webextension-polyfill' import { isNormalGitHubUrl, removeAccount } from '../shared' import { ClearCookiesMessage, GetAccountsMessage, GetAccountsResponse, GetAutoSwitchRulesMessage, GetAutoSwitchRulesResponse, } from '../types' import './index.css' // Script that will be injected in the main page import { createElement } from './createElement' import injectedScript from './injected?script&module' import { ACCOUNT_ITEM_CLASS, ACCOUNT_REMOVE_CLASS, ADD_ACCOUNT_BUTTON_ID, createAccountItem, createAddAccountLink, createDivider } from './ui' async function addSwitchUserMenu(logoutForm: HTMLFormElement) { const currentAccount = document.querySelector<HTMLMetaElement>('meta[name="user-login"]')?.content if (!currentAccount) { console.info('no current account found') return } if (!document.getElementById(ADD_ACCOUNT_BUTTON_ID)) { // Add the "Add another account" menu item and a divider const fragment = createElement('fragment', { children: [ createAddAccountLink(), createDivider(), ], }) // Insert the elements before the logoutForm logoutForm.parentElement?.insertBefore(fragment, logoutForm) } const res: GetAccountsResponse = await browser.runtime.sendMessage({ type: 'getAccounts', } as GetAccountsMessage) if (!res?.success) { return } const { data: accounts } = res const addAccountButton = document.getElementById(ADD_ACCOUNT_BUTTON_ID)! for (const account of accounts) { if (account === currentAccount) { continue } const accountId = `${ACCOUNT_ITEM_CLASS}-${account}` if (!document.getElementById(accountId) && addAccountButton) { const accountWrapper = createAccountItem(account) addAccountButton.parentElement?.insertBefore(accountWrapper, addAccountButton) } } } async function getAutoSwitchRules() { const res: GetAutoSwitchRulesResponse = await browser.runtime.sendMessage({ type: 'getAutoSwitchRules', } as GetAutoSwitchRulesMessage) return res?.success ? res.data : [] } async function addAccount() { await browser.runtime.sendMessage({ type: 'clearCookies' } as ClearCookiesMessage) const autoSwitchRules = await getAutoSwitchRules() window.location.href = isNormalGitHubUrl(window.location.href, autoSwitchRules) ? `/login?return_to=${encodeURIComponent(window.location.href)}` : '/login' } async function switchAccount(account: string) { await browser.runtime.sendMessage({ type: 'switchAccount', account }) const autoSwitchRules = await getAutoSwitchRules() if (isNormalGitHubUrl(window.location.href, autoSwitchRules)) { window.location.reload() } else { window.location.href = '/' } } function injectScript() { const script = document.createElement('script')
script.src = browser.runtime.getURL(injectedScript) script.type = 'module' document.head.prepend(script) }
function ready(fn: () => void) { if (document.readyState !== 'loading') { fn() return } document.addEventListener('DOMContentLoaded', fn) } function watchDom() { new MutationObserver((mutations) => { for (const mutation of mutations) { const isOpen = mutation.type === 'attributes' && mutation.attributeName === 'open' && mutation.target instanceof HTMLElement && mutation.target.hasAttribute('open') if (isOpen || (mutation.type === 'childList' && mutation.target instanceof HTMLElement)) { // Find the logout form on GitHub page or Gist page const logoutForm = mutation.target.querySelector<HTMLFormElement>( '.js-loggout-form, #user-links .logout-form, user-drawer-side-panel nav-list .ActionListItem:last-child', ) if (logoutForm) { addSwitchUserMenu(logoutForm) } } } }).observe(document.documentElement, { childList: true, subtree: true, attributes: true, }) } async function init() { injectScript() ready(watchDom) document.addEventListener('click', (event) => { const target = event.target as HTMLElement if (target.closest(`.${ADD_ACCOUNT_BUTTON_ID}`)) { // add another account event.preventDefault() addAccount() } else if (target.closest(`.${ACCOUNT_ITEM_CLASS}`)) { // switch to account const closestTarget = target.closest(`.${ACCOUNT_ITEM_CLASS}`) as HTMLElement const { account } = closestTarget.dataset switchAccount(account!) } else if (target.closest(`.${ACCOUNT_REMOVE_CLASS}`)) { // remove account const btn = target.closest(`.${ACCOUNT_REMOVE_CLASS}`) as HTMLElement const { account } = btn.dataset removeAccount(account!).then(() => { btn.parentElement?.remove() }) } }) } init()
src/content/index.ts
yuezk-github-account-switcher-36b3c11
[ { "filename": "src/content/injected.ts", "retrieved_chunk": " return url.href\n }\n}\nfunction patchUrl(oldUrl: string | URL) {\n const account = document.querySelector<HTMLMetaElement>('meta[name=\"user-login\"]')?.content\n if (!account) {\n return oldUrl\n }\n const newUrl = new URL(oldUrl, window.location.origin)\n newUrl.searchParams.append(ACCOUNT_PARAM, account)", "score": 0.7592290043830872 }, { "filename": "src/background/index.ts", "retrieved_chunk": " listenMessage()\n if (!browser.declarativeNetRequest) {\n interceptRequests()\n }\n /*\n chrome.declarativeNetRequest.onRuleMatchedDebug.addListener((info) => {\n console.info('onRuleMatchedDebug', info)\n })*/\n}\ninit()", "score": 0.7121803760528564 }, { "filename": "src/content/createElement.ts", "retrieved_chunk": " for (const child of childrenArray) {\n if (typeof child === 'undefined') {\n continue\n }\n if (typeof child === 'string') {\n parent.appendChild(document.createTextNode(child))\n } else {\n parent.appendChild(child)\n }\n }", "score": 0.6886850595474243 }, { "filename": "src/services/cookie.ts", "retrieved_chunk": "import browser from 'webextension-polyfill'\nconst COOKIE_URL = 'https://github.com'\nasync function get(name: string) {\n return browser.cookies.get({ url: COOKIE_URL, name })\n}\nasync function getAll() {\n return browser.cookies.getAll({ url: COOKIE_URL })\n}\nasync function clear() {\n const cookies = await getAll()", "score": 0.6867678165435791 }, { "filename": "src/shared.ts", "retrieved_chunk": " return false\n }\n if (urlMatchesAnyRule(url, rules)) {\n return false\n }\n return true\n}\nexport async function removeAccount(account: string) {\n await browser.runtime.sendMessage({ type: 'removeAccount', account })\n}", "score": 0.6838457584381104 } ]
typescript
script.src = browser.runtime.getURL(injectedScript) script.type = 'module' document.head.prepend(script) }
import browser, { Cookies } from 'webextension-polyfill' import { setBadgeText } from './badge' import cookie from './cookie' import storage from './storage' type Cookie = Cookies.Cookie export type Account = { name: string cookies: Cookie[] active: boolean avatarUrl?: string expiresAt?: Date } type Accounts = Record<string, Cookie[]> async function getAll(): Promise<Account[]> { const accounts = await storage.get<Accounts>('accounts') if (!accounts) { return [] } const currentAccount = await browser.cookies.get({ url: 'https://github.com', name: 'dotcom_user', }) const avatarUrls = await storage.get<Record<string, string>>('avatars') return Object.entries(accounts).map(([name, cookies]) => { const userSessionCookie = cookies.find(({ name }) => name === 'user_session') return { name, cookies, active: currentAccount?.value === name, avatarUrl: avatarUrls?.[name], expiresAt: userSessionCookie?.expirationDate ? new Date(userSessionCookie.expirationDate * 1000) : undefined, } }) } async function getAllNames(): Promise<string[]> { const accounts = await getAll() return accounts.map(({ name }) => name) } async function find(accountName: string): Promise<Account | undefined> { const accounts = await getAll() return accounts.find((account) => account.name === accountName) } async function upsert(accountName: string, cookies: Cookie[]) { await storage.update<Accounts>('accounts', (accounts = {}) => { accounts[accountName] = cookies return accounts }) } async function switchTo(accountName: string) { await cookie.clear() const account = await find(accountName) const cookies = account?.cookies || [] for (const cookie of cookies) { const { hostOnly, domain, session, ...rest } = cookie await browser.cookies.set({ url: 'https://github.com', domain: hostOnly ? undefined : domain, ...rest, }) } if (cookies.length) { setBadgeText(accountName.slice(0, 2)) } else { setBadgeText('...') } } async function remove(accountName: string) { await storage.update
<Accounts>('accounts', (accounts) => {
if (!accounts) { return } delete accounts[accountName] return accounts }) } async function saveAvatar(accountName: string, avatarUrl: string) { await storage.update<Record<string, string>>('avatars', (avatars = {}) => { avatars[accountName] = avatarUrl return avatars }) } export default { getAll, getAllNames, find, upsert, switchTo, remove, saveAvatar, }
src/services/account.ts
yuezk-github-account-switcher-36b3c11
[ { "filename": "src/background/index.ts", "retrieved_chunk": " }\n await setBadgeText(account.slice(0, 2))\n}\nasync function removeAccount(accountName: string) {\n await accountService.remove(accountName)\n await updateDynamicRequestRules()\n}\nasync function buildCookieValue(accountName: string): Promise<string | null> {\n const account = await accountService.find(accountName)\n const cookies = account?.cookies || []", "score": 0.865883469581604 }, { "filename": "src/popup/components/Accounts.tsx", "retrieved_chunk": " } else if (isGitHubUrl(tab?.url)) {\n await browser.tabs.update(tab?.id!, { url: 'https://github.com' })\n } else {\n await browser.tabs.create({ url: 'https://github.com' })\n }\n window.close()\n }\n async function handleRemove(accountName: string) {\n await removeAccount(accountName)\n setAccounts(accounts.filter((account) => account.name !== accountName))", "score": 0.8279375433921814 }, { "filename": "src/popup/components/Accounts.tsx", "retrieved_chunk": " const [tab] = await browser.tabs.query(queryOptions)\n return tab\n}\nexport default function Accounts() {\n const [accounts, setAccounts] = useState<Account[]>([])\n useEffect(() => {\n accountService.getAll().then(setAccounts)\n }, [])\n async function handleLogin() {\n await cookie.clear()", "score": 0.8050764799118042 }, { "filename": "src/shared.ts", "retrieved_chunk": " return false\n }\n if (urlMatchesAnyRule(url, rules)) {\n return false\n }\n return true\n}\nexport async function removeAccount(account: string) {\n await browser.runtime.sendMessage({ type: 'removeAccount', account })\n}", "score": 0.7982927560806274 }, { "filename": "src/background/index.ts", "retrieved_chunk": " if (!account) {\n return\n }\n await accountService.upsert(account, await cookie.getAll())\n const accounts = await accountService.getAll()\n console.info('synced accounts', accounts)\n await updateDynamicRequestRules()\n const res = await fetch(`https://github.com/${account}.png?size=100`)\n if (res.status === 200) {\n accountService.saveAvatar(account, res.url)", "score": 0.7934721112251282 } ]
typescript
<Accounts>('accounts', (accounts) => {
import browser, { DeclarativeNetRequest } from 'webextension-polyfill' import accountService from '../services/account' import { setBadgeText } from '../services/badge' import cookie from '../services/cookie' import ruleService from '../services/rule' import { RequestMessage, Response } from '../types' const RESOURCE_TYPES: DeclarativeNetRequest.ResourceType[] = [ 'main_frame', 'sub_frame', 'csp_report', 'websocket', 'xmlhttprequest', ] async function syncAccounts() { const usernameCookie = await cookie.get('dotcom_user') const sessionCookie = await cookie.get('user_session') if (!usernameCookie || !sessionCookie) { return } const { value: account } = usernameCookie if (!account) { return } await accountService.upsert(account, await cookie.getAll()) const accounts = await accountService.getAll() console.info('synced accounts', accounts) await updateDynamicRequestRules() const res = await fetch(`https://github.com/${account}.png?size=100`) if (res.status === 200) { accountService.saveAvatar(account, res.url) } await setBadgeText(account.slice(0, 2)) } async function removeAccount(accountName: string) { await accountService.remove(accountName) await updateDynamicRequestRules() } async function buildCookieValue(accountName: string): Promise<string | null> { const account = await accountService.find(accountName) const cookies = account?.cookies || [] if (!cookies.length) { return null } return cookies .map((cookie) => `${cookie.name}=${cookie.value}`) .concat(`__account__=${accountName}`) .join('; ') } async function buildAddRules(): Promise<DeclarativeNetRequest.Rule[]> { const requestRules: DeclarativeNetRequest.Rule[] = [] const autoSwitchRules = await ruleService.getAll() for (const [index, rule] of autoSwitchRules.entries()) { const cookieValue = await buildCookieValue(rule.account) if (!cookieValue) { continue } requestRules.push({ id: index + 1, priority: 1, action: { type: 'modifyHeaders', requestHeaders: [ { header: 'Cookie', operation: 'set', value: cookieValue, }, ], }, condition: { regexFilter: `${rule.urlPattern}|__account__=${rule.account}`, resourceTypes: RESOURCE_TYPES, }, }) } return requestRules } async function updateDynamicRequestRules() { if (!browser.declarativeNetRequest) { return } const existingRules = await browser.declarativeNetRequest.getDynamicRules() const removeRuleIds = existingRules.map((rule) => rule.id) const addRules = await buildAddRules() await browser.declarativeNetRequest.updateDynamicRules({ removeRuleIds, addRules, }) const rules = await browser.declarativeNetRequest.getDynamicRules() console.info('Current dynamic rules:', rules) } // Watch the requests, if the main_frame url matches any of the auto switch rules, switch to the account function watchAutoSwitchRequests() { browser.webRequest.onBeforeRequest.addListener( (details) => { ruleService.getAll().then((autoSwitchRules) => { for (const rule of autoSwitchRules) { if (new RegExp(rule.urlPattern).test(details.url)) { console.info('onBeforeRequest: found an auto switch rule for url', details.url, rule) return accountService.switchTo(rule.account) } } }) }, { urls: ['https://github.com/*'], types: ['main_frame'], }, ) } function watchCookies() { browser.cookies.onChanged.addListener(async (changeInfo) => { const { cookie, removed } = changeInfo // Ignore other cookies if (cookie.name !== 'dotcom_user') { return } if (removed) { if (cookie.name === 'dotcom_user') { console.info('dotcom_user cookie removed') await setBadgeText('...') } return } console.info('New dotcom_user cookie', cookie.value) await syncAccounts() }) } function handleMessage(message: RequestMessage) { const { type } = message switch (type) { case 'getAccounts': return accountService.getAllNames() case 'switchAccount': return accountService.switchTo(message.account) case 'removeAccount': return removeAccount(message.account) case 'clearCookies': return cookie
.clear() case 'getAutoSwitchRules': return ruleService.getAll() }
} function listenMessage() { browser.runtime.onMessage.addListener( async (request: RequestMessage, _sender): Promise<Response<unknown>> => { try { const data = await handleMessage(request) return { success: true, data } } catch (error: unknown) { return { success: false, error: error as Error } } }, ) } function interceptRequests() { browser.webRequest.onBeforeSendHeaders.addListener( async (details) => { if (!details.requestHeaders) { return { requestHeaders: details.requestHeaders } } const autoSwitchRules = await ruleService.getAll() for (const rule of autoSwitchRules) { const urlPattern = `${rule.urlPattern}|__account__=${rule.account}` if (new RegExp(urlPattern).test(details.url)) { const cookieValue = await buildCookieValue(rule.account) if (cookieValue) { for (const header of details.requestHeaders) { if (header.name.toLowerCase() === 'cookie') { header.value = cookieValue } } } console.info('interceptRequests: found an auto switch rule for url', details.url, rule) return { requestHeaders: details.requestHeaders } } } return { requestHeaders: details.requestHeaders } }, { urls: ['https://github.com/*'], types: RESOURCE_TYPES, }, ['blocking', 'requestHeaders'], ) } async function init() { await syncAccounts() watchAutoSwitchRequests() watchCookies() listenMessage() if (!browser.declarativeNetRequest) { interceptRequests() } /* chrome.declarativeNetRequest.onRuleMatchedDebug.addListener((info) => { console.info('onRuleMatchedDebug', info) })*/ } init()
src/background/index.ts
yuezk-github-account-switcher-36b3c11
[ { "filename": "src/types.ts", "retrieved_chunk": "export type RemoveAccountMessage = Message<'removeAccount', { account: string }>\nexport type RemoveAccountResponse = Response\nexport type GetAutoSwitchRulesMessage = Message<'getAutoSwitchRules'>\nexport type GetAutoSwitchRulesResponse = Response<Rule[]>\nexport type RequestMessage =\n | GetAccountsMessage\n | ClearCookiesMessage\n | SwitchAccountMessage\n | RemoveAccountMessage\n | GetAutoSwitchRulesMessage", "score": 0.7981640100479126 }, { "filename": "src/content/index.ts", "retrieved_chunk": "async function getAutoSwitchRules() {\n const res: GetAutoSwitchRulesResponse = await browser.runtime.sendMessage({\n type: 'getAutoSwitchRules',\n } as GetAutoSwitchRulesMessage)\n return res?.success ? res.data : []\n}\nasync function addAccount() {\n await browser.runtime.sendMessage({ type: 'clearCookies' } as ClearCookiesMessage)\n const autoSwitchRules = await getAutoSwitchRules()\n window.location.href = isNormalGitHubUrl(window.location.href, autoSwitchRules)", "score": 0.7765440940856934 }, { "filename": "src/popup/components/Accounts.tsx", "retrieved_chunk": " const [tab] = await browser.tabs.query(queryOptions)\n return tab\n}\nexport default function Accounts() {\n const [accounts, setAccounts] = useState<Account[]>([])\n useEffect(() => {\n accountService.getAll().then(setAccounts)\n }, [])\n async function handleLogin() {\n await cookie.clear()", "score": 0.7483631372451782 }, { "filename": "src/popup/components/Accounts.tsx", "retrieved_chunk": " }\n window.close()\n }\n async function handleSwitch(username: string) {\n await accountService.switchTo(username)\n const tab = await getCurrentTab()\n const rules = await rule.getAll()\n // If the current tab is a normal GitHub page, reload it.\n if (isNormalGitHubUrl(tab?.url, rules)) {\n await browser.tabs.reload(tab?.id!)", "score": 0.7481944561004639 }, { "filename": "src/shared.ts", "retrieved_chunk": " return false\n }\n if (urlMatchesAnyRule(url, rules)) {\n return false\n }\n return true\n}\nexport async function removeAccount(account: string) {\n await browser.runtime.sendMessage({ type: 'removeAccount', account })\n}", "score": 0.7423772811889648 } ]
typescript
.clear() case 'getAutoSwitchRules': return ruleService.getAll() }
import { Close, Login, PersonAdd } from '@mui/icons-material' import { Alert, Avatar, Badge, Box, Button, IconButton, List, ListItem, ListItemAvatar, ListItemSecondaryAction, ListItemText, Tooltip, styled, } from '@mui/material' import { useEffect, useState } from 'react' import browser, { Tabs } from 'webextension-polyfill' import accountService, { Account } from '../../services/account' import cookie from '../../services/cookie' import rule from '../../services/rule' import { isGitHubUrl, isNormalGitHubUrl, removeAccount } from '../../shared' const StyledBadge = styled(Badge)(({ theme }) => ({ '& .MuiBadge-badge': { backgroundColor: '#44b700', color: '#44b700', boxShadow: `0 0 0 2px ${theme.palette.background.paper}`, '&::after': { position: 'absolute', top: 0, left: 0, width: '100%', height: '100%', borderRadius: '50%', animation: 'ripple 1.2s infinite ease-in-out', border: '1px solid currentColor', content: '""', }, }, '@keyframes ripple': { '0%': { transform: 'scale(.8)', opacity: 1, }, '100%': { transform: 'scale(2.4)', opacity: 0, }, }, })) function GitHubAvatar({ account }: { account: Account }) { const { name, active } = account const avatarUrl = account.avatarUrl ?? `https://github.com/${name}.png?size=100` const avatar = <Avatar src={avatarUrl} /> if (active) { return ( <StyledBadge overlap="circular" anchorOrigin={{ vertical: 'bottom', horizontal: 'right' }} variant="dot" > {avatar} </StyledBadge> ) } return avatar } async function getCurrentTab(): Promise<Tabs.Tab | undefined> { const queryOptions = { active: true, lastFocusedWindow: true } // `tab` will either be a `tabs.Tab` instance or `undefined`. const [tab] = await browser.tabs.query(queryOptions) return tab } export default function Accounts() { const [accounts, setAccounts] = useState<Account[]>([]) useEffect(() => { accountService.getAll().then(setAccounts) }, []) async function handleLogin() { await cookie.clear() const tab = await getCurrentTab() const rules = await rule.getAll() if (
isNormalGitHubUrl(tab?.url, rules)) {
await browser.tabs.update(tab?.id!, { url: `https://github.com/login?return_to=${encodeURIComponent(tab?.url ?? '')}`, }) } else if (isGitHubUrl(tab?.url)) { await browser.tabs.update(tab?.id!, { url: 'https://github.com/login' }) } else { await browser.tabs.create({ url: 'https://github.com/login' }) } window.close() } async function handleSwitch(username: string) { await accountService.switchTo(username) const tab = await getCurrentTab() const rules = await rule.getAll() // If the current tab is a normal GitHub page, reload it. if (isNormalGitHubUrl(tab?.url, rules)) { await browser.tabs.reload(tab?.id!) } else if (isGitHubUrl(tab?.url)) { await browser.tabs.update(tab?.id!, { url: 'https://github.com' }) } else { await browser.tabs.create({ url: 'https://github.com' }) } window.close() } async function handleRemove(accountName: string) { await removeAccount(accountName) setAccounts(accounts.filter((account) => account.name !== accountName)) } return ( <Box> <Alert severity="info" sx={{ mb: 2 }}> You can manage your logged in accounts here. </Alert> <Box sx={{ mb: 1 }}> <List dense disablePadding> {accounts.map((account, i) => ( <ListItem key={account.name} disableGutters divider={i !== accounts.length - 1}> <ListItemAvatar> <GitHubAvatar account={account} /> </ListItemAvatar> <ListItemText primary={account.name} secondary={account.expiresAt && `Expires at ${account.expiresAt.toLocaleString()}`} /> <ListItemSecondaryAction> <Tooltip title={`Switch to ${account.name}`}> <span> <IconButton color="primary" disabled={account.active} onClick={() => handleSwitch(account.name)} > <Login /> </IconButton> </span> </Tooltip> <Tooltip title={`Remove ${account.name}`} onClick={() => handleRemove(account.name)} > <IconButton color="warning"> <Close /> </IconButton> </Tooltip> </ListItemSecondaryAction> </ListItem> ))} </List> </Box> <Button variant="contained" sx={{ textTransform: 'none' }} startIcon={<PersonAdd />} onClick={handleLogin} > Login Another Account </Button> </Box> ) }
src/popup/components/Accounts.tsx
yuezk-github-account-switcher-36b3c11
[ { "filename": "src/background/index.ts", "retrieved_chunk": " }\n await setBadgeText(account.slice(0, 2))\n}\nasync function removeAccount(accountName: string) {\n await accountService.remove(accountName)\n await updateDynamicRequestRules()\n}\nasync function buildCookieValue(accountName: string): Promise<string | null> {\n const account = await accountService.find(accountName)\n const cookies = account?.cookies || []", "score": 0.8391355276107788 }, { "filename": "src/services/account.ts", "retrieved_chunk": "async function find(accountName: string): Promise<Account | undefined> {\n const accounts = await getAll()\n return accounts.find((account) => account.name === accountName)\n}\nasync function upsert(accountName: string, cookies: Cookie[]) {\n await storage.update<Accounts>('accounts', (accounts = {}) => {\n accounts[accountName] = cookies\n return accounts\n })\n}", "score": 0.8217303156852722 }, { "filename": "src/services/account.ts", "retrieved_chunk": " expiresAt?: Date\n}\ntype Accounts = Record<string, Cookie[]>\nasync function getAll(): Promise<Account[]> {\n const accounts = await storage.get<Accounts>('accounts')\n if (!accounts) {\n return []\n }\n const currentAccount = await browser.cookies.get({\n url: 'https://github.com',", "score": 0.8162555694580078 }, { "filename": "src/content/index.ts", "retrieved_chunk": "async function getAutoSwitchRules() {\n const res: GetAutoSwitchRulesResponse = await browser.runtime.sendMessage({\n type: 'getAutoSwitchRules',\n } as GetAutoSwitchRulesMessage)\n return res?.success ? res.data : []\n}\nasync function addAccount() {\n await browser.runtime.sendMessage({ type: 'clearCookies' } as ClearCookiesMessage)\n const autoSwitchRules = await getAutoSwitchRules()\n window.location.href = isNormalGitHubUrl(window.location.href, autoSwitchRules)", "score": 0.8162364959716797 }, { "filename": "src/background/index.ts", "retrieved_chunk": " const autoSwitchRules = await ruleService.getAll()\n for (const [index, rule] of autoSwitchRules.entries()) {\n const cookieValue = await buildCookieValue(rule.account)\n if (!cookieValue) {\n continue\n }\n requestRules.push({\n id: index + 1,\n priority: 1,\n action: {", "score": 0.8122732639312744 } ]
typescript
isNormalGitHubUrl(tab?.url, rules)) {
import { Close, Login, PersonAdd } from '@mui/icons-material' import { Alert, Avatar, Badge, Box, Button, IconButton, List, ListItem, ListItemAvatar, ListItemSecondaryAction, ListItemText, Tooltip, styled, } from '@mui/material' import { useEffect, useState } from 'react' import browser, { Tabs } from 'webextension-polyfill' import accountService, { Account } from '../../services/account' import cookie from '../../services/cookie' import rule from '../../services/rule' import { isGitHubUrl, isNormalGitHubUrl, removeAccount } from '../../shared' const StyledBadge = styled(Badge)(({ theme }) => ({ '& .MuiBadge-badge': { backgroundColor: '#44b700', color: '#44b700', boxShadow: `0 0 0 2px ${theme.palette.background.paper}`, '&::after': { position: 'absolute', top: 0, left: 0, width: '100%', height: '100%', borderRadius: '50%', animation: 'ripple 1.2s infinite ease-in-out', border: '1px solid currentColor', content: '""', }, }, '@keyframes ripple': { '0%': { transform: 'scale(.8)', opacity: 1, }, '100%': { transform: 'scale(2.4)', opacity: 0, }, }, })) function GitHubAvatar({ account }: { account: Account }) { const { name, active } = account const avatarUrl = account.avatarUrl ?? `https://github.com/${name}.png?size=100` const avatar = <Avatar src={avatarUrl} /> if (active) { return ( <StyledBadge overlap="circular" anchorOrigin={{ vertical: 'bottom', horizontal: 'right' }} variant="dot" > {avatar} </StyledBadge> ) } return avatar } async function getCurrentTab(): Promise<Tabs.Tab | undefined> { const queryOptions = { active: true, lastFocusedWindow: true } // `tab` will either be a `tabs.Tab` instance or `undefined`. const [tab] = await browser.tabs.query(queryOptions) return tab } export default function Accounts() { const [accounts, setAccounts] = useState<Account[]>([]) useEffect(() => { accountService.getAll().then(setAccounts) }, []) async function handleLogin() { await cookie.clear() const tab = await getCurrentTab() const rules = await rule.getAll() if (isNormalGitHubUrl(tab?.url, rules)) { await browser.tabs.update(tab?.id!, { url: `https://github.com/login?return_to=${encodeURIComponent(tab?.url ?? '')}`, }) } else if (isGitHubUrl(tab?.url)) { await browser.tabs.update(tab?.id!, { url: 'https://github.com/login' }) } else { await browser.tabs.create({ url: 'https://github.com/login' }) } window.close() } async function handleSwitch(username: string) { await accountService.switchTo(username) const tab = await getCurrentTab() const rules = await rule.getAll() // If the current tab is a normal GitHub page, reload it. if (isNormalGitHubUrl(tab?.url, rules)) { await browser.tabs.reload(tab?.id!) } else if (isGitHubUrl(tab?.url)) { await browser.tabs.update(tab?.id!, { url: 'https://github.com' }) } else { await browser.tabs.create({ url: 'https://github.com' }) } window.close() } async function handleRemove(accountName: string) { await removeAccount(accountName) setAccounts(accounts.filter((account) => account.name !== accountName)) } return ( <Box> <Alert severity="info" sx={{ mb: 2 }}> You can manage your logged in accounts here. </Alert> <Box sx={{ mb: 1 }}> <List dense disablePadding> {accounts.map((account, i) => ( <ListItem key={account.name} disableGutters divider={i !== accounts.length - 1}> <ListItemAvatar> <GitHubAvatar account={account} /> </ListItemAvatar> <ListItemText primary={account.name} secondary=
{account.expiresAt && `Expires at ${account.expiresAt.toLocaleString()}`}
/> <ListItemSecondaryAction> <Tooltip title={`Switch to ${account.name}`}> <span> <IconButton color="primary" disabled={account.active} onClick={() => handleSwitch(account.name)} > <Login /> </IconButton> </span> </Tooltip> <Tooltip title={`Remove ${account.name}`} onClick={() => handleRemove(account.name)} > <IconButton color="warning"> <Close /> </IconButton> </Tooltip> </ListItemSecondaryAction> </ListItem> ))} </List> </Box> <Button variant="contained" sx={{ textTransform: 'none' }} startIcon={<PersonAdd />} onClick={handleLogin} > Login Another Account </Button> </Box> ) }
src/popup/components/Accounts.tsx
yuezk-github-account-switcher-36b3c11
[ { "filename": "src/popup/components/Settings.tsx", "retrieved_chunk": " setValue(newValue)\n }\n return (\n <TabContext value={value}>\n <Box sx={{ borderBottom: 1, borderColor: 'divider' }}>\n <TabList onChange={handleChange}>\n <Tab\n icon={<People />}\n iconPosition=\"start\"\n label=\"Accounts\"", "score": 0.7968672513961792 }, { "filename": "src/popup/components/RuleItem.tsx", "retrieved_chunk": " value={rule.account}\n onChange={handleAccountChange}\n disabled={!isEditing}\n />\n </Box>\n <Box display=\"flex\" flexShrink={0}>\n {!isEditing && (\n <Tooltip title=\"Edit\">\n <IconButton size=\"small\" color=\"primary\" onClick={handleEdit}>\n <Edit />", "score": 0.7852582335472107 }, { "filename": "src/popup/components/AutoSwitchRules.tsx", "retrieved_chunk": " },\n }}\n >\n {rules.map((rule) => (\n <RuleItem key={rule.id} initialValue={rule} onDone={updateRule} onDelete={removeRule} />\n ))}\n {isAdding && <RuleItem mode=\"edit\" onDone={addRule} onDelete={stopAdding} />}\n </Box>\n <Button\n variant=\"contained\"", "score": 0.7432467937469482 }, { "filename": "src/popup/components/RuleItem.tsx", "retrieved_chunk": " </IconButton>\n </Tooltip>\n )}\n {isEditing && (\n <Tooltip title=\"Done\">\n <IconButton size=\"small\" color=\"primary\" onClick={handleDone}>\n <Done />\n </IconButton>\n </Tooltip>\n )}", "score": 0.7166712284088135 }, { "filename": "src/popup/components/RuleItem.tsx", "retrieved_chunk": " />\n </Box>\n <Box width={150} flexShrink={0}>\n <TextField\n size=\"medium\"\n variant=\"standard\"\n fullWidth\n placeholder=\"GitHub account\"\n error={!!accountValidation}\n helperText={accountValidation}", "score": 0.7075499296188354 } ]
typescript
{account.expiresAt && `Expires at ${account.expiresAt.toLocaleString()}`}
import browser from 'webextension-polyfill' import { isNormalGitHubUrl, removeAccount } from '../shared' import { ClearCookiesMessage, GetAccountsMessage, GetAccountsResponse, GetAutoSwitchRulesMessage, GetAutoSwitchRulesResponse, } from '../types' import './index.css' // Script that will be injected in the main page import { createElement } from './createElement' import injectedScript from './injected?script&module' import { ACCOUNT_ITEM_CLASS, ACCOUNT_REMOVE_CLASS, ADD_ACCOUNT_BUTTON_ID, createAccountItem, createAddAccountLink, createDivider } from './ui' async function addSwitchUserMenu(logoutForm: HTMLFormElement) { const currentAccount = document.querySelector<HTMLMetaElement>('meta[name="user-login"]')?.content if (!currentAccount) { console.info('no current account found') return } if (!document.getElementById(ADD_ACCOUNT_BUTTON_ID)) { // Add the "Add another account" menu item and a divider const fragment = createElement('fragment', { children: [ createAddAccountLink(), createDivider(), ], }) // Insert the elements before the logoutForm logoutForm.parentElement?.insertBefore(fragment, logoutForm) } const res: GetAccountsResponse = await browser.runtime.sendMessage({ type: 'getAccounts', } as GetAccountsMessage) if (!res?.success) { return } const { data: accounts } = res const addAccountButton = document.getElementById(ADD_ACCOUNT_BUTTON_ID)! for (const account of accounts) { if (account === currentAccount) { continue } const accountId = `${ACCOUNT_ITEM_CLASS}-${account}` if (!document.getElementById(accountId) && addAccountButton) { const accountWrapper = createAccountItem(account) addAccountButton.parentElement?.insertBefore(accountWrapper, addAccountButton) } } } async function getAutoSwitchRules() { const res: GetAutoSwitchRulesResponse = await browser.runtime.sendMessage({ type: 'getAutoSwitchRules', } as GetAutoSwitchRulesMessage) return res?.success ? res.data : [] } async function addAccount() { await browser.runtime.sendMessage({ type: 'clearCookies' } as ClearCookiesMessage) const autoSwitchRules = await getAutoSwitchRules() window.location.href = isNormalGitHubUrl(window.location.href, autoSwitchRules) ? `/login?return_to=${encodeURIComponent(window.location.href)}` : '/login' } async function switchAccount(account: string) { await browser.runtime.sendMessage({ type: 'switchAccount', account }) const autoSwitchRules = await getAutoSwitchRules() if (isNormalGitHubUrl(window.location.href, autoSwitchRules)) { window.location.reload() } else { window.location.href = '/' } } function injectScript() { const script = document.createElement('script') script.src = browser.runtime.getURL(injectedScript) script.type = 'module' document.head.prepend(script) } function ready(fn: () => void) { if (document.readyState !== 'loading') { fn() return } document.addEventListener('DOMContentLoaded', fn) } function watchDom() { new MutationObserver((mutations) => { for (const mutation of mutations) { const isOpen = mutation.type === 'attributes' && mutation.attributeName === 'open' && mutation.target instanceof HTMLElement && mutation.target.hasAttribute('open') if (isOpen || (mutation.type === 'childList' && mutation.target instanceof HTMLElement)) { // Find the logout form on GitHub page or Gist page const logoutForm = mutation.target.querySelector<HTMLFormElement>( '.js-loggout-form, #user-links .logout-form, user-drawer-side-panel nav-list .ActionListItem:last-child', ) if (logoutForm) { addSwitchUserMenu(logoutForm) } } } }).observe(document.documentElement, { childList: true, subtree: true, attributes: true, }) } async function init() { injectScript() ready(watchDom) document.addEventListener('click', (event) => { const target = event.target as HTMLElement if (target
.closest(`.${ADD_ACCOUNT_BUTTON_ID}`)) {
// add another account event.preventDefault() addAccount() } else if (target.closest(`.${ACCOUNT_ITEM_CLASS}`)) { // switch to account const closestTarget = target.closest(`.${ACCOUNT_ITEM_CLASS}`) as HTMLElement const { account } = closestTarget.dataset switchAccount(account!) } else if (target.closest(`.${ACCOUNT_REMOVE_CLASS}`)) { // remove account const btn = target.closest(`.${ACCOUNT_REMOVE_CLASS}`) as HTMLElement const { account } = btn.dataset removeAccount(account!).then(() => { btn.parentElement?.remove() }) } }) } init()
src/content/index.ts
yuezk-github-account-switcher-36b3c11
[ { "filename": "src/content/injected.ts", "retrieved_chunk": " return url.href\n }\n}\nfunction patchUrl(oldUrl: string | URL) {\n const account = document.querySelector<HTMLMetaElement>('meta[name=\"user-login\"]')?.content\n if (!account) {\n return oldUrl\n }\n const newUrl = new URL(oldUrl, window.location.origin)\n newUrl.searchParams.append(ACCOUNT_PARAM, account)", "score": 0.7567312717437744 }, { "filename": "src/popup/components/Accounts.tsx", "retrieved_chunk": " }\n window.close()\n }\n async function handleSwitch(username: string) {\n await accountService.switchTo(username)\n const tab = await getCurrentTab()\n const rules = await rule.getAll()\n // If the current tab is a normal GitHub page, reload it.\n if (isNormalGitHubUrl(tab?.url, rules)) {\n await browser.tabs.reload(tab?.id!)", "score": 0.7503033876419067 }, { "filename": "src/background/index.ts", "retrieved_chunk": "function watchCookies() {\n browser.cookies.onChanged.addListener(async (changeInfo) => {\n const { cookie, removed } = changeInfo\n // Ignore other cookies\n if (cookie.name !== 'dotcom_user') {\n return\n }\n if (removed) {\n if (cookie.name === 'dotcom_user') {\n console.info('dotcom_user cookie removed')", "score": 0.7483959197998047 }, { "filename": "src/shared.ts", "retrieved_chunk": " return false\n }\n if (urlMatchesAnyRule(url, rules)) {\n return false\n }\n return true\n}\nexport async function removeAccount(account: string) {\n await browser.runtime.sendMessage({ type: 'removeAccount', account })\n}", "score": 0.7329068183898926 }, { "filename": "src/popup/components/Accounts.tsx", "retrieved_chunk": " } else if (isGitHubUrl(tab?.url)) {\n await browser.tabs.update(tab?.id!, { url: 'https://github.com' })\n } else {\n await browser.tabs.create({ url: 'https://github.com' })\n }\n window.close()\n }\n async function handleRemove(accountName: string) {\n await removeAccount(accountName)\n setAccounts(accounts.filter((account) => account.name !== accountName))", "score": 0.7297602891921997 } ]
typescript
.closest(`.${ADD_ACCOUNT_BUTTON_ID}`)) {
import { createElement, createRemoveIcon } from './createElement' export const ADD_ACCOUNT_BUTTON_ID = 'gh-account-switcher__add-account' export const ACCOUNT_ITEM_CLASS = 'gh-account-switcher__account' export const ACCOUNT_REMOVE_CLASS = 'gh-account-switcher__account-remove' function isNewLook() { return document.querySelector('.AppHeader-user') !== null } function uiLook() { return isNewLook() ? newLook : classicLook } const classicLook = { createDivider() { return createElement('div', { class: 'dropdown-divider' }) }, createAddAccountLink() { return createElement('a', { id: ADD_ACCOUNT_BUTTON_ID, href: '/login', class: `dropdown-item ${ADD_ACCOUNT_BUTTON_ID}`, children: 'Add another account' }) }, createAccountItem(account: string) { const accountId = `${ACCOUNT_ITEM_CLASS}-${account}` return createElement('div', { id: accountId, class: 'gh-account-switcher__account-wrapper', children: [ createElement('button', { 'data-account': account, class: `dropdown-item btn-link ${ACCOUNT_ITEM_CLASS}`, role: 'menuitem', children: [ 'Switch to ', createElement('b', { children: account }), ], }), createElement('button', { title: 'Remove account', class: `btn-link ${ACCOUNT_REMOVE_CLASS}`, 'data-account': account, children
: createRemoveIcon(), }), ] }) }
} const newLook = { createDivider() { return createElement('li', { class: 'ActionList-sectionDivider' }) }, createAddAccountLink() { return createElement('li', { id: ADD_ACCOUNT_BUTTON_ID, class: 'ActionListItem', children: [ createElement('a', { class: `ActionListContent ${ADD_ACCOUNT_BUTTON_ID}`, href: '/login', children: [ createElement('span', { class: 'ActionListItem-label', children: 'Add another account' }) ] }) ] }) }, createAccountItem(account: string) { const accountId = `${ACCOUNT_ITEM_CLASS}-${account}` return createElement('li', { id: accountId, class: 'ActionListItem', children: [ createElement('button', { 'data-account': account, class: `ActionListContent ${ACCOUNT_ITEM_CLASS}`, children: [ createElement('span', { class: 'ActionListItem-label', children: [ 'Switch to ', createElement('b', { children: account }), ] }) ] }), createElement('button', { title: 'Remove account', 'data-account': account, class: `btn-link color-fg-danger ${ACCOUNT_REMOVE_CLASS}`, children: createRemoveIcon(), }) ] }) } } export function createDivider() { const look = uiLook() return look.createDivider(); } export function createAddAccountLink() { const look = uiLook() return look.createAddAccountLink(); } export function createAccountItem(account: string) { const look = uiLook() return look.createAccountItem(account); }
src/content/ui.ts
yuezk-github-account-switcher-36b3c11
[ { "filename": "src/content/index.ts", "retrieved_chunk": " if (!document.getElementById(ADD_ACCOUNT_BUTTON_ID)) {\n // Add the \"Add another account\" menu item and a divider\n const fragment = createElement('fragment', {\n children: [\n createAddAccountLink(),\n createDivider(),\n ],\n })\n // Insert the elements before the logoutForm\n logoutForm.parentElement?.insertBefore(fragment, logoutForm)", "score": 0.7408803105354309 }, { "filename": "src/content/index.ts", "retrieved_chunk": "// Script that will be injected in the main page\nimport { createElement } from './createElement'\nimport injectedScript from './injected?script&module'\nimport { ACCOUNT_ITEM_CLASS, ACCOUNT_REMOVE_CLASS, ADD_ACCOUNT_BUTTON_ID, createAccountItem, createAddAccountLink, createDivider } from './ui'\nasync function addSwitchUserMenu(logoutForm: HTMLFormElement) {\n const currentAccount = document.querySelector<HTMLMetaElement>('meta[name=\"user-login\"]')?.content\n if (!currentAccount) {\n console.info('no current account found')\n return\n }", "score": 0.7314658164978027 }, { "filename": "src/popup/components/AutoSwitchRules.tsx", "retrieved_chunk": " startIcon={<AddCircle />}\n onClick={startAdding}\n disabled={isAdding}\n sx={{ textTransform: 'none' }}\n >\n Add a Rule\n </Button>\n </Box>\n )\n}", "score": 0.7310295104980469 }, { "filename": "src/content/index.ts", "retrieved_chunk": " const closestTarget = target.closest(`.${ACCOUNT_ITEM_CLASS}`) as HTMLElement\n const { account } = closestTarget.dataset\n switchAccount(account!)\n } else if (target.closest(`.${ACCOUNT_REMOVE_CLASS}`)) {\n // remove account\n const btn = target.closest(`.${ACCOUNT_REMOVE_CLASS}`) as HTMLElement\n const { account } = btn.dataset\n removeAccount(account!).then(() => {\n btn.parentElement?.remove()\n })", "score": 0.7263531684875488 }, { "filename": "src/popup/components/Accounts.tsx", "retrieved_chunk": " title={`Remove ${account.name}`}\n onClick={() => handleRemove(account.name)}\n >\n <IconButton color=\"warning\">\n <Close />\n </IconButton>\n </Tooltip>\n </ListItemSecondaryAction>\n </ListItem>\n ))}", "score": 0.7193758487701416 } ]
typescript
: createRemoveIcon(), }), ] }) }
import { AddCircle } from '@mui/icons-material' import { Alert, Box, Button, Link } from '@mui/material' import { useEffect, useState } from 'react' import ruleService, { Rule } from '../../services/rule' import RuleItem from './RuleItem' export default function AutoSwitchRules() { const [rules, setRules] = useState<Rule[]>([]) const [isAdding, setIsAdding] = useState(false) useEffect(() => { ruleService.getAll().then(setRules) }, []) function startAdding() { setIsAdding(true) } function stopAdding() { setIsAdding(false) } async function addRule(rule: Rule) { await ruleService.add(rule) setRules(await ruleService.getAll()) stopAdding() } async function updateRule(rule: Rule) { await ruleService.update(rule) setRules(await ruleService.getAll()) } async function removeRule(rule: Rule) { await ruleService.remove(rule.id) setRules(await ruleService.getAll()) } return ( <Box> <Alert severity="info" sx={{ mb: 2 }}> When the request URL path matches the regular expression, the account will be switched to the specified account automatically,{' '} <Link href="https://github.com/yuezk/github-account-switcher#auto-switching" target="_blank" > see help </Link> . </Alert> <Box display="flex" flexDirection="column" gap={1} sx={{ '& > :last-child': { mb: 2, }, }} > {rules.map((rule) => (
<RuleItem key={rule.id} initialValue={rule} onDone={updateRule} onDelete={removeRule} /> ))}
{isAdding && <RuleItem mode="edit" onDone={addRule} onDelete={stopAdding} />} </Box> <Button variant="contained" startIcon={<AddCircle />} onClick={startAdding} disabled={isAdding} sx={{ textTransform: 'none' }} > Add a Rule </Button> </Box> ) }
src/popup/components/AutoSwitchRules.tsx
yuezk-github-account-switcher-36b3c11
[ { "filename": "src/popup/components/Settings.tsx", "retrieved_chunk": " setValue(newValue)\n }\n return (\n <TabContext value={value}>\n <Box sx={{ borderBottom: 1, borderColor: 'divider' }}>\n <TabList onChange={handleChange}>\n <Tab\n icon={<People />}\n iconPosition=\"start\"\n label=\"Accounts\"", "score": 0.8004235029220581 }, { "filename": "src/popup/components/Accounts.tsx", "retrieved_chunk": " }\n return (\n <Box>\n <Alert severity=\"info\" sx={{ mb: 2 }}>\n You can manage your logged in accounts here.\n </Alert>\n <Box sx={{ mb: 1 }}>\n <List dense disablePadding>\n {accounts.map((account, i) => (\n <ListItem key={account.name} disableGutters divider={i !== accounts.length - 1}>", "score": 0.7887725830078125 }, { "filename": "src/popup/components/RuleItem.tsx", "retrieved_chunk": " </IconButton>\n </Tooltip>\n )}\n {isEditing && (\n <Tooltip title=\"Done\">\n <IconButton size=\"small\" color=\"primary\" onClick={handleDone}>\n <Done />\n </IconButton>\n </Tooltip>\n )}", "score": 0.7651426792144775 }, { "filename": "src/popup/components/Accounts.tsx", "retrieved_chunk": " </List>\n </Box>\n <Button\n variant=\"contained\"\n sx={{ textTransform: 'none' }}\n startIcon={<PersonAdd />}\n onClick={handleLogin}\n >\n Login Another Account\n </Button>", "score": 0.7601166367530823 }, { "filename": "src/popup/components/Settings.tsx", "retrieved_chunk": " value=\"accounts\"\n sx={{ textTransform: 'none', minHeight: 50 }}\n />\n <Tab\n icon={<Rule />}\n iconPosition=\"start\"\n label=\"Auto Switch Rules\"\n value=\"rules\"\n sx={{ textTransform: 'none', minHeight: 50 }}\n />", "score": 0.7600504159927368 } ]
typescript
<RuleItem key={rule.id} initialValue={rule} onDone={updateRule} onDelete={removeRule} /> ))}
import { Close, Login, PersonAdd } from '@mui/icons-material' import { Alert, Avatar, Badge, Box, Button, IconButton, List, ListItem, ListItemAvatar, ListItemSecondaryAction, ListItemText, Tooltip, styled, } from '@mui/material' import { useEffect, useState } from 'react' import browser, { Tabs } from 'webextension-polyfill' import accountService, { Account } from '../../services/account' import cookie from '../../services/cookie' import rule from '../../services/rule' import { isGitHubUrl, isNormalGitHubUrl, removeAccount } from '../../shared' const StyledBadge = styled(Badge)(({ theme }) => ({ '& .MuiBadge-badge': { backgroundColor: '#44b700', color: '#44b700', boxShadow: `0 0 0 2px ${theme.palette.background.paper}`, '&::after': { position: 'absolute', top: 0, left: 0, width: '100%', height: '100%', borderRadius: '50%', animation: 'ripple 1.2s infinite ease-in-out', border: '1px solid currentColor', content: '""', }, }, '@keyframes ripple': { '0%': { transform: 'scale(.8)', opacity: 1, }, '100%': { transform: 'scale(2.4)', opacity: 0, }, }, })) function GitHubAvatar({ account }: { account: Account }) { const { name, active } = account const avatarUrl = account.avatarUrl ?? `https://github.com/${name}.png?size=100` const avatar = <Avatar src={avatarUrl} /> if (active) { return ( <StyledBadge overlap="circular" anchorOrigin={{ vertical: 'bottom', horizontal: 'right' }} variant="dot" > {avatar} </StyledBadge> ) } return avatar } async function getCurrentTab(): Promise<Tabs.Tab | undefined> { const queryOptions = { active: true, lastFocusedWindow: true } // `tab` will either be a `tabs.Tab` instance or `undefined`. const [tab] = await browser.tabs.query(queryOptions) return tab } export default function Accounts() { const [accounts, setAccounts] = useState<Account[]>([]) useEffect(() => { accountService.getAll().then(setAccounts) }, []) async function handleLogin() { await cookie.clear() const tab = await getCurrentTab() const rules =
await rule.getAll() if (isNormalGitHubUrl(tab?.url, rules)) {
await browser.tabs.update(tab?.id!, { url: `https://github.com/login?return_to=${encodeURIComponent(tab?.url ?? '')}`, }) } else if (isGitHubUrl(tab?.url)) { await browser.tabs.update(tab?.id!, { url: 'https://github.com/login' }) } else { await browser.tabs.create({ url: 'https://github.com/login' }) } window.close() } async function handleSwitch(username: string) { await accountService.switchTo(username) const tab = await getCurrentTab() const rules = await rule.getAll() // If the current tab is a normal GitHub page, reload it. if (isNormalGitHubUrl(tab?.url, rules)) { await browser.tabs.reload(tab?.id!) } else if (isGitHubUrl(tab?.url)) { await browser.tabs.update(tab?.id!, { url: 'https://github.com' }) } else { await browser.tabs.create({ url: 'https://github.com' }) } window.close() } async function handleRemove(accountName: string) { await removeAccount(accountName) setAccounts(accounts.filter((account) => account.name !== accountName)) } return ( <Box> <Alert severity="info" sx={{ mb: 2 }}> You can manage your logged in accounts here. </Alert> <Box sx={{ mb: 1 }}> <List dense disablePadding> {accounts.map((account, i) => ( <ListItem key={account.name} disableGutters divider={i !== accounts.length - 1}> <ListItemAvatar> <GitHubAvatar account={account} /> </ListItemAvatar> <ListItemText primary={account.name} secondary={account.expiresAt && `Expires at ${account.expiresAt.toLocaleString()}`} /> <ListItemSecondaryAction> <Tooltip title={`Switch to ${account.name}`}> <span> <IconButton color="primary" disabled={account.active} onClick={() => handleSwitch(account.name)} > <Login /> </IconButton> </span> </Tooltip> <Tooltip title={`Remove ${account.name}`} onClick={() => handleRemove(account.name)} > <IconButton color="warning"> <Close /> </IconButton> </Tooltip> </ListItemSecondaryAction> </ListItem> ))} </List> </Box> <Button variant="contained" sx={{ textTransform: 'none' }} startIcon={<PersonAdd />} onClick={handleLogin} > Login Another Account </Button> </Box> ) }
src/popup/components/Accounts.tsx
yuezk-github-account-switcher-36b3c11
[ { "filename": "src/background/index.ts", "retrieved_chunk": " }\n await setBadgeText(account.slice(0, 2))\n}\nasync function removeAccount(accountName: string) {\n await accountService.remove(accountName)\n await updateDynamicRequestRules()\n}\nasync function buildCookieValue(accountName: string): Promise<string | null> {\n const account = await accountService.find(accountName)\n const cookies = account?.cookies || []", "score": 0.8399566411972046 }, { "filename": "src/services/account.ts", "retrieved_chunk": "async function find(accountName: string): Promise<Account | undefined> {\n const accounts = await getAll()\n return accounts.find((account) => account.name === accountName)\n}\nasync function upsert(accountName: string, cookies: Cookie[]) {\n await storage.update<Accounts>('accounts', (accounts = {}) => {\n accounts[accountName] = cookies\n return accounts\n })\n}", "score": 0.8244367837905884 }, { "filename": "src/services/account.ts", "retrieved_chunk": " expiresAt?: Date\n}\ntype Accounts = Record<string, Cookie[]>\nasync function getAll(): Promise<Account[]> {\n const accounts = await storage.get<Accounts>('accounts')\n if (!accounts) {\n return []\n }\n const currentAccount = await browser.cookies.get({\n url: 'https://github.com',", "score": 0.8175404667854309 }, { "filename": "src/content/index.ts", "retrieved_chunk": "async function getAutoSwitchRules() {\n const res: GetAutoSwitchRulesResponse = await browser.runtime.sendMessage({\n type: 'getAutoSwitchRules',\n } as GetAutoSwitchRulesMessage)\n return res?.success ? res.data : []\n}\nasync function addAccount() {\n await browser.runtime.sendMessage({ type: 'clearCookies' } as ClearCookiesMessage)\n const autoSwitchRules = await getAutoSwitchRules()\n window.location.href = isNormalGitHubUrl(window.location.href, autoSwitchRules)", "score": 0.817084789276123 }, { "filename": "src/background/index.ts", "retrieved_chunk": " const autoSwitchRules = await ruleService.getAll()\n for (const [index, rule] of autoSwitchRules.entries()) {\n const cookieValue = await buildCookieValue(rule.account)\n if (!cookieValue) {\n continue\n }\n requestRules.push({\n id: index + 1,\n priority: 1,\n action: {", "score": 0.8139616847038269 } ]
typescript
await rule.getAll() if (isNormalGitHubUrl(tab?.url, rules)) {
import { Close, Login, PersonAdd } from '@mui/icons-material' import { Alert, Avatar, Badge, Box, Button, IconButton, List, ListItem, ListItemAvatar, ListItemSecondaryAction, ListItemText, Tooltip, styled, } from '@mui/material' import { useEffect, useState } from 'react' import browser, { Tabs } from 'webextension-polyfill' import accountService, { Account } from '../../services/account' import cookie from '../../services/cookie' import rule from '../../services/rule' import { isGitHubUrl, isNormalGitHubUrl, removeAccount } from '../../shared' const StyledBadge = styled(Badge)(({ theme }) => ({ '& .MuiBadge-badge': { backgroundColor: '#44b700', color: '#44b700', boxShadow: `0 0 0 2px ${theme.palette.background.paper}`, '&::after': { position: 'absolute', top: 0, left: 0, width: '100%', height: '100%', borderRadius: '50%', animation: 'ripple 1.2s infinite ease-in-out', border: '1px solid currentColor', content: '""', }, }, '@keyframes ripple': { '0%': { transform: 'scale(.8)', opacity: 1, }, '100%': { transform: 'scale(2.4)', opacity: 0, }, }, })) function GitHubAvatar({ account }: { account: Account }) { const { name, active } = account const avatarUrl = account
.avatarUrl ?? `https://github.com/${name}.png?size=100` const avatar = <Avatar src={avatarUrl} /> if (active) {
return ( <StyledBadge overlap="circular" anchorOrigin={{ vertical: 'bottom', horizontal: 'right' }} variant="dot" > {avatar} </StyledBadge> ) } return avatar } async function getCurrentTab(): Promise<Tabs.Tab | undefined> { const queryOptions = { active: true, lastFocusedWindow: true } // `tab` will either be a `tabs.Tab` instance or `undefined`. const [tab] = await browser.tabs.query(queryOptions) return tab } export default function Accounts() { const [accounts, setAccounts] = useState<Account[]>([]) useEffect(() => { accountService.getAll().then(setAccounts) }, []) async function handleLogin() { await cookie.clear() const tab = await getCurrentTab() const rules = await rule.getAll() if (isNormalGitHubUrl(tab?.url, rules)) { await browser.tabs.update(tab?.id!, { url: `https://github.com/login?return_to=${encodeURIComponent(tab?.url ?? '')}`, }) } else if (isGitHubUrl(tab?.url)) { await browser.tabs.update(tab?.id!, { url: 'https://github.com/login' }) } else { await browser.tabs.create({ url: 'https://github.com/login' }) } window.close() } async function handleSwitch(username: string) { await accountService.switchTo(username) const tab = await getCurrentTab() const rules = await rule.getAll() // If the current tab is a normal GitHub page, reload it. if (isNormalGitHubUrl(tab?.url, rules)) { await browser.tabs.reload(tab?.id!) } else if (isGitHubUrl(tab?.url)) { await browser.tabs.update(tab?.id!, { url: 'https://github.com' }) } else { await browser.tabs.create({ url: 'https://github.com' }) } window.close() } async function handleRemove(accountName: string) { await removeAccount(accountName) setAccounts(accounts.filter((account) => account.name !== accountName)) } return ( <Box> <Alert severity="info" sx={{ mb: 2 }}> You can manage your logged in accounts here. </Alert> <Box sx={{ mb: 1 }}> <List dense disablePadding> {accounts.map((account, i) => ( <ListItem key={account.name} disableGutters divider={i !== accounts.length - 1}> <ListItemAvatar> <GitHubAvatar account={account} /> </ListItemAvatar> <ListItemText primary={account.name} secondary={account.expiresAt && `Expires at ${account.expiresAt.toLocaleString()}`} /> <ListItemSecondaryAction> <Tooltip title={`Switch to ${account.name}`}> <span> <IconButton color="primary" disabled={account.active} onClick={() => handleSwitch(account.name)} > <Login /> </IconButton> </span> </Tooltip> <Tooltip title={`Remove ${account.name}`} onClick={() => handleRemove(account.name)} > <IconButton color="warning"> <Close /> </IconButton> </Tooltip> </ListItemSecondaryAction> </ListItem> ))} </List> </Box> <Button variant="contained" sx={{ textTransform: 'none' }} startIcon={<PersonAdd />} onClick={handleLogin} > Login Another Account </Button> </Box> ) }
src/popup/components/Accounts.tsx
yuezk-github-account-switcher-36b3c11
[ { "filename": "src/services/account.ts", "retrieved_chunk": " if (!accounts) {\n return\n }\n delete accounts[accountName]\n return accounts\n })\n}\nasync function saveAvatar(accountName: string, avatarUrl: string) {\n await storage.update<Record<string, string>>('avatars', (avatars = {}) => {\n avatars[accountName] = avatarUrl", "score": 0.8168008327484131 }, { "filename": "src/services/account.ts", "retrieved_chunk": " name: 'dotcom_user',\n })\n const avatarUrls = await storage.get<Record<string, string>>('avatars')\n return Object.entries(accounts).map(([name, cookies]) => {\n const userSessionCookie = cookies.find(({ name }) => name === 'user_session')\n return {\n name,\n cookies,\n active: currentAccount?.value === name,\n avatarUrl: avatarUrls?.[name],", "score": 0.7891306281089783 }, { "filename": "src/popup/components/Header.tsx", "retrieved_chunk": "import { GitHub } from '@mui/icons-material'\nimport { Avatar, Container, IconButton, Typography } from '@mui/material'\nimport { useState } from 'react'\nimport logo from '../../assets/logo.png'\nexport default function Header() {\n const [active, setActive] = useState(false)\n function handleClick() {\n setActive(!active)\n }\n return (", "score": 0.7781894207000732 }, { "filename": "src/services/account.ts", "retrieved_chunk": " expiresAt?: Date\n}\ntype Accounts = Record<string, Cookie[]>\nasync function getAll(): Promise<Account[]> {\n const accounts = await storage.get<Accounts>('accounts')\n if (!accounts) {\n return []\n }\n const currentAccount = await browser.cookies.get({\n url: 'https://github.com',", "score": 0.7699421644210815 }, { "filename": "src/services/account.ts", "retrieved_chunk": "async function switchTo(accountName: string) {\n await cookie.clear()\n const account = await find(accountName)\n const cookies = account?.cookies || []\n for (const cookie of cookies) {\n const { hostOnly, domain, session, ...rest } = cookie\n await browser.cookies.set({\n url: 'https://github.com',\n domain: hostOnly ? undefined : domain,\n ...rest,", "score": 0.7679917812347412 } ]
typescript
.avatarUrl ?? `https://github.com/${name}.png?size=100` const avatar = <Avatar src={avatarUrl} /> if (active) {
import browser from 'webextension-polyfill' import { isNormalGitHubUrl, removeAccount } from '../shared' import { ClearCookiesMessage, GetAccountsMessage, GetAccountsResponse, GetAutoSwitchRulesMessage, GetAutoSwitchRulesResponse, } from '../types' import './index.css' // Script that will be injected in the main page import { createElement } from './createElement' import injectedScript from './injected?script&module' import { ACCOUNT_ITEM_CLASS, ACCOUNT_REMOVE_CLASS, ADD_ACCOUNT_BUTTON_ID, createAccountItem, createAddAccountLink, createDivider } from './ui' async function addSwitchUserMenu(logoutForm: HTMLFormElement) { const currentAccount = document.querySelector<HTMLMetaElement>('meta[name="user-login"]')?.content if (!currentAccount) { console.info('no current account found') return } if (!document.getElementById(ADD_ACCOUNT_BUTTON_ID)) { // Add the "Add another account" menu item and a divider const fragment = createElement('fragment', { children: [ createAddAccountLink(), createDivider(), ], }) // Insert the elements before the logoutForm logoutForm.parentElement?.insertBefore(fragment, logoutForm) } const res: GetAccountsResponse = await browser.runtime.sendMessage({ type: 'getAccounts', } as GetAccountsMessage) if (!res?.success) { return } const { data: accounts } = res const addAccountButton = document.getElementById(ADD_ACCOUNT_BUTTON_ID)! for (const account of accounts) { if (account === currentAccount) { continue } const accountId = `${ACCOUNT_ITEM_CLASS}-${account}` if (!document.getElementById(accountId) && addAccountButton) { const accountWrapper = createAccountItem(account) addAccountButton.parentElement?.insertBefore(accountWrapper, addAccountButton) } } } async function getAutoSwitchRules() { const res: GetAutoSwitchRulesResponse = await browser.runtime.sendMessage({ type: 'getAutoSwitchRules', } as GetAutoSwitchRulesMessage) return res?.success ? res.data : [] } async function addAccount() { await browser.runtime.sendMessage({ type: 'clearCookies' } as ClearCookiesMessage) const autoSwitchRules = await getAutoSwitchRules() window.location.href = isNormalGitHubUrl(window.location.href, autoSwitchRules) ? `/login?return_to=${encodeURIComponent(window.location.href)}` : '/login' } async function switchAccount(account: string) { await browser.runtime.sendMessage({ type: 'switchAccount', account }) const autoSwitchRules = await getAutoSwitchRules() if (isNormalGitHubUrl(window.location.href, autoSwitchRules)) { window.location.reload() } else { window.location.href = '/' } } function injectScript() { const script = document.createElement('script') script.src = browser.runtime.getURL(injectedScript) script.type = 'module' document.head.prepend(script) } function ready(fn: () => void) { if (document.readyState !== 'loading') { fn() return } document.addEventListener('DOMContentLoaded', fn) } function watchDom() { new MutationObserver((mutations) => { for (const mutation of mutations) { const isOpen = mutation.type === 'attributes' && mutation.attributeName === 'open' && mutation.target instanceof HTMLElement && mutation.target.hasAttribute('open') if (isOpen || (mutation.type === 'childList' && mutation.target instanceof HTMLElement)) { // Find the logout form on GitHub page or Gist page const logoutForm = mutation.target.querySelector<HTMLFormElement>( '.js-loggout-form, #user-links .logout-form, user-drawer-side-panel nav-list .ActionListItem:last-child', ) if (logoutForm) { addSwitchUserMenu(logoutForm) } } } }).observe(document.documentElement, { childList: true, subtree: true, attributes: true, }) } async function init() { injectScript() ready(watchDom) document.addEventListener('click', (event) => { const target = event.target as HTMLElement if (target.closest(`.${ADD_ACCOUNT_BUTTON_ID}`)) { // add another account event.preventDefault() addAccount() } else if (target.closest(`.${ACCOUNT_ITEM_CLASS}`)) { // switch to account const closestTarget = target.closest(`.${ACCOUNT_ITEM_CLASS}`) as HTMLElement const { account } = closestTarget.dataset switchAccount(account!) } else if
(target.closest(`.${ACCOUNT_REMOVE_CLASS}`)) {
// remove account const btn = target.closest(`.${ACCOUNT_REMOVE_CLASS}`) as HTMLElement const { account } = btn.dataset removeAccount(account!).then(() => { btn.parentElement?.remove() }) } }) } init()
src/content/index.ts
yuezk-github-account-switcher-36b3c11
[ { "filename": "src/content/ui.ts", "retrieved_chunk": " class: `dropdown-item ${ADD_ACCOUNT_BUTTON_ID}`,\n children: 'Add another account'\n })\n },\n createAccountItem(account: string) {\n const accountId = `${ACCOUNT_ITEM_CLASS}-${account}`\n return createElement('div', {\n id: accountId,\n class: 'gh-account-switcher__account-wrapper',\n children: [", "score": 0.8007491230964661 }, { "filename": "src/content/ui.ts", "retrieved_chunk": " ]\n })\n },\n createAccountItem(account: string) {\n const accountId = `${ACCOUNT_ITEM_CLASS}-${account}`\n return createElement('li', {\n id: accountId,\n class: 'ActionListItem',\n children: [\n createElement('button', {", "score": 0.7701314687728882 }, { "filename": "src/content/injected.ts", "retrieved_chunk": " return url.href\n }\n}\nfunction patchUrl(oldUrl: string | URL) {\n const account = document.querySelector<HTMLMetaElement>('meta[name=\"user-login\"]')?.content\n if (!account) {\n return oldUrl\n }\n const newUrl = new URL(oldUrl, window.location.origin)\n newUrl.searchParams.append(ACCOUNT_PARAM, account)", "score": 0.7431843280792236 }, { "filename": "src/content/ui.ts", "retrieved_chunk": "const classicLook = {\n createDivider() {\n return createElement('div', {\n class: 'dropdown-divider'\n })\n },\n createAddAccountLink() {\n return createElement('a', {\n id: ADD_ACCOUNT_BUTTON_ID,\n href: '/login',", "score": 0.7424116134643555 }, { "filename": "src/popup/components/Accounts.tsx", "retrieved_chunk": " }\n window.close()\n }\n async function handleSwitch(username: string) {\n await accountService.switchTo(username)\n const tab = await getCurrentTab()\n const rules = await rule.getAll()\n // If the current tab is a normal GitHub page, reload it.\n if (isNormalGitHubUrl(tab?.url, rules)) {\n await browser.tabs.reload(tab?.id!)", "score": 0.7304056882858276 } ]
typescript
(target.closest(`.${ACCOUNT_REMOVE_CLASS}`)) {
import { Close, Login, PersonAdd } from '@mui/icons-material' import { Alert, Avatar, Badge, Box, Button, IconButton, List, ListItem, ListItemAvatar, ListItemSecondaryAction, ListItemText, Tooltip, styled, } from '@mui/material' import { useEffect, useState } from 'react' import browser, { Tabs } from 'webextension-polyfill' import accountService, { Account } from '../../services/account' import cookie from '../../services/cookie' import rule from '../../services/rule' import { isGitHubUrl, isNormalGitHubUrl, removeAccount } from '../../shared' const StyledBadge = styled(Badge)(({ theme }) => ({ '& .MuiBadge-badge': { backgroundColor: '#44b700', color: '#44b700', boxShadow: `0 0 0 2px ${theme.palette.background.paper}`, '&::after': { position: 'absolute', top: 0, left: 0, width: '100%', height: '100%', borderRadius: '50%', animation: 'ripple 1.2s infinite ease-in-out', border: '1px solid currentColor', content: '""', }, }, '@keyframes ripple': { '0%': { transform: 'scale(.8)', opacity: 1, }, '100%': { transform: 'scale(2.4)', opacity: 0, }, }, })) function GitHubAvatar({ account }: { account: Account }) { const { name, active } = account const avatarUrl = account.avatarUrl ?? `https://github.com/${name}.png?size=100` const avatar = <Avatar src={avatarUrl} /> if (active) { return ( <StyledBadge overlap="circular" anchorOrigin={{ vertical: 'bottom', horizontal: 'right' }} variant="dot" > {avatar} </StyledBadge> ) } return avatar } async function getCurrentTab(): Promise<Tabs.Tab | undefined> { const queryOptions = { active: true, lastFocusedWindow: true } // `tab` will either be a `tabs.Tab` instance or `undefined`. const [tab] = await browser.tabs.query(queryOptions) return tab } export default function Accounts() { const [accounts, setAccounts] = useState<Account[]>([]) useEffect(() => { accountService.getAll().then(setAccounts) }, []) async function handleLogin() { await cookie.clear() const tab = await getCurrentTab() const rules = await rule.getAll() if (isNormalGitHubUrl(tab?.url, rules)) { await browser.tabs.update(tab?.id!, { url: `https://github.com/login?return_to=${encodeURIComponent(tab?.url ?? '')}`, }) } else
if (isGitHubUrl(tab?.url)) {
await browser.tabs.update(tab?.id!, { url: 'https://github.com/login' }) } else { await browser.tabs.create({ url: 'https://github.com/login' }) } window.close() } async function handleSwitch(username: string) { await accountService.switchTo(username) const tab = await getCurrentTab() const rules = await rule.getAll() // If the current tab is a normal GitHub page, reload it. if (isNormalGitHubUrl(tab?.url, rules)) { await browser.tabs.reload(tab?.id!) } else if (isGitHubUrl(tab?.url)) { await browser.tabs.update(tab?.id!, { url: 'https://github.com' }) } else { await browser.tabs.create({ url: 'https://github.com' }) } window.close() } async function handleRemove(accountName: string) { await removeAccount(accountName) setAccounts(accounts.filter((account) => account.name !== accountName)) } return ( <Box> <Alert severity="info" sx={{ mb: 2 }}> You can manage your logged in accounts here. </Alert> <Box sx={{ mb: 1 }}> <List dense disablePadding> {accounts.map((account, i) => ( <ListItem key={account.name} disableGutters divider={i !== accounts.length - 1}> <ListItemAvatar> <GitHubAvatar account={account} /> </ListItemAvatar> <ListItemText primary={account.name} secondary={account.expiresAt && `Expires at ${account.expiresAt.toLocaleString()}`} /> <ListItemSecondaryAction> <Tooltip title={`Switch to ${account.name}`}> <span> <IconButton color="primary" disabled={account.active} onClick={() => handleSwitch(account.name)} > <Login /> </IconButton> </span> </Tooltip> <Tooltip title={`Remove ${account.name}`} onClick={() => handleRemove(account.name)} > <IconButton color="warning"> <Close /> </IconButton> </Tooltip> </ListItemSecondaryAction> </ListItem> ))} </List> </Box> <Button variant="contained" sx={{ textTransform: 'none' }} startIcon={<PersonAdd />} onClick={handleLogin} > Login Another Account </Button> </Box> ) }
src/popup/components/Accounts.tsx
yuezk-github-account-switcher-36b3c11
[ { "filename": "src/content/index.ts", "retrieved_chunk": " ? `/login?return_to=${encodeURIComponent(window.location.href)}`\n : '/login'\n}\nasync function switchAccount(account: string) {\n await browser.runtime.sendMessage({ type: 'switchAccount', account })\n const autoSwitchRules = await getAutoSwitchRules()\n if (isNormalGitHubUrl(window.location.href, autoSwitchRules)) {\n window.location.reload()\n } else {\n window.location.href = '/'", "score": 0.8383967876434326 }, { "filename": "src/content/injected.ts", "retrieved_chunk": " return url.href\n }\n}\nfunction patchUrl(oldUrl: string | URL) {\n const account = document.querySelector<HTMLMetaElement>('meta[name=\"user-login\"]')?.content\n if (!account) {\n return oldUrl\n }\n const newUrl = new URL(oldUrl, window.location.origin)\n newUrl.searchParams.append(ACCOUNT_PARAM, account)", "score": 0.7846174836158752 }, { "filename": "src/content/index.ts", "retrieved_chunk": "async function getAutoSwitchRules() {\n const res: GetAutoSwitchRulesResponse = await browser.runtime.sendMessage({\n type: 'getAutoSwitchRules',\n } as GetAutoSwitchRulesMessage)\n return res?.success ? res.data : []\n}\nasync function addAccount() {\n await browser.runtime.sendMessage({ type: 'clearCookies' } as ClearCookiesMessage)\n const autoSwitchRules = await getAutoSwitchRules()\n window.location.href = isNormalGitHubUrl(window.location.href, autoSwitchRules)", "score": 0.779248833656311 }, { "filename": "src/services/account.ts", "retrieved_chunk": "async function switchTo(accountName: string) {\n await cookie.clear()\n const account = await find(accountName)\n const cookies = account?.cookies || []\n for (const cookie of cookies) {\n const { hostOnly, domain, session, ...rest } = cookie\n await browser.cookies.set({\n url: 'https://github.com',\n domain: hostOnly ? undefined : domain,\n ...rest,", "score": 0.7689046263694763 }, { "filename": "src/shared.ts", "retrieved_chunk": " return false\n }\n if (urlMatchesAnyRule(url, rules)) {\n return false\n }\n return true\n}\nexport async function removeAccount(account: string) {\n await browser.runtime.sendMessage({ type: 'removeAccount', account })\n}", "score": 0.7612799406051636 } ]
typescript
if (isGitHubUrl(tab?.url)) {
import browser, { Cookies } from 'webextension-polyfill' import { setBadgeText } from './badge' import cookie from './cookie' import storage from './storage' type Cookie = Cookies.Cookie export type Account = { name: string cookies: Cookie[] active: boolean avatarUrl?: string expiresAt?: Date } type Accounts = Record<string, Cookie[]> async function getAll(): Promise<Account[]> { const accounts = await storage.get<Accounts>('accounts') if (!accounts) { return [] } const currentAccount = await browser.cookies.get({ url: 'https://github.com', name: 'dotcom_user', }) const avatarUrls = await storage.get<Record<string, string>>('avatars') return Object.entries(accounts).map(([name, cookies]) => { const userSessionCookie = cookies.find(({ name }) => name === 'user_session') return { name, cookies, active: currentAccount?.value === name, avatarUrl: avatarUrls?.[name], expiresAt: userSessionCookie?.expirationDate ? new Date(userSessionCookie.expirationDate * 1000) : undefined, } }) } async function getAllNames(): Promise<string[]> { const accounts = await getAll() return accounts.map(({ name }) => name) } async function find(accountName: string): Promise<Account | undefined> { const accounts = await getAll() return accounts.find((account) => account.name === accountName) } async function upsert(accountName: string, cookies: Cookie[]) { await storage.update<Accounts>('accounts', (accounts = {}) => { accounts[accountName] = cookies return accounts }) } async function switchTo(accountName: string) { await cookie.clear() const account = await find(accountName) const cookies = account?.cookies || [] for (const cookie of cookies) { const { hostOnly, domain, session, ...rest } = cookie await browser.cookies.set({ url: 'https://github.com', domain: hostOnly ? undefined : domain, ...rest, }) } if (cookies.length) { setBadgeText(accountName.slice(0, 2)) } else { setBadgeText('...') } } async function remove(accountName: string) {
await storage.update<Accounts>('accounts', (accounts) => {
if (!accounts) { return } delete accounts[accountName] return accounts }) } async function saveAvatar(accountName: string, avatarUrl: string) { await storage.update<Record<string, string>>('avatars', (avatars = {}) => { avatars[accountName] = avatarUrl return avatars }) } export default { getAll, getAllNames, find, upsert, switchTo, remove, saveAvatar, }
src/services/account.ts
yuezk-github-account-switcher-36b3c11
[ { "filename": "src/background/index.ts", "retrieved_chunk": " }\n await setBadgeText(account.slice(0, 2))\n}\nasync function removeAccount(accountName: string) {\n await accountService.remove(accountName)\n await updateDynamicRequestRules()\n}\nasync function buildCookieValue(accountName: string): Promise<string | null> {\n const account = await accountService.find(accountName)\n const cookies = account?.cookies || []", "score": 0.8693202137947083 }, { "filename": "src/popup/components/Accounts.tsx", "retrieved_chunk": " } else if (isGitHubUrl(tab?.url)) {\n await browser.tabs.update(tab?.id!, { url: 'https://github.com' })\n } else {\n await browser.tabs.create({ url: 'https://github.com' })\n }\n window.close()\n }\n async function handleRemove(accountName: string) {\n await removeAccount(accountName)\n setAccounts(accounts.filter((account) => account.name !== accountName))", "score": 0.8229975700378418 }, { "filename": "src/shared.ts", "retrieved_chunk": " return false\n }\n if (urlMatchesAnyRule(url, rules)) {\n return false\n }\n return true\n}\nexport async function removeAccount(account: string) {\n await browser.runtime.sendMessage({ type: 'removeAccount', account })\n}", "score": 0.8084151744842529 }, { "filename": "src/popup/components/Accounts.tsx", "retrieved_chunk": " const [tab] = await browser.tabs.query(queryOptions)\n return tab\n}\nexport default function Accounts() {\n const [accounts, setAccounts] = useState<Account[]>([])\n useEffect(() => {\n accountService.getAll().then(setAccounts)\n }, [])\n async function handleLogin() {\n await cookie.clear()", "score": 0.7992666959762573 }, { "filename": "src/background/index.ts", "retrieved_chunk": " if (!account) {\n return\n }\n await accountService.upsert(account, await cookie.getAll())\n const accounts = await accountService.getAll()\n console.info('synced accounts', accounts)\n await updateDynamicRequestRules()\n const res = await fetch(`https://github.com/${account}.png?size=100`)\n if (res.status === 200) {\n accountService.saveAvatar(account, res.url)", "score": 0.7956951856613159 } ]
typescript
await storage.update<Accounts>('accounts', (accounts) => {
import { Close, Login, PersonAdd } from '@mui/icons-material' import { Alert, Avatar, Badge, Box, Button, IconButton, List, ListItem, ListItemAvatar, ListItemSecondaryAction, ListItemText, Tooltip, styled, } from '@mui/material' import { useEffect, useState } from 'react' import browser, { Tabs } from 'webextension-polyfill' import accountService, { Account } from '../../services/account' import cookie from '../../services/cookie' import rule from '../../services/rule' import { isGitHubUrl, isNormalGitHubUrl, removeAccount } from '../../shared' const StyledBadge = styled(Badge)(({ theme }) => ({ '& .MuiBadge-badge': { backgroundColor: '#44b700', color: '#44b700', boxShadow: `0 0 0 2px ${theme.palette.background.paper}`, '&::after': { position: 'absolute', top: 0, left: 0, width: '100%', height: '100%', borderRadius: '50%', animation: 'ripple 1.2s infinite ease-in-out', border: '1px solid currentColor', content: '""', }, }, '@keyframes ripple': { '0%': { transform: 'scale(.8)', opacity: 1, }, '100%': { transform: 'scale(2.4)', opacity: 0, }, }, })) function GitHubAvatar({ account }: { account: Account }) { const { name, active } = account const avatarUrl = account.avatarUrl ?? `https://github.com/${name}.png?size=100` const avatar = <Avatar src={avatarUrl} /> if (active) { return ( <StyledBadge overlap="circular" anchorOrigin={{ vertical: 'bottom', horizontal: 'right' }} variant="dot" > {avatar} </StyledBadge> ) } return avatar } async function getCurrentTab(): Promise<Tabs.Tab | undefined> { const queryOptions = { active: true, lastFocusedWindow: true } // `tab` will either be a `tabs.Tab` instance or `undefined`. const [tab] = await browser.tabs.query(queryOptions) return tab } export default function Accounts() { const [accounts, setAccounts] = useState<Account[]>([]) useEffect(() => { accountService
.getAll().then(setAccounts) }, []) async function handleLogin() {
await cookie.clear() const tab = await getCurrentTab() const rules = await rule.getAll() if (isNormalGitHubUrl(tab?.url, rules)) { await browser.tabs.update(tab?.id!, { url: `https://github.com/login?return_to=${encodeURIComponent(tab?.url ?? '')}`, }) } else if (isGitHubUrl(tab?.url)) { await browser.tabs.update(tab?.id!, { url: 'https://github.com/login' }) } else { await browser.tabs.create({ url: 'https://github.com/login' }) } window.close() } async function handleSwitch(username: string) { await accountService.switchTo(username) const tab = await getCurrentTab() const rules = await rule.getAll() // If the current tab is a normal GitHub page, reload it. if (isNormalGitHubUrl(tab?.url, rules)) { await browser.tabs.reload(tab?.id!) } else if (isGitHubUrl(tab?.url)) { await browser.tabs.update(tab?.id!, { url: 'https://github.com' }) } else { await browser.tabs.create({ url: 'https://github.com' }) } window.close() } async function handleRemove(accountName: string) { await removeAccount(accountName) setAccounts(accounts.filter((account) => account.name !== accountName)) } return ( <Box> <Alert severity="info" sx={{ mb: 2 }}> You can manage your logged in accounts here. </Alert> <Box sx={{ mb: 1 }}> <List dense disablePadding> {accounts.map((account, i) => ( <ListItem key={account.name} disableGutters divider={i !== accounts.length - 1}> <ListItemAvatar> <GitHubAvatar account={account} /> </ListItemAvatar> <ListItemText primary={account.name} secondary={account.expiresAt && `Expires at ${account.expiresAt.toLocaleString()}`} /> <ListItemSecondaryAction> <Tooltip title={`Switch to ${account.name}`}> <span> <IconButton color="primary" disabled={account.active} onClick={() => handleSwitch(account.name)} > <Login /> </IconButton> </span> </Tooltip> <Tooltip title={`Remove ${account.name}`} onClick={() => handleRemove(account.name)} > <IconButton color="warning"> <Close /> </IconButton> </Tooltip> </ListItemSecondaryAction> </ListItem> ))} </List> </Box> <Button variant="contained" sx={{ textTransform: 'none' }} startIcon={<PersonAdd />} onClick={handleLogin} > Login Another Account </Button> </Box> ) }
src/popup/components/Accounts.tsx
yuezk-github-account-switcher-36b3c11
[ { "filename": "src/services/account.ts", "retrieved_chunk": "async function find(accountName: string): Promise<Account | undefined> {\n const accounts = await getAll()\n return accounts.find((account) => account.name === accountName)\n}\nasync function upsert(accountName: string, cookies: Cookie[]) {\n await storage.update<Accounts>('accounts', (accounts = {}) => {\n accounts[accountName] = cookies\n return accounts\n })\n}", "score": 0.8501187562942505 }, { "filename": "src/services/account.ts", "retrieved_chunk": " expiresAt?: Date\n}\ntype Accounts = Record<string, Cookie[]>\nasync function getAll(): Promise<Account[]> {\n const accounts = await storage.get<Accounts>('accounts')\n if (!accounts) {\n return []\n }\n const currentAccount = await browser.cookies.get({\n url: 'https://github.com',", "score": 0.8365877866744995 }, { "filename": "src/background/index.ts", "retrieved_chunk": " }\n await setBadgeText(account.slice(0, 2))\n}\nasync function removeAccount(accountName: string) {\n await accountService.remove(accountName)\n await updateDynamicRequestRules()\n}\nasync function buildCookieValue(accountName: string): Promise<string | null> {\n const account = await accountService.find(accountName)\n const cookies = account?.cookies || []", "score": 0.8340029120445251 }, { "filename": "src/content/index.ts", "retrieved_chunk": " }\n const res: GetAccountsResponse = await browser.runtime.sendMessage({\n type: 'getAccounts',\n } as GetAccountsMessage)\n if (!res?.success) {\n return\n }\n const { data: accounts } = res\n const addAccountButton = document.getElementById(ADD_ACCOUNT_BUTTON_ID)!\n for (const account of accounts) {", "score": 0.8067933320999146 }, { "filename": "src/services/account.ts", "retrieved_chunk": " expiresAt: userSessionCookie?.expirationDate\n ? new Date(userSessionCookie.expirationDate * 1000)\n : undefined,\n }\n })\n}\nasync function getAllNames(): Promise<string[]> {\n const accounts = await getAll()\n return accounts.map(({ name }) => name)\n}", "score": 0.8000561594963074 } ]
typescript
.getAll().then(setAccounts) }, []) async function handleLogin() {
import type { GeneralOptions } from '../../typings/General' import { isAuthenticated } from '../../helpers/isAuthenticated' import fs from 'fs' import path from 'path' import { extractCodeFromFile, extractCodeFromString } from '../../helpers/extractCode' import { config } from '../../helpers/authSystem' import { openAIChat } from '../../helpers/openAIChat' import { red, yellow, green } from 'kleur/colors' export const generateTestAction = async (options: GeneralOptions) => { const componentName = options[Object.keys(options)[0]] const componentPath = options[Object.keys(options)[1]] const testLibrary = options[Object.keys(options)[2]] const componentExtension = path.extname(componentPath) // verify authentication const isAuth = await isAuthenticated() if (!isAuth) return if (!componentName || !componentPath) { return console.log( red(`\nYou did not enter the expected component name or path!`), yellow( `\n* use --component or -c to declare component name\n* use --path or -p to declare component path\nuse --library or -l to declare the desired test library` ) ) } // read the contents of the component file const componentCode = extractCodeFromFile(componentPath) if (!componentCode) { return console.log( red(`\nI didn't find your component. Check the path and try again!`), yellow(`\nexample path: ./src/components/MyComponent/index.tsx`) ) } // generate test code const params = { text: `Create the code with test (containing all necessary imports) in ${ testLibrary ? testLibrary : 'Jest' } in code form based on the following component:\n${componentCode}`, method: 'POST', key: config.apiKey } const openAIChatResponse
= await openAIChat(params) const testCode = extractCodeFromString(openAIChatResponse.data) if (!testCode) {
return console.log( red( `\nUnable to generate a test. Check the component code and try again!` ) ) } // get component folder path const componentFolderPath = componentPath.split('/').slice(0, -1).join('/') // save the test code to a new file const testFilePath = `${componentFolderPath}/${componentName}.test${componentExtension}` fs.writeFileSync(testFilePath, testCode) console.log( green(`\nTest generated successfully in: ${testFilePath}`), yellow( `\nif you don't like the generated test, you can run the command again to generate another one over the previous one` ) ) }
src/commands/generateTest/generateTestAction.ts
zonixlab-zonix-e7c108a
[ { "filename": "src/commands/auth/authAction.ts", "retrieved_chunk": " )\n }\n const params = {\n text: `Hello!`,\n method: 'POST',\n key\n }\n const openAIChatResponse = await openAIChat(params)\n if (openAIChatResponse.error) {\n return console.log(", "score": 0.8679550886154175 }, { "filename": "src/helpers/isAuthenticated.ts", "retrieved_chunk": "import { config } from './authSystem'\nimport { openAIChat } from './openAIChat'\nimport { red, yellow } from 'kleur/colors'\nexport const isAuthenticated = async () => {\n const params = {\n text: `Hello!`,\n method: 'POST',\n key: config.apiKey\n }\n const openAIChatResponse = await openAIChat(params)", "score": 0.853073000907898 }, { "filename": "src/commands/hello/helloAction.ts", "retrieved_chunk": " if (!isAuth) return\n const params = {\n text: `Return me a random greeting from movies, cartoons or series`,\n method: 'POST',\n key: config.apiKey\n }\n const openAIChatResponse = await openAIChat(params)\n return console.log(\n green(`\\n${openAIChatResponse.data}`),\n yellow(`\\nuse --name or -n to declare your name and get a greeting`)", "score": 0.8372193574905396 }, { "filename": "src/helpers/openAIChat.ts", "retrieved_chunk": "import axios, { AxiosError } from 'axios'\nimport type { OpenAIChatProps } from '../typings/OpenAI'\nexport const openAIChat = async ({ text, method, key }: OpenAIChatProps) => {\n try {\n const chatBody = {\n model: 'gpt-3.5-turbo',\n messages: [\n {\n role: 'user',\n content: text", "score": 0.828617513179779 }, { "filename": "src/commands/auth/authAction.ts", "retrieved_chunk": "import type { GeneralOptions } from '../../typings/General'\nimport { writeConfig } from '../../helpers/authSystem'\nimport { openAIChat } from '../../helpers/openAIChat'\nimport { red, yellow, green } from 'kleur/colors'\nexport const authAction = async (options: GeneralOptions) => {\n const key = options[Object.keys(options)[0]]\n if (!key) {\n return console.log(\n red(`\\nYou have not entered the expected key!`),\n yellow(`\\n* use the --key or -k option to declare your API key`)", "score": 0.7852782011032104 } ]
typescript
= await openAIChat(params) const testCode = extractCodeFromString(openAIChatResponse.data) if (!testCode) {
import browser, { Cookies } from 'webextension-polyfill' import { setBadgeText } from './badge' import cookie from './cookie' import storage from './storage' type Cookie = Cookies.Cookie export type Account = { name: string cookies: Cookie[] active: boolean avatarUrl?: string expiresAt?: Date } type Accounts = Record<string, Cookie[]> async function getAll(): Promise<Account[]> { const accounts = await storage.get<Accounts>('accounts') if (!accounts) { return [] } const currentAccount = await browser.cookies.get({ url: 'https://github.com', name: 'dotcom_user', }) const avatarUrls = await storage.get<Record<string, string>>('avatars') return Object.entries(accounts).map(([name, cookies]) => { const userSessionCookie = cookies.find(({ name }) => name === 'user_session') return { name, cookies, active: currentAccount?.value === name, avatarUrl: avatarUrls?.[name], expiresAt: userSessionCookie?.expirationDate ? new Date(userSessionCookie.expirationDate * 1000) : undefined, } }) } async function getAllNames(): Promise<string[]> { const accounts = await getAll() return accounts.map(({ name }) => name) } async function find(accountName: string): Promise<Account | undefined> { const accounts = await getAll() return accounts.find((account) => account.name === accountName) } async function upsert(accountName: string, cookies: Cookie[]) {
await storage.update<Accounts>('accounts', (accounts = {}) => {
accounts[accountName] = cookies return accounts }) } async function switchTo(accountName: string) { await cookie.clear() const account = await find(accountName) const cookies = account?.cookies || [] for (const cookie of cookies) { const { hostOnly, domain, session, ...rest } = cookie await browser.cookies.set({ url: 'https://github.com', domain: hostOnly ? undefined : domain, ...rest, }) } if (cookies.length) { setBadgeText(accountName.slice(0, 2)) } else { setBadgeText('...') } } async function remove(accountName: string) { await storage.update<Accounts>('accounts', (accounts) => { if (!accounts) { return } delete accounts[accountName] return accounts }) } async function saveAvatar(accountName: string, avatarUrl: string) { await storage.update<Record<string, string>>('avatars', (avatars = {}) => { avatars[accountName] = avatarUrl return avatars }) } export default { getAll, getAllNames, find, upsert, switchTo, remove, saveAvatar, }
src/services/account.ts
yuezk-github-account-switcher-36b3c11
[ { "filename": "src/background/index.ts", "retrieved_chunk": " }\n await setBadgeText(account.slice(0, 2))\n}\nasync function removeAccount(accountName: string) {\n await accountService.remove(accountName)\n await updateDynamicRequestRules()\n}\nasync function buildCookieValue(accountName: string): Promise<string | null> {\n const account = await accountService.find(accountName)\n const cookies = account?.cookies || []", "score": 0.8701870441436768 }, { "filename": "src/popup/components/Accounts.tsx", "retrieved_chunk": " const [tab] = await browser.tabs.query(queryOptions)\n return tab\n}\nexport default function Accounts() {\n const [accounts, setAccounts] = useState<Account[]>([])\n useEffect(() => {\n accountService.getAll().then(setAccounts)\n }, [])\n async function handleLogin() {\n await cookie.clear()", "score": 0.8343994617462158 }, { "filename": "src/services/rule.ts", "retrieved_chunk": "import storage from './storage'\nexport type Rule = {\n id: number\n urlPattern: string\n account: string\n}\nasync function getAll(): Promise<Rule[]> {\n const rules = await storage.get<Rule[]>('rules')\n return rules || []\n}", "score": 0.8280638456344604 }, { "filename": "src/services/rule.ts", "retrieved_chunk": "async function remove(id: number) {\n await storage.update<Rule[]>('rules', (rules = []) => {\n return rules.filter((rule) => rule.id !== id)\n })\n}\nexport default {\n getAll,\n add,\n update,\n remove,", "score": 0.8201175928115845 }, { "filename": "src/content/index.ts", "retrieved_chunk": " }\n const res: GetAccountsResponse = await browser.runtime.sendMessage({\n type: 'getAccounts',\n } as GetAccountsMessage)\n if (!res?.success) {\n return\n }\n const { data: accounts } = res\n const addAccountButton = document.getElementById(ADD_ACCOUNT_BUTTON_ID)!\n for (const account of accounts) {", "score": 0.8130254745483398 } ]
typescript
await storage.update<Accounts>('accounts', (accounts = {}) => {
import browser, { Cookies } from 'webextension-polyfill' import { setBadgeText } from './badge' import cookie from './cookie' import storage from './storage' type Cookie = Cookies.Cookie export type Account = { name: string cookies: Cookie[] active: boolean avatarUrl?: string expiresAt?: Date } type Accounts = Record<string, Cookie[]> async function getAll(): Promise<Account[]> { const accounts = await storage.get<Accounts>('accounts') if (!accounts) { return [] } const currentAccount = await browser.cookies.get({ url: 'https://github.com', name: 'dotcom_user', }) const avatarUrls = await storage.get<Record<string, string>>('avatars') return Object.entries(accounts).map(([name, cookies]) => { const userSessionCookie = cookies.find(({ name }) => name === 'user_session') return { name, cookies, active: currentAccount?.value === name, avatarUrl: avatarUrls?.[name], expiresAt: userSessionCookie?.expirationDate ? new Date(userSessionCookie.expirationDate * 1000) : undefined, } }) } async function getAllNames(): Promise<string[]> { const accounts = await getAll() return accounts.map(({ name }) => name) } async function find(accountName: string): Promise<Account | undefined> { const accounts = await getAll() return accounts.find((account) => account.name === accountName) } async function upsert(accountName: string, cookies: Cookie[]) { await storage.update<Accounts>('accounts', (accounts = {}) => { accounts[accountName] = cookies return accounts }) } async function switchTo(accountName: string) { await cookie.
clear() const account = await find(accountName) const cookies = account?.cookies || [] for (const cookie of cookies) {
const { hostOnly, domain, session, ...rest } = cookie await browser.cookies.set({ url: 'https://github.com', domain: hostOnly ? undefined : domain, ...rest, }) } if (cookies.length) { setBadgeText(accountName.slice(0, 2)) } else { setBadgeText('...') } } async function remove(accountName: string) { await storage.update<Accounts>('accounts', (accounts) => { if (!accounts) { return } delete accounts[accountName] return accounts }) } async function saveAvatar(accountName: string, avatarUrl: string) { await storage.update<Record<string, string>>('avatars', (avatars = {}) => { avatars[accountName] = avatarUrl return avatars }) } export default { getAll, getAllNames, find, upsert, switchTo, remove, saveAvatar, }
src/services/account.ts
yuezk-github-account-switcher-36b3c11
[ { "filename": "src/background/index.ts", "retrieved_chunk": " }\n await setBadgeText(account.slice(0, 2))\n}\nasync function removeAccount(accountName: string) {\n await accountService.remove(accountName)\n await updateDynamicRequestRules()\n}\nasync function buildCookieValue(accountName: string): Promise<string | null> {\n const account = await accountService.find(accountName)\n const cookies = account?.cookies || []", "score": 0.8574434518814087 }, { "filename": "src/popup/components/Accounts.tsx", "retrieved_chunk": " const [tab] = await browser.tabs.query(queryOptions)\n return tab\n}\nexport default function Accounts() {\n const [accounts, setAccounts] = useState<Account[]>([])\n useEffect(() => {\n accountService.getAll().then(setAccounts)\n }, [])\n async function handleLogin() {\n await cookie.clear()", "score": 0.8515998125076294 }, { "filename": "src/content/index.ts", "retrieved_chunk": " }\n const res: GetAccountsResponse = await browser.runtime.sendMessage({\n type: 'getAccounts',\n } as GetAccountsMessage)\n if (!res?.success) {\n return\n }\n const { data: accounts } = res\n const addAccountButton = document.getElementById(ADD_ACCOUNT_BUTTON_ID)!\n for (const account of accounts) {", "score": 0.8474550247192383 }, { "filename": "src/background/index.ts", "retrieved_chunk": " 'websocket',\n 'xmlhttprequest',\n]\nasync function syncAccounts() {\n const usernameCookie = await cookie.get('dotcom_user')\n const sessionCookie = await cookie.get('user_session')\n if (!usernameCookie || !sessionCookie) {\n return\n }\n const { value: account } = usernameCookie", "score": 0.8336089849472046 }, { "filename": "src/background/index.ts", "retrieved_chunk": " const autoSwitchRules = await ruleService.getAll()\n for (const [index, rule] of autoSwitchRules.entries()) {\n const cookieValue = await buildCookieValue(rule.account)\n if (!cookieValue) {\n continue\n }\n requestRules.push({\n id: index + 1,\n priority: 1,\n action: {", "score": 0.8322648406028748 } ]
typescript
clear() const account = await find(accountName) const cookies = account?.cookies || [] for (const cookie of cookies) {
import {ArcballCamera} from "arcball_camera"; import {Controller} from "ez_canvas_controller"; import {mat4, vec3} from "gl-matrix"; import {Volume, volumes} from "./volume"; import {MarchingCubes} from "./marching_cubes"; import renderMeshShaders from "./render_mesh.wgsl"; import {compileShader, fillSelector} from "./util"; (async () => { if (navigator.gpu === undefined) { document.getElementById("webgpu-canvas").setAttribute("style", "display:none;"); document.getElementById("no-webgpu").setAttribute("style", "display:block;"); return; } // Get a GPU device to render with let adapter = await navigator.gpu.requestAdapter(); console.log(adapter.limits); let deviceRequiredFeatures: GPUFeatureName[] = []; const timestampSupport = adapter.features.has("timestamp-query"); // Enable timestamp queries if the device supports them if (timestampSupport) { deviceRequiredFeatures.push("timestamp-query"); } else { console.log("Device does not support timestamp queries"); } let deviceDescriptor = { requiredFeatures: deviceRequiredFeatures, requiredLimits: { maxBufferSize: adapter.limits.maxBufferSize, maxStorageBufferBindingSize: adapter.limits.maxStorageBufferBindingSize, } }; let device = await adapter.requestDevice(deviceDescriptor); // Get a context to display our rendered image on the canvas let canvas = document.getElementById("webgpu-canvas") as HTMLCanvasElement; let context = canvas.getContext("webgpu"); let volumePicker = document.getElementById("volumeList") as HTMLSelectElement;
fillSelector(volumePicker, volumes);
let isovalueSlider = document.getElementById("isovalueSlider") as HTMLInputElement; // Force computing the surface on the initial load let currentIsovalue = -1; let perfDisplay = document.getElementById("stats") as HTMLElement; let timestampDisplay = document.getElementById("timestamp-stats") as HTMLElement; // Setup shader modules let shaderModule = await compileShader(device, renderMeshShaders, "renderMeshShaders"); if (window.location.hash) { let linkedDataset = decodeURI(window.location.hash.substring(1)); if (volumes.has(linkedDataset)) { volumePicker.value = linkedDataset; } } let currentVolume = volumePicker.value; let volume = await Volume.load(volumes.get(currentVolume), device); let mc = await MarchingCubes.create(volume, device); let isosurface = null; // Vertex attribute state and shader stage let vertexState = { // Shader stage info module: shaderModule, entryPoint: "vertex_main", // Vertex buffer info buffers: [{ arrayStride: 4 * 4, attributes: [ {format: "float32x4" as GPUVertexFormat, offset: 0, shaderLocation: 0} ] }] }; // Setup render outputs let swapChainFormat = "bgra8unorm" as GPUTextureFormat; context.configure( {device: device, format: swapChainFormat, usage: GPUTextureUsage.RENDER_ATTACHMENT}); let depthFormat = "depth24plus-stencil8" as GPUTextureFormat; let depthTexture = device.createTexture({ size: {width: canvas.width, height: canvas.height, depthOrArrayLayers: 1}, format: depthFormat, usage: GPUTextureUsage.RENDER_ATTACHMENT }); let fragmentState = { // Shader info module: shaderModule, entryPoint: "fragment_main", // Output render target info targets: [{format: swapChainFormat}] }; let bindGroupLayout = device.createBindGroupLayout({ entries: [{binding: 0, visibility: GPUShaderStage.VERTEX, buffer: {type: "uniform"}}] }); // Create render pipeline let layout = device.createPipelineLayout({bindGroupLayouts: [bindGroupLayout]}); let renderPipeline = device.createRenderPipeline({ layout: layout, vertex: vertexState, fragment: fragmentState, depthStencil: {format: depthFormat, depthWriteEnabled: true, depthCompare: "less"} }); let renderPassDesc = { colorAttachments: [{ view: null as GPUTextureView, loadOp: "clear" as GPULoadOp, clearValue: [0.3, 0.3, 0.3, 1], storeOp: "store" as GPUStoreOp }], depthStencilAttachment: { view: depthTexture.createView(), depthLoadOp: "clear" as GPULoadOp, depthClearValue: 1.0, depthStoreOp: "store" as GPUStoreOp, stencilLoadOp: "clear" as GPULoadOp, stencilClearValue: 0, stencilStoreOp: "store" as GPUStoreOp } }; let viewParamsBuffer = device.createBuffer({ size: (4 * 4 + 4) * 4, usage: GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST, mappedAtCreation: false, }); let uploadBuffer = device.createBuffer({ size: viewParamsBuffer.size, usage: GPUBufferUsage.MAP_WRITE | GPUBufferUsage.COPY_SRC, mappedAtCreation: false, }); let bindGroup = device.createBindGroup({ layout: bindGroupLayout, entries: [{binding: 0, resource: {buffer: viewParamsBuffer}}] }); // Setup camera and camera controls const defaultEye = vec3.set(vec3.create(), 0.0, 0.0, volume.dims[2] * 0.75); const center = vec3.set(vec3.create(), 0.0, 0.0, 0.5); const up = vec3.set(vec3.create(), 0.0, 1.0, 0.0); let camera = new ArcballCamera(defaultEye, center, up, 2, [canvas.width, canvas.height]); let proj = mat4.perspective( mat4.create(), 50 * Math.PI / 180.0, canvas.width / canvas.height, 0.1, 1000); let projView = mat4.create(); // Register mouse and touch listeners var controller = new Controller(); controller.mousemove = function (prev: Array<number>, cur: Array<number>, evt: MouseEvent) { if (evt.buttons == 1) { camera.rotate(prev, cur); } else if (evt.buttons == 2) { camera.pan([cur[0] - prev[0], prev[1] - cur[1]]); } }; controller.wheel = function (amt: number) { camera.zoom(amt); }; controller.pinch = controller.wheel; controller.twoFingerDrag = function (drag: number) { camera.pan(drag); }; controller.registerForCanvas(canvas); let animationFrame = function () { let resolve = null; let promise = new Promise(r => resolve = r); window.requestAnimationFrame(resolve); return promise }; requestAnimationFrame(animationFrame); // Render! while (true) { await animationFrame(); if (document.hidden) { continue; } let sliderValue = parseFloat(isovalueSlider.value) / 255.0; let recomputeSurface = sliderValue != currentIsovalue; // When a new volume is selected, recompute the surface and reposition the camera if (volumePicker.value != currentVolume) { if (isosurface.buffer) { isosurface.buffer.destroy(); } currentVolume = volumePicker.value; history.replaceState(history.state, "#" + currentVolume, "#" + currentVolume); volume = await Volume.load(volumes.get(currentVolume), device); mc = await MarchingCubes.create(volume, device); isovalueSlider.value = "128"; sliderValue = parseFloat(isovalueSlider.value) / 255.0; recomputeSurface = true; const defaultEye = vec3.set(vec3.create(), 0.0, 0.0, volume.dims[2] * 0.75); camera = new ArcballCamera(defaultEye, center, up, 2, [canvas.width, canvas.height]); } if (recomputeSurface) { if (isosurface && isosurface.buffer) { isosurface.buffer.destroy(); } currentIsovalue = sliderValue; let start = performance.now(); isosurface = await mc.computeSurface(currentIsovalue); let end = performance.now(); perfDisplay.innerHTML = `<p>Compute Time: ${(end - start).toFixed((2))}ms<br/># Triangles: ${isosurface.count / 3}</p>` timestampDisplay.innerHTML = `<h4>Timing Breakdown</h4> <p>Note: if timestamp-query is not supported, -1 is shown for kernel times</p> Compute Active Voxels: ${mc.computeActiveVoxelsTime.toFixed(2)}ms <ul> <li> Mark Active Voxels Kernel: ${mc.markActiveVoxelsKernelTime.toFixed(2)}ms </li> <li> Exclusive Scan: ${mc.computeActiveVoxelsScanTime.toFixed(2)}ms </li> <li> Stream Compact: ${mc.computeActiveVoxelsCompactTime.toFixed(2)}ms </li> </ul> Compute Vertex Offsets: ${mc.computeVertexOffsetsTime.toFixed(2)}ms <ul> <li> Compute # of Vertices Kernel: ${mc.computeNumVertsKernelTime.toFixed(2)}ms </li> <li> Exclusive Scan: ${mc.computeVertexOffsetsScanTime.toFixed(2)}ms </li> </ul> Compute Vertices: ${mc.computeVerticesTime.toFixed(2)}ms <ul> <li> Compute Vertices Kernel: ${mc.computeVerticesKernelTime.toFixed(2)}ms </li> </ul>`; } projView = mat4.mul(projView, proj, camera.camera); { await uploadBuffer.mapAsync(GPUMapMode.WRITE); let map = uploadBuffer.getMappedRange(); new Float32Array(map).set(projView); new Uint32Array(map, 16 * 4, 4).set(volume.dims); uploadBuffer.unmap(); } renderPassDesc.colorAttachments[0].view = context.getCurrentTexture().createView(); let commandEncoder = device.createCommandEncoder(); commandEncoder.copyBufferToBuffer( uploadBuffer, 0, viewParamsBuffer, 0, viewParamsBuffer.size); let renderPass = commandEncoder.beginRenderPass(renderPassDesc); if (isosurface.count > 0) { renderPass.setBindGroup(0, bindGroup); renderPass.setPipeline(renderPipeline); renderPass.setVertexBuffer(0, isosurface.buffer); renderPass.draw(isosurface.count, 1, 0, 0); } renderPass.end(); device.queue.submit([commandEncoder.finish()]); } })();
src/app.ts
Twinklebear-webgpu-marching-cubes-38227e8
[ { "filename": "src/volume.ts", "retrieved_chunk": " private async fetch()\n {\n const voxelSize = voxelTypeSize(this.#dataType);\n const volumeSize = this.#dimensions[0] * this.#dimensions[1]\n * this.#dimensions[2] * voxelSize;\n let loadingProgressText = document.getElementById(\"loadingText\");\n let loadingProgressBar = document.getElementById(\"loadingProgressBar\");\n loadingProgressText.innerHTML = \"Loading Volume...\";\n loadingProgressBar.setAttribute(\"style\", \"width: 0%\");\n let url = \"https://cdn.willusher.io/demo-volumes/\" + this.#file;", "score": 0.7653090357780457 }, { "filename": "src/volume.ts", "retrieved_chunk": " }\n async upload(device: GPUDevice)\n {\n this.#texture = device.createTexture({\n size: this.#dimensions,\n format: voxelTypeToTextureType(this.#dataType),\n dimension: \"3d\",\n usage: GPUTextureUsage.TEXTURE_BINDING | GPUTextureUsage.COPY_DST\n });\n // TODO: might need to chunk the upload to support very large volumes?", "score": 0.7356553673744202 }, { "filename": "src/marching_cubes.ts", "retrieved_chunk": " this.#device = device;\n this.#volume = volume;\n this.#timestampQuerySupport = device.features.has(\"timestamp-query\");\n }\n static async create(volume: Volume, device: GPUDevice)\n {\n let mc = new MarchingCubes(volume, device);\n mc.#exclusiveScan = await ExclusiveScan.create(device);\n mc.#streamCompactIds = await StreamCompactIDs.create(device);\n // Upload the case table", "score": 0.7312251329421997 }, { "filename": "src/marching_cubes.ts", "retrieved_chunk": " ]\n });\n mc.#volumeInfoBG = device.createBindGroup({\n layout: volumeInfoBGLayout,\n entries: [\n {\n binding: 0,\n resource: mc.#volume.texture.createView(),\n },\n {", "score": 0.730647087097168 }, { "filename": "src/push_constant_builder.ts", "retrieved_chunk": " if (appPushConstants) {\n this.stride = alignTo(8 + appPushConstants.byteLength,\n device.limits.minUniformBufferOffsetAlignment);\n appPushConstantsView = new Uint8Array(appPushConstants);\n }\n if (this.stride * nDispatches > device.limits.maxUniformBufferBindingSize) {\n console.log(\"Error! PushConstants uniform buffer is too big for a uniform buffer\");\n throw Error(\"PushConstants uniform buffer is too big for a uniform buffer\");\n }\n this.pushConstantsBuffer = device.createBuffer({", "score": 0.7290290594100952 } ]
typescript
fillSelector(volumePicker, volumes);