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": "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": 38.149730894948476 }, { "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": 28.608993038289753 }, { "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": 24.51408771778717 }, { "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": 23.224635973079963 }, { "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": 23.000858142006734 } ]
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": 72.89703755984593 }, { "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": 59.57097187152852 }, { "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": 56.377056417011225 }, { "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": 53.47069592914357 }, { "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": 46.46737079117297 } ]
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/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": 38.149730894948476 }, { "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": 28.608993038289753 }, { "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": 24.51408771778717 }, { "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": 23.224635973079963 }, { "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": 23.000858142006734 } ]
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/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": 38.149730894948476 }, { "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": 28.608993038289753 }, { "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": 24.51408771778717 }, { "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": 23.224635973079963 }, { "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": 23.000858142006734 } ]
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/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": 22.83681930597048 }, { "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": 21.423557814740164 }, { "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": 19.494003440695092 }, { "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": 16.481519929494308 }, { "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": 15.239739232064757 } ]
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": 69.347524503614 }, { "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": 55.72731208195683 }, { "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": 52.713105523137195 }, { "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": 47.75531517610286 }, { "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": 40.39480327142541 } ]
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": 27.158259400388708 }, { "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": 20.78525238090867 }, { "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": 20.253269806912602 }, { "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": 19.39965891910634 }, { "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": 19.053346594302518 } ]
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/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": 25.17674483153457 }, { "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": 21.519248205680835 }, { "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": 14.704494515969065 }, { "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": 14.52096382956769 }, { "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": 13.0432478269565 } ]
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": "\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": 22.83681930597048 }, { "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": 21.423557814740164 }, { "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": 19.494003440695092 }, { "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": 16.481519929494308 }, { "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": 15.239739232064757 } ]
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": "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": 51.19444342910969 }, { "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": 46.515652103483355 }, { "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": 30.44601486306335 }, { "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": 30.255923291967687 }, { "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": 29.722912654169647 } ]
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": "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": 51.19444342910969 }, { "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": 46.515652103483355 }, { "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": 30.44601486306335 }, { "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": 30.255923291967687 }, { "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": 29.722912654169647 } ]
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": 48.142081159546606 }, { "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": 39.17839069384367 }, { "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": 22.141034914113174 }, { "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": 15.10902212360909 }, { "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": 13.6666178704322 } ]
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/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": 22.83681930597048 }, { "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": 21.423557814740164 }, { "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": 19.494003440695092 }, { "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": 16.481519929494308 }, { "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": 15.239739232064757 } ]
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/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": 51.19444342910969 }, { "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": 43.36719387464417 }, { "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": 30.44601486306335 }, { "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": 29.722912654169647 }, { "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": 27.317438987433736 } ]
typescript
const orderByOptions = calcs?.map(cal => getCalculationAlias(cal));
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": 46.68063194420681 }, { "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": 38.04325223983672 }, { "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": 22.141034914113174 }, { "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": 15.10902212360909 }, { "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": 13.6666178704322 } ]
typescript
: getServiceName(stack), Parameters, Origin: "cdk" }, });
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": " 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": 18.203907248461853 }, { "filename": "src/chat_gpt.ts", "retrieved_chunk": " messages: ChatGPTMessage[],\n model: \"gpt-3.5-turbo\" | \"gpt-3.5-turbo-0301\" | \"gpt-4-0314\" | \"gpt-4-32k\",\n temperature: number = 0.7,\n top_p: number = 0.9,\n maxRetries: number = 3\n): Promise<string> {\n const config = new Configuration({\n apiKey: OPENAI_TOKEN,\n });\n const openai = new OpenAIApi(config);", "score": 13.818561049782012 }, { "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": 13.030053168978744 }, { "filename": "src/chat_gpt.ts", "retrieved_chunk": "import { Configuration, OpenAIApi } from 'openai';\nimport logger from './logger';\nexport interface ChatGPTMessage {\n role: 'system' | 'user' | 'assistant';\n content: string;\n}\n// My environment variable is saving the open ai api key as OPENAI_API_KEY not OPENAI_TOKEN. Commented for pull request\nconst OPENAI_TOKEN = process.env.OPENAI_API_KEY;\n// const OPENAI_TOKEN = process.env.OPENAI_TOKEN;\nexport async function ChatGPT_completion(", "score": 9.249452072218164 }, { "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": 4.286376631516787 } ]
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": " key: $el.attr('key')!,\n value: $el.attr('value')!,\n description: $el.text()\n };\n }).get();\n return <Enum>{\n type: 'enum',\n name: address,\n address: address,\n description: $('description').text(),", "score": 49.64871810770282 }, { "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": 45.061959915736715 }, { "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": 39.289507321895236 }, { "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": 38.98950130172173 }, { "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": 32.04481641312424 } ]
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/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": 37.96909073484513 }, { "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": 37.48984450813158 }, { "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": 34.67155417336093 }, { "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": 30.851390042180963 }, { "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": 30.273337452572317 } ]
typescript
else if (isPanel(page)) return this.writePanel(page);
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": " 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": 20.68006754204296 }, { "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": 20.275709808243892 }, { "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": 15.175296692362942 }, { "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": 14.464787692119842 }, { "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": 11.300249553901356 } ]
typescript
string, golemFile: GolemFile, golemFilePath: string, context: Map<string, any> = new Map()): Promise<void> {
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/lua-language-server.ts", "retrieved_chunk": "export function makeConfigJson(name: string, words: string[], files: string[], settings: ConfigSettings) {\n let config: Config = {\n \"$schema\": \"https://raw.githubusercontent.com/LuaLS/LLS-Addons/main/schemas/addon_config.schema.json\",\n \"name\": name,\n };\n if (words.length > 0) {\n config[\"words\"] = words;\n }\n if (files.length > 0) {\n config[\"files\"] = files;", "score": 34.5316215174642 }, { "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": 28.891814590899557 }, { "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": 28.359088574787144 }, { "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": 28.219021653443235 }, { "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": 28.077205806795526 } ]
typescript
toLowerCamelCase(name);
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 }).get();\n return <Struct>{\n type: 'struct',\n name: address,\n address: address,\n description: $('description').text(),\n realm: $('realm').text() as Realm,\n fields", "score": 42.57942819464495 }, { "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": 37.887393847105365 }, { "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": 32.32238866657483 }, { "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": 22.031595298714038 }, { "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": 19.77163342954303 } ]
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/chat_gpt.ts", "retrieved_chunk": " messages: ChatGPTMessage[],\n model: \"gpt-3.5-turbo\" | \"gpt-3.5-turbo-0301\" | \"gpt-4-0314\" | \"gpt-4-32k\",\n temperature: number = 0.7,\n top_p: number = 0.9,\n maxRetries: number = 3\n): Promise<string> {\n const config = new Configuration({\n apiKey: OPENAI_TOKEN,\n });\n const openai = new OpenAIApi(config);", "score": 21.454791843845545 }, { "filename": "src/utils.ts", "retrieved_chunk": " defaultMap.set(\"default\", context.get(\"default\"));\n writeFileSync(cachedOutputPath, JSON.stringify(Object.fromEntries(defaultMap), null, 2), 'utf-8');\n }else{\n writeFileSync(cachedOutputPath, JSON.stringify(Object.fromEntries(context), null, 2), 'utf-8');\n }\n}\nexport function appendToGolemFile(golemFilePath: string, target: string): void {\n appendFileSync(golemFilePath, target, 'utf-8');\n}\nexport function loadOutputFromCache(target: string, cacheKey: string): string {", "score": 19.973083582044794 }, { "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": 14.465841178217612 }, { "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": 10.661005337627879 }, { "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": 8.212396766298244 } ]
typescript
const concatenatedOutput = golemTarget.dependencies.map(dep => context.get(dep)).join('');
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": " 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": 19.814358550624647 }, { "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": 18.826971017666686 }, { "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": 14.270741870117604 }, { "filename": "src/utils.ts", "retrieved_chunk": " defaultMap.set(\"default\", context.get(\"default\"));\n writeFileSync(cachedOutputPath, JSON.stringify(Object.fromEntries(defaultMap), null, 2), 'utf-8');\n }else{\n writeFileSync(cachedOutputPath, JSON.stringify(Object.fromEntries(context), null, 2), 'utf-8');\n }\n}\nexport function appendToGolemFile(golemFilePath: string, target: string): void {\n appendFileSync(golemFilePath, target, 'utf-8');\n}\nexport function loadOutputFromCache(target: string, cacheKey: string): string {", "score": 11.07620015357451 }, { "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": 11.05542848062818 } ]
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/scrapers/wiki-page-markup-scraper.ts", "retrieved_chunk": " };\n } else if (isPanel) {\n return <Panel>{\n type: 'panel',\n name: address,\n address: address,\n description: $('description').text(),\n realm: $('realm').text() as Realm,\n parent: $('parent').text()\n };", "score": 24.45387365430068 }, { "filename": "src/cli-library-publisher.ts", "retrieved_chunk": "import packageJson from '../package.json' assert { type: \"json\" };\nimport { GluaApiWriter } from './api-writer/glua-api-writer.js';\nimport { makeConfigJson } from './utils/lua-language-server.js';\nimport { readMetadata } from './utils/metadata.js';\nimport { walk } from './utils/filesystem.js';\nimport { Command } from 'commander';\nimport path from 'path';\nimport fs from 'fs';\nconst libraryName = 'garrysmod';\n// Patterns to recognize in GLua files, so that the language server can recommend this library to be activated:", "score": 16.75810342327987 }, { "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": 15.789006037674199 }, { "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": 14.836642033345676 }, { "filename": "src/cli-scraper.ts", "retrieved_chunk": "import { WikiPageMarkupScraper } from './scrapers/wiki-page-markup-scraper.js';\nimport { WikiPageListScraper } from './scrapers/wiki-page-list-scraper.js';\nimport packageJson from '../package.json' assert { type: \"json\" };\nimport { GluaApiWriter } from './api-writer/glua-api-writer.js';\nimport { scrapeAndCollect } from './scrapers/collector.js';\nimport { writeMetadata } from './utils/metadata.js';\nimport { RequestInitWithRetry } from 'fetch-retry';\nimport { Command } from 'commander';\nimport path from 'path';\nimport fs from 'fs';", "score": 14.718549340169663 } ]
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": " 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": 26.24830257665474 }, { "filename": "src/utils/lua-language-server.ts", "retrieved_chunk": "export function makeConfigJson(name: string, words: string[], files: string[], settings: ConfigSettings) {\n let config: Config = {\n \"$schema\": \"https://raw.githubusercontent.com/LuaLS/LLS-Addons/main/schemas/addon_config.schema.json\",\n \"name\": name,\n };\n if (words.length > 0) {\n config[\"words\"] = words;\n }\n if (files.length > 0) {\n config[\"files\"] = files;", "score": 26.053158860947097 }, { "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": 25.442519649920843 }, { "filename": "src/utils/lua-language-server.ts", "retrieved_chunk": "export type ConfigSettings = {\n [key: string]: any,\n};\nexport type Config = {\n \"$schema\": string,\n \"name\": string,\n \"words\"?: string[],\n \"files\"?: string[],\n \"settings\"?: ConfigSettings,\n};", "score": 23.709842236663953 }, { "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": 23.369605653139555 } ]
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/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": 20.656774901532277 }, { "filename": "src/utils/lua-language-server.ts", "retrieved_chunk": "export function makeConfigJson(name: string, words: string[], files: string[], settings: ConfigSettings) {\n let config: Config = {\n \"$schema\": \"https://raw.githubusercontent.com/LuaLS/LLS-Addons/main/schemas/addon_config.schema.json\",\n \"name\": name,\n };\n if (words.length > 0) {\n config[\"words\"] = words;\n }\n if (files.length > 0) {\n config[\"files\"] = files;", "score": 20.16513045370984 }, { "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": 19.952692802956495 }, { "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": 19.698538485579054 }, { "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": 19.694779536379915 } ]
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": " description: $el.text()\n };\n }).get();\n return <Struct>{\n type: 'struct',\n name: address,\n address: address,\n description: $('description').text(),\n realm: $('realm').text() as Realm,\n fields", "score": 31.89240433733586 }, { "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": 29.803995426832966 }, { "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": 23.04917454519357 }, { "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": 20.18066535223559 }, { "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": 19.77163342954303 } ]
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/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": 21.65575685534705 }, { "filename": "src/cli-library-publisher.ts", "retrieved_chunk": "import packageJson from '../package.json' assert { type: \"json\" };\nimport { GluaApiWriter } from './api-writer/glua-api-writer.js';\nimport { makeConfigJson } from './utils/lua-language-server.js';\nimport { readMetadata } from './utils/metadata.js';\nimport { walk } from './utils/filesystem.js';\nimport { Command } from 'commander';\nimport path from 'path';\nimport fs from 'fs';\nconst libraryName = 'garrysmod';\n// Patterns to recognize in GLua files, so that the language server can recommend this library to be activated:", "score": 15.000495381920581 }, { "filename": "src/cli-scraper.ts", "retrieved_chunk": "import { WikiPageMarkupScraper } from './scrapers/wiki-page-markup-scraper.js';\nimport { WikiPageListScraper } from './scrapers/wiki-page-list-scraper.js';\nimport packageJson from '../package.json' assert { type: \"json\" };\nimport { GluaApiWriter } from './api-writer/glua-api-writer.js';\nimport { scrapeAndCollect } from './scrapers/collector.js';\nimport { writeMetadata } from './utils/metadata.js';\nimport { RequestInitWithRetry } from 'fetch-retry';\nimport { Command } from 'commander';\nimport path from 'path';\nimport fs from 'fs';", "score": 14.718549340169663 }, { "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": 14.22751240273035 }, { "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": 11.65772049706397 } ]
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/scrapers/wiki-page-markup-scraper.ts", "retrieved_chunk": " description: $el.text()\n };\n }).get();\n return <Struct>{\n type: 'struct',\n name: address,\n address: address,\n description: $('description').text(),\n realm: $('realm').text() as Realm,\n fields", "score": 21.90065330454229 }, { "filename": "src/scrapers/wiki-page-markup-scraper.ts", "retrieved_chunk": " };\n } else if (isPanel) {\n return <Panel>{\n type: 'panel',\n name: address,\n address: address,\n description: $('description').text(),\n realm: $('realm').text() as Realm,\n parent: $('parent').text()\n };", "score": 21.572077255587804 }, { "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": 20.519854218732327 }, { "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": 19.12042465347511 }, { "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": 17.614445341919694 } ]
typescript
luaDocComment += `---\n---[(View on wiki)](${func.url})\n`;
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": 50.67041020931984 }, { "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": 39.176213809978854 }, { "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": 37.00150122908682 }, { "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": 36.97304735794126 }, { "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": 34.892311407033844 } ]
typescript
<T extends object> extends TraverseScraper<Table<T>> {
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/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": 24.351243272338472 }, { "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": 23.3208909968257 }, { "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": 22.874764154031972 }, { "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": 20.638595465369434 }, { "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": 20.50302554186569 } ]
typescript
<T> implements Scrapeable {
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": 28.840950620808254 }, { "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": 25.617847542072408 }, { "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": 21.6780741667319 }, { "filename": "src/scrapers/wiki-page-markup-scraper.ts", "retrieved_chunk": " };\n } else if (isPanel) {\n return <Panel>{\n type: 'panel',\n name: address,\n address: address,\n description: $('description').text(),\n realm: $('realm').text() as Realm,\n parent: $('parent').text()\n };", "score": 21.483274503107182 }, { "filename": "src/scrapers/wiki-page-markup-scraper.ts", "retrieved_chunk": " description: $el.text()\n };\n }).get();\n return <Struct>{\n type: 'struct',\n name: address,\n address: address,\n description: $('description').text(),\n realm: $('realm').text() as Realm,\n fields", "score": 21.456739800809146 } ]
typescript
func.arguments.forEach((arg, index) => {
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": 27.5096402816913 }, { "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": 25.107094179751623 }, { "filename": "src/scrapers/wiki-page-markup-scraper.ts", "retrieved_chunk": " };\n } else if (isPanel) {\n return <Panel>{\n type: 'panel',\n name: address,\n address: address,\n description: $('description').text(),\n realm: $('realm').text() as Realm,\n parent: $('parent').text()\n };", "score": 20.211455275018267 }, { "filename": "src/scrapers/wiki-page-markup-scraper.ts", "retrieved_chunk": " description: $el.text()\n };\n }).get();\n return <Struct>{\n type: 'struct',\n name: address,\n address: address,\n description: $('description').text(),\n realm: $('realm').text() as Realm,\n fields", "score": 20.16568989676449 }, { "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": 19.156467512119843 } ]
typescript
.forEach((arg, index) => {
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 }).get();\n return <Struct>{\n type: 'struct',\n name: address,\n address: address,\n description: $('description').text(),\n realm: $('realm').text() as Realm,\n fields", "score": 21.90065330454229 }, { "filename": "src/scrapers/wiki-page-markup-scraper.ts", "retrieved_chunk": " };\n } else if (isPanel) {\n return <Panel>{\n type: 'panel',\n name: address,\n address: address,\n description: $('description').text(),\n realm: $('realm').text() as Realm,\n parent: $('parent').text()\n };", "score": 21.572077255587804 }, { "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": 19.12042465347511 }, { "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": 17.614445341919694 }, { "filename": "src/scrapers/wiki-page-markup-scraper.ts", "retrieved_chunk": "import { ScrapeCallback, Scraper } from './scraper.js';\nimport { deserializeXml } from '../utils/xml.js';\nexport type WikiFunctionType = 'panelfunc' | 'classfunc' | 'libraryfunc' | 'hook';\nexport type Realm = 'Menu' | 'Client' | 'Server' | 'Shared' | 'Client and menu';\nexport type CommonWikiProperties = {\n type: WikiFunctionType | 'enum' | 'struct' | 'panel';\n address: string;\n name: string;\n description: string;\n realm: Realm;", "score": 16.87618271734844 } ]
typescript
let luaDocComment = `---[${realm.toUpperCase()}] ${putCommentBeforeEachLine(func.description!.trim())}\n`;
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": 50.67041020931984 }, { "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": 39.176213809978854 }, { "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": 37.00150122908682 }, { "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": 36.97304735794126 }, { "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": 34.892311407033844 } ]
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": 26.082078501948104 }, { "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": 22.473443785699367 }, { "filename": "src/scrapers/wiki-page-markup-scraper.ts", "retrieved_chunk": " };\n } else if (isPanel) {\n return <Panel>{\n type: 'panel',\n name: address,\n address: address,\n description: $('description').text(),\n realm: $('realm').text() as Realm,\n parent: $('parent').text()\n };", "score": 20.747140736325605 }, { "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": 19.23843367834675 }, { "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": 18.709005613670193 } ]
typescript
= this.writeClass(func.parent);
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": 26.24830257665474 }, { "filename": "src/utils/lua-language-server.ts", "retrieved_chunk": "export function makeConfigJson(name: string, words: string[], files: string[], settings: ConfigSettings) {\n let config: Config = {\n \"$schema\": \"https://raw.githubusercontent.com/LuaLS/LLS-Addons/main/schemas/addon_config.schema.json\",\n \"name\": name,\n };\n if (words.length > 0) {\n config[\"words\"] = words;\n }\n if (files.length > 0) {\n config[\"files\"] = files;", "score": 26.053158860947097 }, { "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": 25.442519649920843 }, { "filename": "src/utils/lua-language-server.ts", "retrieved_chunk": "export type ConfigSettings = {\n [key: string]: any,\n};\nexport type Config = {\n \"$schema\": string,\n \"name\": string,\n \"words\"?: string[],\n \"files\"?: string[],\n \"settings\"?: ConfigSettings,\n};", "score": 23.709842236663953 }, { "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": 23.369605653139555 } ]
typescript
(safeFileName(pageAddress, '.'), override);
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": " 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": 23.176110820522013 }, { "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": 21.429668106797994 }, { "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": 16.470274468439197 }, { "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": 15.650241440824018 }, { "filename": "src/utils.ts", "retrieved_chunk": " defaultMap.set(\"default\", context.get(\"default\"));\n writeFileSync(cachedOutputPath, JSON.stringify(Object.fromEntries(defaultMap), null, 2), 'utf-8');\n }else{\n writeFileSync(cachedOutputPath, JSON.stringify(Object.fromEntries(context), null, 2), 'utf-8');\n }\n}\nexport function appendToGolemFile(golemFilePath: string, target: string): void {\n appendFileSync(golemFilePath, target, 'utf-8');\n}\nexport function loadOutputFromCache(target: string, cacheKey: string): string {", "score": 11.77764484721233 } ]
typescript
const golemTarget = golemFile[target];
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/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": 41.4728135590942 }, { "filename": "src/cli-library-publisher.ts", "retrieved_chunk": "const libraryWordMatchers = [\n 'include%s*%(?',\n 'AddCSLuaFile%s*%(?',\n 'hook%.Add%s*%(',\n];\n// Same as above, but for files:\nconst libraryFileMatchers: string[] = [];\nconst libraryDirectory = 'library';\nasync function main() {\n const program = new Command();", "score": 34.94794418904302 }, { "filename": "src/utils/string.ts", "retrieved_chunk": " }).replace(/\\s+/g, '');\n}\n/**\n * Replaces all newlines in a string with spaces\n */\nexport function removeNewlines(text: string) {\n return text.replace(/\\r?\\n/g, ' ');\n}\n/**\n * Puts a comment before each line in a string", "score": 34.378347054044234 }, { "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": 26.12992950719546 }, { "filename": "src/cli-scraper.ts", "retrieved_chunk": "async function startScrape() {\n const program = new Command();\n program\n .version(packageJson.version)\n .description('Scrapes the Garry\\'s Mod wiki for API information')\n .option('-o, --output <path>', 'The path to the directory where the output json and lua files should be saved', './output')\n .option('-u, --url <url>', 'The pagelist URL of the Garry\\'s Mod wiki that holds all pages to scrape', 'https://wiki.facepunch.com/gmod/')\n .option('-c, --customOverrides [path]', 'The path to a directory containing custom overrides for the API')\n .option('-w, --wipe', 'Clean the output directory before scraping', false)\n .parse(process.argv);", "score": 25.58637539055384 } ]
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/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": 27.5096402816913 }, { "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": 25.107094179751623 }, { "filename": "src/scrapers/wiki-page-markup-scraper.ts", "retrieved_chunk": " };\n } else if (isPanel) {\n return <Panel>{\n type: 'panel',\n name: address,\n address: address,\n description: $('description').text(),\n realm: $('realm').text() as Realm,\n parent: $('parent').text()\n };", "score": 20.211455275018267 }, { "filename": "src/scrapers/wiki-page-markup-scraper.ts", "retrieved_chunk": " description: $el.text()\n };\n }).get();\n return <Struct>{\n type: 'struct',\n name: address,\n address: address,\n description: $('description').text(),\n realm: $('realm').text() as Realm,\n fields", "score": 20.16568989676449 }, { "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": 19.156467512119843 } ]
typescript
(arg, index) => {
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/chat_gpt.ts", "retrieved_chunk": " messages: ChatGPTMessage[],\n model: \"gpt-3.5-turbo\" | \"gpt-3.5-turbo-0301\" | \"gpt-4-0314\" | \"gpt-4-32k\",\n temperature: number = 0.7,\n top_p: number = 0.9,\n maxRetries: number = 3\n): Promise<string> {\n const config = new Configuration({\n apiKey: OPENAI_TOKEN,\n });\n const openai = new OpenAIApi(config);", "score": 21.454791843845545 }, { "filename": "src/utils.ts", "retrieved_chunk": " defaultMap.set(\"default\", context.get(\"default\"));\n writeFileSync(cachedOutputPath, JSON.stringify(Object.fromEntries(defaultMap), null, 2), 'utf-8');\n }else{\n writeFileSync(cachedOutputPath, JSON.stringify(Object.fromEntries(context), null, 2), 'utf-8');\n }\n}\nexport function appendToGolemFile(golemFilePath: string, target: string): void {\n appendFileSync(golemFilePath, target, 'utf-8');\n}\nexport function loadOutputFromCache(target: string, cacheKey: string): string {", "score": 19.973083582044794 }, { "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": 14.465841178217612 }, { "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": 10.661005337627879 }, { "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": 8.212396766298244 } ]
typescript
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/utils/lua-language-server.ts", "retrieved_chunk": "export function makeConfigJson(name: string, words: string[], files: string[], settings: ConfigSettings) {\n let config: Config = {\n \"$schema\": \"https://raw.githubusercontent.com/LuaLS/LLS-Addons/main/schemas/addon_config.schema.json\",\n \"name\": name,\n };\n if (words.length > 0) {\n config[\"words\"] = words;\n }\n if (files.length > 0) {\n config[\"files\"] = files;", "score": 34.5316215174642 }, { "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": 28.891814590899557 }, { "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": 28.359088574787144 }, { "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": 28.219021653443235 }, { "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": 28.077205806795526 } ]
typescript
= toLowerCamelCase(name);
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": " 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": 43.11012334712276 }, { "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": 29.18437813730559 }, { "filename": "src/errors.ts", "retrieved_chunk": "import logger from './logger';\nexport class GolemError extends Error {\n constructor(message: string) {\n super(message);\n this.name = 'GolemError';\n }\n}\nexport function handleGolemError(error: GolemError): void {\n logger.error(`[${error.name}] ${error.message}`);\n}", "score": 27.473312013040093 }, { "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": 25.871114978320072 }, { "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": 25.160264718394235 } ]
typescript
.warn( `Rate limit or server error encountered (status: ${error.response.status}). Retrying in ${waitTime} ms...` );
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/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": 90.01337099113574 }, { "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": 84.33316454757804 }, { "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": 77.61847641440643 }, { "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": 36.35348747921291 }, { "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": 32.89779610402842 } ]
typescript
= deserializeXml<WikiPage | null>(content, ($) => {
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": 45.4212138894439 }, { "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": 40.740216791825105 }, { "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": 31.19521934422292 }, { "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": 18.821600256086473 }, { "filename": "src/scrapers/table-scraper.ts", "retrieved_chunk": " if (rows.length === 0)\n rows = $(tableElement).find('tr').toArray();\n if (shouldTrimHeadings)\n rows = rows.slice(headingRows.length);\n let isEmpty = true;\n for (const row of rows) {\n const rowResult = this.fromRowElement($, row, headings);\n if (rowResult === null)\n continue;\n tableResult.addRow(rowResult);", "score": 17.55640094588532 } ]
typescript
await this.visitOne(url, callback);
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/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": 56.63958860832484 }, { "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": 52.46284337815087 }, { "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": 39.42487432631245 }, { "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": 38.98691740010407 }, { "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": 36.34518297332425 } ]
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/api-writer/glua-api-writer.ts", "retrieved_chunk": " return api;\n }\n private writeEnum(_enum: Enum) {\n let api: string = '';\n const isContainedInTable = _enum.items[0]?.key.includes('.') ?? false;\n api += `---@enum ${_enum.name}\\n`;\n if (isContainedInTable)\n api += `local ${_enum.name} = {\\n`;\n const writeItem = (key: string, item: typeof _enum.items[0]) => {\n if (isContainedInTable) {", "score": 45.30548569893612 }, { "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": 43.65482261696826 }, { "filename": "src/scrapers/table-scraper.ts", "retrieved_chunk": " if (rows.length === 0)\n rows = $(tableElement).find('tr').toArray();\n if (shouldTrimHeadings)\n rows = rows.slice(headingRows.length);\n let isEmpty = true;\n for (const row of rows) {\n const rowResult = this.fromRowElement($, row, headings);\n if (rowResult === null)\n continue;\n tableResult.addRow(rowResult);", "score": 35.461254131265555 }, { "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": 34.210002353423654 }, { "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": 33.92417959244329 } ]
typescript
const $el = $(this);
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": 75.73344327783497 }, { "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": 71.74142159162383 }, { "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": 67.54276545071119 }, { "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": 22.18831717563272 }, { "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": 20.589390434607015 } ]
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/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": 90.01337099113574 }, { "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": 87.19501103676605 }, { "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": 84.33316454757804 }, { "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": 36.35348747921291 }, { "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": 35.46967553126165 } ]
typescript
const page = deserializeXml<WikiPage | null>(content, ($) => {
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/chat_gpt.ts", "retrieved_chunk": " messages: ChatGPTMessage[],\n model: \"gpt-3.5-turbo\" | \"gpt-3.5-turbo-0301\" | \"gpt-4-0314\" | \"gpt-4-32k\",\n temperature: number = 0.7,\n top_p: number = 0.9,\n maxRetries: number = 3\n): Promise<string> {\n const config = new Configuration({\n apiKey: OPENAI_TOKEN,\n });\n const openai = new OpenAIApi(config);", "score": 13.818561049782012 }, { "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": 13.030053168978744 }, { "filename": "src/chat_gpt.ts", "retrieved_chunk": "import { Configuration, OpenAIApi } from 'openai';\nimport logger from './logger';\nexport interface ChatGPTMessage {\n role: 'system' | 'user' | 'assistant';\n content: string;\n}\n// My environment variable is saving the open ai api key as OPENAI_API_KEY not OPENAI_TOKEN. Commented for pull request\nconst OPENAI_TOKEN = process.env.OPENAI_API_KEY;\n// const OPENAI_TOKEN = process.env.OPENAI_TOKEN;\nexport async function ChatGPT_completion(", "score": 9.249452072218164 }, { "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": 8.874145819333119 }, { "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": 3.9142418346529646 } ]
typescript
await ChatGPT_completion(taskGenerationMessages, model, 0.7, 0.9);
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/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": 28.498983975912196 }, { "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": 19.681108621620034 }, { "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": 18.315637403119702 }, { "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": 17.961958537789993 }, { "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": 17.861112211890813 } ]
typescript
const tableResult = new Table<T>(this.baseUrl);
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": 37.96909073484513 }, { "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": 35.33614741749899 }, { "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": 34.67155417336093 }, { "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": 30.851390042180963 }, { "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": 30.273337452572317 } ]
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/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": 24.725857947693697 }, { "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": 23.92474904100741 }, { "filename": "src/api-writer/glua-api-writer.ts", "retrieved_chunk": "import { ClassFunction, Enum, Function, HookFunction, LibraryFunction, Panel, PanelFunction, Realm, Struct, WikiPage, isPanel } from '../scrapers/wiki-page-markup-scraper.js';\nimport { putCommentBeforeEachLine, removeNewlines, safeFileName, toLowerCamelCase } from '../utils/string.js';\nimport {\n isClassFunction,\n isHookFunction,\n isLibraryFunction,\n isPanelFunction,\n isStruct,\n isEnum,\n} from '../scrapers/wiki-page-markup-scraper.js';", "score": 22.827482128214523 }, { "filename": "src/api-writer/glua-api-writer.ts", "retrieved_chunk": " else if (isHookFunction(page))\n return this.writeHookFunction(page);\n else if (isPanel(page))\n return this.writePanel(page);\n else if (isPanelFunction(page))\n return this.writePanelFunction(page);\n else if (isEnum(page))\n return this.writeEnum(page);\n else if (isStruct(page))\n return this.writeStruct(page);", "score": 18.90864433191667 }, { "filename": "src/api-writer/glua-api-writer.ts", "retrieved_chunk": " return `_${name}`;\n return name;\n }\n public addOverride(pageAddress: string, override: string) {\n this.pageOverrides.set(safeFileName(pageAddress, '.'), override);\n }\n public writePage(page: WikiPage) {\n const fileSafeAddress = safeFileName(page.address, '.');\n if (this.pageOverrides.has(fileSafeAddress)) {\n let api = '';", "score": 17.941952518616144 } ]
typescript
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/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": 26.35612939003162 }, { "filename": "src/cli-library-publisher.ts", "retrieved_chunk": "import packageJson from '../package.json' assert { type: \"json\" };\nimport { GluaApiWriter } from './api-writer/glua-api-writer.js';\nimport { makeConfigJson } from './utils/lua-language-server.js';\nimport { readMetadata } from './utils/metadata.js';\nimport { walk } from './utils/filesystem.js';\nimport { Command } from 'commander';\nimport path from 'path';\nimport fs from 'fs';\nconst libraryName = 'garrysmod';\n// Patterns to recognize in GLua files, so that the language server can recommend this library to be activated:", "score": 20.0485581866163 }, { "filename": "src/scrapers/table-scraper.ts", "retrieved_chunk": " if (tableResult)\n results.push(tableResult);\n }\n return results;\n };\n }\n private fromTableElement($: cheerio.CheerioAPI, tableElement: cheerio.Element): Table<T> | null {\n const tableResult = new Table<T>(this.baseUrl);\n let headingRows = $(tableElement).find('thead > tr');\n let shouldTrimHeadings = false;", "score": 19.22901706978334 }, { "filename": "src/cli-scraper.ts", "retrieved_chunk": "import { WikiPageMarkupScraper } from './scrapers/wiki-page-markup-scraper.js';\nimport { WikiPageListScraper } from './scrapers/wiki-page-list-scraper.js';\nimport packageJson from '../package.json' assert { type: \"json\" };\nimport { GluaApiWriter } from './api-writer/glua-api-writer.js';\nimport { scrapeAndCollect } from './scrapers/collector.js';\nimport { writeMetadata } from './utils/metadata.js';\nimport { RequestInitWithRetry } from 'fetch-retry';\nimport { Command } from 'commander';\nimport path from 'path';\nimport fs from 'fs';", "score": 18.398186675212077 }, { "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": 16.352705093996235 } ]
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/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": 24.725857947693697 }, { "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": 23.92474904100741 }, { "filename": "src/api-writer/glua-api-writer.ts", "retrieved_chunk": "import { ClassFunction, Enum, Function, HookFunction, LibraryFunction, Panel, PanelFunction, Realm, Struct, WikiPage, isPanel } from '../scrapers/wiki-page-markup-scraper.js';\nimport { putCommentBeforeEachLine, removeNewlines, safeFileName, toLowerCamelCase } from '../utils/string.js';\nimport {\n isClassFunction,\n isHookFunction,\n isLibraryFunction,\n isPanelFunction,\n isStruct,\n isEnum,\n} from '../scrapers/wiki-page-markup-scraper.js';", "score": 22.827482128214523 }, { "filename": "src/api-writer/glua-api-writer.ts", "retrieved_chunk": " else if (isHookFunction(page))\n return this.writeHookFunction(page);\n else if (isPanel(page))\n return this.writePanel(page);\n else if (isPanelFunction(page))\n return this.writePanelFunction(page);\n else if (isEnum(page))\n return this.writeEnum(page);\n else if (isStruct(page))\n return this.writeStruct(page);", "score": 18.90864433191667 }, { "filename": "src/api-writer/glua-api-writer.ts", "retrieved_chunk": " return `_${name}`;\n return name;\n }\n public addOverride(pageAddress: string, override: string) {\n this.pageOverrides.set(safeFileName(pageAddress, '.'), override);\n }\n public writePage(page: WikiPage) {\n const fileSafeAddress = safeFileName(page.address, '.');\n if (this.pageOverrides.has(fileSafeAddress)) {\n let api = '';", "score": 17.941952518616144 } ]
typescript
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/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": 26.082078501948104 }, { "filename": "src/scrapers/wiki-page-markup-scraper.ts", "retrieved_chunk": " };\n } else if (isPanel) {\n return <Panel>{\n type: 'panel',\n name: address,\n address: address,\n description: $('description').text(),\n realm: $('realm').text() as Realm,\n parent: $('parent').text()\n };", "score": 25.33851582759725 }, { "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": 22.473443785699367 }, { "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": 19.23843367834675 }, { "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": 18.709005613670193 } ]
typescript
api += this.writeFunctionLuaDocComment(func, func.realm);
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": 79.99523354796406 }, { "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": 71.74142159162383 }, { "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": 67.54276545071119 }, { "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": 22.18831717563272 }, { "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": 20.589390434607015 } ]
typescript
public getScrapeCallback(): ScrapeCallback<WikiPage> {
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": 43.342797030990944 }, { "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": 39.61336968698775 }, { "filename": "src/scrapers/table-scraper.ts", "retrieved_chunk": " public url: string;\n public childUrls: Set<string> = new Set();\n constructor(url: string, public rows: Row<T>[] = []) {\n this.url = url;\n }\n public addRow(row: Row<T>) {\n this.rows.push(row);\n }\n}\nexport class TableScraper<T extends object> extends TraverseScraper<Table<T>> {", "score": 31.513140671973723 }, { "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": 31.22936042417911 }, { "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": 27.96219467064759 } ]
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": 50.67041020931984 }, { "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": 39.176213809978854 }, { "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": 37.00150122908682 }, { "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": 36.97304735794126 }, { "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": 34.892311407033844 } ]
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": 45.4212138894439 }, { "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": 40.740216791825105 }, { "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": 31.19521934422292 }, { "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": 18.821600256086473 }, { "filename": "src/scrapers/table-scraper.ts", "retrieved_chunk": " if (rows.length === 0)\n rows = $(tableElement).find('tr').toArray();\n if (shouldTrimHeadings)\n rows = rows.slice(headingRows.length);\n let isEmpty = true;\n for (const row of rows) {\n const rowResult = this.fromRowElement($, row, headings);\n if (rowResult === null)\n continue;\n tableResult.addRow(rowResult);", "score": 17.55640094588532 } ]
typescript
= await this.visitOne(url, callback);
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": 59.42629950854463 }, { "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": 43.69860971732073 }, { "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": 29.855582563488717 }, { "filename": "src/scrapers/wiki-page-markup-scraper.ts", "retrieved_chunk": " url: string;\n}\nexport type WikiIdentifier = {\n name: string;\n type: string;\n description?: string;\n};\nexport type FunctionArgument = WikiIdentifier & {\n default?: string;\n};", "score": 24.29779387197529 }, { "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": 23.712218361945308 } ]
typescript
.map(ret => this.transformType(ret.type)).join(', ')}`;
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/api-writer/glua-api-writer.ts", "retrieved_chunk": "import { ClassFunction, Enum, Function, HookFunction, LibraryFunction, Panel, PanelFunction, Realm, Struct, WikiPage, isPanel } from '../scrapers/wiki-page-markup-scraper.js';\nimport { putCommentBeforeEachLine, removeNewlines, safeFileName, toLowerCamelCase } from '../utils/string.js';\nimport {\n isClassFunction,\n isHookFunction,\n isLibraryFunction,\n isPanelFunction,\n isStruct,\n isEnum,\n} from '../scrapers/wiki-page-markup-scraper.js';", "score": 37.86729569023719 }, { "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": 34.01261042903865 }, { "filename": "src/api-writer/glua-api-writer.ts", "retrieved_chunk": " else if (isHookFunction(page))\n return this.writeHookFunction(page);\n else if (isPanel(page))\n return this.writePanel(page);\n else if (isPanelFunction(page))\n return this.writePanelFunction(page);\n else if (isEnum(page))\n return this.writeEnum(page);\n else if (isStruct(page))\n return this.writeStruct(page);", "score": 29.633630368508328 }, { "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": 29.097705710891304 }, { "filename": "src/api-writer/glua-api-writer.ts", "retrieved_chunk": " return `_${name}`;\n return name;\n }\n public addOverride(pageAddress: string, override: string) {\n this.pageOverrides.set(safeFileName(pageAddress, '.'), override);\n }\n public writePage(page: WikiPage) {\n const fileSafeAddress = safeFileName(page.address, '.');\n if (this.pageOverrides.has(fileSafeAddress)) {\n let api = '';", "score": 26.455231247992447 } ]
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/wiki-page-markup-scraper.ts", "retrieved_chunk": " key: $el.attr('key')!,\n value: $el.attr('value')!,\n description: $el.text()\n };\n }).get();\n return <Enum>{\n type: 'enum',\n name: address,\n address: address,\n description: $('description').text(),", "score": 55.246122516958486 }, { "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": 53.87331760539657 }, { "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": 48.17200914418108 }, { "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": 44.290468927597985 }, { "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": 33.674227266247776 } ]
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/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": 90.01337099113574 }, { "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": 84.33316454757804 }, { "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": 77.61847641440643 }, { "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": 36.35348747921291 }, { "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": 32.89779610402842 } ]
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/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": 27.695275009375298 }, { "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": 25.803437189542798 }, { "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": 25.627379143371893 }, { "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": 24.827287013028318 }, { "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": 23.464557936670992 } ]
typescript
removeAccount(accountName) setAccounts(accounts.filter((account) => account.name !== accountName)) }
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": " 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": 15.771948952295666 }, { "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": 12.852507664182975 }, { "filename": "src/content/createElement.ts", "retrieved_chunk": "}\nexport function createRemoveIcon() {\n return createElement('svg', {\n ns: 'http://www.w3.org/2000/svg',\n 'aria-hidden': 'true',\n viewBox: '0 0 16 16',\n height: '16',\n width: '16',\n version: '1.1',\n 'data-view-component': 'true',", "score": 9.596042983624098 }, { "filename": "src/content/createElement.ts", "retrieved_chunk": " const { children, ns, ...rest } = attributes\n const el = ns ? document.createElementNS(ns, tagName) : document.createElement(tagName)\n for (const [key, value] of Object.entries(rest)) {\n el.setAttribute(key, value)\n }\n appendChildren(el, children)\n return el\n}\nfunction appendChildren(parent: Node, children: Child | Child[] = []) {\n const childrenArray = Array.isArray(children) ? children : [children]", "score": 8.107709515047203 }, { "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": 7.695829558552559 } ]
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/shared.ts", "retrieved_chunk": " if (!url) {\n return false\n }\n return /^https:\\/\\/(.+?\\.)?github\\.com/.test(url)\n}\nexport function isNormalGitHubUrl(url: string | undefined, rules: Rule[]) {\n if (!url) {\n return false\n }\n if (!isGitHubUrl(url)) {", "score": 38.71488896810468 }, { "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": 29.510062628131514 }, { "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": 26.736231211634927 }, { "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": 26.351751427896353 }, { "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": 26.175000951961714 } ]
typescript
isGitHubUrl(tab?.url)) {
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 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": 17.094495909040948 }, { "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": 17.05275087001335 }, { "filename": "src/services/account.ts", "retrieved_chunk": "import browser, { Cookies } from 'webextension-polyfill'\nimport { setBadgeText } from './badge'\nimport cookie from './cookie'\nimport storage from './storage'\ntype Cookie = Cookies.Cookie\nexport type Account = {\n name: string\n cookies: Cookie[]\n active: boolean\n avatarUrl?: string", "score": 15.197963827658484 }, { "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": 12.848842698103013 }, { "filename": "src/popup/components/Accounts.tsx", "retrieved_chunk": " ListItemAvatar,\n ListItemSecondaryAction,\n ListItemText,\n Tooltip,\n styled,\n} from '@mui/material'\nimport { useEffect, useState } from 'react'\nimport browser, { Tabs } from 'webextension-polyfill'\nimport accountService, { Account } from '../../services/account'\nimport cookie from '../../services/cookie'", "score": 12.445091915508673 } ]
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": 22.065023306404832 }, { "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": 20.741693406941167 }, { "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": 20.717031198412023 }, { "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": 19.1917873516827 }, { "filename": "src/content/ui.ts", "retrieved_chunk": "import { createElement, createRemoveIcon } from './createElement'\nexport const ADD_ACCOUNT_BUTTON_ID = 'gh-account-switcher__add-account'\nexport const ACCOUNT_ITEM_CLASS = 'gh-account-switcher__account'\nexport const ACCOUNT_REMOVE_CLASS = 'gh-account-switcher__account-remove'\nfunction isNewLook() {\n return document.querySelector('.AppHeader-user') !== null\n}\nfunction uiLook() {\n return isNewLook() ? newLook : classicLook\n}", "score": 14.784502808588968 } ]
typescript
const accountId = `${ACCOUNT_ITEM_CLASS}-${account}` if (!document.getElementById(accountId) && 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/global.d.ts", "retrieved_chunk": "/// <reference types=\"vite/client\" />\ndeclare const __APP_VERSION__: string\ndeclare module '*?script&module' {\n const src: string\n export default src\n}", "score": 38.80856561955049 }, { "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": 14.046560464134604 }, { "filename": "src/content/createElement.ts", "retrieved_chunk": "type Child = Node | string | undefined\nexport function createElement(\n tagName: string,\n attributes: Record<string, string> | { ns?: string; children?: Child | Child[] },\n) {\n if (tagName === 'fragment') {\n const fragment = document.createDocumentFragment()\n appendChildren(fragment, attributes.children)\n return fragment\n }", "score": 9.538930557417965 }, { "filename": "src/content/createElement.ts", "retrieved_chunk": " const { children, ns, ...rest } = attributes\n const el = ns ? document.createElementNS(ns, tagName) : document.createElement(tagName)\n for (const [key, value] of Object.entries(rest)) {\n el.setAttribute(key, value)\n }\n appendChildren(el, children)\n return el\n}\nfunction appendChildren(parent: Node, children: Child | Child[] = []) {\n const childrenArray = Array.isArray(children) ? children : [children]", "score": 8.803884803020832 }, { "filename": "src/content/injected.ts", "retrieved_chunk": "type FetchFn = typeof fetch\ntype FetchInput = Parameters<FetchFn>[0]\nconst ACCOUNT_PARAM = '__account__'\nclass PatchedResponse extends Response {\n constructor(private readonly response: Response) {\n super(response.body, response)\n }\n get url() {\n const url = new URL(this.response.url, window.location.origin)\n url.searchParams.delete(ACCOUNT_PARAM)", "score": 8.185960537693521 } ]
typescript
getURL(injectedScript) script.type = 'module' document.head.prepend(script) }
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": 26.537143484956502 }, { "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": 25.65727742199019 }, { "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": 20.741693406941163 }, { "filename": "src/content/ui.ts", "retrieved_chunk": "import { createElement, createRemoveIcon } from './createElement'\nexport const ADD_ACCOUNT_BUTTON_ID = 'gh-account-switcher__add-account'\nexport const ACCOUNT_ITEM_CLASS = 'gh-account-switcher__account'\nexport const ACCOUNT_REMOVE_CLASS = 'gh-account-switcher__account-remove'\nfunction isNewLook() {\n return document.querySelector('.AppHeader-user') !== null\n}\nfunction uiLook() {\n return isNewLook() ? newLook : classicLook\n}", "score": 15.518786893440662 }, { "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": 15.296221107362125 } ]
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/popup/components/RuleItem.tsx", "retrieved_chunk": " function handleAccountChange(event: React.ChangeEvent<HTMLInputElement>) {\n const value = event.target.value\n const { message } = validateAccount(value)\n setAccountValidation(message)\n setRule({ ...rule, account: value })\n }\n return (\n <Box display=\"flex\" gap={2} alignItems=\"flex-start\">\n <Box flex=\"1\">\n <TextField", "score": 16.278752440350328 }, { "filename": "src/popup/components/RuleItem.tsx", "retrieved_chunk": " function handleDelete() {\n setIsEditing(false)\n onDelete(rule)\n }\n function handleUrlPatternChange(event: React.ChangeEvent<HTMLInputElement>) {\n const value = event.target.value\n const { message } = validateUrlPattern(value)\n setUrlPatternValidation(message)\n setRule({ ...rule, urlPattern: value })\n }", "score": 15.503794112038456 }, { "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": 15.215468281786066 }, { "filename": "src/content/ui.ts", "retrieved_chunk": " 'data-account': account,\n class: `ActionListContent ${ACCOUNT_ITEM_CLASS}`,\n children: [\n createElement('span', {\n class: 'ActionListItem-label',\n children: [\n 'Switch to ',\n createElement('b', { children: account }),\n ]\n })", "score": 14.8592196533886 }, { "filename": "src/content/ui.ts", "retrieved_chunk": " createElement('button', {\n 'data-account': account,\n class: `dropdown-item btn-link ${ACCOUNT_ITEM_CLASS}`,\n role: 'menuitem',\n children: [\n 'Switch to ',\n createElement('b', { children: account }),\n ],\n }),\n createElement('button', {", "score": 14.161767548164683 } ]
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": 16.455205442143523 }, { "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": 15.77887071616842 }, { "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": 13.75103119519179 }, { "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": 12.247448608661255 }, { "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": 11.924739847018852 } ]
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/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": 32.18145914974821 }, { "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": 29.72712740572347 }, { "filename": "src/popup/components/AutoSwitchRules.tsx", "retrieved_chunk": " stopAdding()\n }\n async function updateRule(rule: Rule) {\n await ruleService.update(rule)\n setRules(await ruleService.getAll())\n }\n async function removeRule(rule: Rule) {\n await ruleService.remove(rule.id)\n setRules(await ruleService.getAll())\n }", "score": 21.51551168042269 }, { "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": 18.579601770614154 }, { "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": 18.06282463624039 } ]
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/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": 22.320118132522197 }, { "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": 21.929772946100794 }, { "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": 21.639947571155524 }, { "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": 21.5779666760216 }, { "filename": "src/popup/components/AutoSwitchRules.tsx", "retrieved_chunk": "import { AddCircle } from '@mui/icons-material'\nimport { Alert, Box, Button, Link } from '@mui/material'\nimport { useEffect, useState } from 'react'\nimport ruleService, { Rule } from '../../services/rule'\nimport RuleItem from './RuleItem'\nexport default function AutoSwitchRules() {\n const [rules, setRules] = useState<Rule[]>([])\n const [isAdding, setIsAdding] = useState(false)\n useEffect(() => {\n ruleService.getAll().then(setRules)", "score": 21.473269338887942 } ]
typescript
const rules = 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/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": 22.320118132522197 }, { "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": 21.929772946100794 }, { "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": 21.639947571155524 }, { "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": 21.5779666760216 }, { "filename": "src/popup/components/AutoSwitchRules.tsx", "retrieved_chunk": "import { AddCircle } from '@mui/icons-material'\nimport { Alert, Box, Button, Link } from '@mui/material'\nimport { useEffect, useState } from 'react'\nimport ruleService, { Rule } from '../../services/rule'\nimport RuleItem from './RuleItem'\nexport default function AutoSwitchRules() {\n const [rules, setRules] = useState<Rule[]>([])\n const [isAdding, setIsAdding] = useState(false)\n useEffect(() => {\n ruleService.getAll().then(setRules)", "score": 21.473269338887942 } ]
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/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": 32.18145914974821 }, { "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": 29.72712740572347 }, { "filename": "src/popup/components/AutoSwitchRules.tsx", "retrieved_chunk": " stopAdding()\n }\n async function updateRule(rule: Rule) {\n await ruleService.update(rule)\n setRules(await ruleService.getAll())\n }\n async function removeRule(rule: Rule) {\n await ruleService.remove(rule.id)\n setRules(await ruleService.getAll())\n }", "score": 21.51551168042269 }, { "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": 18.579601770614154 }, { "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": 18.06282463624039 } ]
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/AutoSwitchRules.tsx", "retrieved_chunk": " return (\n <Box>\n <Alert severity=\"info\" sx={{ mb: 2 }}>\n When the request URL path matches the regular expression, the account will be switched to\n the specified account automatically,{' '}\n <Link\n href=\"https://github.com/yuezk/github-account-switcher#auto-switching\"\n target=\"_blank\"\n >\n see help", "score": 32.565681851810204 }, { "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": 28.609951171281004 }, { "filename": "src/popup/components/Accounts.tsx", "retrieved_chunk": " const tab = await getCurrentTab()\n const rules = await rule.getAll()\n if (isNormalGitHubUrl(tab?.url, rules)) {\n await browser.tabs.update(tab?.id!, {\n url: `https://github.com/login?return_to=${encodeURIComponent(tab?.url ?? '')}`,\n })\n } else if (isGitHubUrl(tab?.url)) {\n await browser.tabs.update(tab?.id!, { url: 'https://github.com/login' })\n } else {\n await browser.tabs.create({ url: 'https://github.com/login' })", "score": 21.302314948643982 }, { "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": 21.03541074557489 }, { "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": 18.084844969902743 } ]
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/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": 16.600446971133863 }, { "filename": "src/popup/components/Header.tsx", "retrieved_chunk": " transform: 'rotate(-10turn)',\n },\n }}\n />\n GitHub Account Switcher\n </Typography>\n <IconButton\n size=\"small\"\n href=\"https://github.com/yuezk/github-account-switcher\"\n target=\"_blank\"", "score": 13.500037074529459 }, { "filename": "src/content/createElement.ts", "retrieved_chunk": " class: 'octicon octicon-trash',\n children: createElement('path', {\n ns: 'http://www.w3.org/2000/svg',\n d: 'M11 1.75V3h2.25a.75.75 0 0 1 0 1.5H2.75a.75.75 0 0 1 0-1.5H5V1.75C5 .784 5.784 0 6.75 0h2.5C10.216 0 11 .784 11 1.75ZM4.496 6.675l.66 6.6a.25.25 0 0 0 .249.225h5.19a.25.25 0 0 0 .249-.225l.66-6.6a.75.75 0 0 1 1.492.149l-.66 6.6A1.748 1.748 0 0 1 10.595 15h-5.19a1.75 1.75 0 0 1-1.741-1.575l-.66-6.6a.75.75 0 1 1 1.492-.15ZM6.5 1.75V3h3V1.75a.25.25 0 0 0-.25-.25h-2.5a.25.25 0 0 0-.25.25Z',\n }),\n })\n}", "score": 10.915275632356582 }, { "filename": "src/content/createElement.ts", "retrieved_chunk": "}\nexport function createRemoveIcon() {\n return createElement('svg', {\n ns: 'http://www.w3.org/2000/svg',\n 'aria-hidden': 'true',\n viewBox: '0 0 16 16',\n height: '16',\n width: '16',\n version: '1.1',\n 'data-view-component': 'true',", "score": 7.032014792535113 }, { "filename": "src/popup/components/AutoSwitchRules.tsx", "retrieved_chunk": " </Link>\n .\n </Alert>\n <Box\n display=\"flex\"\n flexDirection=\"column\"\n gap={1}\n sx={{\n '& > :last-child': {\n mb: 2,", "score": 6.5658454341773576 } ]
typescript
function GitHubAvatar({ account }: { account: Account }) {
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": 63.0523789053423 }, { "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": 53.16479165381312 }, { "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": 44.84888833226669 }, { "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": 35.37067912660444 }, { "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": 34.90568109938905 } ]
typescript
const account = await accountService.find(accountName) const cookies = account?.cookies || [] if (!cookies.length) {
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/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": 29.956614050310748 }, { "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": 18.072892963205526 }, { "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": 16.911361662226106 }, { "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": 14.299207890176126 }, { "filename": "src/background/index.ts", "retrieved_chunk": " }\n const existingRules = await browser.declarativeNetRequest.getDynamicRules()\n const removeRuleIds = existingRules.map((rule) => rule.id)\n const addRules = await buildAddRules()\n await browser.declarativeNetRequest.updateDynamicRules({\n removeRuleIds,\n addRules,\n })\n const rules = await browser.declarativeNetRequest.getDynamicRules()\n console.info('Current dynamic rules:', rules)", "score": 13.944519840343538 } ]
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": "import browser, { Cookies } from 'webextension-polyfill'\nimport { setBadgeText } from './badge'\nimport cookie from './cookie'\nimport storage from './storage'\ntype Cookie = Cookies.Cookie\nexport type Account = {\n name: string\n cookies: Cookie[]\n active: boolean\n avatarUrl?: string", "score": 12.825257602439564 }, { "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": 12.551431136889773 }, { "filename": "src/popup/components/RuleItem.tsx", "retrieved_chunk": " function handleDelete() {\n setIsEditing(false)\n onDelete(rule)\n }\n function handleUrlPatternChange(event: React.ChangeEvent<HTMLInputElement>) {\n const value = event.target.value\n const { message } = validateUrlPattern(value)\n setUrlPatternValidation(message)\n setRule({ ...rule, urlPattern: value })\n }", "score": 11.709751367248522 }, { "filename": "src/popup/components/RuleItem.tsx", "retrieved_chunk": " function handleAccountChange(event: React.ChangeEvent<HTMLInputElement>) {\n const value = event.target.value\n const { message } = validateAccount(value)\n setAccountValidation(message)\n setRule({ ...rule, account: value })\n }\n return (\n <Box display=\"flex\" gap={2} alignItems=\"flex-start\">\n <Box flex=\"1\">\n <TextField", "score": 11.18081532815079 }, { "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": 11.170733164796818 } ]
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/global.d.ts", "retrieved_chunk": "/// <reference types=\"vite/client\" />\ndeclare const __APP_VERSION__: string\ndeclare module '*?script&module' {\n const src: string\n export default src\n}", "score": 38.80856561955049 }, { "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": 14.046560464134604 }, { "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": 9.912442152001528 }, { "filename": "src/content/createElement.ts", "retrieved_chunk": "type Child = Node | string | undefined\nexport function createElement(\n tagName: string,\n attributes: Record<string, string> | { ns?: string; children?: Child | Child[] },\n) {\n if (tagName === 'fragment') {\n const fragment = document.createDocumentFragment()\n appendChildren(fragment, attributes.children)\n return fragment\n }", "score": 9.538930557417965 }, { "filename": "src/content/createElement.ts", "retrieved_chunk": " const { children, ns, ...rest } = attributes\n const el = ns ? document.createElementNS(ns, tagName) : document.createElement(tagName)\n for (const [key, value] of Object.entries(rest)) {\n el.setAttribute(key, value)\n }\n appendChildren(el, children)\n return el\n}\nfunction appendChildren(parent: Node, children: Child | Child[] = []) {\n const childrenArray = Array.isArray(children) ? children : [children]", "score": 8.803884803020832 } ]
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": 39.304341049102696 }, { "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": 25.708252477699304 }, { "filename": "src/background/index.ts", "retrieved_chunk": " if (!cookies.length) {\n return null\n }\n return cookies\n .map((cookie) => `${cookie.name}=${cookie.value}`)\n .concat(`__account__=${accountName}`)\n .join('; ')\n}\nasync function buildAddRules(): Promise<DeclarativeNetRequest.Rule[]> {\n const requestRules: DeclarativeNetRequest.Rule[] = []", "score": 18.044077627847226 }, { "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": 14.603801402532287 }, { "filename": "src/services/badge.ts", "retrieved_chunk": "import browser from 'webextension-polyfill'\nexport async function setBadgeText(text: string) {\n const action = browser.action || browser.browserAction\n await action.setBadgeText({\n text\n })\n await action.setBadgeBackgroundColor({\n color: '#44b700',\n })\n action.setBadgeTextColor({", "score": 13.991916756602853 } ]
typescript
<Accounts>('accounts', (accounts) => {
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/popup/components/RuleItem.tsx", "retrieved_chunk": " function handleDelete() {\n setIsEditing(false)\n onDelete(rule)\n }\n function handleUrlPatternChange(event: React.ChangeEvent<HTMLInputElement>) {\n const value = event.target.value\n const { message } = validateUrlPattern(value)\n setUrlPatternValidation(message)\n setRule({ ...rule, urlPattern: value })\n }", "score": 20.435320114094207 }, { "filename": "src/popup/components/RuleItem.tsx", "retrieved_chunk": " function handleAccountChange(event: React.ChangeEvent<HTMLInputElement>) {\n const value = event.target.value\n const { message } = validateAccount(value)\n setAccountValidation(message)\n setRule({ ...rule, account: value })\n }\n return (\n <Box display=\"flex\" gap={2} alignItems=\"flex-start\">\n <Box flex=\"1\">\n <TextField", "score": 18.514182058873264 }, { "filename": "src/popup/components/Header.tsx", "retrieved_chunk": " transform: 'rotate(-10turn)',\n },\n }}\n />\n GitHub Account Switcher\n </Typography>\n <IconButton\n size=\"small\"\n href=\"https://github.com/yuezk/github-account-switcher\"\n target=\"_blank\"", "score": 11.065609289096447 }, { "filename": "src/popup/index.tsx", "retrieved_chunk": "import React from 'react'\nimport ReactDOM from 'react-dom/client'\nimport App from './Popup'\nReactDOM.createRoot(document.getElementById('app') as HTMLElement).render(\n <React.StrictMode>\n <App />\n </React.StrictMode>,\n)", "score": 10.769430544877503 }, { "filename": "src/content/createElement.ts", "retrieved_chunk": "type Child = Node | string | undefined\nexport function createElement(\n tagName: string,\n attributes: Record<string, string> | { ns?: string; children?: Child | Child[] },\n) {\n if (tagName === 'fragment') {\n const fragment = document.createDocumentFragment()\n appendChildren(fragment, attributes.children)\n return fragment\n }", "score": 9.391316871765206 } ]
typescript
.closest(`.${ADD_ACCOUNT_BUTTON_ID}`)) {
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/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": 13.148361389725896 }, { "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": 12.645613845911322 }, { "filename": "src/popup/components/RuleItem.tsx", "retrieved_chunk": " }\n}\nfunction validateAccount(account: string): { valid: boolean; message?: string } {\n if (account.trim() === '') {\n return {\n valid: false,\n message: 'Account is required',\n }\n }\n if (!isValidAccount(account)) {", "score": 11.814700830465316 }, { "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": 11.47405744079583 }, { "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": 11.233765075289192 } ]
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": " 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": 22.320118132522197 }, { "filename": "src/popup/components/AutoSwitchRules.tsx", "retrieved_chunk": "import { AddCircle } from '@mui/icons-material'\nimport { Alert, Box, Button, Link } from '@mui/material'\nimport { useEffect, useState } from 'react'\nimport ruleService, { Rule } from '../../services/rule'\nimport RuleItem from './RuleItem'\nexport default function AutoSwitchRules() {\n const [rules, setRules] = useState<Rule[]>([])\n const [isAdding, setIsAdding] = useState(false)\n useEffect(() => {\n ruleService.getAll().then(setRules)", "score": 18.615235448553218 }, { "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": 17.979881251707344 }, { "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": 17.522641970183585 }, { "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": 17.313675373042116 } ]
typescript
isNormalGitHubUrl(tab?.url, rules)) {
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": " 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": 15.771948952295666 }, { "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": 12.852507664182975 }, { "filename": "src/content/createElement.ts", "retrieved_chunk": "}\nexport function createRemoveIcon() {\n return createElement('svg', {\n ns: 'http://www.w3.org/2000/svg',\n 'aria-hidden': 'true',\n viewBox: '0 0 16 16',\n height: '16',\n width: '16',\n version: '1.1',\n 'data-view-component': 'true',", "score": 9.596042983624098 }, { "filename": "src/content/createElement.ts", "retrieved_chunk": " const { children, ns, ...rest } = attributes\n const el = ns ? document.createElementNS(ns, tagName) : document.createElement(tagName)\n for (const [key, value] of Object.entries(rest)) {\n el.setAttribute(key, value)\n }\n appendChildren(el, children)\n return el\n}\nfunction appendChildren(parent: Node, children: Child | Child[] = []) {\n const childrenArray = Array.isArray(children) ? children : [children]", "score": 8.107709515047203 }, { "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": 7.695829558552559 } ]
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/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": 24.771873106942962 }, { "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": 17.60444917815301 }, { "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": 15.358177167533231 }, { "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": 14.261157736564618 }, { "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": 13.295727485579526 } ]
typescript
{account.expiresAt && `Expires at ${account.expiresAt.toLocaleString()}`}
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/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": 29.956614050310748 }, { "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": 19.982545366691383 }, { "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": 18.072892963205526 }, { "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": 14.299207890176126 }, { "filename": "src/background/index.ts", "retrieved_chunk": " }\n const existingRules = await browser.declarativeNetRequest.getDynamicRules()\n const removeRuleIds = existingRules.map((rule) => rule.id)\n const addRules = await buildAddRules()\n await browser.declarativeNetRequest.updateDynamicRules({\n removeRuleIds,\n addRules,\n })\n const rules = await browser.declarativeNetRequest.getDynamicRules()\n console.info('Current dynamic rules:', rules)", "score": 13.944519840343538 } ]
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": " 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": 22.320118132522197 }, { "filename": "src/popup/components/AutoSwitchRules.tsx", "retrieved_chunk": "import { AddCircle } from '@mui/icons-material'\nimport { Alert, Box, Button, Link } from '@mui/material'\nimport { useEffect, useState } from 'react'\nimport ruleService, { Rule } from '../../services/rule'\nimport RuleItem from './RuleItem'\nexport default function AutoSwitchRules() {\n const [rules, setRules] = useState<Rule[]>([])\n const [isAdding, setIsAdding] = useState(false)\n useEffect(() => {\n ruleService.getAll().then(setRules)", "score": 18.615235448553218 }, { "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": 17.979881251707344 }, { "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": 17.522641970183585 }, { "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": 17.313675373042116 } ]
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": " 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": 24.035309106295216 }, { "filename": "src/services/account.ts", "retrieved_chunk": "import browser, { Cookies } from 'webextension-polyfill'\nimport { setBadgeText } from './badge'\nimport cookie from './cookie'\nimport storage from './storage'\ntype Cookie = Cookies.Cookie\nexport type Account = {\n name: string\n cookies: Cookie[]\n active: boolean\n avatarUrl?: string", "score": 22.33351981182175 }, { "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": 19.82182939207726 }, { "filename": "src/popup/components/Header.tsx", "retrieved_chunk": " transform: 'rotate(-10turn)',\n },\n }}\n />\n GitHub Account Switcher\n </Typography>\n <IconButton\n size=\"small\"\n href=\"https://github.com/yuezk/github-account-switcher\"\n target=\"_blank\"", "score": 18.546031506849392 }, { "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": 16.309440023163013 } ]
typescript
.avatarUrl ?? `https://github.com/${name}.png?size=100` const avatar = <Avatar src={avatarUrl} /> if (active) {
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": " if (!url) {\n return false\n }\n return /^https:\\/\\/(.+?\\.)?github\\.com/.test(url)\n}\nexport function isNormalGitHubUrl(url: string | undefined, rules: Rule[]) {\n if (!url) {\n return false\n }\n if (!isGitHubUrl(url)) {", "score": 38.71488896810468 }, { "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": 29.510062628131514 }, { "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": 26.736231211634927 }, { "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": 26.351751427896353 }, { "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": 26.175000951961714 } ]
typescript
if (isGitHubUrl(tab?.url)) {
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": " 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": 16.1012832232295 }, { "filename": "src/popup/components/AutoSwitchRules.tsx", "retrieved_chunk": "import { AddCircle } from '@mui/icons-material'\nimport { Alert, Box, Button, Link } from '@mui/material'\nimport { useEffect, useState } from 'react'\nimport ruleService, { Rule } from '../../services/rule'\nimport RuleItem from './RuleItem'\nexport default function AutoSwitchRules() {\n const [rules, setRules] = useState<Rule[]>([])\n const [isAdding, setIsAdding] = useState(false)\n useEffect(() => {\n ruleService.getAll().then(setRules)", "score": 15.968945344793255 }, { "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": 14.182916248768333 }, { "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": 11.98660993228532 }, { "filename": "src/popup/components/Settings.tsx", "retrieved_chunk": "import { People, Rule } from '@mui/icons-material'\nimport { TabContext, TabList, TabPanel } from '@mui/lab'\nimport { Box, Tab } from '@mui/material'\nimport { useState } from 'react'\nimport Accounts from './Accounts'\nimport AutoSwitchRules from './AutoSwitchRules'\ntype TabValue = 'rules' | 'accounts'\nexport default function Settings() {\n const [value, setValue] = useState<TabValue>('accounts')\n const handleChange = (event: React.SyntheticEvent, newValue: TabValue) => {", "score": 11.532407401901517 } ]
typescript
.getAll().then(setAccounts) }, []) async function handleLogin() {
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": 56.20387133173602 }, { "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": 50.00761345682296 }, { "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": 40.509273709295854 }, { "filename": "src/background/index.ts", "retrieved_chunk": " if (!cookies.length) {\n return null\n }\n return cookies\n .map((cookie) => `${cookie.name}=${cookie.value}`)\n .concat(`__account__=${accountName}`)\n .join('; ')\n}\nasync function buildAddRules(): Promise<DeclarativeNetRequest.Rule[]> {\n const requestRules: DeclarativeNetRequest.Rule[] = []", "score": 36.36173539492637 }, { "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": 36.13518719152455 } ]
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": 39.304341049102696 }, { "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": 25.708252477699304 }, { "filename": "src/background/index.ts", "retrieved_chunk": " if (!cookies.length) {\n return null\n }\n return cookies\n .map((cookie) => `${cookie.name}=${cookie.value}`)\n .concat(`__account__=${accountName}`)\n .join('; ')\n}\nasync function buildAddRules(): Promise<DeclarativeNetRequest.Rule[]> {\n const requestRules: DeclarativeNetRequest.Rule[] = []", "score": 18.044077627847226 }, { "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": 14.603801402532287 }, { "filename": "src/services/badge.ts", "retrieved_chunk": "import browser from 'webextension-polyfill'\nexport async function setBadgeText(text: string) {\n const action = browser.action || browser.browserAction\n await action.setBadgeText({\n text\n })\n await action.setBadgeBackgroundColor({\n color: '#44b700',\n })\n action.setBadgeTextColor({", "score": 13.991916756602853 } ]
typescript
await storage.update<Accounts>('accounts', (accounts) => {
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/translate/translateAction.ts", "retrieved_chunk": " text: `Translate to ${language}: ${text}`,\n method: 'POST',\n key: config.apiKey\n }\n const openAIChatResponse = await openAIChat(params)\n console.log(`\\n${green(openAIChatResponse.data)}`)\n}", "score": 21.530820315315683 }, { "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": 18.162949119618737 }, { "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": 17.58795462598804 }, { "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": 16.623192175509207 }, { "filename": "src/commands/generateTest/index.ts", "retrieved_chunk": "import { Command } from 'commander'\nimport { generateTestAction } from './generateTestAction'\nimport type { GeneralOptions } from '../../typings/General'\nexport const generateTest = new Command()\n .command('generate-test')\n .description('enter the path of the component that will receive the test')\n .option('-c, --component <string>', 'component name')\n .option('-p, --path <path>', 'component path')\n .option('-l, --library <string>', 'test library')\n .action((options: GeneralOptions) => generateTestAction(options))", "score": 13.93084729316747 } ]
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": 48.87747625703146 }, { "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": 39.601399816042345 }, { "filename": "src/background/index.ts", "retrieved_chunk": " if (!cookies.length) {\n return null\n }\n return cookies\n .map((cookie) => `${cookie.name}=${cookie.value}`)\n .concat(`__account__=${accountName}`)\n .join('; ')\n}\nasync function buildAddRules(): Promise<DeclarativeNetRequest.Rule[]> {\n const requestRules: DeclarativeNetRequest.Rule[] = []", "score": 38.50775071887061 }, { "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": 27.87128174298597 }, { "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": 27.36856631251729 } ]
typescript
clear() const account = await find(accountName) const cookies = account?.cookies || [] for (const cookie of cookies) {
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/popup/components/RuleItem.tsx", "retrieved_chunk": " function handleAccountChange(event: React.ChangeEvent<HTMLInputElement>) {\n const value = event.target.value\n const { message } = validateAccount(value)\n setAccountValidation(message)\n setRule({ ...rule, account: value })\n }\n return (\n <Box display=\"flex\" gap={2} alignItems=\"flex-start\">\n <Box flex=\"1\">\n <TextField", "score": 16.278752440350328 }, { "filename": "src/popup/components/RuleItem.tsx", "retrieved_chunk": " function handleDelete() {\n setIsEditing(false)\n onDelete(rule)\n }\n function handleUrlPatternChange(event: React.ChangeEvent<HTMLInputElement>) {\n const value = event.target.value\n const { message } = validateUrlPattern(value)\n setUrlPatternValidation(message)\n setRule({ ...rule, urlPattern: value })\n }", "score": 15.503794112038456 }, { "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": 15.215468281786066 }, { "filename": "src/content/ui.ts", "retrieved_chunk": " 'data-account': account,\n class: `ActionListContent ${ACCOUNT_ITEM_CLASS}`,\n children: [\n createElement('span', {\n class: 'ActionListItem-label',\n children: [\n 'Switch to ',\n createElement('b', { children: account }),\n ]\n })", "score": 14.8592196533886 }, { "filename": "src/content/ui.ts", "retrieved_chunk": " createElement('button', {\n 'data-account': account,\n class: `dropdown-item btn-link ${ACCOUNT_ITEM_CLASS}`,\n role: 'menuitem',\n children: [\n 'Switch to ',\n createElement('b', { children: account }),\n ],\n }),\n createElement('button', {", "score": 14.161767548164683 } ]
typescript
(target.closest(`.${ACCOUNT_REMOVE_CLASS}`)) {
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": 33.19536647992001 }, { "filename": "src/util.ts", "retrieved_chunk": " }\n return shaderModule;\n}\nexport function fillSelector(selector: HTMLSelectElement, dict: Map<string, string>)\n{\n for (let v of dict.keys()) {\n let opt = document.createElement(\"option\") as HTMLOptionElement;\n opt.value = v;\n opt.innerHTML = v;\n selector.appendChild(opt);", "score": 32.80885290950636 }, { "filename": "src/marching_cubes.ts", "retrieved_chunk": " // active or not. We'll run a scan on this buffer so it also needs to be\n // aligned to the scan size.\n mc.#voxelActive = device.createBuffer({\n size: mc.#exclusiveScan.getAlignedSize(volume.dualGridNumVoxels) * 4,\n usage: GPUBufferUsage.STORAGE | GPUBufferUsage.COPY_SRC,\n });\n // Compile shaders for our compute kernels\n let markActiveVoxel = await compileShader(device,\n computeVoxelValuesWgsl + \"\\n\" + markActiveVoxelsWgsl, \"mark_active_voxel.wgsl\");\n let computeNumVerts = await compileShader(device,", "score": 18.912261308518133 }, { "filename": "src/stream_compact_ids.ts", "retrieved_chunk": " });\n // Make a remainder elements bindgroup if we have some remainder to make sure\n // we don't bind out of bounds regions of the buffer. If there's no remiander we\n // just set remainderParamsBG to paramsBG so that on our last dispatch we can just\n // always bindg remainderParamsBG\n let remainderParamsBG = paramsBG;\n const remainderElements = size % elementsPerDispatch;\n if (remainderElements != 0) {\n // Note: We don't set the offset here, as that will still be handled by the\n // dynamic offsets. We just need to set the right size, so that", "score": 18.669473924336017 }, { "filename": "src/push_constant_builder.ts", "retrieved_chunk": " constructor(device: GPUDevice, totalWorkGroups: number, appPushConstants?: ArrayBuffer)\n {\n this.#maxWorkgroupsPerDimension = device.limits.maxComputeWorkgroupsPerDimension;\n this.totalWorkGroups = totalWorkGroups;\n let nDispatches =\n Math.ceil(totalWorkGroups / device.limits.maxComputeWorkgroupsPerDimension);\n // Determine if we have some additional push constant data and align the push constant\n // stride accordingly\n this.stride = device.limits.minUniformBufferOffsetAlignment;\n let appPushConstantsView = null;", "score": 17.37063090472877 } ]
typescript
fillSelector(volumePicker, volumes);