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/types/alert.ts",
"retrieved_chunk": "import { CfnResource } from \"aws-cdk-lib\";\nimport { QueryOperationString, QueryParameters } from \"./query\";\nexport type AlertProps<TKey extends string> = {\n\tdescription?: string;\n\tenabled?: boolean;\n\tparameters: {\n\t\tquery: CfnResource | QueryParameters<TKey>,\n\t\tthreshold?: {\n\t\t\toperation?: QueryOperationString,\n\t\t\tvalue: string | number",
"score": 0.8412778377532959
},
{
"filename": "src/resources/alert.ts",
"retrieved_chunk": "import { CfnResource, Stack } from \"aws-cdk-lib\";\nimport { Baselime as Config } from \"../config\";\nimport { Query } from \"./query\";\nimport { AlertProps, DeploymentAlertParameters } from \"../types/alert\";\nimport { QueryProps } from \"../types/query\";\nimport { getServiceName } from \"../utils/service-name\";\nexport class Alert<TKey extends string> extends CfnResource {\n\tconstructor(id: string, props: AlertProps<TKey>) {\n\t\tconst stack = Stack.of(Config.getConstruct());\n\t\tconst defaultFrequency = \"1hour\";",
"score": 0.8407533764839172
},
{
"filename": "src/resources/dashboard.ts",
"retrieved_chunk": "import { CfnResource, Stack } from \"aws-cdk-lib\";\nimport { Baselime as Config } from \"../config\";\nimport { DashboardProps } from \"../types/dashboard\";\nimport { getServiceName } from \"../utils/service-name\";\nexport class Dashboard extends CfnResource {\n\tconstructor(id: string, props: DashboardProps) {\n\t\tconst stack = Stack.of(Config.getConstruct());\n\t\tconst parameters = {\n\t\t\t...props.parameters,\n\t\t\twidgets: props.parameters.widgets.map(el => ({ ...el, query: el.query.ref }))",
"score": 0.8235413432121277
},
{
"filename": "src/resources/alert.ts",
"retrieved_chunk": "\t\t\t};\n\t\t}\n\t\tif (\"filters\" in props.parameters.query) {\n\t\t\tconst query = new Query(`${id}-query`, {\n\t\t\t\tparameters: {\n\t\t\t\t\t...props.parameters.query,\n\t\t\t\t\tcalculations: props.parameters.query.calculations || [\n\t\t\t\t\t\t{ operation: \"COUNT\" },\n\t\t\t\t\t],\n\t\t\t\t},",
"score": 0.8220397233963013
},
{
"filename": "src/types/query.ts",
"retrieved_chunk": "import { F } from \"ts-toolbelt\";\nexport type QueryProps<TKey extends string> = {\n\tdescription?: string;\n\tparameters: QueryParameters<TKey>\n\tdisableStackFilter?: boolean\n};\nexport type QueryParameters<TKey extends string> = {\n\tdatasets?: Datasets[];\n\tfilterCombination?: \"AND\" | \"OR\";\n\tfilters: Filter[];",
"score": 0.8178369998931885
}
] |
typescript
|
props: QueryProps<TKey>
constructor(id: string, props: QueryProps<TKey>) {
|
import { CfnResource, Stack } from "aws-cdk-lib";
import { Baselime as Config } from "../config";
import { QueryProps, Filter, DeploymentQueryParameters } from "../types/query";
import { AlertProps } from "../types/alert";
import { Alert } from './alert';
import { getServiceName } from '../utils/service-name';
function buildCalculation(cal: { alias?: string; operation: string; key?: string }) {
const short = buildShortCalculation(cal);
return `${short}${cal.alias ? ` as ${cal.alias}` : ""}`;
}
function hasDuplicates<T>(array: T[]) {
return (new Set(array)).size !== array.length;
}
function buildShortCalculation(cal: { alias?: string; operation: string; key?: string }) {
if (cal.operation === "COUNT") {
return cal.operation;
}
return `${cal.operation}(${cal.key})`;
}
function getCalculationAlias(cal: { alias?: string; operation: string; key?: string }) {
return cal.alias ? cal.alias : buildShortCalculation(cal);
}
export function stringifyFilter(filter: Filter): string {
const { key, operation, value } = filter;
if (!operation) {
return `${key} = ${value}`;
}
if (["EXISTS", "DOES_NOT_EXIST"].includes(operation)) {
return `${key} ${operation}`;
}
if (["IN", "NOT_IN"].some(o => o === operation)) {
return `${key} ${operation} (${value})`;
}
return `${key} ${operation} ${value}`;
}
/**
*
*/
export class Query<TKey extends string> extends CfnResource {
id: string;
props: QueryProps<TKey>
constructor(id: string, props: QueryProps<TKey>) {
const stack = Stack.of(Config.getConstruct());
const calcs = props.parameters.calculations;
const orderByOptions = calcs?.map(cal => getCalculationAlias(cal));
if (calcs?.length && hasDuplicates(calcs.filter(c => c.alias).map(c => c.alias))) {
throw Error("Aliases must me unique across all calculations / visualisations.")
}
if (props.parameters.orderBy && !orderByOptions?.includes(props.parameters.orderBy.value)) {
throw Error("The orderBy must be present in the calculations / visualisations.")
}
const disableStackFilter = props.disableStackFilter || Config.getDisableStackFilter();
if (!disableStackFilter) {
props.parameters.filters?.push({ operation: "=", key: "$baselime.stackId", value: stack.stackName })
}
const Parameters: DeploymentQueryParameters = {
...props.parameters,
datasets: props.parameters.datasets || ['lambda-logs'],
calculations: props.parameters.calculations ? props.parameters.calculations.map(buildCalculation) : [],
filters: props.parameters.filters?.map(stringifyFilter),
|
groupBys: props.parameters.groupBys?.map(groupBy => {
|
return {
...groupBy,
type: groupBy?.type || "string"
}
}),
filterCombination: props.parameters.filterCombination || "AND",
};
super(Config.getConstruct(), id, {
type: "Custom::BaselimeQuery",
properties: {
id,
ServiceToken: Config.getServiceToken(),
BaselimeApiKey: Config.getApiKey(),
Description: props.description,
Service: getServiceName(stack),
Parameters,
Origin: "cdk"
},
});
this.id = id;
this.props = props;
}
addAlert(alert: ChangeFields<AlertProps<TKey>, {
parameters: Omit<AlertProps<TKey>['parameters'], "query">
}>) {
const alertProps = {
...alert,
parameters: {
...alert.parameters,
query: this
}
}
new Alert(`${this.id}-alert`, alertProps);
}
addFilters(filters: QueryProps<string>["parameters"]["filters"]) {
this.addPropertyOverride('Parameters.filters', [...filters || []])
}
};
type ChangeFields<T, R> = Omit<T, keyof R> & R;
|
src/resources/query.ts
|
baselime-cdk-82637d8
|
[
{
"filename": "src/resources/alert.ts",
"retrieved_chunk": "\t\t\t};\n\t\t}\n\t\tif (\"filters\" in props.parameters.query) {\n\t\t\tconst query = new Query(`${id}-query`, {\n\t\t\t\tparameters: {\n\t\t\t\t\t...props.parameters.query,\n\t\t\t\t\tcalculations: props.parameters.query.calculations || [\n\t\t\t\t\t\t{ operation: \"COUNT\" },\n\t\t\t\t\t],\n\t\t\t\t},",
"score": 0.8485311269760132
},
{
"filename": "src/resources/alert.ts",
"retrieved_chunk": "\t\t\t});\n\t\t\tParameters = {\n\t\t\t\t...props.parameters,\n\t\t\t\tthreshold: `${props.parameters.threshold?.operation || \">\"} ${props.parameters.threshold?.value || 0\n\t\t\t\t\t}`,\n\t\t\t\tquery: query.ref,\n\t\t\t\tfrequency: props.parameters.frequency || defaultFrequency,\n\t\t\t\twindow: props.parameters.window || defaultWindow,\n\t\t\t};\n\t\t}",
"score": 0.8466163277626038
},
{
"filename": "src/resources/dashboard.ts",
"retrieved_chunk": "\t\t}\n\t\tsuper(Config.getConstruct(), id, {\n\t\t\ttype: \"Custom::BaselimeDashboard\",\n\t\t\tproperties: {\n\t\t\t\tid,\n\t\t\t\tServiceToken: Config.getServiceToken(),\n\t\t\t\tBaselimeApiKey: Config.getApiKey(),\n\t\t\t\tDescription: props.description,\n\t\t\t\tService: getServiceName(stack),\n\t\t\t\tParameters: parameters,",
"score": 0.8399603366851807
},
{
"filename": "src/resources/alert.ts",
"retrieved_chunk": "\t\tconst defaultWindow = \"1hour\";\n\t\tlet Parameters: DeploymentAlertParameters | undefined = undefined;\n\t\tif (\"ref\" in props.parameters.query) {\n\t\t\tParameters = {\n\t\t\t\t...props.parameters,\n\t\t\t\tthreshold: `${props.parameters.threshold?.operation || \">\"} ${props.parameters.threshold?.value\n\t\t\t\t\t}`,\n\t\t\t\tquery: props.parameters.query.ref,\n\t\t\t\tfrequency: props.parameters.frequency || defaultFrequency,\n\t\t\t\twindow: props.parameters.window || defaultWindow,",
"score": 0.8229415416717529
},
{
"filename": "src/types/query.ts",
"retrieved_chunk": "};\nexport type DeploymentQueryParameters = {\n\tdatasets: string[];\n\tcalculations?: string[];\n\tfilterCombination: \"AND\" | \"OR\";\n\tfilters?: string[];\n\tgroupBys?: QueryGroupBy[];\n\torderBy?: {\n\t\tvalue: string;\n\t\torder?: \"ASC\" | \"DESC\";",
"score": 0.8171054124832153
}
] |
typescript
|
groupBys: props.parameters.groupBys?.map(groupBy => {
|
import { CfnResource, Stack } from "aws-cdk-lib";
import { Baselime as Config } from "../config";
import { QueryProps, Filter, DeploymentQueryParameters } from "../types/query";
import { AlertProps } from "../types/alert";
import { Alert } from './alert';
import { getServiceName } from '../utils/service-name';
function buildCalculation(cal: { alias?: string; operation: string; key?: string }) {
const short = buildShortCalculation(cal);
return `${short}${cal.alias ? ` as ${cal.alias}` : ""}`;
}
function hasDuplicates<T>(array: T[]) {
return (new Set(array)).size !== array.length;
}
function buildShortCalculation(cal: { alias?: string; operation: string; key?: string }) {
if (cal.operation === "COUNT") {
return cal.operation;
}
return `${cal.operation}(${cal.key})`;
}
function getCalculationAlias(cal: { alias?: string; operation: string; key?: string }) {
return cal.alias ? cal.alias : buildShortCalculation(cal);
}
export function stringifyFilter(filter: Filter): string {
const { key, operation, value } = filter;
if (!operation) {
return `${key} = ${value}`;
}
if (["EXISTS", "DOES_NOT_EXIST"].includes(operation)) {
return `${key} ${operation}`;
}
if (["IN", "NOT_IN"].some(o => o === operation)) {
return `${key} ${operation} (${value})`;
}
return `${key} ${operation} ${value}`;
}
/**
*
*/
export class Query<TKey extends string> extends CfnResource {
id: string;
props: QueryProps<TKey>
|
constructor(id: string, props: QueryProps<TKey>) {
|
const stack = Stack.of(Config.getConstruct());
const calcs = props.parameters.calculations;
const orderByOptions = calcs?.map(cal => getCalculationAlias(cal));
if (calcs?.length && hasDuplicates(calcs.filter(c => c.alias).map(c => c.alias))) {
throw Error("Aliases must me unique across all calculations / visualisations.")
}
if (props.parameters.orderBy && !orderByOptions?.includes(props.parameters.orderBy.value)) {
throw Error("The orderBy must be present in the calculations / visualisations.")
}
const disableStackFilter = props.disableStackFilter || Config.getDisableStackFilter();
if (!disableStackFilter) {
props.parameters.filters?.push({ operation: "=", key: "$baselime.stackId", value: stack.stackName })
}
const Parameters: DeploymentQueryParameters = {
...props.parameters,
datasets: props.parameters.datasets || ['lambda-logs'],
calculations: props.parameters.calculations ? props.parameters.calculations.map(buildCalculation) : [],
filters: props.parameters.filters?.map(stringifyFilter),
groupBys: props.parameters.groupBys?.map(groupBy => {
return {
...groupBy,
type: groupBy?.type || "string"
}
}),
filterCombination: props.parameters.filterCombination || "AND",
};
super(Config.getConstruct(), id, {
type: "Custom::BaselimeQuery",
properties: {
id,
ServiceToken: Config.getServiceToken(),
BaselimeApiKey: Config.getApiKey(),
Description: props.description,
Service: getServiceName(stack),
Parameters,
Origin: "cdk"
},
});
this.id = id;
this.props = props;
}
addAlert(alert: ChangeFields<AlertProps<TKey>, {
parameters: Omit<AlertProps<TKey>['parameters'], "query">
}>) {
const alertProps = {
...alert,
parameters: {
...alert.parameters,
query: this
}
}
new Alert(`${this.id}-alert`, alertProps);
}
addFilters(filters: QueryProps<string>["parameters"]["filters"]) {
this.addPropertyOverride('Parameters.filters', [...filters || []])
}
};
type ChangeFields<T, R> = Omit<T, keyof R> & R;
|
src/resources/query.ts
|
baselime-cdk-82637d8
|
[
{
"filename": "src/types/alert.ts",
"retrieved_chunk": "import { CfnResource } from \"aws-cdk-lib\";\nimport { QueryOperationString, QueryParameters } from \"./query\";\nexport type AlertProps<TKey extends string> = {\n\tdescription?: string;\n\tenabled?: boolean;\n\tparameters: {\n\t\tquery: CfnResource | QueryParameters<TKey>,\n\t\tthreshold?: {\n\t\t\toperation?: QueryOperationString,\n\t\t\tvalue: string | number",
"score": 0.8412778377532959
},
{
"filename": "src/resources/alert.ts",
"retrieved_chunk": "import { CfnResource, Stack } from \"aws-cdk-lib\";\nimport { Baselime as Config } from \"../config\";\nimport { Query } from \"./query\";\nimport { AlertProps, DeploymentAlertParameters } from \"../types/alert\";\nimport { QueryProps } from \"../types/query\";\nimport { getServiceName } from \"../utils/service-name\";\nexport class Alert<TKey extends string> extends CfnResource {\n\tconstructor(id: string, props: AlertProps<TKey>) {\n\t\tconst stack = Stack.of(Config.getConstruct());\n\t\tconst defaultFrequency = \"1hour\";",
"score": 0.8407533764839172
},
{
"filename": "src/resources/dashboard.ts",
"retrieved_chunk": "import { CfnResource, Stack } from \"aws-cdk-lib\";\nimport { Baselime as Config } from \"../config\";\nimport { DashboardProps } from \"../types/dashboard\";\nimport { getServiceName } from \"../utils/service-name\";\nexport class Dashboard extends CfnResource {\n\tconstructor(id: string, props: DashboardProps) {\n\t\tconst stack = Stack.of(Config.getConstruct());\n\t\tconst parameters = {\n\t\t\t...props.parameters,\n\t\t\twidgets: props.parameters.widgets.map(el => ({ ...el, query: el.query.ref }))",
"score": 0.8235413432121277
},
{
"filename": "src/resources/alert.ts",
"retrieved_chunk": "\t\t\t};\n\t\t}\n\t\tif (\"filters\" in props.parameters.query) {\n\t\t\tconst query = new Query(`${id}-query`, {\n\t\t\t\tparameters: {\n\t\t\t\t\t...props.parameters.query,\n\t\t\t\t\tcalculations: props.parameters.query.calculations || [\n\t\t\t\t\t\t{ operation: \"COUNT\" },\n\t\t\t\t\t],\n\t\t\t\t},",
"score": 0.8220397233963013
},
{
"filename": "src/types/query.ts",
"retrieved_chunk": "import { F } from \"ts-toolbelt\";\nexport type QueryProps<TKey extends string> = {\n\tdescription?: string;\n\tparameters: QueryParameters<TKey>\n\tdisableStackFilter?: boolean\n};\nexport type QueryParameters<TKey extends string> = {\n\tdatasets?: Datasets[];\n\tfilterCombination?: \"AND\" | \"OR\";\n\tfilters: Filter[];",
"score": 0.8178369998931885
}
] |
typescript
|
constructor(id: string, props: QueryProps<TKey>) {
|
import { CfnResource, Stack } from "aws-cdk-lib";
import { Baselime as Config } from "../config";
import { QueryProps, Filter, DeploymentQueryParameters } from "../types/query";
import { AlertProps } from "../types/alert";
import { Alert } from './alert';
import { getServiceName } from '../utils/service-name';
function buildCalculation(cal: { alias?: string; operation: string; key?: string }) {
const short = buildShortCalculation(cal);
return `${short}${cal.alias ? ` as ${cal.alias}` : ""}`;
}
function hasDuplicates<T>(array: T[]) {
return (new Set(array)).size !== array.length;
}
function buildShortCalculation(cal: { alias?: string; operation: string; key?: string }) {
if (cal.operation === "COUNT") {
return cal.operation;
}
return `${cal.operation}(${cal.key})`;
}
function getCalculationAlias(cal: { alias?: string; operation: string; key?: string }) {
return cal.alias ? cal.alias : buildShortCalculation(cal);
}
export function stringifyFilter(filter: Filter): string {
const { key, operation, value } = filter;
if (!operation) {
return `${key} = ${value}`;
}
if (["EXISTS", "DOES_NOT_EXIST"].includes(operation)) {
return `${key} ${operation}`;
}
if (["IN", "NOT_IN"].some(o => o === operation)) {
return `${key} ${operation} (${value})`;
}
return `${key} ${operation} ${value}`;
}
/**
*
*/
export class Query<TKey extends string> extends CfnResource {
id: string;
props:
|
QueryProps<TKey>
constructor(id: string, props: QueryProps<TKey>) {
|
const stack = Stack.of(Config.getConstruct());
const calcs = props.parameters.calculations;
const orderByOptions = calcs?.map(cal => getCalculationAlias(cal));
if (calcs?.length && hasDuplicates(calcs.filter(c => c.alias).map(c => c.alias))) {
throw Error("Aliases must me unique across all calculations / visualisations.")
}
if (props.parameters.orderBy && !orderByOptions?.includes(props.parameters.orderBy.value)) {
throw Error("The orderBy must be present in the calculations / visualisations.")
}
const disableStackFilter = props.disableStackFilter || Config.getDisableStackFilter();
if (!disableStackFilter) {
props.parameters.filters?.push({ operation: "=", key: "$baselime.stackId", value: stack.stackName })
}
const Parameters: DeploymentQueryParameters = {
...props.parameters,
datasets: props.parameters.datasets || ['lambda-logs'],
calculations: props.parameters.calculations ? props.parameters.calculations.map(buildCalculation) : [],
filters: props.parameters.filters?.map(stringifyFilter),
groupBys: props.parameters.groupBys?.map(groupBy => {
return {
...groupBy,
type: groupBy?.type || "string"
}
}),
filterCombination: props.parameters.filterCombination || "AND",
};
super(Config.getConstruct(), id, {
type: "Custom::BaselimeQuery",
properties: {
id,
ServiceToken: Config.getServiceToken(),
BaselimeApiKey: Config.getApiKey(),
Description: props.description,
Service: getServiceName(stack),
Parameters,
Origin: "cdk"
},
});
this.id = id;
this.props = props;
}
addAlert(alert: ChangeFields<AlertProps<TKey>, {
parameters: Omit<AlertProps<TKey>['parameters'], "query">
}>) {
const alertProps = {
...alert,
parameters: {
...alert.parameters,
query: this
}
}
new Alert(`${this.id}-alert`, alertProps);
}
addFilters(filters: QueryProps<string>["parameters"]["filters"]) {
this.addPropertyOverride('Parameters.filters', [...filters || []])
}
};
type ChangeFields<T, R> = Omit<T, keyof R> & R;
|
src/resources/query.ts
|
baselime-cdk-82637d8
|
[
{
"filename": "src/types/alert.ts",
"retrieved_chunk": "import { CfnResource } from \"aws-cdk-lib\";\nimport { QueryOperationString, QueryParameters } from \"./query\";\nexport type AlertProps<TKey extends string> = {\n\tdescription?: string;\n\tenabled?: boolean;\n\tparameters: {\n\t\tquery: CfnResource | QueryParameters<TKey>,\n\t\tthreshold?: {\n\t\t\toperation?: QueryOperationString,\n\t\t\tvalue: string | number",
"score": 0.8509859442710876
},
{
"filename": "src/resources/alert.ts",
"retrieved_chunk": "import { CfnResource, Stack } from \"aws-cdk-lib\";\nimport { Baselime as Config } from \"../config\";\nimport { Query } from \"./query\";\nimport { AlertProps, DeploymentAlertParameters } from \"../types/alert\";\nimport { QueryProps } from \"../types/query\";\nimport { getServiceName } from \"../utils/service-name\";\nexport class Alert<TKey extends string> extends CfnResource {\n\tconstructor(id: string, props: AlertProps<TKey>) {\n\t\tconst stack = Stack.of(Config.getConstruct());\n\t\tconst defaultFrequency = \"1hour\";",
"score": 0.8502434492111206
},
{
"filename": "src/types/query.ts",
"retrieved_chunk": "import { F } from \"ts-toolbelt\";\nexport type QueryProps<TKey extends string> = {\n\tdescription?: string;\n\tparameters: QueryParameters<TKey>\n\tdisableStackFilter?: boolean\n};\nexport type QueryParameters<TKey extends string> = {\n\tdatasets?: Datasets[];\n\tfilterCombination?: \"AND\" | \"OR\";\n\tfilters: Filter[];",
"score": 0.8287854790687561
},
{
"filename": "src/resources/dashboard.ts",
"retrieved_chunk": "import { CfnResource, Stack } from \"aws-cdk-lib\";\nimport { Baselime as Config } from \"../config\";\nimport { DashboardProps } from \"../types/dashboard\";\nimport { getServiceName } from \"../utils/service-name\";\nexport class Dashboard extends CfnResource {\n\tconstructor(id: string, props: DashboardProps) {\n\t\tconst stack = Stack.of(Config.getConstruct());\n\t\tconst parameters = {\n\t\t\t...props.parameters,\n\t\t\twidgets: props.parameters.widgets.map(el => ({ ...el, query: el.query.ref }))",
"score": 0.8286200761795044
},
{
"filename": "src/resources/alert.ts",
"retrieved_chunk": "\t\t\t};\n\t\t}\n\t\tif (\"filters\" in props.parameters.query) {\n\t\t\tconst query = new Query(`${id}-query`, {\n\t\t\t\tparameters: {\n\t\t\t\t\t...props.parameters.query,\n\t\t\t\t\tcalculations: props.parameters.query.calculations || [\n\t\t\t\t\t\t{ operation: \"COUNT\" },\n\t\t\t\t\t],\n\t\t\t\t},",
"score": 0.8214820623397827
}
] |
typescript
|
QueryProps<TKey>
constructor(id: string, props: QueryProps<TKey>) {
|
import { CfnResource, Stack } from "aws-cdk-lib";
import { Baselime as Config } from "../config";
import { QueryProps, Filter, DeploymentQueryParameters } from "../types/query";
import { AlertProps } from "../types/alert";
import { Alert } from './alert';
import { getServiceName } from '../utils/service-name';
function buildCalculation(cal: { alias?: string; operation: string; key?: string }) {
const short = buildShortCalculation(cal);
return `${short}${cal.alias ? ` as ${cal.alias}` : ""}`;
}
function hasDuplicates<T>(array: T[]) {
return (new Set(array)).size !== array.length;
}
function buildShortCalculation(cal: { alias?: string; operation: string; key?: string }) {
if (cal.operation === "COUNT") {
return cal.operation;
}
return `${cal.operation}(${cal.key})`;
}
function getCalculationAlias(cal: { alias?: string; operation: string; key?: string }) {
return cal.alias ? cal.alias : buildShortCalculation(cal);
}
export function stringifyFilter(filter: Filter): string {
const { key, operation, value } = filter;
if (!operation) {
return `${key} = ${value}`;
}
if (["EXISTS", "DOES_NOT_EXIST"].includes(operation)) {
return `${key} ${operation}`;
}
if (["IN", "NOT_IN"].some(o => o === operation)) {
return `${key} ${operation} (${value})`;
}
return `${key} ${operation} ${value}`;
}
/**
*
*/
export class Query<TKey extends string> extends CfnResource {
id: string;
props: QueryProps<TKey>
constructor(id: string, props: QueryProps<TKey>) {
const stack = Stack.of(Config.getConstruct());
const calcs = props.parameters.calculations;
const orderByOptions = calcs?.map(cal => getCalculationAlias(cal));
if (calcs?.length && hasDuplicates(calcs.filter(c => c.alias).map(c => c.alias))) {
throw Error("Aliases must me unique across all calculations / visualisations.")
}
if (props.parameters.orderBy && !orderByOptions?.includes(props.parameters.orderBy.value)) {
throw Error("The orderBy must be present in the calculations / visualisations.")
}
const disableStackFilter = props.disableStackFilter || Config.getDisableStackFilter();
if (!disableStackFilter) {
props.parameters.filters?.push({ operation: "=", key: "$baselime.stackId", value: stack.stackName })
}
const Parameters: DeploymentQueryParameters = {
...props.parameters,
datasets: props.parameters.datasets || ['lambda-logs'],
calculations: props.parameters.calculations ? props.parameters.calculations.map(buildCalculation) : [],
filters: props.parameters.filters?.map(stringifyFilter),
groupBys: props.parameters.groupBys?.map(groupBy => {
return {
...groupBy,
type: groupBy?.type || "string"
}
}),
filterCombination: props.parameters.filterCombination || "AND",
};
super(Config.getConstruct(), id, {
type: "Custom::BaselimeQuery",
properties: {
id,
ServiceToken: Config.getServiceToken(),
BaselimeApiKey: Config.getApiKey(),
Description: props.description,
Service: getServiceName(stack),
Parameters,
Origin: "cdk"
},
});
this.id = id;
this.props = props;
}
addAlert
|
(alert: ChangeFields<AlertProps<TKey>, {
|
parameters: Omit<AlertProps<TKey>['parameters'], "query">
}>) {
const alertProps = {
...alert,
parameters: {
...alert.parameters,
query: this
}
}
new Alert(`${this.id}-alert`, alertProps);
}
addFilters(filters: QueryProps<string>["parameters"]["filters"]) {
this.addPropertyOverride('Parameters.filters', [...filters || []])
}
};
type ChangeFields<T, R> = Omit<T, keyof R> & R;
|
src/resources/query.ts
|
baselime-cdk-82637d8
|
[
{
"filename": "src/resources/alert.ts",
"retrieved_chunk": "import { CfnResource, Stack } from \"aws-cdk-lib\";\nimport { Baselime as Config } from \"../config\";\nimport { Query } from \"./query\";\nimport { AlertProps, DeploymentAlertParameters } from \"../types/alert\";\nimport { QueryProps } from \"../types/query\";\nimport { getServiceName } from \"../utils/service-name\";\nexport class Alert<TKey extends string> extends CfnResource {\n\tconstructor(id: string, props: AlertProps<TKey>) {\n\t\tconst stack = Stack.of(Config.getConstruct());\n\t\tconst defaultFrequency = \"1hour\";",
"score": 0.8473438024520874
},
{
"filename": "src/types/alert.ts",
"retrieved_chunk": "import { CfnResource } from \"aws-cdk-lib\";\nimport { QueryOperationString, QueryParameters } from \"./query\";\nexport type AlertProps<TKey extends string> = {\n\tdescription?: string;\n\tenabled?: boolean;\n\tparameters: {\n\t\tquery: CfnResource | QueryParameters<TKey>,\n\t\tthreshold?: {\n\t\t\toperation?: QueryOperationString,\n\t\t\tvalue: string | number",
"score": 0.8292766213417053
},
{
"filename": "src/resources/alert.ts",
"retrieved_chunk": "\t\tif (!Parameters) throw new Error(\"Invalid alert parameters. Declare at least one of filters or ref in the query.\")\n\t\tsuper(Config.getConstruct(), id, {\n\t\t\ttype: \"Custom::BaselimeAlert\",\n\t\t\tproperties: {\n\t\t\t\tid,\n\t\t\t\tServiceToken: Config.getServiceToken(),\n\t\t\t\tBaselimeApiKey: Config.getApiKey(),\n\t\t\t\tenabled: props.enabled,\n\t\t\t\tDescription: props.description,\n\t\t\t\tService: getServiceName(stack),",
"score": 0.807956874370575
},
{
"filename": "src/resources/dashboard.ts",
"retrieved_chunk": "import { CfnResource, Stack } from \"aws-cdk-lib\";\nimport { Baselime as Config } from \"../config\";\nimport { DashboardProps } from \"../types/dashboard\";\nimport { getServiceName } from \"../utils/service-name\";\nexport class Dashboard extends CfnResource {\n\tconstructor(id: string, props: DashboardProps) {\n\t\tconst stack = Stack.of(Config.getConstruct());\n\t\tconst parameters = {\n\t\t\t...props.parameters,\n\t\t\twidgets: props.parameters.widgets.map(el => ({ ...el, query: el.query.ref }))",
"score": 0.7952832579612732
},
{
"filename": "src/resources/dashboard.ts",
"retrieved_chunk": "\t\t}\n\t\tsuper(Config.getConstruct(), id, {\n\t\t\ttype: \"Custom::BaselimeDashboard\",\n\t\t\tproperties: {\n\t\t\t\tid,\n\t\t\t\tServiceToken: Config.getServiceToken(),\n\t\t\t\tBaselimeApiKey: Config.getApiKey(),\n\t\t\t\tDescription: props.description,\n\t\t\t\tService: getServiceName(stack),\n\t\t\t\tParameters: parameters,",
"score": 0.789391040802002
}
] |
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\tParameters = {\n\t\t\t\t...props.parameters,\n\t\t\t\tthreshold: `${props.parameters.threshold?.operation || \">\"} ${props.parameters.threshold?.value || 0\n\t\t\t\t\t}`,\n\t\t\t\tquery: query.ref,\n\t\t\t\tfrequency: props.parameters.frequency || defaultFrequency,\n\t\t\t\twindow: props.parameters.window || defaultWindow,\n\t\t\t};\n\t\t}",
"score": 0.8572933077812195
},
{
"filename": "src/resources/alert.ts",
"retrieved_chunk": "\t\t\t};\n\t\t}\n\t\tif (\"filters\" in props.parameters.query) {\n\t\t\tconst query = new Query(`${id}-query`, {\n\t\t\t\tparameters: {\n\t\t\t\t\t...props.parameters.query,\n\t\t\t\t\tcalculations: props.parameters.query.calculations || [\n\t\t\t\t\t\t{ operation: \"COUNT\" },\n\t\t\t\t\t],\n\t\t\t\t},",
"score": 0.852108359336853
},
{
"filename": "src/resources/dashboard.ts",
"retrieved_chunk": "\t\t}\n\t\tsuper(Config.getConstruct(), id, {\n\t\t\ttype: \"Custom::BaselimeDashboard\",\n\t\t\tproperties: {\n\t\t\t\tid,\n\t\t\t\tServiceToken: Config.getServiceToken(),\n\t\t\t\tBaselimeApiKey: Config.getApiKey(),\n\t\t\t\tDescription: props.description,\n\t\t\t\tService: getServiceName(stack),\n\t\t\t\tParameters: parameters,",
"score": 0.8451871871948242
},
{
"filename": "src/types/query.ts",
"retrieved_chunk": "};\nexport type DeploymentQueryParameters = {\n\tdatasets: string[];\n\tcalculations?: string[];\n\tfilterCombination: \"AND\" | \"OR\";\n\tfilters?: string[];\n\tgroupBys?: QueryGroupBy[];\n\torderBy?: {\n\t\tvalue: string;\n\t\torder?: \"ASC\" | \"DESC\";",
"score": 0.8326929211616516
},
{
"filename": "src/resources/alert.ts",
"retrieved_chunk": "\t\tconst defaultWindow = \"1hour\";\n\t\tlet Parameters: DeploymentAlertParameters | undefined = undefined;\n\t\tif (\"ref\" in props.parameters.query) {\n\t\t\tParameters = {\n\t\t\t\t...props.parameters,\n\t\t\t\tthreshold: `${props.parameters.threshold?.operation || \">\"} ${props.parameters.threshold?.value\n\t\t\t\t\t}`,\n\t\t\t\tquery: props.parameters.query.ref,\n\t\t\t\tfrequency: props.parameters.frequency || defaultFrequency,\n\t\t\t\twindow: props.parameters.window || defaultWindow,",
"score": 0.8320674896240234
}
] |
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": "import { CfnResource, Stack } from \"aws-cdk-lib\";\nimport { Baselime as Config } from \"../config\";\nimport { Query } from \"./query\";\nimport { AlertProps, DeploymentAlertParameters } from \"../types/alert\";\nimport { QueryProps } from \"../types/query\";\nimport { getServiceName } from \"../utils/service-name\";\nexport class Alert<TKey extends string> extends CfnResource {\n\tconstructor(id: string, props: AlertProps<TKey>) {\n\t\tconst stack = Stack.of(Config.getConstruct());\n\t\tconst defaultFrequency = \"1hour\";",
"score": 0.8415075540542603
},
{
"filename": "src/types/alert.ts",
"retrieved_chunk": "import { CfnResource } from \"aws-cdk-lib\";\nimport { QueryOperationString, QueryParameters } from \"./query\";\nexport type AlertProps<TKey extends string> = {\n\tdescription?: string;\n\tenabled?: boolean;\n\tparameters: {\n\t\tquery: CfnResource | QueryParameters<TKey>,\n\t\tthreshold?: {\n\t\t\toperation?: QueryOperationString,\n\t\t\tvalue: string | number",
"score": 0.8405464887619019
},
{
"filename": "src/resources/alert.ts",
"retrieved_chunk": "\t\tconst defaultWindow = \"1hour\";\n\t\tlet Parameters: DeploymentAlertParameters | undefined = undefined;\n\t\tif (\"ref\" in props.parameters.query) {\n\t\t\tParameters = {\n\t\t\t\t...props.parameters,\n\t\t\t\tthreshold: `${props.parameters.threshold?.operation || \">\"} ${props.parameters.threshold?.value\n\t\t\t\t\t}`,\n\t\t\t\tquery: props.parameters.query.ref,\n\t\t\t\tfrequency: props.parameters.frequency || defaultFrequency,\n\t\t\t\twindow: props.parameters.window || defaultWindow,",
"score": 0.8314533233642578
},
{
"filename": "src/resources/alert.ts",
"retrieved_chunk": "\t\tif (!Parameters) throw new Error(\"Invalid alert parameters. Declare at least one of filters or ref in the query.\")\n\t\tsuper(Config.getConstruct(), id, {\n\t\t\ttype: \"Custom::BaselimeAlert\",\n\t\t\tproperties: {\n\t\t\t\tid,\n\t\t\t\tServiceToken: Config.getServiceToken(),\n\t\t\t\tBaselimeApiKey: Config.getApiKey(),\n\t\t\t\tenabled: props.enabled,\n\t\t\t\tDescription: props.description,\n\t\t\t\tService: getServiceName(stack),",
"score": 0.827271580696106
},
{
"filename": "src/resources/alert.ts",
"retrieved_chunk": "\t\t\t});\n\t\t\tParameters = {\n\t\t\t\t...props.parameters,\n\t\t\t\tthreshold: `${props.parameters.threshold?.operation || \">\"} ${props.parameters.threshold?.value || 0\n\t\t\t\t\t}`,\n\t\t\t\tquery: query.ref,\n\t\t\t\tfrequency: props.parameters.frequency || defaultFrequency,\n\t\t\t\twindow: props.parameters.window || defaultWindow,\n\t\t\t};\n\t\t}",
"score": 0.8231188058853149
}
] |
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\tif (!Parameters) throw new Error(\"Invalid alert parameters. Declare at least one of filters or ref in the query.\")\n\t\tsuper(Config.getConstruct(), id, {\n\t\t\ttype: \"Custom::BaselimeAlert\",\n\t\t\tproperties: {\n\t\t\t\tid,\n\t\t\t\tServiceToken: Config.getServiceToken(),\n\t\t\t\tBaselimeApiKey: Config.getApiKey(),\n\t\t\t\tenabled: props.enabled,\n\t\t\t\tDescription: props.description,\n\t\t\t\tService: getServiceName(stack),",
"score": 0.8233322501182556
},
{
"filename": "src/resources/alert.ts",
"retrieved_chunk": "\t\t\t};\n\t\t}\n\t\tif (\"filters\" in props.parameters.query) {\n\t\t\tconst query = new Query(`${id}-query`, {\n\t\t\t\tparameters: {\n\t\t\t\t\t...props.parameters.query,\n\t\t\t\t\tcalculations: props.parameters.query.calculations || [\n\t\t\t\t\t\t{ operation: \"COUNT\" },\n\t\t\t\t\t],\n\t\t\t\t},",
"score": 0.8190149068832397
},
{
"filename": "src/resources/alert.ts",
"retrieved_chunk": "\t\t\t});\n\t\t\tParameters = {\n\t\t\t\t...props.parameters,\n\t\t\t\tthreshold: `${props.parameters.threshold?.operation || \">\"} ${props.parameters.threshold?.value || 0\n\t\t\t\t\t}`,\n\t\t\t\tquery: query.ref,\n\t\t\t\tfrequency: props.parameters.frequency || defaultFrequency,\n\t\t\t\twindow: props.parameters.window || defaultWindow,\n\t\t\t};\n\t\t}",
"score": 0.8114420175552368
},
{
"filename": "src/resources/alert.ts",
"retrieved_chunk": "\t\tconst defaultWindow = \"1hour\";\n\t\tlet Parameters: DeploymentAlertParameters | undefined = undefined;\n\t\tif (\"ref\" in props.parameters.query) {\n\t\t\tParameters = {\n\t\t\t\t...props.parameters,\n\t\t\t\tthreshold: `${props.parameters.threshold?.operation || \">\"} ${props.parameters.threshold?.value\n\t\t\t\t\t}`,\n\t\t\t\tquery: props.parameters.query.ref,\n\t\t\t\tfrequency: props.parameters.frequency || defaultFrequency,\n\t\t\t\twindow: props.parameters.window || defaultWindow,",
"score": 0.8067582845687866
},
{
"filename": "src/types/alert.ts",
"retrieved_chunk": "import { CfnResource } from \"aws-cdk-lib\";\nimport { QueryOperationString, QueryParameters } from \"./query\";\nexport type AlertProps<TKey extends string> = {\n\tdescription?: string;\n\tenabled?: boolean;\n\tparameters: {\n\t\tquery: CfnResource | QueryParameters<TKey>,\n\t\tthreshold?: {\n\t\t\toperation?: QueryOperationString,\n\t\t\tvalue: string | number",
"score": 0.7967289686203003
}
] |
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/alert.ts",
"retrieved_chunk": "import { CfnResource, Stack } from \"aws-cdk-lib\";\nimport { Baselime as Config } from \"../config\";\nimport { Query } from \"./query\";\nimport { AlertProps, DeploymentAlertParameters } from \"../types/alert\";\nimport { QueryProps } from \"../types/query\";\nimport { getServiceName } from \"../utils/service-name\";\nexport class Alert<TKey extends string> extends CfnResource {\n\tconstructor(id: string, props: AlertProps<TKey>) {\n\t\tconst stack = Stack.of(Config.getConstruct());\n\t\tconst defaultFrequency = \"1hour\";",
"score": 0.8576632738113403
},
{
"filename": "src/types/alert.ts",
"retrieved_chunk": "import { CfnResource } from \"aws-cdk-lib\";\nimport { QueryOperationString, QueryParameters } from \"./query\";\nexport type AlertProps<TKey extends string> = {\n\tdescription?: string;\n\tenabled?: boolean;\n\tparameters: {\n\t\tquery: CfnResource | QueryParameters<TKey>,\n\t\tthreshold?: {\n\t\t\toperation?: QueryOperationString,\n\t\t\tvalue: string | number",
"score": 0.8432838320732117
},
{
"filename": "src/resources/alert.ts",
"retrieved_chunk": "\t\tif (!Parameters) throw new Error(\"Invalid alert parameters. Declare at least one of filters or ref in the query.\")\n\t\tsuper(Config.getConstruct(), id, {\n\t\t\ttype: \"Custom::BaselimeAlert\",\n\t\t\tproperties: {\n\t\t\t\tid,\n\t\t\t\tServiceToken: Config.getServiceToken(),\n\t\t\t\tBaselimeApiKey: Config.getApiKey(),\n\t\t\t\tenabled: props.enabled,\n\t\t\t\tDescription: props.description,\n\t\t\t\tService: getServiceName(stack),",
"score": 0.8140503168106079
},
{
"filename": "src/resources/dashboard.ts",
"retrieved_chunk": "import { CfnResource, Stack } from \"aws-cdk-lib\";\nimport { Baselime as Config } from \"../config\";\nimport { DashboardProps } from \"../types/dashboard\";\nimport { getServiceName } from \"../utils/service-name\";\nexport class Dashboard extends CfnResource {\n\tconstructor(id: string, props: DashboardProps) {\n\t\tconst stack = Stack.of(Config.getConstruct());\n\t\tconst parameters = {\n\t\t\t...props.parameters,\n\t\t\twidgets: props.parameters.widgets.map(el => ({ ...el, query: el.query.ref }))",
"score": 0.8020367622375488
},
{
"filename": "src/resources/dashboard.ts",
"retrieved_chunk": "\t\t}\n\t\tsuper(Config.getConstruct(), id, {\n\t\t\ttype: \"Custom::BaselimeDashboard\",\n\t\t\tproperties: {\n\t\t\t\tid,\n\t\t\t\tServiceToken: Config.getServiceToken(),\n\t\t\t\tBaselimeApiKey: Config.getApiKey(),\n\t\t\t\tDescription: props.description,\n\t\t\t\tService: getServiceName(stack),\n\t\t\t\tParameters: parameters,",
"score": 0.7936064004898071
}
] |
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": 0.856496274471283
},
{
"filename": "src/resources/alert.ts",
"retrieved_chunk": "\t\t\t};\n\t\t}\n\t\tif (\"filters\" in props.parameters.query) {\n\t\t\tconst query = new Query(`${id}-query`, {\n\t\t\t\tparameters: {\n\t\t\t\t\t...props.parameters.query,\n\t\t\t\t\tcalculations: props.parameters.query.calculations || [\n\t\t\t\t\t\t{ operation: \"COUNT\" },\n\t\t\t\t\t],\n\t\t\t\t},",
"score": 0.8429108262062073
},
{
"filename": "src/types/alert.ts",
"retrieved_chunk": "import { CfnResource } from \"aws-cdk-lib\";\nimport { QueryOperationString, QueryParameters } from \"./query\";\nexport type AlertProps<TKey extends string> = {\n\tdescription?: string;\n\tenabled?: boolean;\n\tparameters: {\n\t\tquery: CfnResource | QueryParameters<TKey>,\n\t\tthreshold?: {\n\t\t\toperation?: QueryOperationString,\n\t\t\tvalue: string | number",
"score": 0.8404648900032043
},
{
"filename": "src/resources/dashboard.ts",
"retrieved_chunk": "import { CfnResource, Stack } from \"aws-cdk-lib\";\nimport { Baselime as Config } from \"../config\";\nimport { DashboardProps } from \"../types/dashboard\";\nimport { getServiceName } from \"../utils/service-name\";\nexport class Dashboard extends CfnResource {\n\tconstructor(id: string, props: DashboardProps) {\n\t\tconst stack = Stack.of(Config.getConstruct());\n\t\tconst parameters = {\n\t\t\t...props.parameters,\n\t\t\twidgets: props.parameters.widgets.map(el => ({ ...el, query: el.query.ref }))",
"score": 0.8397892117500305
},
{
"filename": "src/types/query.ts",
"retrieved_chunk": "import { F } from \"ts-toolbelt\";\nexport type QueryProps<TKey extends string> = {\n\tdescription?: string;\n\tparameters: QueryParameters<TKey>\n\tdisableStackFilter?: boolean\n};\nexport type QueryParameters<TKey extends string> = {\n\tdatasets?: Datasets[];\n\tfilterCombination?: \"AND\" | \"OR\";\n\tfilters: Filter[];",
"score": 0.8252931833267212
}
] |
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": 0.8745593428611755
},
{
"filename": "src/types/alert.ts",
"retrieved_chunk": "import { CfnResource } from \"aws-cdk-lib\";\nimport { QueryOperationString, QueryParameters } from \"./query\";\nexport type AlertProps<TKey extends string> = {\n\tdescription?: string;\n\tenabled?: boolean;\n\tparameters: {\n\t\tquery: CfnResource | QueryParameters<TKey>,\n\t\tthreshold?: {\n\t\t\toperation?: QueryOperationString,\n\t\t\tvalue: string | number",
"score": 0.8558971285820007
},
{
"filename": "src/resources/dashboard.ts",
"retrieved_chunk": "import { CfnResource, Stack } from \"aws-cdk-lib\";\nimport { Baselime as Config } from \"../config\";\nimport { DashboardProps } from \"../types/dashboard\";\nimport { getServiceName } from \"../utils/service-name\";\nexport class Dashboard extends CfnResource {\n\tconstructor(id: string, props: DashboardProps) {\n\t\tconst stack = Stack.of(Config.getConstruct());\n\t\tconst parameters = {\n\t\t\t...props.parameters,\n\t\t\twidgets: props.parameters.widgets.map(el => ({ ...el, query: el.query.ref }))",
"score": 0.8539568185806274
},
{
"filename": "src/types/query.ts",
"retrieved_chunk": "import { F } from \"ts-toolbelt\";\nexport type QueryProps<TKey extends string> = {\n\tdescription?: string;\n\tparameters: QueryParameters<TKey>\n\tdisableStackFilter?: boolean\n};\nexport type QueryParameters<TKey extends string> = {\n\tdatasets?: Datasets[];\n\tfilterCombination?: \"AND\" | \"OR\";\n\tfilters: Filter[];",
"score": 0.8494443893432617
},
{
"filename": "src/index.ts",
"retrieved_chunk": "export interface QueryProps {\n\tDescription?: string;\n\tService?: string;\n\tParameters: {\n\t\tdatasets: string[];\n\t\tcalculations?: string[];\n\t\tfilters?: string[];\n\t\tgroupBys?: Array<{\n\t\t\ttype: \"string\" | \"number\" | \"boolean\";\n\t\t\tvalue: string;",
"score": 0.8418479561805725
}
] |
typescript
|
.filter(c => c.alias).map(c => c.alias))) {
|
import { CfnResource, Stack } from "aws-cdk-lib";
import { Baselime as Config } from "../config";
import { QueryProps, Filter, DeploymentQueryParameters } from "../types/query";
import { AlertProps } from "../types/alert";
import { Alert } from './alert';
import { getServiceName } from '../utils/service-name';
function buildCalculation(cal: { alias?: string; operation: string; key?: string }) {
const short = buildShortCalculation(cal);
return `${short}${cal.alias ? ` as ${cal.alias}` : ""}`;
}
function hasDuplicates<T>(array: T[]) {
return (new Set(array)).size !== array.length;
}
function buildShortCalculation(cal: { alias?: string; operation: string; key?: string }) {
if (cal.operation === "COUNT") {
return cal.operation;
}
return `${cal.operation}(${cal.key})`;
}
function getCalculationAlias(cal: { alias?: string; operation: string; key?: string }) {
return cal.alias ? cal.alias : buildShortCalculation(cal);
}
export function stringifyFilter(filter: Filter): string {
const { key, operation, value } = filter;
if (!operation) {
return `${key} = ${value}`;
}
if (["EXISTS", "DOES_NOT_EXIST"].includes(operation)) {
return `${key} ${operation}`;
}
if (["IN", "NOT_IN"].some(o => o === operation)) {
return `${key} ${operation} (${value})`;
}
return `${key} ${operation} ${value}`;
}
/**
*
*/
export class Query<TKey extends string> extends CfnResource {
id: string;
props: QueryProps<TKey>
constructor(id: string, props: QueryProps<TKey>) {
const stack = Stack.of(Config.getConstruct());
const calcs = props.parameters.calculations;
const orderByOptions = calcs?.map(cal => getCalculationAlias(cal));
if (calcs?.length && hasDuplicates(calcs.filter(c => c.alias).map(c => c.alias))) {
throw Error("Aliases must me unique across all calculations / visualisations.")
}
if (props.parameters.orderBy && !orderByOptions?.includes(props.parameters.orderBy.value)) {
throw Error("The orderBy must be present in the calculations / visualisations.")
}
const disableStackFilter = props.disableStackFilter || Config.getDisableStackFilter();
if (!disableStackFilter) {
props.parameters.filters?.push({ operation: "=", key: "$baselime.stackId", value: stack.stackName })
}
const Parameters: DeploymentQueryParameters = {
...props.parameters,
datasets: props.parameters.datasets || ['lambda-logs'],
calculations: props.parameters.calculations ? props.parameters.calculations.map(buildCalculation) : [],
filters: props.parameters.filters?.map(stringifyFilter),
groupBys: props.parameters.groupBys?.map(groupBy => {
return {
...groupBy,
type: groupBy?.type || "string"
}
}),
filterCombination: props.parameters.filterCombination || "AND",
};
super(Config.getConstruct(), id, {
type: "Custom::BaselimeQuery",
properties: {
id,
ServiceToken: Config.getServiceToken(),
BaselimeApiKey: Config.getApiKey(),
Description: props.description,
|
Service: getServiceName(stack),
Parameters,
Origin: "cdk"
},
});
|
this.id = id;
this.props = props;
}
addAlert(alert: ChangeFields<AlertProps<TKey>, {
parameters: Omit<AlertProps<TKey>['parameters'], "query">
}>) {
const alertProps = {
...alert,
parameters: {
...alert.parameters,
query: this
}
}
new Alert(`${this.id}-alert`, alertProps);
}
addFilters(filters: QueryProps<string>["parameters"]["filters"]) {
this.addPropertyOverride('Parameters.filters', [...filters || []])
}
};
type ChangeFields<T, R> = Omit<T, keyof R> & R;
|
src/resources/query.ts
|
baselime-cdk-82637d8
|
[
{
"filename": "src/resources/dashboard.ts",
"retrieved_chunk": "\t\t}\n\t\tsuper(Config.getConstruct(), id, {\n\t\t\ttype: \"Custom::BaselimeDashboard\",\n\t\t\tproperties: {\n\t\t\t\tid,\n\t\t\t\tServiceToken: Config.getServiceToken(),\n\t\t\t\tBaselimeApiKey: Config.getApiKey(),\n\t\t\t\tDescription: props.description,\n\t\t\t\tService: getServiceName(stack),\n\t\t\t\tParameters: parameters,",
"score": 0.8943645358085632
},
{
"filename": "src/resources/alert.ts",
"retrieved_chunk": "\t\t\t\tParameters,\n\t\t\t\tChannels: props.channels || Config.getDefaultChannel() && [Config.getDefaultChannel()],\n\t\t\t\tOrigin: \"cdk\",\n\t\t\t},\n\t\t});\n\t}\n}",
"score": 0.8729135394096375
},
{
"filename": "src/resources/alert.ts",
"retrieved_chunk": "\t\tif (!Parameters) throw new Error(\"Invalid alert parameters. Declare at least one of filters or ref in the query.\")\n\t\tsuper(Config.getConstruct(), id, {\n\t\t\ttype: \"Custom::BaselimeAlert\",\n\t\t\tproperties: {\n\t\t\t\tid,\n\t\t\t\tServiceToken: Config.getServiceToken(),\n\t\t\t\tBaselimeApiKey: Config.getApiKey(),\n\t\t\t\tenabled: props.enabled,\n\t\t\t\tDescription: props.description,\n\t\t\t\tService: getServiceName(stack),",
"score": 0.8326147794723511
},
{
"filename": "src/resources/dashboard.ts",
"retrieved_chunk": "import { CfnResource, Stack } from \"aws-cdk-lib\";\nimport { Baselime as Config } from \"../config\";\nimport { DashboardProps } from \"../types/dashboard\";\nimport { getServiceName } from \"../utils/service-name\";\nexport class Dashboard extends CfnResource {\n\tconstructor(id: string, props: DashboardProps) {\n\t\tconst stack = Stack.of(Config.getConstruct());\n\t\tconst parameters = {\n\t\t\t...props.parameters,\n\t\t\twidgets: props.parameters.widgets.map(el => ({ ...el, query: el.query.ref }))",
"score": 0.831200361251831
},
{
"filename": "src/config.ts",
"retrieved_chunk": "\t\tconstruct = target;\n\t\tbaselimeSecret = options.apiKey;\n\t\tserviceName = options.serviceName;\n\t\tserviceToken = `arn:aws:lambda:${options.region || process.env.CDK_DEPLOY_REGION || \"eu-west-1\"\n\t\t\t}:${options._account || \"097948374213\"}:function:baselime-orl-cloudformation`;\n\t\tdefaultChannel = options.defaultChannel;\n\t\tdisableStackFilter = options.disableStackFilter;\n\t}\n\texport function getConstruct() {\n\t\treturn construct;",
"score": 0.8282217979431152
}
] |
typescript
|
Service: getServiceName(stack),
Parameters,
Origin: "cdk"
},
});
|
import { CfnResource, Stack } from "aws-cdk-lib";
import { Baselime as Config } from "../config";
import { QueryProps, Filter, DeploymentQueryParameters } from "../types/query";
import { AlertProps } from "../types/alert";
import { Alert } from './alert';
import { getServiceName } from '../utils/service-name';
function buildCalculation(cal: { alias?: string; operation: string; key?: string }) {
const short = buildShortCalculation(cal);
return `${short}${cal.alias ? ` as ${cal.alias}` : ""}`;
}
function hasDuplicates<T>(array: T[]) {
return (new Set(array)).size !== array.length;
}
function buildShortCalculation(cal: { alias?: string; operation: string; key?: string }) {
if (cal.operation === "COUNT") {
return cal.operation;
}
return `${cal.operation}(${cal.key})`;
}
function getCalculationAlias(cal: { alias?: string; operation: string; key?: string }) {
return cal.alias ? cal.alias : buildShortCalculation(cal);
}
export function stringifyFilter(filter: Filter): string {
const { key, operation, value } = filter;
if (!operation) {
return `${key} = ${value}`;
}
if (["EXISTS", "DOES_NOT_EXIST"].includes(operation)) {
return `${key} ${operation}`;
}
if (["IN", "NOT_IN"].some(o => o === operation)) {
return `${key} ${operation} (${value})`;
}
return `${key} ${operation} ${value}`;
}
/**
*
*/
export class Query<TKey extends string> extends CfnResource {
id: string;
props: QueryProps<TKey>
constructor(id: string, props: QueryProps<TKey>) {
const stack = Stack.of(Config.getConstruct());
const calcs = props.parameters.calculations;
const orderByOptions = calcs?.map(cal => getCalculationAlias(cal));
if (calcs?.length && hasDuplicates(calcs.filter(c => c.alias).map(c => c.alias))) {
throw Error("Aliases must me unique across all calculations / visualisations.")
}
if (props.parameters.orderBy && !orderByOptions?.includes(props.parameters.orderBy.value)) {
throw Error("The orderBy must be present in the calculations / visualisations.")
}
const disableStackFilter = props.disableStackFilter || Config.getDisableStackFilter();
if (!disableStackFilter) {
props.parameters.filters?.push({ operation: "=", key: "$baselime.stackId", value: stack.stackName })
}
const Parameters: DeploymentQueryParameters = {
...props.parameters,
datasets: props.parameters.datasets || ['lambda-logs'],
calculations: props.parameters.calculations ? props.parameters.calculations.map(buildCalculation) : [],
filters: props.parameters.filters?.map(stringifyFilter),
groupBys: props.parameters.groupBys?.map(groupBy => {
return {
...groupBy,
type: groupBy?.type || "string"
}
}),
filterCombination: props.parameters.filterCombination || "AND",
};
super(Config.getConstruct(), id, {
type: "Custom::BaselimeQuery",
properties: {
id,
ServiceToken: Config.getServiceToken(),
BaselimeApiKey: Config.getApiKey(),
Description: props.description,
Service: getServiceName(stack),
Parameters,
Origin: "cdk"
},
});
this.id = id;
this.props = props;
}
addAlert(alert
|
: ChangeFields<AlertProps<TKey>, {
|
parameters: Omit<AlertProps<TKey>['parameters'], "query">
}>) {
const alertProps = {
...alert,
parameters: {
...alert.parameters,
query: this
}
}
new Alert(`${this.id}-alert`, alertProps);
}
addFilters(filters: QueryProps<string>["parameters"]["filters"]) {
this.addPropertyOverride('Parameters.filters', [...filters || []])
}
};
type ChangeFields<T, R> = Omit<T, keyof R> & R;
|
src/resources/query.ts
|
baselime-cdk-82637d8
|
[
{
"filename": "src/resources/alert.ts",
"retrieved_chunk": "import { CfnResource, Stack } from \"aws-cdk-lib\";\nimport { Baselime as Config } from \"../config\";\nimport { Query } from \"./query\";\nimport { AlertProps, DeploymentAlertParameters } from \"../types/alert\";\nimport { QueryProps } from \"../types/query\";\nimport { getServiceName } from \"../utils/service-name\";\nexport class Alert<TKey extends string> extends CfnResource {\n\tconstructor(id: string, props: AlertProps<TKey>) {\n\t\tconst stack = Stack.of(Config.getConstruct());\n\t\tconst defaultFrequency = \"1hour\";",
"score": 0.8528459072113037
},
{
"filename": "src/types/alert.ts",
"retrieved_chunk": "import { CfnResource } from \"aws-cdk-lib\";\nimport { QueryOperationString, QueryParameters } from \"./query\";\nexport type AlertProps<TKey extends string> = {\n\tdescription?: string;\n\tenabled?: boolean;\n\tparameters: {\n\t\tquery: CfnResource | QueryParameters<TKey>,\n\t\tthreshold?: {\n\t\t\toperation?: QueryOperationString,\n\t\t\tvalue: string | number",
"score": 0.836438775062561
},
{
"filename": "src/resources/alert.ts",
"retrieved_chunk": "\t\tif (!Parameters) throw new Error(\"Invalid alert parameters. Declare at least one of filters or ref in the query.\")\n\t\tsuper(Config.getConstruct(), id, {\n\t\t\ttype: \"Custom::BaselimeAlert\",\n\t\t\tproperties: {\n\t\t\t\tid,\n\t\t\t\tServiceToken: Config.getServiceToken(),\n\t\t\t\tBaselimeApiKey: Config.getApiKey(),\n\t\t\t\tenabled: props.enabled,\n\t\t\t\tDescription: props.description,\n\t\t\t\tService: getServiceName(stack),",
"score": 0.8120108842849731
},
{
"filename": "src/resources/dashboard.ts",
"retrieved_chunk": "import { CfnResource, Stack } from \"aws-cdk-lib\";\nimport { Baselime as Config } from \"../config\";\nimport { DashboardProps } from \"../types/dashboard\";\nimport { getServiceName } from \"../utils/service-name\";\nexport class Dashboard extends CfnResource {\n\tconstructor(id: string, props: DashboardProps) {\n\t\tconst stack = Stack.of(Config.getConstruct());\n\t\tconst parameters = {\n\t\t\t...props.parameters,\n\t\t\twidgets: props.parameters.widgets.map(el => ({ ...el, query: el.query.ref }))",
"score": 0.8000202775001526
},
{
"filename": "src/resources/dashboard.ts",
"retrieved_chunk": "\t\t}\n\t\tsuper(Config.getConstruct(), id, {\n\t\t\ttype: \"Custom::BaselimeDashboard\",\n\t\t\tproperties: {\n\t\t\t\tid,\n\t\t\t\tServiceToken: Config.getServiceToken(),\n\t\t\t\tBaselimeApiKey: Config.getApiKey(),\n\t\t\t\tDescription: props.description,\n\t\t\t\tService: getServiceName(stack),\n\t\t\t\tParameters: parameters,",
"score": 0.7910525798797607
}
] |
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": 0.8709684610366821
},
{
"filename": "src/types/alert.ts",
"retrieved_chunk": "import { CfnResource } from \"aws-cdk-lib\";\nimport { QueryOperationString, QueryParameters } from \"./query\";\nexport type AlertProps<TKey extends string> = {\n\tdescription?: string;\n\tenabled?: boolean;\n\tparameters: {\n\t\tquery: CfnResource | QueryParameters<TKey>,\n\t\tthreshold?: {\n\t\t\toperation?: QueryOperationString,\n\t\t\tvalue: string | number",
"score": 0.8580714464187622
},
{
"filename": "src/resources/dashboard.ts",
"retrieved_chunk": "import { CfnResource, Stack } from \"aws-cdk-lib\";\nimport { Baselime as Config } from \"../config\";\nimport { DashboardProps } from \"../types/dashboard\";\nimport { getServiceName } from \"../utils/service-name\";\nexport class Dashboard extends CfnResource {\n\tconstructor(id: string, props: DashboardProps) {\n\t\tconst stack = Stack.of(Config.getConstruct());\n\t\tconst parameters = {\n\t\t\t...props.parameters,\n\t\t\twidgets: props.parameters.widgets.map(el => ({ ...el, query: el.query.ref }))",
"score": 0.8530169129371643
},
{
"filename": "src/types/query.ts",
"retrieved_chunk": "import { F } from \"ts-toolbelt\";\nexport type QueryProps<TKey extends string> = {\n\tdescription?: string;\n\tparameters: QueryParameters<TKey>\n\tdisableStackFilter?: boolean\n};\nexport type QueryParameters<TKey extends string> = {\n\tdatasets?: Datasets[];\n\tfilterCombination?: \"AND\" | \"OR\";\n\tfilters: Filter[];",
"score": 0.8486735820770264
},
{
"filename": "src/index.ts",
"retrieved_chunk": "export interface QueryProps {\n\tDescription?: string;\n\tService?: string;\n\tParameters: {\n\t\tdatasets: string[];\n\t\tcalculations?: string[];\n\t\tfilters?: string[];\n\t\tgroupBys?: Array<{\n\t\t\ttype: \"string\" | \"number\" | \"boolean\";\n\t\t\tvalue: string;",
"score": 0.8468305468559265
}
] |
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": 0.8966026306152344
},
{
"filename": "src/resources/alert.ts",
"retrieved_chunk": "\t\t\t\tParameters,\n\t\t\t\tChannels: props.channels || Config.getDefaultChannel() && [Config.getDefaultChannel()],\n\t\t\t\tOrigin: \"cdk\",\n\t\t\t},\n\t\t});\n\t}\n}",
"score": 0.8667164444923401
},
{
"filename": "src/resources/alert.ts",
"retrieved_chunk": "\t\tif (!Parameters) throw new Error(\"Invalid alert parameters. Declare at least one of filters or ref in the query.\")\n\t\tsuper(Config.getConstruct(), id, {\n\t\t\ttype: \"Custom::BaselimeAlert\",\n\t\t\tproperties: {\n\t\t\t\tid,\n\t\t\t\tServiceToken: Config.getServiceToken(),\n\t\t\t\tBaselimeApiKey: Config.getApiKey(),\n\t\t\t\tenabled: props.enabled,\n\t\t\t\tDescription: props.description,\n\t\t\t\tService: getServiceName(stack),",
"score": 0.8296231031417847
},
{
"filename": "src/resources/dashboard.ts",
"retrieved_chunk": "import { CfnResource, Stack } from \"aws-cdk-lib\";\nimport { Baselime as Config } from \"../config\";\nimport { DashboardProps } from \"../types/dashboard\";\nimport { getServiceName } from \"../utils/service-name\";\nexport class Dashboard extends CfnResource {\n\tconstructor(id: string, props: DashboardProps) {\n\t\tconst stack = Stack.of(Config.getConstruct());\n\t\tconst parameters = {\n\t\t\t...props.parameters,\n\t\t\twidgets: props.parameters.widgets.map(el => ({ ...el, query: el.query.ref }))",
"score": 0.829054594039917
},
{
"filename": "src/config.ts",
"retrieved_chunk": "\t\tconstruct = target;\n\t\tbaselimeSecret = options.apiKey;\n\t\tserviceName = options.serviceName;\n\t\tserviceToken = `arn:aws:lambda:${options.region || process.env.CDK_DEPLOY_REGION || \"eu-west-1\"\n\t\t\t}:${options._account || \"097948374213\"}:function:baselime-orl-cloudformation`;\n\t\tdefaultChannel = options.defaultChannel;\n\t\tdisableStackFilter = options.disableStackFilter;\n\t}\n\texport function getConstruct() {\n\t\treturn construct;",
"score": 0.8193256855010986
}
] |
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/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": 0.8314285278320312
},
{
"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": 0.8311746120452881
},
{
"filename": "src/chat_gpt.ts",
"retrieved_chunk": " for (let i = 0; i < maxRetries; i++) {\n try {\n const completion = await openai.createChatCompletion({\n model: model,\n messages: messages,\n });\n return (completion.data!.choices[0]!.message?.content || \"\").trim();\n } catch (error: any) {\n if (error.response && (error.response.status === 429 || (error.response.status >= 500 && error.response.status < 600))) {\n const resetMs = parseInt(error.response.headers['x-ratelimit-reset-requests']) || 1000;",
"score": 0.8197121620178223
},
{
"filename": "src/golem.ts",
"retrieved_chunk": " const golemFilePath = argv.golemFile as string;\n // console.log(golemFilePath);\n // Add this line to create the .golem/ directory\n createGolemCacheDir();\n // Read the Golem file content\n const golemFileContent = fs.readFileSync(golemFilePath, 'utf8');\n const golemFile = parseGolemFile(golemFileContent);\n console.log(golemFile);\n // Execute the default target with an empty context\n await executeTarget('default', golemFile, golemFilePath, new Map());",
"score": 0.7709474563598633
},
{
"filename": "src/types.ts",
"retrieved_chunk": "export interface GolemTarget {\n dependencies: string[];\n prompt: string;\n model?: string; // Add this line\n task_generation_prompt?: string; // Add this line\n [key: string]: string[] | string | undefined;\n}\nexport type GolemFile = {\n default: string[];\n} & {",
"score": 0.7632367610931396
}
] |
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": " const isEnum = $('enum').length > 0;\n const isStruct = $('structure').length > 0;\n const isFunction = $('function').length > 0;\n const isPanel = $('panel').length > 0;\n const mainElement = $(isEnum ? 'enum' : isStruct ? 'struct' : isPanel ? 'panel' : 'function');\n const address = response.url.split('/').pop()!.split('?')[0];\n if (isEnum) {\n const items = $('items item').map(function () {\n const $el = $(this);\n return <EnumValue>{",
"score": 0.8027828931808472
},
{
"filename": "src/scrapers/wiki-page-markup-scraper.ts",
"retrieved_chunk": " key: string;\n value: string;\n description: string;\n};\nexport type Enum = CommonWikiProperties & {\n type: 'enum';\n items: EnumValue[];\n};\nexport type StructField = {\n name: string;",
"score": 0.7974306344985962
},
{
"filename": "src/cli-scraper.ts",
"retrieved_chunk": " if (!fs.existsSync(`${moduleFile}.lua`))\n fs.writeFileSync(`${moduleFile}.lua`, '---@meta\\n\\n');\n if (!fs.existsSync(moduleFile))\n fs.mkdirSync(moduleFile, { recursive: true });\n fileName = fileName.replace(/[^a-z0-9]/gi, '_').toLowerCase();\n // Lua API\n fs.appendFileSync(path.join(baseDirectory, `${moduleName}.lua`), api);\n // JSON data\n const json = JSON.stringify(pageMarkups, null, 2);\n fs.writeFileSync(path.join(baseDirectory, moduleName, `${fileName}.json`), json);",
"score": 0.7941164374351501
},
{
"filename": "src/cli-scraper.ts",
"retrieved_chunk": " return;\n const api = writer.writePages(pageMarkups);\n let fileName = pageIndex.address;\n let moduleName = fileName;\n if (fileName.includes('.') || fileName.includes(':') || fileName.includes('/')) {\n [moduleName, fileName] = fileName.split(/[:.\\/]/, 2);\n }\n // Make sure modules like Entity and ENTITY are placed in the same file.\n moduleName = moduleName.toLowerCase();\n const moduleFile = path.join(baseDirectory, moduleName);",
"score": 0.7670182585716248
},
{
"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": 0.7638375163078308
}
] |
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/cli-scraper.ts",
"retrieved_chunk": " return;\n const api = writer.writePages(pageMarkups);\n let fileName = pageIndex.address;\n let moduleName = fileName;\n if (fileName.includes('.') || fileName.includes(':') || fileName.includes('/')) {\n [moduleName, fileName] = fileName.split(/[:.\\/]/, 2);\n }\n // Make sure modules like Entity and ENTITY are placed in the same file.\n moduleName = moduleName.toLowerCase();\n const moduleFile = path.join(baseDirectory, moduleName);",
"score": 0.8607462644577026
},
{
"filename": "src/scrapers/wiki-page-markup-scraper.ts",
"retrieved_chunk": " return page.type === 'libraryfunc';\n}\nexport function isHookFunction(page: WikiPage): page is HookFunction {\n return page.type === 'hook';\n}\nexport function isPanelFunction(page: WikiPage): page is PanelFunction {\n return page.type === 'panelfunc';\n}\nexport function isPanel(page: WikiPage): page is Panel {\n return page.type === 'panel';",
"score": 0.8368933796882629
},
{
"filename": "src/cli-scraper.ts",
"retrieved_chunk": " if (!fs.existsSync(`${moduleFile}.lua`))\n fs.writeFileSync(`${moduleFile}.lua`, '---@meta\\n\\n');\n if (!fs.existsSync(moduleFile))\n fs.mkdirSync(moduleFile, { recursive: true });\n fileName = fileName.replace(/[^a-z0-9]/gi, '_').toLowerCase();\n // Lua API\n fs.appendFileSync(path.join(baseDirectory, `${moduleName}.lua`), api);\n // JSON data\n const json = JSON.stringify(pageMarkups, null, 2);\n fs.writeFileSync(path.join(baseDirectory, moduleName, `${fileName}.json`), json);",
"score": 0.8247728943824768
},
{
"filename": "src/scrapers/wiki-page-markup-scraper.ts",
"retrieved_chunk": " parent: string;\n};\nexport type WikiPage = ClassFunction | LibraryFunction | HookFunction | PanelFunction | Panel | Enum | Struct;\n/**\n * Guards\n */\nexport function isClassFunction(page: WikiPage): page is ClassFunction {\n return page.type === 'classfunc';\n}\nexport function isLibraryFunction(page: WikiPage): page is LibraryFunction {",
"score": 0.8182677030563354
},
{
"filename": "src/scrapers/wiki-page-markup-scraper.ts",
"retrieved_chunk": " ...base,\n type: 'hook',\n isHook: 'yes'\n };\n } else if (isPanelFunction) {\n return <PanelFunction> {\n ...base,\n type: 'panelfunc',\n isPanelFunction: 'yes'\n };",
"score": 0.8140116930007935
}
] |
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": 0.8313734531402588
},
{
"filename": "src/types.ts",
"retrieved_chunk": "export interface GolemTarget {\n dependencies: string[];\n prompt: string;\n model?: string; // Add this line\n task_generation_prompt?: string; // Add this line\n [key: string]: string[] | string | undefined;\n}\nexport type GolemFile = {\n default: string[];\n} & {",
"score": 0.8025490641593933
},
{
"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": 0.800033688545227
},
{
"filename": "src/golem.ts",
"retrieved_chunk": "#!/usr/bin/env node\nimport yargs from 'yargs';\nimport { executeTarget } from './executor';\nimport { parseGolemFile } from './parser';\nimport fs from 'fs';\nimport logger from './logger';\nimport { createGolemCacheDir } from './utils'; // Add this import\nyargs\n .command(\n 'golem [golemFile]',",
"score": 0.79814213514328
},
{
"filename": "src/golem.ts",
"retrieved_chunk": " 'Run the specified Golem file or the default Golem file if none is provided.',\n (yargs) => {\n yargs.positional('golemFile', {\n describe: 'Path to the Golem file',\n default: 'Golem.yaml',\n type: 'string',\n });\n },\n async (argv) => {\n try {",
"score": 0.771274983882904
}
] |
typescript
|
string, golemFile: GolemFile, golemFilePath: string, context: Map<string, any> = new Map()): Promise<void> {
|
import { exec } from 'child_process';
import { GolemFile, GolemTarget, isGolemTarget } from './types';
import { ChatGPTMessage, ChatGPT_completion } from './chat_gpt';
import { readFile } from 'fs/promises';
import { dirname } from 'path';
import logger from './logger';
import {
generateCacheKey,
isCacheValid,
saveOutputToCache,
loadOutputFromCache,
appendToGolemFile
} from './utils';
import { writeFileSync} from 'fs';
// TODO 1: Check if prompt asks for additional targets.
// TODO 2: Check if targets have other dependencies.
// TODO 3: Saving properly (for example, it saves all of the previous context for imp task)
// TODO 4: Use different files
interface ExecutionContext {
[key: string]: any;
}
const mainPrompt: ChatGPTMessage = {
role: 'system',
content: `You are an Agentic LLM assistant, designed only to produce code and helpful information. You may be asked to generate new targets. If the prompt given to you contains the phrase 'generate new targets', your response will be to generate a list of targets to help answer the prompt. The targets must be written as unnumbered items separated by lines starting with 'Target:'.
The items in the list will not be arranged in any particular order. For example:
Prompt: As an agentic LLM, generate new targets for the next iteration.
Response:
Target: Write a function to divide two numbers.
Target: Create a class called Employee.
Target: Write unit tests for the function GetPeopleInterests.
It is not always the case that you will be asked to generate new targets. If the prompt does not contain the phrase 'generate new targets', then proceed to answer the prompt as truthfully as possible. For example:
Prompt: What is capital of France?
Response: Paris.
Prompt: How many days are in the month of April?
Response: 30 days.
You are opinionated. If asked to provide a subjective answer, start by saying 'In my opinion' then answer the prompt. For example:
Prompt: What is the best sport?
Response: In my opinion, soccer.
`
}
export async function executeTarget(target: string, golemFile: GolemFile, golemFilePath: string, context: Map<string, any> = new Map()): Promise<void> {
const golemTarget = golemFile[target];
if (!golemTarget) {
throw new Error(`Target "${target}" not found in Golem file.`);
}
console.log(`Executing target: ${target}`);
if (golemTarget.dependencies) {
console.log(`Dependencies for ${target}: ${golemTarget.dependencies}`);
for (const dependency of golemTarget.dependencies) {
if (dependency) {
await executeTarget(dependency, golemFile, golemFilePath, context);
}
}
}
await executeAIChatWithCache(target, golemFile, golemFilePath, context);
console.log(`Context after ${target} execution:`, context);
}
function executeCommand(command: string): Promise<void> {
return new Promise((resolve, reject) => {
exec(command, (error, stdout, stderr) => {
if (error) {
logger.error(`Error executing command: ${command}`);
logger.error(stderr);
reject(error);
} else {
logger.debug(stdout);
resolve();
}
});
});
}
async function executeAIChatWithCache(target: string, golemFile: GolemFile, golemFilePath: string, context: Map<string, any>): Promise<void> {
const golemFileToArray: any = [];
for (const key in golemFile){
const val = golemFile[key as keyof typeof golemFile];
golemFileToArray.push(val);
}
const golemTarget = golemFile[target];
if (!golemTarget || !isGolemTarget(golemTarget)) {
return;
}
const cacheKey = generateCacheKey(target, golemTarget.dependencies || [], [...golemFileToArray] || '');
if (isCacheValid(target, cacheKey)) {
console.log("Returning Cached output");
const cachedOutput = loadOutputFromCache(target, cacheKey);
context.set(target, cachedOutput);
} else {
await executeAIChat(target, golemFile, golemFilePath, context);
saveOutputToCache(target, cacheKey, context);
}
}
async function executeAIChat(target: string, golemFile: GolemFile, golemFilePath: string, context: Map<string, any>): Promise<void> {
// ============== Setup start ====================================
const contextOfCurrentTarget: string[] = [];
const allOutputs: {[key: string]: any} = {};
const golemTarget = golemFile[target];
console.log("gT", golemTarget);
if (!golemTarget) {
throw new Error(`Target "${target}" not found in Golem file.`);
}
if (!isGolemTarget(golemTarget)) {
return;
}
if (!golemTarget.prompt && !golemTarget.model) {
golemTarget.model = 'cat';
}
let prompt = golemTarget.prompt ?? "{no prompt}";
if (isGolemTarget(golemTarget) && golemTarget.prompt) {
prompt = golemTarget.prompt;
const placeholderRegex = /{{\s*([\w\/.-]+)\s*}}/g;
let match;
while ((match = placeholderRegex.exec(prompt)) !== null) {
const key = match[1];
if (context.has(key)) {
prompt = prompt.replace(match[0], context.get(key));
} else {
prompt = prompt.replace(match[0], "");
}
}
}
else if (!golemTarget.prompt) {
const defaultValues = new Map(context.entries());
context.set("default", Object.fromEntries(defaultValues));
return;
}
const model = golemTarget.model ?? 'gpt-3.5-turbo';
// ============== Setup end ====================================
if (model === 'cat') {
|
const concatenatedOutput = golemTarget.dependencies.map(dep => context.get(dep)).join('');
|
context.set(target, concatenatedOutput);
} else if (model == "gpt-3.5-turbo" || model == "gpt-3.5-turbo-0301" || model == "gpt-4-0314" || model == "gpt-4-32k") {
if ("model" in golemTarget) {
delete golemTarget.model;
}
// This gets the 'keys' (subtasks) of a target (task)
const golemTargetKeys: string[] = Object.keys(golemTarget);
// It starts from 1 as index 0 is dependencies. This can be changed if needed
for (let i = 1; i < golemTargetKeys.length; i++){
// console.log("gTKi", golemTargetKeys[i]);
const val: any = golemTarget[golemTargetKeys[i] as keyof typeof golemTarget];
// console.log("val", val);
const previousContext: string | undefined = contextOfCurrentTarget[0] || '';
// Concat the previousContext (if undefined) to the current subtask (here, named val)
const content = previousContext + val;
// console.log("content", content);
// This block of code replaces the {{}} placeholders in the string from the yaml file
// with the output of the subtask or task it requires
const replacedString = content.replace(/{{(.*?)}}/g, (match, p1) => {
// Remove the curly braces from the placeholder
const placeholder = p1.trim();
// Replace the placeholder with the corresponding value from the map
return context.get(placeholder) || placeholder;
});
// console.log("context", context);
// console.log("replacedString", replacedString);
const taskGenerationMessages: ChatGPTMessage[] = [
mainPrompt,
{
role: 'user',
content: replacedString,
},
];
const response = await ChatGPT_completion(taskGenerationMessages, model, 0.7, 0.9);
contextOfCurrentTarget.length = 0; //clear the previous context
contextOfCurrentTarget.push(response); //append the new context to be used in the next iteration
allOutputs[golemTargetKeys[i]] = response;
const lines: string[] = response.split('\n');
// Extract the targets from the lines that start with "Target:"
const targets: string[] = lines.filter((line: string) => line.startsWith("Target:"))
.map((line: string) => line.slice(8));
let count = 1;
targets.forEach((createdTarget: string) => {
const targetName = target.concat("_target".concat(count.toString()));
const newTarget: string = `\n${targetName}:\n dependencies: []\n prompt: ${createdTarget}`;
appendToGolemFile(golemFilePath, newTarget);
golemTargetKeys.push(targetName);
golemTarget[targetName] = createdTarget;
count += 1;
});
if (golemTargetKeys.length === 2){
if (!response) {
context.set(target, `Default value for ${target}`);
} else {
context.set(target, response);
console.log(context);
}
}
else if (golemTargetKeys.length > 2){
try {
for (const key in allOutputs) {
context.set(key, allOutputs[key]);
}
}catch (error: any) {
logger.error(`Error generating AI response: ${error.message}`);
}
}
}
}else {
throw new Error(`No such supported model ${model}`);
}
}
|
src/executor.ts
|
Confabulation-Corporation-golem-ac8b554
|
[
{
"filename": "src/types.ts",
"retrieved_chunk": "export interface GolemTarget {\n dependencies: string[];\n prompt: string;\n model?: string; // Add this line\n task_generation_prompt?: string; // Add this line\n [key: string]: string[] | string | undefined;\n}\nexport type GolemFile = {\n default: string[];\n} & {",
"score": 0.8430581092834473
},
{
"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": 0.8384198546409607
},
{
"filename": "src/golem.ts",
"retrieved_chunk": " const golemFilePath = argv.golemFile as string;\n // console.log(golemFilePath);\n // Add this line to create the .golem/ directory\n createGolemCacheDir();\n // Read the Golem file content\n const golemFileContent = fs.readFileSync(golemFilePath, 'utf8');\n const golemFile = parseGolemFile(golemFileContent);\n console.log(golemFile);\n // Execute the default target with an empty context\n await executeTarget('default', golemFile, golemFilePath, new Map());",
"score": 0.836183488368988
},
{
"filename": "src/utils.ts",
"retrieved_chunk": " return join('.golem', `${target}_${cacheKey}_output.txt`);\n}\nexport function isCacheValid(target: string, cacheKey: string): boolean {\n const cachedOutputPath = getCachedOutputPath(target, cacheKey);\n return existsSync(cachedOutputPath);\n}\nexport function saveOutputToCache(target: string, cacheKey: string, context: Map<string, any>): void {\n const cachedOutputPath = getCachedOutputPath(target, cacheKey);\n const defaultMap = new Map();\n if (context.has(\"default\")) {",
"score": 0.834858775138855
},
{
"filename": "src/types.ts",
"retrieved_chunk": " [target: string]: GolemTarget | undefined;\n};\nexport function isGolemTarget(target: GolemTarget | string[] | undefined): target is GolemTarget {\n return target !== undefined && (target as GolemTarget).dependencies !== undefined;\n}",
"score": 0.8048906922340393
}
] |
typescript
|
const concatenatedOutput = golemTarget.dependencies.map(dep => context.get(dep)).join('');
|
import { ClassFunction, Enum, Function, HookFunction, LibraryFunction, Panel, PanelFunction, Realm, Struct, WikiPage, isPanel } from '../scrapers/wiki-page-markup-scraper.js';
import { putCommentBeforeEachLine, removeNewlines, safeFileName, toLowerCamelCase } from '../utils/string.js';
import {
isClassFunction,
isHookFunction,
isLibraryFunction,
isPanelFunction,
isStruct,
isEnum,
} from '../scrapers/wiki-page-markup-scraper.js';
export const RESERVERD_KEYWORDS = new Set([
'and',
'break',
'continue',
'do',
'else',
'elseif',
'end',
'false',
'for',
'function',
'goto',
'if',
'in',
'local',
'nil',
'not',
'or',
'repeat',
'return',
'then',
'true',
'until',
'while'
]);
export class GluaApiWriter {
private readonly writtenClasses: Set<string> = new Set();
private readonly writtenLibraryGlobals: Set<string> = new Set();
private readonly pageOverrides: Map<string, string> = new Map();
constructor() { }
public static safeName(name: string) {
if (name.includes('/'))
name = name.replace(/\//g, ' or ');
if (name.includes('='))
name = name.split('=')[0];
if (name.includes(' '))
name =
|
toLowerCamelCase(name);
|
// Remove any remaining characters not valid in a Lua variable/function name.
name = name.replace(/[^A-Za-z\d_.]/g, '');
if (RESERVERD_KEYWORDS.has(name))
return `_${name}`;
return name;
}
public addOverride(pageAddress: string, override: string) {
this.pageOverrides.set(safeFileName(pageAddress, '.'), override);
}
public writePage(page: WikiPage) {
const fileSafeAddress = safeFileName(page.address, '.');
if (this.pageOverrides.has(fileSafeAddress)) {
let api = '';
if (isClassFunction(page))
api += this.writeClass(page.parent);
else if (isLibraryFunction(page))
api += this.writeLibraryGlobal(page);
api += this.pageOverrides.get(fileSafeAddress);
return `${api}\n\n`;
} else if (isClassFunction(page))
return this.writeClassFunction(page);
else if (isLibraryFunction(page))
return this.writeLibraryFunction(page);
else if (isHookFunction(page))
return this.writeHookFunction(page);
else if (isPanel(page))
return this.writePanel(page);
else if (isPanelFunction(page))
return this.writePanelFunction(page);
else if (isEnum(page))
return this.writeEnum(page);
else if (isStruct(page))
return this.writeStruct(page);
}
private writeClass(className: string, parent?: string, classFields: string = '') {
let api: string = '';
if (!this.writtenClasses.has(className)) {
const classOverride = `class.${className}`;
if (this.pageOverrides.has(classOverride)) {
api += this.pageOverrides.get(classOverride)!.replace(/\n$/g, '') + '\n\n';
api = api.replace('---{{CLASS_FIELDS}}\n', classFields);
} else {
api += `---@class ${className}`;
if (parent)
api += ` : ${parent}`;
api += '\n';
api += classFields;
api += `local ${className} = {}\n\n`;
}
this.writtenClasses.add(className);
}
return api;
}
private writeLibraryGlobal(func: LibraryFunction) {
if (!func.dontDefineParent && !this.writtenLibraryGlobals.has(func.parent)) {
const global = `${func.parent} = {}\n\n`;
this.writtenLibraryGlobals.add(func.parent);
return global;
}
return '';
}
private writeClassFunction(func: ClassFunction) {
let api: string = this.writeClass(func.parent);
api += this.writeFunctionLuaDocComment(func, func.realm);
api += this.writeFunctionDeclaration(func, func.realm, ':');
return api;
}
private writeLibraryFunction(func: LibraryFunction) {
let api: string = this.writeLibraryGlobal(func);
api += this.writeFunctionLuaDocComment(func, func.realm);
api += this.writeFunctionDeclaration(func, func.realm);
return api;
}
private writeHookFunction(func: HookFunction) {
return this.writeClassFunction(func);
}
private writePanel(panel: Panel) {
return this.writeClass(panel.name, panel.parent);
}
private writePanelFunction(func: PanelFunction) {
let api: string = '';
api += this.writeFunctionLuaDocComment(func, func.realm);
api += this.writeFunctionDeclaration(func, func.realm, ':');
return api;
}
private writeEnum(_enum: Enum) {
let api: string = '';
const isContainedInTable = _enum.items[0]?.key.includes('.') ?? false;
api += `---@enum ${_enum.name}\n`;
if (isContainedInTable)
api += `local ${_enum.name} = {\n`;
const writeItem = (key: string, item: typeof _enum.items[0]) => {
if (isContainedInTable) {
key = key.split('.')[1];
api += ` ${key} = ${item.value}, ` + (item.description ? `--[[ ${item.description} ]]` : '') + '\n';
} else {
const comment = item.description ? `${putCommentBeforeEachLine(item.description, false)}\n` : '';
api += `${comment}${key} = ${item.value}\n`;
}
};
for (const item of _enum.items)
writeItem(item.key, item);
if (isContainedInTable)
api += '}';
api += `\n\n`;
return api;
}
private writeStruct(struct: Struct) {
let fields: string = '';
for (const field of struct.fields) {
fields += `---@field ${GluaApiWriter.safeName(field.name)} ${this.transformType(field.type)} ${removeNewlines(field.description!)}\n`;
}
return this.writeClass(struct.name, undefined, fields);
}
public writePages(pages: WikiPage[]) {
let api: string = '';
for (const page of pages) {
api += this.writePage(page);
}
return api;
}
private transformType(type: string) {
if (type === 'vararg')
return '...';
return type;
}
private writeFunctionLuaDocComment(func: Function, realm: Realm) {
let luaDocComment = `---[${realm.toUpperCase()}] ${putCommentBeforeEachLine(func.description!.trim())}\n`;
luaDocComment += `---\n---[(View on wiki)](${func.url})\n`;
if (func.arguments) {
func.arguments.forEach((arg, index) => {
if (!arg.name)
arg.name = arg.type;
if (arg.type === 'vararg')
arg.name = '...';
luaDocComment += `---@param ${GluaApiWriter.safeName(arg.name)}${arg.default !== undefined ? `?` : ''} ${this.transformType(arg.type)} ${putCommentBeforeEachLine(arg.description!)}\n`;
});
}
if (func.returns) {
const returns = `---@return ${func.returns.map(ret => this.transformType(ret.type)).join(', ')}`;
func.returns.forEach(ret => {
const description = removeNewlines(ret.description ?? '');
if (func.returns!.length === 1) {
luaDocComment += `${returns} #${description}\n`;
return;
}
luaDocComment += `${returns} #${this.transformType(ret.type)} - ${description}\n`;
});
}
return luaDocComment;
}
private writeFunctionDeclaration(func: Function, realm: Realm, indexer: string = '.') {
let declaration = `function ${func.parent ? `${func.parent}${indexer}` : ''}${GluaApiWriter.safeName(func.name)}(`;
if (func.arguments) {
declaration += func.arguments.map(arg => {
if (arg.type === 'vararg')
return '...';
return GluaApiWriter.safeName(arg.name!);
}).join(', ');
}
declaration += ') end\n\n';
return declaration;
}
}
|
src/api-writer/glua-api-writer.ts
|
luttje-glua-api-snippets-9f40376
|
[
{
"filename": "src/scrapers/page-traverse-scraper.ts",
"retrieved_chunk": " const title = decodeEntities(content.match(/<title>(.*?)<\\/title>/)?.[1] || '');\n const page = this.factory(url, title);\n const links = content.match(/<a\\s+(?:[^>]*?\\s+)?href=([\"'])([\\s\\S]*?)\\1(?:[^>]*?\\s+)?>(?:[\\s\\S]*?<\\/a>)?/gi)\n ?.map(link => link.replace(/\\n/g, ''))\n ?.map(link => link.match(/href=([\"'])([\\s\\S]*?)\\1/i)?.[2] || '') || [];\n for (let link of links) {\n link = decodeEntities(link);\n let absoluteUrl = link.startsWith('http') ? link : new URL(link, url).toString();\n if (page.childUrls.has(absoluteUrl))\n continue;",
"score": 0.7791120409965515
},
{
"filename": "src/cli-scraper.ts",
"retrieved_chunk": " return;\n const api = writer.writePages(pageMarkups);\n let fileName = pageIndex.address;\n let moduleName = fileName;\n if (fileName.includes('.') || fileName.includes(':') || fileName.includes('/')) {\n [moduleName, fileName] = fileName.split(/[:.\\/]/, 2);\n }\n // Make sure modules like Entity and ENTITY are placed in the same file.\n moduleName = moduleName.toLowerCase();\n const moduleFile = path.join(baseDirectory, moduleName);",
"score": 0.7751716375350952
},
{
"filename": "src/scrapers/page-traverse-scraper.ts",
"retrieved_chunk": " if (this.childPageFilter && !this.childPageFilter(absoluteUrl))\n continue;\n page.childUrls.add(absoluteUrl);\n }\n results.push(page);\n return results;\n };\n }\n}",
"score": 0.7694259881973267
},
{
"filename": "src/scrapers/wiki-page-markup-scraper.ts",
"retrieved_chunk": " }\n }\n return null;\n });\n if (!page)\n return [];\n page.url = response.url.replace(/\\?format=text$/, '');\n return [page];\n };\n }",
"score": 0.7693597078323364
},
{
"filename": "src/scrapers/wiki-page-markup-scraper.ts",
"retrieved_chunk": " parent: string;\n};\nexport type WikiPage = ClassFunction | LibraryFunction | HookFunction | PanelFunction | Panel | Enum | Struct;\n/**\n * Guards\n */\nexport function isClassFunction(page: WikiPage): page is ClassFunction {\n return page.type === 'classfunc';\n}\nexport function isLibraryFunction(page: WikiPage): page is LibraryFunction {",
"score": 0.7686444520950317
}
] |
typescript
|
toLowerCamelCase(name);
|
import { exec } from 'child_process';
import { GolemFile, GolemTarget, isGolemTarget } from './types';
import { ChatGPTMessage, ChatGPT_completion } from './chat_gpt';
import { readFile } from 'fs/promises';
import { dirname } from 'path';
import logger from './logger';
import {
generateCacheKey,
isCacheValid,
saveOutputToCache,
loadOutputFromCache,
appendToGolemFile
} from './utils';
import { writeFileSync} from 'fs';
// TODO 1: Check if prompt asks for additional targets.
// TODO 2: Check if targets have other dependencies.
// TODO 3: Saving properly (for example, it saves all of the previous context for imp task)
// TODO 4: Use different files
interface ExecutionContext {
[key: string]: any;
}
const mainPrompt: ChatGPTMessage = {
role: 'system',
content: `You are an Agentic LLM assistant, designed only to produce code and helpful information. You may be asked to generate new targets. If the prompt given to you contains the phrase 'generate new targets', your response will be to generate a list of targets to help answer the prompt. The targets must be written as unnumbered items separated by lines starting with 'Target:'.
The items in the list will not be arranged in any particular order. For example:
Prompt: As an agentic LLM, generate new targets for the next iteration.
Response:
Target: Write a function to divide two numbers.
Target: Create a class called Employee.
Target: Write unit tests for the function GetPeopleInterests.
It is not always the case that you will be asked to generate new targets. If the prompt does not contain the phrase 'generate new targets', then proceed to answer the prompt as truthfully as possible. For example:
Prompt: What is capital of France?
Response: Paris.
Prompt: How many days are in the month of April?
Response: 30 days.
You are opinionated. If asked to provide a subjective answer, start by saying 'In my opinion' then answer the prompt. For example:
Prompt: What is the best sport?
Response: In my opinion, soccer.
`
}
export async function executeTarget(target: string, golemFile: GolemFile, golemFilePath: string, context: Map<string, any> = new Map()): Promise<void> {
const golemTarget = golemFile[target];
if (!golemTarget) {
throw new Error(`Target "${target}" not found in Golem file.`);
}
console.log(`Executing target: ${target}`);
if (golemTarget.dependencies) {
console.log(`Dependencies for ${target}: ${golemTarget.dependencies}`);
for (const dependency of golemTarget.dependencies) {
if (dependency) {
await executeTarget(dependency, golemFile, golemFilePath, context);
}
}
}
await executeAIChatWithCache(target, golemFile, golemFilePath, context);
console.log(`Context after ${target} execution:`, context);
}
function executeCommand(command: string): Promise<void> {
return new Promise((resolve, reject) => {
exec(command, (error, stdout, stderr) => {
if (error) {
logger.error(`Error executing command: ${command}`);
logger.error(stderr);
reject(error);
} else {
logger.debug(stdout);
resolve();
}
});
});
}
async function executeAIChatWithCache(target: string, golemFile: GolemFile, golemFilePath: string, context: Map<string, any>): Promise<void> {
const golemFileToArray: any = [];
for (const key in golemFile){
const val = golemFile[key as keyof typeof golemFile];
golemFileToArray.push(val);
}
const golemTarget = golemFile[target];
if (!golemTarget ||
|
!isGolemTarget(golemTarget)) {
|
return;
}
const cacheKey = generateCacheKey(target, golemTarget.dependencies || [], [...golemFileToArray] || '');
if (isCacheValid(target, cacheKey)) {
console.log("Returning Cached output");
const cachedOutput = loadOutputFromCache(target, cacheKey);
context.set(target, cachedOutput);
} else {
await executeAIChat(target, golemFile, golemFilePath, context);
saveOutputToCache(target, cacheKey, context);
}
}
async function executeAIChat(target: string, golemFile: GolemFile, golemFilePath: string, context: Map<string, any>): Promise<void> {
// ============== Setup start ====================================
const contextOfCurrentTarget: string[] = [];
const allOutputs: {[key: string]: any} = {};
const golemTarget = golemFile[target];
console.log("gT", golemTarget);
if (!golemTarget) {
throw new Error(`Target "${target}" not found in Golem file.`);
}
if (!isGolemTarget(golemTarget)) {
return;
}
if (!golemTarget.prompt && !golemTarget.model) {
golemTarget.model = 'cat';
}
let prompt = golemTarget.prompt ?? "{no prompt}";
if (isGolemTarget(golemTarget) && golemTarget.prompt) {
prompt = golemTarget.prompt;
const placeholderRegex = /{{\s*([\w\/.-]+)\s*}}/g;
let match;
while ((match = placeholderRegex.exec(prompt)) !== null) {
const key = match[1];
if (context.has(key)) {
prompt = prompt.replace(match[0], context.get(key));
} else {
prompt = prompt.replace(match[0], "");
}
}
}
else if (!golemTarget.prompt) {
const defaultValues = new Map(context.entries());
context.set("default", Object.fromEntries(defaultValues));
return;
}
const model = golemTarget.model ?? 'gpt-3.5-turbo';
// ============== Setup end ====================================
if (model === 'cat') {
const concatenatedOutput = golemTarget.dependencies.map(dep => context.get(dep)).join('');
context.set(target, concatenatedOutput);
} else if (model == "gpt-3.5-turbo" || model == "gpt-3.5-turbo-0301" || model == "gpt-4-0314" || model == "gpt-4-32k") {
if ("model" in golemTarget) {
delete golemTarget.model;
}
// This gets the 'keys' (subtasks) of a target (task)
const golemTargetKeys: string[] = Object.keys(golemTarget);
// It starts from 1 as index 0 is dependencies. This can be changed if needed
for (let i = 1; i < golemTargetKeys.length; i++){
// console.log("gTKi", golemTargetKeys[i]);
const val: any = golemTarget[golemTargetKeys[i] as keyof typeof golemTarget];
// console.log("val", val);
const previousContext: string | undefined = contextOfCurrentTarget[0] || '';
// Concat the previousContext (if undefined) to the current subtask (here, named val)
const content = previousContext + val;
// console.log("content", content);
// This block of code replaces the {{}} placeholders in the string from the yaml file
// with the output of the subtask or task it requires
const replacedString = content.replace(/{{(.*?)}}/g, (match, p1) => {
// Remove the curly braces from the placeholder
const placeholder = p1.trim();
// Replace the placeholder with the corresponding value from the map
return context.get(placeholder) || placeholder;
});
// console.log("context", context);
// console.log("replacedString", replacedString);
const taskGenerationMessages: ChatGPTMessage[] = [
mainPrompt,
{
role: 'user',
content: replacedString,
},
];
const response = await ChatGPT_completion(taskGenerationMessages, model, 0.7, 0.9);
contextOfCurrentTarget.length = 0; //clear the previous context
contextOfCurrentTarget.push(response); //append the new context to be used in the next iteration
allOutputs[golemTargetKeys[i]] = response;
const lines: string[] = response.split('\n');
// Extract the targets from the lines that start with "Target:"
const targets: string[] = lines.filter((line: string) => line.startsWith("Target:"))
.map((line: string) => line.slice(8));
let count = 1;
targets.forEach((createdTarget: string) => {
const targetName = target.concat("_target".concat(count.toString()));
const newTarget: string = `\n${targetName}:\n dependencies: []\n prompt: ${createdTarget}`;
appendToGolemFile(golemFilePath, newTarget);
golemTargetKeys.push(targetName);
golemTarget[targetName] = createdTarget;
count += 1;
});
if (golemTargetKeys.length === 2){
if (!response) {
context.set(target, `Default value for ${target}`);
} else {
context.set(target, response);
console.log(context);
}
}
else if (golemTargetKeys.length > 2){
try {
for (const key in allOutputs) {
context.set(key, allOutputs[key]);
}
}catch (error: any) {
logger.error(`Error generating AI response: ${error.message}`);
}
}
}
}else {
throw new Error(`No such supported model ${model}`);
}
}
|
src/executor.ts
|
Confabulation-Corporation-golem-ac8b554
|
[
{
"filename": "src/golem.ts",
"retrieved_chunk": " const golemFilePath = argv.golemFile as string;\n // console.log(golemFilePath);\n // Add this line to create the .golem/ directory\n createGolemCacheDir();\n // Read the Golem file content\n const golemFileContent = fs.readFileSync(golemFilePath, 'utf8');\n const golemFile = parseGolemFile(golemFileContent);\n console.log(golemFile);\n // Execute the default target with an empty context\n await executeTarget('default', golemFile, golemFilePath, new Map());",
"score": 0.8725970387458801
},
{
"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": 0.8679987192153931
},
{
"filename": "src/utils.ts",
"retrieved_chunk": " return join('.golem', `${target}_${cacheKey}_output.txt`);\n}\nexport function isCacheValid(target: string, cacheKey: string): boolean {\n const cachedOutputPath = getCachedOutputPath(target, cacheKey);\n return existsSync(cachedOutputPath);\n}\nexport function saveOutputToCache(target: string, cacheKey: string, context: Map<string, any>): void {\n const cachedOutputPath = getCachedOutputPath(target, cacheKey);\n const defaultMap = new Map();\n if (context.has(\"default\")) {",
"score": 0.8474873304367065
},
{
"filename": "src/golem.ts",
"retrieved_chunk": "#!/usr/bin/env node\nimport yargs from 'yargs';\nimport { executeTarget } from './executor';\nimport { parseGolemFile } from './parser';\nimport fs from 'fs';\nimport logger from './logger';\nimport { createGolemCacheDir } from './utils'; // Add this import\nyargs\n .command(\n 'golem [golemFile]',",
"score": 0.8242442011833191
},
{
"filename": "src/utils.ts",
"retrieved_chunk": " const cachedOutputPath = getCachedOutputPath(target, cacheKey);\n return readFileSync(cachedOutputPath, 'utf-8');\n}\nexport function createGolemCacheDir(): void {\n if (!existsSync('.golem')) {\n mkdirSync('.golem');\n }\n}",
"score": 0.8188768029212952
}
] |
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/cli-scraper.ts",
"retrieved_chunk": " return;\n const api = writer.writePages(pageMarkups);\n let fileName = pageIndex.address;\n let moduleName = fileName;\n if (fileName.includes('.') || fileName.includes(':') || fileName.includes('/')) {\n [moduleName, fileName] = fileName.split(/[:.\\/]/, 2);\n }\n // Make sure modules like Entity and ENTITY are placed in the same file.\n moduleName = moduleName.toLowerCase();\n const moduleFile = path.join(baseDirectory, moduleName);",
"score": 0.815163791179657
},
{
"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": 0.8087722659111023
},
{
"filename": "src/cli-scraper.ts",
"retrieved_chunk": " if (!fs.existsSync(`${moduleFile}.lua`))\n fs.writeFileSync(`${moduleFile}.lua`, '---@meta\\n\\n');\n if (!fs.existsSync(moduleFile))\n fs.mkdirSync(moduleFile, { recursive: true });\n fileName = fileName.replace(/[^a-z0-9]/gi, '_').toLowerCase();\n // Lua API\n fs.appendFileSync(path.join(baseDirectory, `${moduleName}.lua`), api);\n // JSON data\n const json = JSON.stringify(pageMarkups, null, 2);\n fs.writeFileSync(path.join(baseDirectory, moduleName, `${fileName}.json`), json);",
"score": 0.8036730289459229
},
{
"filename": "src/cli-scraper.ts",
"retrieved_chunk": " const fileContent = fs.readFileSync(filePath, { encoding: 'utf-8' });\n const pageName = file.replace(/\\.lua$/, '');\n writer.addOverride(pageName, fileContent);\n }\n }\n const pageIndexes = await scrapeAndCollect(pageListScraper);\n for (const pageIndex of pageIndexes) {\n const pageMarkupScraper = new WikiPageMarkupScraper(`${baseUrl}/${pageIndex.address}?format=text`);\n pageMarkupScraper.on('scraped', (url, pageMarkups) => {\n if (pageMarkups.length === 0)",
"score": 0.8020683526992798
},
{
"filename": "src/cli-scraper.ts",
"retrieved_chunk": " const options = program.opts();\n if (!options.url) {\n console.error('No URL provided');\n process.exit(1);\n }\n const baseDirectory = options.output.replace(/\\/$/, '');\n const customDirectory = options.customOverrides?.replace(/\\/$/, '') ?? null;\n const baseUrl = options.url.replace(/\\/$/, '');\n const pageListScraper = new WikiPageListScraper(`${baseUrl}/~pagelist?format=json`);\n const writer = new GluaApiWriter();",
"score": 0.7848894000053406
}
] |
typescript
|
public writePages(pages: 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": " const isEnum = $('enum').length > 0;\n const isStruct = $('structure').length > 0;\n const isFunction = $('function').length > 0;\n const isPanel = $('panel').length > 0;\n const mainElement = $(isEnum ? 'enum' : isStruct ? 'struct' : isPanel ? 'panel' : 'function');\n const address = response.url.split('/').pop()!.split('?')[0];\n if (isEnum) {\n const items = $('items item').map(function () {\n const $el = $(this);\n return <EnumValue>{",
"score": 0.808290421962738
},
{
"filename": "src/scrapers/wiki-page-markup-scraper.ts",
"retrieved_chunk": "};\nexport type HookFunction = Function & {\n type: 'hook';\n isHook: 'yes';\n};\nexport type PanelFunction = Function & {\n type: 'panelfunc';\n isPanelFunction: 'yes';\n};\nexport type EnumValue = {",
"score": 0.8037632703781128
},
{
"filename": "src/scrapers/wiki-page-markup-scraper.ts",
"retrieved_chunk": " } else if (isFunction) {\n const isClassFunction = mainElement.attr('type') === 'classfunc';\n const isLibraryFunction = mainElement.attr('type') === 'libraryfunc';\n const isHookFunction = mainElement.attr('type') === 'hook';\n const isPanelFunction = mainElement.attr('type') === 'panelfunc';\n const arguments_ = $('args arg').map(function() {\n const $el = $(this);\n const argument = <FunctionArgument> {\n name: $el.attr('name')!,\n type: $el.attr('type')!,",
"score": 0.7731991410255432
},
{
"filename": "src/scrapers/wiki-page-markup-scraper.ts",
"retrieved_chunk": " ...base,\n type: 'hook',\n isHook: 'yes'\n };\n } else if (isPanelFunction) {\n return <PanelFunction> {\n ...base,\n type: 'panelfunc',\n isPanelFunction: 'yes'\n };",
"score": 0.7675175666809082
},
{
"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": 0.766033411026001
}
] |
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/cli-scraper.ts",
"retrieved_chunk": " return;\n const api = writer.writePages(pageMarkups);\n let fileName = pageIndex.address;\n let moduleName = fileName;\n if (fileName.includes('.') || fileName.includes(':') || fileName.includes('/')) {\n [moduleName, fileName] = fileName.split(/[:.\\/]/, 2);\n }\n // Make sure modules like Entity and ENTITY are placed in the same file.\n moduleName = moduleName.toLowerCase();\n const moduleFile = path.join(baseDirectory, moduleName);",
"score": 0.812981128692627
},
{
"filename": "src/cli-scraper.ts",
"retrieved_chunk": " if (!fs.existsSync(`${moduleFile}.lua`))\n fs.writeFileSync(`${moduleFile}.lua`, '---@meta\\n\\n');\n if (!fs.existsSync(moduleFile))\n fs.mkdirSync(moduleFile, { recursive: true });\n fileName = fileName.replace(/[^a-z0-9]/gi, '_').toLowerCase();\n // Lua API\n fs.appendFileSync(path.join(baseDirectory, `${moduleName}.lua`), api);\n // JSON data\n const json = JSON.stringify(pageMarkups, null, 2);\n fs.writeFileSync(path.join(baseDirectory, moduleName, `${fileName}.json`), json);",
"score": 0.7958983182907104
},
{
"filename": "src/cli-scraper.ts",
"retrieved_chunk": " const fileContent = fs.readFileSync(filePath, { encoding: 'utf-8' });\n const pageName = file.replace(/\\.lua$/, '');\n writer.addOverride(pageName, fileContent);\n }\n }\n const pageIndexes = await scrapeAndCollect(pageListScraper);\n for (const pageIndex of pageIndexes) {\n const pageMarkupScraper = new WikiPageMarkupScraper(`${baseUrl}/${pageIndex.address}?format=text`);\n pageMarkupScraper.on('scraped', (url, pageMarkups) => {\n if (pageMarkups.length === 0)",
"score": 0.7883584499359131
},
{
"filename": "src/scrapers/page-traverse-scraper.ts",
"retrieved_chunk": " if (this.childPageFilter && !this.childPageFilter(absoluteUrl))\n continue;\n page.childUrls.add(absoluteUrl);\n }\n results.push(page);\n return results;\n };\n }\n}",
"score": 0.7802354097366333
},
{
"filename": "src/scrapers/page-traverse-scraper.ts",
"retrieved_chunk": " const title = decodeEntities(content.match(/<title>(.*?)<\\/title>/)?.[1] || '');\n const page = this.factory(url, title);\n const links = content.match(/<a\\s+(?:[^>]*?\\s+)?href=([\"'])([\\s\\S]*?)\\1(?:[^>]*?\\s+)?>(?:[\\s\\S]*?<\\/a>)?/gi)\n ?.map(link => link.replace(/\\n/g, ''))\n ?.map(link => link.match(/href=([\"'])([\\s\\S]*?)\\1/i)?.[2] || '') || [];\n for (let link of links) {\n link = decodeEntities(link);\n let absoluteUrl = link.startsWith('http') ? link : new URL(link, url).toString();\n if (page.childUrls.has(absoluteUrl))\n continue;",
"score": 0.7639281153678894
}
] |
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/cli-scraper.ts",
"retrieved_chunk": " return;\n const api = writer.writePages(pageMarkups);\n let fileName = pageIndex.address;\n let moduleName = fileName;\n if (fileName.includes('.') || fileName.includes(':') || fileName.includes('/')) {\n [moduleName, fileName] = fileName.split(/[:.\\/]/, 2);\n }\n // Make sure modules like Entity and ENTITY are placed in the same file.\n moduleName = moduleName.toLowerCase();\n const moduleFile = path.join(baseDirectory, moduleName);",
"score": 0.8387199640274048
},
{
"filename": "src/cli-scraper.ts",
"retrieved_chunk": " const fileContent = fs.readFileSync(filePath, { encoding: 'utf-8' });\n const pageName = file.replace(/\\.lua$/, '');\n writer.addOverride(pageName, fileContent);\n }\n }\n const pageIndexes = await scrapeAndCollect(pageListScraper);\n for (const pageIndex of pageIndexes) {\n const pageMarkupScraper = new WikiPageMarkupScraper(`${baseUrl}/${pageIndex.address}?format=text`);\n pageMarkupScraper.on('scraped', (url, pageMarkups) => {\n if (pageMarkups.length === 0)",
"score": 0.8201336860656738
},
{
"filename": "src/cli-scraper.ts",
"retrieved_chunk": " if (!fs.existsSync(`${moduleFile}.lua`))\n fs.writeFileSync(`${moduleFile}.lua`, '---@meta\\n\\n');\n if (!fs.existsSync(moduleFile))\n fs.mkdirSync(moduleFile, { recursive: true });\n fileName = fileName.replace(/[^a-z0-9]/gi, '_').toLowerCase();\n // Lua API\n fs.appendFileSync(path.join(baseDirectory, `${moduleName}.lua`), api);\n // JSON data\n const json = JSON.stringify(pageMarkups, null, 2);\n fs.writeFileSync(path.join(baseDirectory, moduleName, `${fileName}.json`), json);",
"score": 0.8075608611106873
},
{
"filename": "src/scrapers/wiki-page-markup-scraper.ts",
"retrieved_chunk": " return page.type === 'libraryfunc';\n}\nexport function isHookFunction(page: WikiPage): page is HookFunction {\n return page.type === 'hook';\n}\nexport function isPanelFunction(page: WikiPage): page is PanelFunction {\n return page.type === 'panelfunc';\n}\nexport function isPanel(page: WikiPage): page is Panel {\n return page.type === 'panel';",
"score": 0.77901291847229
},
{
"filename": "src/scrapers/page-traverse-scraper.ts",
"retrieved_chunk": " if (this.childPageFilter && !this.childPageFilter(absoluteUrl))\n continue;\n page.childUrls.add(absoluteUrl);\n }\n results.push(page);\n return results;\n };\n }\n}",
"score": 0.7779982089996338
}
] |
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/cli-scraper.ts",
"retrieved_chunk": " if (!fs.existsSync(`${moduleFile}.lua`))\n fs.writeFileSync(`${moduleFile}.lua`, '---@meta\\n\\n');\n if (!fs.existsSync(moduleFile))\n fs.mkdirSync(moduleFile, { recursive: true });\n fileName = fileName.replace(/[^a-z0-9]/gi, '_').toLowerCase();\n // Lua API\n fs.appendFileSync(path.join(baseDirectory, `${moduleName}.lua`), api);\n // JSON data\n const json = JSON.stringify(pageMarkups, null, 2);\n fs.writeFileSync(path.join(baseDirectory, moduleName, `${fileName}.json`), json);",
"score": 0.7723940014839172
},
{
"filename": "src/cli-library-publisher.ts",
"retrieved_chunk": " \"/**/\",\n \"continue\",\n ],\n \"Lua.diagnostics.disable\": [\n \"duplicate-set-field\", // Prevents complaining when a function exists twice in both the CLIENT and SERVER realm\n ],\n // TODO: runtime.path\n });\n fs.writeFileSync(path.join(options.output, 'config.json'), JSON.stringify(config, null, 2));\n const files = walk(options.input, (file, isDirectory) => isDirectory || (file.endsWith(`.lua`)));",
"score": 0.7696807980537415
},
{
"filename": "src/scrapers/wiki-page-markup-scraper.ts",
"retrieved_chunk": " realm: $('realm').text() as Realm,\n items\n };\n } else if (isStruct) {\n const fields = $('fields item').map(function () {\n const $el = $(this);\n return <StructField>{\n name: $el.attr('name')!,\n type: $el.attr('type')!,\n default: $el.attr('default'),",
"score": 0.7655230164527893
},
{
"filename": "src/cli-scraper.ts",
"retrieved_chunk": " return;\n const api = writer.writePages(pageMarkups);\n let fileName = pageIndex.address;\n let moduleName = fileName;\n if (fileName.includes('.') || fileName.includes(':') || fileName.includes('/')) {\n [moduleName, fileName] = fileName.split(/[:.\\/]/, 2);\n }\n // Make sure modules like Entity and ENTITY are placed in the same file.\n moduleName = moduleName.toLowerCase();\n const moduleFile = path.join(baseDirectory, moduleName);",
"score": 0.7618589997291565
},
{
"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": 0.7613303661346436
}
] |
typescript
|
${removeNewlines(field.description!)}\n`;
|
import { ClassFunction, Enum, Function, HookFunction, LibraryFunction, Panel, PanelFunction, Realm, Struct, WikiPage, isPanel } from '../scrapers/wiki-page-markup-scraper.js';
import { putCommentBeforeEachLine, removeNewlines, safeFileName, toLowerCamelCase } from '../utils/string.js';
import {
isClassFunction,
isHookFunction,
isLibraryFunction,
isPanelFunction,
isStruct,
isEnum,
} from '../scrapers/wiki-page-markup-scraper.js';
export const RESERVERD_KEYWORDS = new Set([
'and',
'break',
'continue',
'do',
'else',
'elseif',
'end',
'false',
'for',
'function',
'goto',
'if',
'in',
'local',
'nil',
'not',
'or',
'repeat',
'return',
'then',
'true',
'until',
'while'
]);
export class GluaApiWriter {
private readonly writtenClasses: Set<string> = new Set();
private readonly writtenLibraryGlobals: Set<string> = new Set();
private readonly pageOverrides: Map<string, string> = new Map();
constructor() { }
public static safeName(name: string) {
if (name.includes('/'))
name = name.replace(/\//g, ' or ');
if (name.includes('='))
name = name.split('=')[0];
if (name.includes(' '))
name = toLowerCamelCase(name);
// Remove any remaining characters not valid in a Lua variable/function name.
name = name.replace(/[^A-Za-z\d_.]/g, '');
if (RESERVERD_KEYWORDS.has(name))
return `_${name}`;
return name;
}
public addOverride(pageAddress: string, override: string) {
this.pageOverrides.set(safeFileName(pageAddress, '.'), override);
}
public writePage(page: WikiPage) {
const fileSafeAddress = safeFileName(page.address, '.');
if (this.pageOverrides.has(fileSafeAddress)) {
let api = '';
if (isClassFunction(page))
api += this.writeClass(page.parent);
else if (isLibraryFunction(page))
api += this.writeLibraryGlobal(page);
api += this.pageOverrides.get(fileSafeAddress);
return `${api}\n\n`;
} else if (isClassFunction(page))
return this.writeClassFunction(page);
else if (isLibraryFunction(page))
return this.writeLibraryFunction(page);
else if (isHookFunction(page))
return this.writeHookFunction(page);
else if (isPanel(page))
return this.writePanel(page);
else if (isPanelFunction(page))
return this.writePanelFunction(page);
else if (isEnum(page))
return this.writeEnum(page);
else if (isStruct(page))
return this.writeStruct(page);
}
private writeClass(className: string, parent?: string, classFields: string = '') {
let api: string = '';
if (!this.writtenClasses.has(className)) {
const classOverride = `class.${className}`;
if (this.pageOverrides.has(classOverride)) {
api += this.pageOverrides.get(classOverride)!.replace(/\n$/g, '') + '\n\n';
api = api.replace('---{{CLASS_FIELDS}}\n', classFields);
} else {
api += `---@class ${className}`;
if (parent)
api += ` : ${parent}`;
api += '\n';
api += classFields;
api += `local ${className} = {}\n\n`;
}
this.writtenClasses.add(className);
}
return api;
}
private writeLibraryGlobal
|
(func: LibraryFunction) {
|
if (!func.dontDefineParent && !this.writtenLibraryGlobals.has(func.parent)) {
const global = `${func.parent} = {}\n\n`;
this.writtenLibraryGlobals.add(func.parent);
return global;
}
return '';
}
private writeClassFunction(func: ClassFunction) {
let api: string = this.writeClass(func.parent);
api += this.writeFunctionLuaDocComment(func, func.realm);
api += this.writeFunctionDeclaration(func, func.realm, ':');
return api;
}
private writeLibraryFunction(func: LibraryFunction) {
let api: string = this.writeLibraryGlobal(func);
api += this.writeFunctionLuaDocComment(func, func.realm);
api += this.writeFunctionDeclaration(func, func.realm);
return api;
}
private writeHookFunction(func: HookFunction) {
return this.writeClassFunction(func);
}
private writePanel(panel: Panel) {
return this.writeClass(panel.name, panel.parent);
}
private writePanelFunction(func: PanelFunction) {
let api: string = '';
api += this.writeFunctionLuaDocComment(func, func.realm);
api += this.writeFunctionDeclaration(func, func.realm, ':');
return api;
}
private writeEnum(_enum: Enum) {
let api: string = '';
const isContainedInTable = _enum.items[0]?.key.includes('.') ?? false;
api += `---@enum ${_enum.name}\n`;
if (isContainedInTable)
api += `local ${_enum.name} = {\n`;
const writeItem = (key: string, item: typeof _enum.items[0]) => {
if (isContainedInTable) {
key = key.split('.')[1];
api += ` ${key} = ${item.value}, ` + (item.description ? `--[[ ${item.description} ]]` : '') + '\n';
} else {
const comment = item.description ? `${putCommentBeforeEachLine(item.description, false)}\n` : '';
api += `${comment}${key} = ${item.value}\n`;
}
};
for (const item of _enum.items)
writeItem(item.key, item);
if (isContainedInTable)
api += '}';
api += `\n\n`;
return api;
}
private writeStruct(struct: Struct) {
let fields: string = '';
for (const field of struct.fields) {
fields += `---@field ${GluaApiWriter.safeName(field.name)} ${this.transformType(field.type)} ${removeNewlines(field.description!)}\n`;
}
return this.writeClass(struct.name, undefined, fields);
}
public writePages(pages: WikiPage[]) {
let api: string = '';
for (const page of pages) {
api += this.writePage(page);
}
return api;
}
private transformType(type: string) {
if (type === 'vararg')
return '...';
return type;
}
private writeFunctionLuaDocComment(func: Function, realm: Realm) {
let luaDocComment = `---[${realm.toUpperCase()}] ${putCommentBeforeEachLine(func.description!.trim())}\n`;
luaDocComment += `---\n---[(View on wiki)](${func.url})\n`;
if (func.arguments) {
func.arguments.forEach((arg, index) => {
if (!arg.name)
arg.name = arg.type;
if (arg.type === 'vararg')
arg.name = '...';
luaDocComment += `---@param ${GluaApiWriter.safeName(arg.name)}${arg.default !== undefined ? `?` : ''} ${this.transformType(arg.type)} ${putCommentBeforeEachLine(arg.description!)}\n`;
});
}
if (func.returns) {
const returns = `---@return ${func.returns.map(ret => this.transformType(ret.type)).join(', ')}`;
func.returns.forEach(ret => {
const description = removeNewlines(ret.description ?? '');
if (func.returns!.length === 1) {
luaDocComment += `${returns} #${description}\n`;
return;
}
luaDocComment += `${returns} #${this.transformType(ret.type)} - ${description}\n`;
});
}
return luaDocComment;
}
private writeFunctionDeclaration(func: Function, realm: Realm, indexer: string = '.') {
let declaration = `function ${func.parent ? `${func.parent}${indexer}` : ''}${GluaApiWriter.safeName(func.name)}(`;
if (func.arguments) {
declaration += func.arguments.map(arg => {
if (arg.type === 'vararg')
return '...';
return GluaApiWriter.safeName(arg.name!);
}).join(', ');
}
declaration += ') end\n\n';
return declaration;
}
}
|
src/api-writer/glua-api-writer.ts
|
luttje-glua-api-snippets-9f40376
|
[
{
"filename": "src/scrapers/wiki-page-markup-scraper.ts",
"retrieved_chunk": " if (base.parent === 'Global') {\n base.parent = '_G';\n (<LibraryFunction>base).dontDefineParent = true;\n }\n return <LibraryFunction> {\n ...base,\n type: 'libraryfunc'\n };\n } else if (isHookFunction) {\n return <HookFunction> {",
"score": 0.7989793419837952
},
{
"filename": "src/scrapers/wiki-page-markup-scraper.ts",
"retrieved_chunk": " realm: $('realm:first').text() as Realm,\n arguments: arguments_,\n returns\n };\n if (isClassFunction) {\n return <ClassFunction> {\n ...base,\n type: 'classfunc'\n };\n } else if (isLibraryFunction) {",
"score": 0.7988100051879883
},
{
"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": 0.7882020473480225
},
{
"filename": "src/scrapers/wiki-page-markup-scraper.ts",
"retrieved_chunk": "export type FunctionReturn = WikiIdentifier & {};\nexport type Function = CommonWikiProperties & {\n parent: string;\n arguments?: FunctionArgument[];\n returns?: FunctionReturn[];\n};\nexport type ClassFunction = Function & {};\nexport type LibraryFunction = Function & {\n type: 'libraryfunc';\n dontDefineParent?: boolean;",
"score": 0.7825103402137756
},
{
"filename": "src/scrapers/wiki-page-markup-scraper.ts",
"retrieved_chunk": " } else if (isFunction) {\n const isClassFunction = mainElement.attr('type') === 'classfunc';\n const isLibraryFunction = mainElement.attr('type') === 'libraryfunc';\n const isHookFunction = mainElement.attr('type') === 'hook';\n const isPanelFunction = mainElement.attr('type') === 'panelfunc';\n const arguments_ = $('args arg').map(function() {\n const $el = $(this);\n const argument = <FunctionArgument> {\n name: $el.attr('name')!,\n type: $el.attr('type')!,",
"score": 0.7779268622398376
}
] |
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": " realm: $('realm:first').text() as Realm,\n arguments: arguments_,\n returns\n };\n if (isClassFunction) {\n return <ClassFunction> {\n ...base,\n type: 'classfunc'\n };\n } else if (isLibraryFunction) {",
"score": 0.8169296979904175
},
{
"filename": "src/cli-scraper.ts",
"retrieved_chunk": " if (!fs.existsSync(`${moduleFile}.lua`))\n fs.writeFileSync(`${moduleFile}.lua`, '---@meta\\n\\n');\n if (!fs.existsSync(moduleFile))\n fs.mkdirSync(moduleFile, { recursive: true });\n fileName = fileName.replace(/[^a-z0-9]/gi, '_').toLowerCase();\n // Lua API\n fs.appendFileSync(path.join(baseDirectory, `${moduleName}.lua`), api);\n // JSON data\n const json = JSON.stringify(pageMarkups, null, 2);\n fs.writeFileSync(path.join(baseDirectory, moduleName, `${fileName}.json`), json);",
"score": 0.7926573753356934
},
{
"filename": "src/scrapers/wiki-page-markup-scraper.ts",
"retrieved_chunk": " } else if (isFunction) {\n const isClassFunction = mainElement.attr('type') === 'classfunc';\n const isLibraryFunction = mainElement.attr('type') === 'libraryfunc';\n const isHookFunction = mainElement.attr('type') === 'hook';\n const isPanelFunction = mainElement.attr('type') === 'panelfunc';\n const arguments_ = $('args arg').map(function() {\n const $el = $(this);\n const argument = <FunctionArgument> {\n name: $el.attr('name')!,\n type: $el.attr('type')!,",
"score": 0.787750244140625
},
{
"filename": "src/scrapers/wiki-page-markup-scraper.ts",
"retrieved_chunk": "export type FunctionReturn = WikiIdentifier & {};\nexport type Function = CommonWikiProperties & {\n parent: string;\n arguments?: FunctionArgument[];\n returns?: FunctionReturn[];\n};\nexport type ClassFunction = Function & {};\nexport type LibraryFunction = Function & {\n type: 'libraryfunc';\n dontDefineParent?: boolean;",
"score": 0.7871640920639038
},
{
"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": 0.7848998308181763
}
] |
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": 0.8783703446388245
},
{
"filename": "src/scrapers/page-traverse-scraper.ts",
"retrieved_chunk": "import { Scrapeable, TraverseScraper } from './traverse-scraper.js';\nimport { decodeEntities } from './decode-entities.js';\nimport { ScrapeCallback } from './scraper.js';\nexport class Page implements Scrapeable {\n public url: string;\n public title: string;\n public childUrls: Set<string> = new Set();\n constructor(url: string, title: string) {\n this.url = url;\n this.title = title;",
"score": 0.8556016683578491
},
{
"filename": "src/scrapers/page-traverse-scraper.ts",
"retrieved_chunk": " }\n}\nexport class PageTraverseScraper<T extends Page = Page> extends TraverseScraper<T> {\n private readonly factory: (url: string, title: string) => T;\n constructor(baseUrl: string, factory?: (url: string, title: string) => T) {\n super(baseUrl);\n this.factory = factory ?? ((url: string, title: string) => new Page(url, title) as T);\n }\n /**\n * Scrapes a page for its URL and title, and returns a list of child URLs",
"score": 0.8337332010269165
},
{
"filename": "src/scrapers/scraper.ts",
"retrieved_chunk": "export class Scraper<T extends ScrapeResult> extends TypedEventEmitter<ScraperEvents<T>> {\n protected retryOptions: RequestInitWithRetry = {};\n constructor(\n protected readonly baseUrl: string,\n protected readonly scrapeCallback?: ScrapeCallback<T>\n ) { \n super();\n }\n public getScrapeCallback(): ScrapeCallback<T> {\n return this.scrapeCallback || ((_: Response, __: string): T[] => []);",
"score": 0.8227839469909668
},
{
"filename": "src/scrapers/wiki-history-scraper.ts",
"retrieved_chunk": " public history: WikiHistory[] = [];\n constructor(url: string, title: string) {\n super(url, title);\n }\n}\nexport class WikiHistoryPageScraper extends PageTraverseScraper<WikiHistoryPage> {\n constructor(baseUrl: string) {\n super(baseUrl, (url: string, title: string) => new WikiHistoryPage(url, title));\n }\n /**",
"score": 0.8131017088890076
}
] |
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": 0.7996170520782471
},
{
"filename": "src/scrapers/json-scraper.ts",
"retrieved_chunk": " }\n public static makeScrapeCallback<T extends object = object>(): ScrapeCallback<T> {\n return (response: Response, content: string): T[] => {\n return JSON.parse(content);\n };\n }\n}",
"score": 0.7924349308013916
},
{
"filename": "src/scrapers/page-traverse-scraper.ts",
"retrieved_chunk": "import { Scrapeable, TraverseScraper } from './traverse-scraper.js';\nimport { decodeEntities } from './decode-entities.js';\nimport { ScrapeCallback } from './scraper.js';\nexport class Page implements Scrapeable {\n public url: string;\n public title: string;\n public childUrls: Set<string> = new Set();\n constructor(url: string, title: string) {\n this.url = url;\n this.title = title;",
"score": 0.791676938533783
},
{
"filename": "src/scrapers/scraper.ts",
"retrieved_chunk": "import { TypedEventEmitter } from '../utils/typed-event-emitter.js';\nimport { RequestInitWithRetry } from 'fetch-retry';\nimport fetchRetry from 'fetch-retry';\nconst fetch = fetchRetry(global.fetch);\nexport type ScrapeCallback<T> = (response: Response, content: string) => T[] | Promise<T[]>;\nexport type ScrapeResult = object;\nexport type ScraperEvents<T> = {\n beforescrape: [url: string];\n scraped: [url: string, results: T[]];\n}",
"score": 0.7824434041976929
},
{
"filename": "src/scrapers/traverse-scraper.ts",
"retrieved_chunk": "import { Scraper, ScrapeCallback } from './scraper.js';\nexport interface Scrapeable {\n childUrls: Set<string>;\n}\nexport class TraverseScraper<T extends Scrapeable> extends Scraper<T> {\n protected readonly traversedUrls: Set<string> = new Set();\n protected childPageFilter?: (url: string) => boolean;\n public setChildPageFilter(filter: (url: string) => boolean): void {\n this.childPageFilter = filter;\n }",
"score": 0.7787653207778931
}
] |
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": 0.8114444613456726
},
{
"filename": "src/scrapers/wiki-page-markup-scraper.ts",
"retrieved_chunk": " } else if (isFunction) {\n const isClassFunction = mainElement.attr('type') === 'classfunc';\n const isLibraryFunction = mainElement.attr('type') === 'libraryfunc';\n const isHookFunction = mainElement.attr('type') === 'hook';\n const isPanelFunction = mainElement.attr('type') === 'panelfunc';\n const arguments_ = $('args arg').map(function() {\n const $el = $(this);\n const argument = <FunctionArgument> {\n name: $el.attr('name')!,\n type: $el.attr('type')!,",
"score": 0.7956539392471313
},
{
"filename": "src/scrapers/wiki-page-markup-scraper.ts",
"retrieved_chunk": "export type FunctionReturn = WikiIdentifier & {};\nexport type Function = CommonWikiProperties & {\n parent: string;\n arguments?: FunctionArgument[];\n returns?: FunctionReturn[];\n};\nexport type ClassFunction = Function & {};\nexport type LibraryFunction = Function & {\n type: 'libraryfunc';\n dontDefineParent?: boolean;",
"score": 0.7792893052101135
},
{
"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": 0.7787009477615356
},
{
"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": 0.7758395671844482
}
] |
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": 0.8187528848648071
},
{
"filename": "src/scrapers/wiki-page-markup-scraper.ts",
"retrieved_chunk": " } else if (isFunction) {\n const isClassFunction = mainElement.attr('type') === 'classfunc';\n const isLibraryFunction = mainElement.attr('type') === 'libraryfunc';\n const isHookFunction = mainElement.attr('type') === 'hook';\n const isPanelFunction = mainElement.attr('type') === 'panelfunc';\n const arguments_ = $('args arg').map(function() {\n const $el = $(this);\n const argument = <FunctionArgument> {\n name: $el.attr('name')!,\n type: $el.attr('type')!,",
"score": 0.7989466190338135
},
{
"filename": "src/scrapers/wiki-page-markup-scraper.ts",
"retrieved_chunk": "export type FunctionReturn = WikiIdentifier & {};\nexport type Function = CommonWikiProperties & {\n parent: string;\n arguments?: FunctionArgument[];\n returns?: FunctionReturn[];\n};\nexport type ClassFunction = Function & {};\nexport type LibraryFunction = Function & {\n type: 'libraryfunc';\n dontDefineParent?: boolean;",
"score": 0.7783505916595459
},
{
"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": 0.7781930565834045
},
{
"filename": "src/scrapers/wiki-page-markup-scraper.ts",
"retrieved_chunk": " description: $el.text()\n };\n if ($el.attr('default'))\n argument.default = $el.attr('default')!;\n return argument;\n }).get();\n const returns = $('rets ret').map(function() {\n const $el = $(this);\n return <FunctionReturn> {\n name: $el.attr('name')!,",
"score": 0.7744588851928711
}
] |
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": " realm: $('realm:first').text() as Realm,\n arguments: arguments_,\n returns\n };\n if (isClassFunction) {\n return <ClassFunction> {\n ...base,\n type: 'classfunc'\n };\n } else if (isLibraryFunction) {",
"score": 0.8106729984283447
},
{
"filename": "src/cli-scraper.ts",
"retrieved_chunk": " if (!fs.existsSync(`${moduleFile}.lua`))\n fs.writeFileSync(`${moduleFile}.lua`, '---@meta\\n\\n');\n if (!fs.existsSync(moduleFile))\n fs.mkdirSync(moduleFile, { recursive: true });\n fileName = fileName.replace(/[^a-z0-9]/gi, '_').toLowerCase();\n // Lua API\n fs.appendFileSync(path.join(baseDirectory, `${moduleName}.lua`), api);\n // JSON data\n const json = JSON.stringify(pageMarkups, null, 2);\n fs.writeFileSync(path.join(baseDirectory, moduleName, `${fileName}.json`), json);",
"score": 0.7933804392814636
},
{
"filename": "src/scrapers/wiki-page-markup-scraper.ts",
"retrieved_chunk": " } else if (isFunction) {\n const isClassFunction = mainElement.attr('type') === 'classfunc';\n const isLibraryFunction = mainElement.attr('type') === 'libraryfunc';\n const isHookFunction = mainElement.attr('type') === 'hook';\n const isPanelFunction = mainElement.attr('type') === 'panelfunc';\n const arguments_ = $('args arg').map(function() {\n const $el = $(this);\n const argument = <FunctionArgument> {\n name: $el.attr('name')!,\n type: $el.attr('type')!,",
"score": 0.7818378806114197
},
{
"filename": "src/cli-library-publisher.ts",
"retrieved_chunk": " \"/**/\",\n \"continue\",\n ],\n \"Lua.diagnostics.disable\": [\n \"duplicate-set-field\", // Prevents complaining when a function exists twice in both the CLIENT and SERVER realm\n ],\n // TODO: runtime.path\n });\n fs.writeFileSync(path.join(options.output, 'config.json'), JSON.stringify(config, null, 2));\n const files = walk(options.input, (file, isDirectory) => isDirectory || (file.endsWith(`.lua`)));",
"score": 0.7740651369094849
},
{
"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": 0.7724549770355225
}
] |
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": 0.8745193481445312
},
{
"filename": "src/scrapers/page-traverse-scraper.ts",
"retrieved_chunk": "import { Scrapeable, TraverseScraper } from './traverse-scraper.js';\nimport { decodeEntities } from './decode-entities.js';\nimport { ScrapeCallback } from './scraper.js';\nexport class Page implements Scrapeable {\n public url: string;\n public title: string;\n public childUrls: Set<string> = new Set();\n constructor(url: string, title: string) {\n this.url = url;\n this.title = title;",
"score": 0.8523293733596802
},
{
"filename": "src/scrapers/page-traverse-scraper.ts",
"retrieved_chunk": " }\n}\nexport class PageTraverseScraper<T extends Page = Page> extends TraverseScraper<T> {\n private readonly factory: (url: string, title: string) => T;\n constructor(baseUrl: string, factory?: (url: string, title: string) => T) {\n super(baseUrl);\n this.factory = factory ?? ((url: string, title: string) => new Page(url, title) as T);\n }\n /**\n * Scrapes a page for its URL and title, and returns a list of child URLs",
"score": 0.8326044082641602
},
{
"filename": "src/scrapers/scraper.ts",
"retrieved_chunk": "export class Scraper<T extends ScrapeResult> extends TypedEventEmitter<ScraperEvents<T>> {\n protected retryOptions: RequestInitWithRetry = {};\n constructor(\n protected readonly baseUrl: string,\n protected readonly scrapeCallback?: ScrapeCallback<T>\n ) { \n super();\n }\n public getScrapeCallback(): ScrapeCallback<T> {\n return this.scrapeCallback || ((_: Response, __: string): T[] => []);",
"score": 0.8197234869003296
},
{
"filename": "src/scrapers/wiki-history-scraper.ts",
"retrieved_chunk": " public history: WikiHistory[] = [];\n constructor(url: string, title: string) {\n super(url, title);\n }\n}\nexport class WikiHistoryPageScraper extends PageTraverseScraper<WikiHistoryPage> {\n constructor(baseUrl: string) {\n super(baseUrl, (url: string, title: string) => new WikiHistoryPage(url, title));\n }\n /**",
"score": 0.8112674951553345
}
] |
typescript
|
extends TraverseScraper<Table<T>> {
|
import { ClassFunction, Enum, Function, HookFunction, LibraryFunction, Panel, PanelFunction, Realm, Struct, WikiPage, isPanel } from '../scrapers/wiki-page-markup-scraper.js';
import { putCommentBeforeEachLine, removeNewlines, safeFileName, toLowerCamelCase } from '../utils/string.js';
import {
isClassFunction,
isHookFunction,
isLibraryFunction,
isPanelFunction,
isStruct,
isEnum,
} from '../scrapers/wiki-page-markup-scraper.js';
export const RESERVERD_KEYWORDS = new Set([
'and',
'break',
'continue',
'do',
'else',
'elseif',
'end',
'false',
'for',
'function',
'goto',
'if',
'in',
'local',
'nil',
'not',
'or',
'repeat',
'return',
'then',
'true',
'until',
'while'
]);
export class GluaApiWriter {
private readonly writtenClasses: Set<string> = new Set();
private readonly writtenLibraryGlobals: Set<string> = new Set();
private readonly pageOverrides: Map<string, string> = new Map();
constructor() { }
public static safeName(name: string) {
if (name.includes('/'))
name = name.replace(/\//g, ' or ');
if (name.includes('='))
name = name.split('=')[0];
if (name.includes(' '))
name = toLowerCamelCase(name);
// Remove any remaining characters not valid in a Lua variable/function name.
name = name.replace(/[^A-Za-z\d_.]/g, '');
if (RESERVERD_KEYWORDS.has(name))
return `_${name}`;
return name;
}
public addOverride(pageAddress: string, override: string) {
this.pageOverrides.set(safeFileName(pageAddress, '.'), override);
}
public writePage(page: WikiPage) {
const fileSafeAddress = safeFileName(page.address, '.');
if (this.pageOverrides.has(fileSafeAddress)) {
let api = '';
if (isClassFunction(page))
api += this.writeClass(page.parent);
else if (isLibraryFunction(page))
api += this.writeLibraryGlobal(page);
api += this.pageOverrides.get(fileSafeAddress);
return `${api}\n\n`;
} else if (isClassFunction(page))
return this.writeClassFunction(page);
else if (isLibraryFunction(page))
return this.writeLibraryFunction(page);
else if (isHookFunction(page))
return this.writeHookFunction(page);
else if (isPanel(page))
return this.writePanel(page);
else if (isPanelFunction(page))
return this.writePanelFunction(page);
else if (isEnum(page))
return this.writeEnum(page);
else if (isStruct(page))
return this.writeStruct(page);
}
private writeClass(className: string, parent?: string, classFields: string = '') {
let api: string = '';
if (!this.writtenClasses.has(className)) {
const classOverride = `class.${className}`;
if (this.pageOverrides.has(classOverride)) {
api += this.pageOverrides.get(classOverride)!.replace(/\n$/g, '') + '\n\n';
api = api.replace('---{{CLASS_FIELDS}}\n', classFields);
} else {
api += `---@class ${className}`;
if (parent)
api += ` : ${parent}`;
api += '\n';
api += classFields;
api += `local ${className} = {}\n\n`;
}
this.writtenClasses.add(className);
}
return api;
}
private writeLibraryGlobal(func: LibraryFunction) {
if (!func.dontDefineParent && !this.writtenLibraryGlobals.has(func.parent)) {
const global = `${func.parent} = {}\n\n`;
this.writtenLibraryGlobals.add(func.parent);
return global;
}
return '';
}
private writeClassFunction(func: ClassFunction) {
let api: string
|
= this.writeClass(func.parent);
|
api += this.writeFunctionLuaDocComment(func, func.realm);
api += this.writeFunctionDeclaration(func, func.realm, ':');
return api;
}
private writeLibraryFunction(func: LibraryFunction) {
let api: string = this.writeLibraryGlobal(func);
api += this.writeFunctionLuaDocComment(func, func.realm);
api += this.writeFunctionDeclaration(func, func.realm);
return api;
}
private writeHookFunction(func: HookFunction) {
return this.writeClassFunction(func);
}
private writePanel(panel: Panel) {
return this.writeClass(panel.name, panel.parent);
}
private writePanelFunction(func: PanelFunction) {
let api: string = '';
api += this.writeFunctionLuaDocComment(func, func.realm);
api += this.writeFunctionDeclaration(func, func.realm, ':');
return api;
}
private writeEnum(_enum: Enum) {
let api: string = '';
const isContainedInTable = _enum.items[0]?.key.includes('.') ?? false;
api += `---@enum ${_enum.name}\n`;
if (isContainedInTable)
api += `local ${_enum.name} = {\n`;
const writeItem = (key: string, item: typeof _enum.items[0]) => {
if (isContainedInTable) {
key = key.split('.')[1];
api += ` ${key} = ${item.value}, ` + (item.description ? `--[[ ${item.description} ]]` : '') + '\n';
} else {
const comment = item.description ? `${putCommentBeforeEachLine(item.description, false)}\n` : '';
api += `${comment}${key} = ${item.value}\n`;
}
};
for (const item of _enum.items)
writeItem(item.key, item);
if (isContainedInTable)
api += '}';
api += `\n\n`;
return api;
}
private writeStruct(struct: Struct) {
let fields: string = '';
for (const field of struct.fields) {
fields += `---@field ${GluaApiWriter.safeName(field.name)} ${this.transformType(field.type)} ${removeNewlines(field.description!)}\n`;
}
return this.writeClass(struct.name, undefined, fields);
}
public writePages(pages: WikiPage[]) {
let api: string = '';
for (const page of pages) {
api += this.writePage(page);
}
return api;
}
private transformType(type: string) {
if (type === 'vararg')
return '...';
return type;
}
private writeFunctionLuaDocComment(func: Function, realm: Realm) {
let luaDocComment = `---[${realm.toUpperCase()}] ${putCommentBeforeEachLine(func.description!.trim())}\n`;
luaDocComment += `---\n---[(View on wiki)](${func.url})\n`;
if (func.arguments) {
func.arguments.forEach((arg, index) => {
if (!arg.name)
arg.name = arg.type;
if (arg.type === 'vararg')
arg.name = '...';
luaDocComment += `---@param ${GluaApiWriter.safeName(arg.name)}${arg.default !== undefined ? `?` : ''} ${this.transformType(arg.type)} ${putCommentBeforeEachLine(arg.description!)}\n`;
});
}
if (func.returns) {
const returns = `---@return ${func.returns.map(ret => this.transformType(ret.type)).join(', ')}`;
func.returns.forEach(ret => {
const description = removeNewlines(ret.description ?? '');
if (func.returns!.length === 1) {
luaDocComment += `${returns} #${description}\n`;
return;
}
luaDocComment += `${returns} #${this.transformType(ret.type)} - ${description}\n`;
});
}
return luaDocComment;
}
private writeFunctionDeclaration(func: Function, realm: Realm, indexer: string = '.') {
let declaration = `function ${func.parent ? `${func.parent}${indexer}` : ''}${GluaApiWriter.safeName(func.name)}(`;
if (func.arguments) {
declaration += func.arguments.map(arg => {
if (arg.type === 'vararg')
return '...';
return GluaApiWriter.safeName(arg.name!);
}).join(', ');
}
declaration += ') end\n\n';
return declaration;
}
}
|
src/api-writer/glua-api-writer.ts
|
luttje-glua-api-snippets-9f40376
|
[
{
"filename": "src/scrapers/wiki-page-markup-scraper.ts",
"retrieved_chunk": " if (base.parent === 'Global') {\n base.parent = '_G';\n (<LibraryFunction>base).dontDefineParent = true;\n }\n return <LibraryFunction> {\n ...base,\n type: 'libraryfunc'\n };\n } else if (isHookFunction) {\n return <HookFunction> {",
"score": 0.8236066102981567
},
{
"filename": "src/scrapers/wiki-page-markup-scraper.ts",
"retrieved_chunk": "export type FunctionReturn = WikiIdentifier & {};\nexport type Function = CommonWikiProperties & {\n parent: string;\n arguments?: FunctionArgument[];\n returns?: FunctionReturn[];\n};\nexport type ClassFunction = Function & {};\nexport type LibraryFunction = Function & {\n type: 'libraryfunc';\n dontDefineParent?: boolean;",
"score": 0.8012567758560181
},
{
"filename": "src/scrapers/wiki-page-markup-scraper.ts",
"retrieved_chunk": " realm: $('realm:first').text() as Realm,\n arguments: arguments_,\n returns\n };\n if (isClassFunction) {\n return <ClassFunction> {\n ...base,\n type: 'classfunc'\n };\n } else if (isLibraryFunction) {",
"score": 0.8009297251701355
},
{
"filename": "src/scrapers/wiki-page-markup-scraper.ts",
"retrieved_chunk": " } else if (isFunction) {\n const isClassFunction = mainElement.attr('type') === 'classfunc';\n const isLibraryFunction = mainElement.attr('type') === 'libraryfunc';\n const isHookFunction = mainElement.attr('type') === 'hook';\n const isPanelFunction = mainElement.attr('type') === 'panelfunc';\n const arguments_ = $('args arg').map(function() {\n const $el = $(this);\n const argument = <FunctionArgument> {\n name: $el.attr('name')!,\n type: $el.attr('type')!,",
"score": 0.7918365597724915
},
{
"filename": "src/cli-scraper.ts",
"retrieved_chunk": " return;\n const api = writer.writePages(pageMarkups);\n let fileName = pageIndex.address;\n let moduleName = fileName;\n if (fileName.includes('.') || fileName.includes(':') || fileName.includes('/')) {\n [moduleName, fileName] = fileName.split(/[:.\\/]/, 2);\n }\n // Make sure modules like Entity and ENTITY are placed in the same file.\n moduleName = moduleName.toLowerCase();\n const moduleFile = path.join(baseDirectory, moduleName);",
"score": 0.7824670076370239
}
] |
typescript
|
= this.writeClass(func.parent);
|
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": 0.8433088660240173
},
{
"filename": "src/types.ts",
"retrieved_chunk": "export interface GolemTarget {\n dependencies: string[];\n prompt: string;\n model?: string; // Add this line\n task_generation_prompt?: string; // Add this line\n [key: string]: string[] | string | undefined;\n}\nexport type GolemFile = {\n default: string[];\n} & {",
"score": 0.8163984417915344
},
{
"filename": "src/golem.ts",
"retrieved_chunk": "#!/usr/bin/env node\nimport yargs from 'yargs';\nimport { executeTarget } from './executor';\nimport { parseGolemFile } from './parser';\nimport fs from 'fs';\nimport logger from './logger';\nimport { createGolemCacheDir } from './utils'; // Add this import\nyargs\n .command(\n 'golem [golemFile]',",
"score": 0.8112956881523132
},
{
"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": 0.8083865642547607
},
{
"filename": "src/golem.ts",
"retrieved_chunk": " 'Run the specified Golem file or the default Golem file if none is provided.',\n (yargs) => {\n yargs.positional('golemFile', {\n describe: 'Path to the Golem file',\n default: 'Golem.yaml',\n type: 'string',\n });\n },\n async (argv) => {\n try {",
"score": 0.7857240438461304
}
] |
typescript
|
const golemTarget = golemFile[target];
|
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": 0.8144690990447998
},
{
"filename": "src/cli-scraper.ts",
"retrieved_chunk": " if (!fs.existsSync(`${moduleFile}.lua`))\n fs.writeFileSync(`${moduleFile}.lua`, '---@meta\\n\\n');\n if (!fs.existsSync(moduleFile))\n fs.mkdirSync(moduleFile, { recursive: true });\n fileName = fileName.replace(/[^a-z0-9]/gi, '_').toLowerCase();\n // Lua API\n fs.appendFileSync(path.join(baseDirectory, `${moduleName}.lua`), api);\n // JSON data\n const json = JSON.stringify(pageMarkups, null, 2);\n fs.writeFileSync(path.join(baseDirectory, moduleName, `${fileName}.json`), json);",
"score": 0.7935532927513123
},
{
"filename": "src/cli-scraper.ts",
"retrieved_chunk": " const fileContent = fs.readFileSync(filePath, { encoding: 'utf-8' });\n const pageName = file.replace(/\\.lua$/, '');\n writer.addOverride(pageName, fileContent);\n }\n }\n const pageIndexes = await scrapeAndCollect(pageListScraper);\n for (const pageIndex of pageIndexes) {\n const pageMarkupScraper = new WikiPageMarkupScraper(`${baseUrl}/${pageIndex.address}?format=text`);\n pageMarkupScraper.on('scraped', (url, pageMarkups) => {\n if (pageMarkups.length === 0)",
"score": 0.7849425673484802
},
{
"filename": "src/scrapers/page-traverse-scraper.ts",
"retrieved_chunk": " if (this.childPageFilter && !this.childPageFilter(absoluteUrl))\n continue;\n page.childUrls.add(absoluteUrl);\n }\n results.push(page);\n return results;\n };\n }\n}",
"score": 0.7813346982002258
},
{
"filename": "src/scrapers/page-traverse-scraper.ts",
"retrieved_chunk": " const title = decodeEntities(content.match(/<title>(.*?)<\\/title>/)?.[1] || '');\n const page = this.factory(url, title);\n const links = content.match(/<a\\s+(?:[^>]*?\\s+)?href=([\"'])([\\s\\S]*?)\\1(?:[^>]*?\\s+)?>(?:[\\s\\S]*?<\\/a>)?/gi)\n ?.map(link => link.replace(/\\n/g, ''))\n ?.map(link => link.match(/href=([\"'])([\\s\\S]*?)\\1/i)?.[2] || '') || [];\n for (let link of links) {\n link = decodeEntities(link);\n let absoluteUrl = link.startsWith('http') ? link : new URL(link, url).toString();\n if (page.childUrls.has(absoluteUrl))\n continue;",
"score": 0.7648907899856567
}
] |
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/types.ts",
"retrieved_chunk": "export interface GolemTarget {\n dependencies: string[];\n prompt: string;\n model?: string; // Add this line\n task_generation_prompt?: string; // Add this line\n [key: string]: string[] | string | undefined;\n}\nexport type GolemFile = {\n default: string[];\n} & {",
"score": 0.8437289595603943
},
{
"filename": "src/golem.ts",
"retrieved_chunk": " const golemFilePath = argv.golemFile as string;\n // console.log(golemFilePath);\n // Add this line to create the .golem/ directory\n createGolemCacheDir();\n // Read the Golem file content\n const golemFileContent = fs.readFileSync(golemFilePath, 'utf8');\n const golemFile = parseGolemFile(golemFileContent);\n console.log(golemFile);\n // Execute the default target with an empty context\n await executeTarget('default', golemFile, golemFilePath, new Map());",
"score": 0.8375351428985596
},
{
"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": 0.8364484310150146
},
{
"filename": "src/utils.ts",
"retrieved_chunk": " return join('.golem', `${target}_${cacheKey}_output.txt`);\n}\nexport function isCacheValid(target: string, cacheKey: string): boolean {\n const cachedOutputPath = getCachedOutputPath(target, cacheKey);\n return existsSync(cachedOutputPath);\n}\nexport function saveOutputToCache(target: string, cacheKey: string, context: Map<string, any>): void {\n const cachedOutputPath = getCachedOutputPath(target, cacheKey);\n const defaultMap = new Map();\n if (context.has(\"default\")) {",
"score": 0.8331166505813599
},
{
"filename": "src/types.ts",
"retrieved_chunk": " [target: string]: GolemTarget | undefined;\n};\nexport function isGolemTarget(target: GolemTarget | string[] | undefined): target is GolemTarget {\n return target !== undefined && (target as GolemTarget).dependencies !== undefined;\n}",
"score": 0.8038314580917358
}
] |
typescript
|
golemTarget.dependencies.map(dep => context.get(dep)).join('');
|
import { Scrapeable, TraverseScraper } from './traverse-scraper.js';
import { decodeEntities } from './decode-entities.js';
import { ScrapeCallback } from './scraper.js';
export class Page implements Scrapeable {
public url: string;
public title: string;
public childUrls: Set<string> = new Set();
constructor(url: string, title: string) {
this.url = url;
this.title = title;
}
}
export class PageTraverseScraper<T extends Page = Page> extends TraverseScraper<T> {
private readonly factory: (url: string, title: string) => T;
constructor(baseUrl: string, factory?: (url: string, title: string) => T) {
super(baseUrl);
this.factory = factory ?? ((url: string, title: string) => new Page(url, title) as T);
}
/**
* Scrapes a page for its URL and title, and returns a list of child URLs
*
* @param response The response from the page
* @param content The content of the request
*
* @returns A list containing only the scraped page
*/
public getScrapeCallback(): ScrapeCallback<T> {
return (response: Response, content: string): T[] => {
const results: T[] = [];
const url = response.url;
const title = decodeEntities(content.match(/<title>(.*?)<\/title>/)?.[1] || '');
const page = this.factory(url, title);
const links = content.match(/<a\s+(?:[^>]*?\s+)?href=(["'])([\s\S]*?)\1(?:[^>]*?\s+)?>(?:[\s\S]*?<\/a>)?/gi)
?.map(link => link.replace(/\n/g, ''))
?.map(link => link.match(/href=(["'])([\s\S]*?)\1/i)?.[2] || '') || [];
for (let link of links) {
link = decodeEntities(link);
let absoluteUrl = link.startsWith('http') ? link : new URL(link, url).toString();
if (page.childUrls.has(absoluteUrl))
continue;
|
if (this.childPageFilter && !this.childPageFilter(absoluteUrl))
continue;
|
page.childUrls.add(absoluteUrl);
}
results.push(page);
return results;
};
}
}
|
src/scrapers/page-traverse-scraper.ts
|
luttje-glua-api-snippets-9f40376
|
[
{
"filename": "src/scrapers/traverse-scraper.ts",
"retrieved_chunk": " if (url.endsWith('/'))\n url = url.substring(0, url.length - 1);\n if (url.includes('#'))\n url = url.substring(0, url.indexOf('#'));\n if (this.traversedUrls.has(url))\n return false;\n if (this.childPageFilter && !this.childPageFilter(url))\n return false;\n return url;\n }",
"score": 0.8417432308197021
},
{
"filename": "src/scrapers/wiki-page-markup-scraper.ts",
"retrieved_chunk": " }\n }\n return null;\n });\n if (!page)\n return [];\n page.url = response.url.replace(/\\?format=text$/, '');\n return [page];\n };\n }",
"score": 0.835647702217102
},
{
"filename": "src/scrapers/traverse-scraper.ts",
"retrieved_chunk": " this.traversedUrls.add(url);\n for (const result of currentResults) {\n for (const childUrl of result.childUrls) {\n const traverseUrl = this.getTraverseUrl(childUrl);\n if (traverseUrl && !urlsToTraverse.includes(traverseUrl))\n urlsToTraverse.push(traverseUrl);\n }\n }\n }\n }",
"score": 0.8287518620491028
},
{
"filename": "src/cli-scraper.ts",
"retrieved_chunk": " const fileContent = fs.readFileSync(filePath, { encoding: 'utf-8' });\n const pageName = file.replace(/\\.lua$/, '');\n writer.addOverride(pageName, fileContent);\n }\n }\n const pageIndexes = await scrapeAndCollect(pageListScraper);\n for (const pageIndex of pageIndexes) {\n const pageMarkupScraper = new WikiPageMarkupScraper(`${baseUrl}/${pageIndex.address}?format=text`);\n pageMarkupScraper.on('scraped', (url, pageMarkups) => {\n if (pageMarkups.length === 0)",
"score": 0.8172538876533508
},
{
"filename": "src/scrapers/traverse-scraper.ts",
"retrieved_chunk": " /**\n * Override scraping so we traverse all child URLs of the first scraped page\n */\n public async scrape(): Promise<void> {\n const callback = this.getScrapeCallback();\n await this.traverse(this.baseUrl, callback.bind(this));\n }\n protected getTraverseUrl(url: string): string | false {\n if (!url.startsWith(this.baseUrl))\n return false;",
"score": 0.8113260865211487
}
] |
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": 0.8153016567230225
},
{
"filename": "src/scrapers/wiki-page-markup-scraper.ts",
"retrieved_chunk": " } else if (isFunction) {\n const isClassFunction = mainElement.attr('type') === 'classfunc';\n const isLibraryFunction = mainElement.attr('type') === 'libraryfunc';\n const isHookFunction = mainElement.attr('type') === 'hook';\n const isPanelFunction = mainElement.attr('type') === 'panelfunc';\n const arguments_ = $('args arg').map(function() {\n const $el = $(this);\n const argument = <FunctionArgument> {\n name: $el.attr('name')!,\n type: $el.attr('type')!,",
"score": 0.7961540222167969
},
{
"filename": "src/scrapers/wiki-page-markup-scraper.ts",
"retrieved_chunk": "export type FunctionReturn = WikiIdentifier & {};\nexport type Function = CommonWikiProperties & {\n parent: string;\n arguments?: FunctionArgument[];\n returns?: FunctionReturn[];\n};\nexport type ClassFunction = Function & {};\nexport type LibraryFunction = Function & {\n type: 'libraryfunc';\n dontDefineParent?: boolean;",
"score": 0.7767759561538696
},
{
"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": 0.776641845703125
},
{
"filename": "src/scrapers/wiki-page-markup-scraper.ts",
"retrieved_chunk": " description: $el.text()\n };\n if ($el.attr('default'))\n argument.default = $el.attr('default')!;\n return argument;\n }).get();\n const returns = $('rets ret').map(function() {\n const $el = $(this);\n return <FunctionReturn> {\n name: $el.attr('name')!,",
"score": 0.7732945680618286
}
] |
typescript
|
(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/page-traverse-scraper.ts",
"retrieved_chunk": " const title = decodeEntities(content.match(/<title>(.*?)<\\/title>/)?.[1] || '');\n const page = this.factory(url, title);\n const links = content.match(/<a\\s+(?:[^>]*?\\s+)?href=([\"'])([\\s\\S]*?)\\1(?:[^>]*?\\s+)?>(?:[\\s\\S]*?<\\/a>)?/gi)\n ?.map(link => link.replace(/\\n/g, ''))\n ?.map(link => link.match(/href=([\"'])([\\s\\S]*?)\\1/i)?.[2] || '') || [];\n for (let link of links) {\n link = decodeEntities(link);\n let absoluteUrl = link.startsWith('http') ? link : new URL(link, url).toString();\n if (page.childUrls.has(absoluteUrl))\n continue;",
"score": 0.7797108292579651
},
{
"filename": "src/cli-scraper.ts",
"retrieved_chunk": " return;\n const api = writer.writePages(pageMarkups);\n let fileName = pageIndex.address;\n let moduleName = fileName;\n if (fileName.includes('.') || fileName.includes(':') || fileName.includes('/')) {\n [moduleName, fileName] = fileName.split(/[:.\\/]/, 2);\n }\n // Make sure modules like Entity and ENTITY are placed in the same file.\n moduleName = moduleName.toLowerCase();\n const moduleFile = path.join(baseDirectory, moduleName);",
"score": 0.7788342237472534
},
{
"filename": "src/utils/string.ts",
"retrieved_chunk": " */\nexport function putCommentBeforeEachLine(text: string, skipLineOne: boolean = true) {\n return text.split(/\\r?\\n/g).map((line, index) => {\n if (index === 0 && skipLineOne)\n return line;\n return `--- ${line}`;\n }).join('\\n');\n}\n/**\n * Makes a string safe for use as a file name",
"score": 0.7732628583908081
},
{
"filename": "src/scrapers/page-traverse-scraper.ts",
"retrieved_chunk": " if (this.childPageFilter && !this.childPageFilter(absoluteUrl))\n continue;\n page.childUrls.add(absoluteUrl);\n }\n results.push(page);\n return results;\n };\n }\n}",
"score": 0.77158522605896
},
{
"filename": "src/scrapers/page-traverse-scraper.ts",
"retrieved_chunk": "import { Scrapeable, TraverseScraper } from './traverse-scraper.js';\nimport { decodeEntities } from './decode-entities.js';\nimport { ScrapeCallback } from './scraper.js';\nexport class Page implements Scrapeable {\n public url: string;\n public title: string;\n public childUrls: Set<string> = new Set();\n constructor(url: string, title: string) {\n this.url = url;\n this.title = title;",
"score": 0.7714078426361084
}
] |
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": " },\n ];\n const response = await ChatGPT_completion(taskGenerationMessages, model, 0.7, 0.9);\n contextOfCurrentTarget.length = 0; //clear the previous context\n contextOfCurrentTarget.push(response); //append the new context to be used in the next iteration\n allOutputs[golemTargetKeys[i]] = response;\n const lines: string[] = response.split('\\n');\n // Extract the targets from the lines that start with \"Target:\"\n const targets: string[] = lines.filter((line: string) => line.startsWith(\"Target:\"))\n .map((line: string) => line.slice(8));",
"score": 0.7772988677024841
},
{
"filename": "src/executor.ts",
"retrieved_chunk": " // Replace the placeholder with the corresponding value from the map\n return context.get(placeholder) || placeholder;\n });\n // console.log(\"context\", context);\n // console.log(\"replacedString\", replacedString);\n const taskGenerationMessages: ChatGPTMessage[] = [\n mainPrompt,\n {\n role: 'user',\n content: replacedString,",
"score": 0.7739962935447693
},
{
"filename": "src/executor.ts",
"retrieved_chunk": " if (error) {\n logger.error(`Error executing command: ${command}`);\n logger.error(stderr);\n reject(error);\n } else {\n logger.debug(stdout);\n resolve();\n }\n });\n });",
"score": 0.7729175686836243
},
{
"filename": "src/golem.ts",
"retrieved_chunk": " } catch (error: any) {\n logger.error(`Error: ${error.message}`);\n }\n }\n )\n .demandCommand(1, 'You must provide a valid command.')\n .help()\n .alias('h', 'help')\n .strict().argv;",
"score": 0.7694448828697205
},
{
"filename": "src/executor.ts",
"retrieved_chunk": " let match;\n while ((match = placeholderRegex.exec(prompt)) !== null) {\n const key = match[1];\n if (context.has(key)) {\n prompt = prompt.replace(match[0], context.get(key));\n } else {\n prompt = prompt.replace(match[0], \"\");\n }\n }\n }",
"score": 0.758270263671875
}
] |
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": 0.9144686460494995
},
{
"filename": "src/scrapers/wiki-history-scraper.ts",
"retrieved_chunk": " * Scrapes a wiki history page for information on wiki changes\n * \n * @param response The response from the page\n * @param content The content of the request\n * \n * @returns A list containing only the scraped page\n */\n public getScrapeCallback(): ScrapeCallback<WikiHistoryPage> {\n const baseScrapeCallback = super.getScrapeCallback();\n return async (response: Response, content: string): Promise<WikiHistoryPage[]> => {",
"score": 0.9092755317687988
},
{
"filename": "src/scrapers/json-scraper.ts",
"retrieved_chunk": "import { ScrapeCallback, Scraper } from './scraper.js';\nexport class JsonScraper<T extends object = object> extends Scraper<T> {\n /**\n * @param response The response from the page\n * @param content The content of the request\n * \n * @returns A list containing only the scraped page\n */\n public getScrapeCallback(): ScrapeCallback<T> {\n return JsonScraper.makeScrapeCallback<T>();",
"score": 0.8715843558311462
},
{
"filename": "src/scrapers/wiki-history-scraper.ts",
"retrieved_chunk": " const pages = await baseScrapeCallback(response, content);\n if (pages.length === 0)\n return [];\n // There is only one page per response\n const page = pages[0];\n const $ = cheerio.load(content);\n const changeElements = $('table.changelist > tbody > .entry');\n if (!changeElements)\n return [page];\n for (const changeElement of changeElements) {",
"score": 0.8469361066818237
},
{
"filename": "src/scrapers/json-scraper.ts",
"retrieved_chunk": " }\n public static makeScrapeCallback<T extends object = object>(): ScrapeCallback<T> {\n return (response: Response, content: string): T[] => {\n return JSON.parse(content);\n };\n }\n}",
"score": 0.8179690837860107
}
] |
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": 0.9103140234947205
},
{
"filename": "src/scrapers/scraper.ts",
"retrieved_chunk": " response = await fetch(url, this.retryOptions);\n content = await response.text();\n } catch (e) {\n console.warn(`Error fetching ${url}: ${e}`);\n return [];\n }\n const scrapedResults = await callback(response, content);\n this.emit('scraped', url, scrapedResults);\n return scrapedResults;\n }",
"score": 0.8710311055183411
},
{
"filename": "src/scrapers/scraper.ts",
"retrieved_chunk": " }\n public setRetryOptions(options: RequestInitWithRetry): void {\n this.retryOptions = options;\n }\n /**\n * Scrapes the base url and has the callback process the response\n */\n public async scrape(): Promise<void> {\n const callback = this.getScrapeCallback();\n await this.visitOne(this.baseUrl, callback);",
"score": 0.8471486568450928
},
{
"filename": "src/scrapers/page-traverse-scraper.ts",
"retrieved_chunk": " }\n}\nexport class PageTraverseScraper<T extends Page = Page> extends TraverseScraper<T> {\n private readonly factory: (url: string, title: string) => T;\n constructor(baseUrl: string, factory?: (url: string, title: string) => T) {\n super(baseUrl);\n this.factory = factory ?? ((url: string, title: string) => new Page(url, title) as T);\n }\n /**\n * Scrapes a page for its URL and title, and returns a list of child URLs",
"score": 0.8292868137359619
},
{
"filename": "src/scrapers/collector.ts",
"retrieved_chunk": "import { Scraper, ScrapeResult } from \"./scraper.js\";\nexport async function scrapeAndCollect<T extends ScrapeResult>(scraper: Scraper<T>) {\n const collected: T[] = [];\n scraper.on(\"scraped\", (url: string, results: T[]) => {\n collected.push(...results);\n });\n await scraper.scrape();\n return collected;\n}",
"score": 0.824603796005249
}
] |
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": 0.8502689599990845
},
{
"filename": "src/scrapers/page-traverse-scraper.ts",
"retrieved_chunk": " }\n}\nexport class PageTraverseScraper<T extends Page = Page> extends TraverseScraper<T> {\n private readonly factory: (url: string, title: string) => T;\n constructor(baseUrl: string, factory?: (url: string, title: string) => T) {\n super(baseUrl);\n this.factory = factory ?? ((url: string, title: string) => new Page(url, title) as T);\n }\n /**\n * Scrapes a page for its URL and title, and returns a list of child URLs",
"score": 0.8389948606491089
},
{
"filename": "src/scrapers/traverse-scraper.ts",
"retrieved_chunk": "import { Scraper, ScrapeCallback } from './scraper.js';\nexport interface Scrapeable {\n childUrls: Set<string>;\n}\nexport class TraverseScraper<T extends Scrapeable> extends Scraper<T> {\n protected readonly traversedUrls: Set<string> = new Set();\n protected childPageFilter?: (url: string) => boolean;\n public setChildPageFilter(filter: (url: string) => boolean): void {\n this.childPageFilter = filter;\n }",
"score": 0.8358287215232849
},
{
"filename": "src/scrapers/page-traverse-scraper.ts",
"retrieved_chunk": "import { Scrapeable, TraverseScraper } from './traverse-scraper.js';\nimport { decodeEntities } from './decode-entities.js';\nimport { ScrapeCallback } from './scraper.js';\nexport class Page implements Scrapeable {\n public url: string;\n public title: string;\n public childUrls: Set<string> = new Set();\n constructor(url: string, title: string) {\n this.url = url;\n this.title = title;",
"score": 0.8066473007202148
},
{
"filename": "src/scrapers/json-scraper.ts",
"retrieved_chunk": " }\n public static makeScrapeCallback<T extends object = object>(): ScrapeCallback<T> {\n return (response: Response, content: string): T[] => {\n return JSON.parse(content);\n };\n }\n}",
"score": 0.8042469024658203
}
] |
typescript
|
public getScrapeCallback(): ScrapeCallback<Table<T>> {
|
import { ScrapeCallback, Scraper } from './scraper.js';
import { deserializeXml } from '../utils/xml.js';
export type WikiFunctionType = 'panelfunc' | 'classfunc' | 'libraryfunc' | 'hook';
export type Realm = 'Menu' | 'Client' | 'Server' | 'Shared' | 'Client and menu';
export type CommonWikiProperties = {
type: WikiFunctionType | 'enum' | 'struct' | 'panel';
address: string;
name: string;
description: string;
realm: Realm;
url: string;
}
export type WikiIdentifier = {
name: string;
type: string;
description?: string;
};
export type FunctionArgument = WikiIdentifier & {
default?: string;
};
export type FunctionReturn = WikiIdentifier & {};
export type Function = CommonWikiProperties & {
parent: string;
arguments?: FunctionArgument[];
returns?: FunctionReturn[];
};
export type ClassFunction = Function & {};
export type LibraryFunction = Function & {
type: 'libraryfunc';
dontDefineParent?: boolean;
};
export type HookFunction = Function & {
type: 'hook';
isHook: 'yes';
};
export type PanelFunction = Function & {
type: 'panelfunc';
isPanelFunction: 'yes';
};
export type EnumValue = {
key: string;
value: string;
description: string;
};
export type Enum = CommonWikiProperties & {
type: 'enum';
items: EnumValue[];
};
export type StructField = {
name: string;
type: string;
default?: any;
description: string;
};
export type Struct = CommonWikiProperties & {
type: 'struct';
fields: StructField[];
};
export type Panel = CommonWikiProperties & {
type: 'panel';
parent: string;
};
export type WikiPage = ClassFunction | LibraryFunction | HookFunction | PanelFunction | Panel | Enum | Struct;
/**
* Guards
*/
export function isClassFunction(page: WikiPage): page is ClassFunction {
return page.type === 'classfunc';
}
export function isLibraryFunction(page: WikiPage): page is LibraryFunction {
return page.type === 'libraryfunc';
}
export function isHookFunction(page: WikiPage): page is HookFunction {
return page.type === 'hook';
}
export function isPanelFunction(page: WikiPage): page is PanelFunction {
return page.type === 'panelfunc';
}
export function isPanel(page: WikiPage): page is Panel {
return page.type === 'panel';
}
export function isEnum(page: WikiPage): page is Enum {
return page.type === 'enum';
}
export function isStruct(page: WikiPage): page is Struct {
return page.type === 'struct';
}
/**
* Scraper
*/
export class WikiPageMarkupScraper extends Scraper<WikiPage> {
/**
* @param response The response from the page
* @param content The content of the request
*
* @returns A list containing only the scraped page
*/
public getScrapeCallback(): ScrapeCallback<WikiPage> {
return (response: Response, content: string): WikiPage[] => {
const page = deserializeXml<WikiPage | null>(content, ($) => {
const isEnum = $('enum').length > 0;
const isStruct = $('structure').length > 0;
const isFunction = $('function').length > 0;
const isPanel = $('panel').length > 0;
const mainElement = $(isEnum ? 'enum' : isStruct ? 'struct' : isPanel ? 'panel' : 'function');
const address = response.url.split('/').pop()!.split('?')[0];
if (isEnum) {
const items = $('items item').map(function () {
|
const $el = $(this);
|
return <EnumValue>{
key: $el.attr('key')!,
value: $el.attr('value')!,
description: $el.text()
};
}).get();
return <Enum>{
type: 'enum',
name: address,
address: address,
description: $('description').text(),
realm: $('realm').text() as Realm,
items
};
} else if (isStruct) {
const fields = $('fields item').map(function () {
const $el = $(this);
return <StructField>{
name: $el.attr('name')!,
type: $el.attr('type')!,
default: $el.attr('default'),
description: $el.text()
};
}).get();
return <Struct>{
type: 'struct',
name: address,
address: address,
description: $('description').text(),
realm: $('realm').text() as Realm,
fields
};
} else if (isPanel) {
return <Panel>{
type: 'panel',
name: address,
address: address,
description: $('description').text(),
realm: $('realm').text() as Realm,
parent: $('parent').text()
};
} else if (isFunction) {
const isClassFunction = mainElement.attr('type') === 'classfunc';
const isLibraryFunction = mainElement.attr('type') === 'libraryfunc';
const isHookFunction = mainElement.attr('type') === 'hook';
const isPanelFunction = mainElement.attr('type') === 'panelfunc';
const arguments_ = $('args arg').map(function() {
const $el = $(this);
const argument = <FunctionArgument> {
name: $el.attr('name')!,
type: $el.attr('type')!,
description: $el.text()
};
if ($el.attr('default'))
argument.default = $el.attr('default')!;
return argument;
}).get();
const returns = $('rets ret').map(function() {
const $el = $(this);
return <FunctionReturn> {
name: $el.attr('name')!,
type: $el.attr('type')!,
description: $el.text()
};
}).get();
const base = <Function> {
type: mainElement.attr('type')!,
parent: mainElement.attr('parent')!,
name: mainElement.attr('name')!,
address: address,
description: $('description:first').text(),
realm: $('realm:first').text() as Realm,
arguments: arguments_,
returns
};
if (isClassFunction) {
return <ClassFunction> {
...base,
type: 'classfunc'
};
} else if (isLibraryFunction) {
if (base.parent === 'Global') {
base.parent = '_G';
(<LibraryFunction>base).dontDefineParent = true;
}
return <LibraryFunction> {
...base,
type: 'libraryfunc'
};
} else if (isHookFunction) {
return <HookFunction> {
...base,
type: 'hook',
isHook: 'yes'
};
} else if (isPanelFunction) {
return <PanelFunction> {
...base,
type: 'panelfunc',
isPanelFunction: 'yes'
};
}
}
return null;
});
if (!page)
return [];
page.url = response.url.replace(/\?format=text$/, '');
return [page];
};
}
}
|
src/scrapers/wiki-page-markup-scraper.ts
|
luttje-glua-api-snippets-9f40376
|
[
{
"filename": "src/scrapers/page-traverse-scraper.ts",
"retrieved_chunk": " const title = decodeEntities(content.match(/<title>(.*?)<\\/title>/)?.[1] || '');\n const page = this.factory(url, title);\n const links = content.match(/<a\\s+(?:[^>]*?\\s+)?href=([\"'])([\\s\\S]*?)\\1(?:[^>]*?\\s+)?>(?:[\\s\\S]*?<\\/a>)?/gi)\n ?.map(link => link.replace(/\\n/g, ''))\n ?.map(link => link.match(/href=([\"'])([\\s\\S]*?)\\1/i)?.[2] || '') || [];\n for (let link of links) {\n link = decodeEntities(link);\n let absoluteUrl = link.startsWith('http') ? link : new URL(link, url).toString();\n if (page.childUrls.has(absoluteUrl))\n continue;",
"score": 0.8198434114456177
},
{
"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": 0.8179154992103577
},
{
"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": 0.8156849145889282
},
{
"filename": "src/utils/xml.ts",
"retrieved_chunk": "import * as cheerio from 'cheerio';\nexport function deserializeXml<T extends object | null>(xml: string, deserializer: ($: cheerio.CheerioAPI) => T): T {\n const $ = cheerio.load(xml, { xmlMode: true });\n return deserializer($);\n}",
"score": 0.8033176064491272
},
{
"filename": "src/scrapers/wiki-history-scraper.ts",
"retrieved_chunk": " const pages = await baseScrapeCallback(response, content);\n if (pages.length === 0)\n return [];\n // There is only one page per response\n const page = pages[0];\n const $ = cheerio.load(content);\n const changeElements = $('table.changelist > tbody > .entry');\n if (!changeElements)\n return [page];\n for (const changeElement of changeElements) {",
"score": 0.8030117750167847
}
] |
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/wiki-history-scraper.ts",
"retrieved_chunk": " * Scrapes a wiki history page for information on wiki changes\n * \n * @param response The response from the page\n * @param content The content of the request\n * \n * @returns A list containing only the scraped page\n */\n public getScrapeCallback(): ScrapeCallback<WikiHistoryPage> {\n const baseScrapeCallback = super.getScrapeCallback();\n return async (response: Response, content: string): Promise<WikiHistoryPage[]> => {",
"score": 0.917955219745636
},
{
"filename": "src/scrapers/page-traverse-scraper.ts",
"retrieved_chunk": " * \n * @param response The response from the page\n * @param content The content of the request\n * \n * @returns A list containing only the scraped page\n */\n public getScrapeCallback(): ScrapeCallback<T> {\n return (response: Response, content: string): T[] => {\n const results: T[] = [];\n const url = response.url;",
"score": 0.9063231945037842
},
{
"filename": "src/scrapers/json-scraper.ts",
"retrieved_chunk": "import { ScrapeCallback, Scraper } from './scraper.js';\nexport class JsonScraper<T extends object = object> extends Scraper<T> {\n /**\n * @param response The response from the page\n * @param content The content of the request\n * \n * @returns A list containing only the scraped page\n */\n public getScrapeCallback(): ScrapeCallback<T> {\n return JsonScraper.makeScrapeCallback<T>();",
"score": 0.8987113237380981
},
{
"filename": "src/scrapers/wiki-page-list-scraper.ts",
"retrieved_chunk": "import { JsonScraper } from './json-scraper.js';\nexport type WikiPageIndexObject = {\n address: string;\n updateCount: number;\n viewCount: number;\n}\nexport class WikiPageListScraper extends JsonScraper<WikiPageIndexObject> {}",
"score": 0.8216531276702881
},
{
"filename": "src/scrapers/wiki-history-scraper.ts",
"retrieved_chunk": "import { Page, PageTraverseScraper } from './page-traverse-scraper.js';\nimport { ScrapeCallback } from './scraper.js';\nimport * as cheerio from 'cheerio';\nexport interface WikiHistory {\n dateTime: Date;\n change: string;\n user: string;\n url: string;\n}\nexport class WikiHistoryPage extends Page {",
"score": 0.8183212280273438
}
] |
typescript
|
: ScrapeCallback<WikiPage> {
|
import { ScrapeCallback, Scraper } from './scraper.js';
import { deserializeXml } from '../utils/xml.js';
export type WikiFunctionType = 'panelfunc' | 'classfunc' | 'libraryfunc' | 'hook';
export type Realm = 'Menu' | 'Client' | 'Server' | 'Shared' | 'Client and menu';
export type CommonWikiProperties = {
type: WikiFunctionType | 'enum' | 'struct' | 'panel';
address: string;
name: string;
description: string;
realm: Realm;
url: string;
}
export type WikiIdentifier = {
name: string;
type: string;
description?: string;
};
export type FunctionArgument = WikiIdentifier & {
default?: string;
};
export type FunctionReturn = WikiIdentifier & {};
export type Function = CommonWikiProperties & {
parent: string;
arguments?: FunctionArgument[];
returns?: FunctionReturn[];
};
export type ClassFunction = Function & {};
export type LibraryFunction = Function & {
type: 'libraryfunc';
dontDefineParent?: boolean;
};
export type HookFunction = Function & {
type: 'hook';
isHook: 'yes';
};
export type PanelFunction = Function & {
type: 'panelfunc';
isPanelFunction: 'yes';
};
export type EnumValue = {
key: string;
value: string;
description: string;
};
export type Enum = CommonWikiProperties & {
type: 'enum';
items: EnumValue[];
};
export type StructField = {
name: string;
type: string;
default?: any;
description: string;
};
export type Struct = CommonWikiProperties & {
type: 'struct';
fields: StructField[];
};
export type Panel = CommonWikiProperties & {
type: 'panel';
parent: string;
};
export type WikiPage = ClassFunction | LibraryFunction | HookFunction | PanelFunction | Panel | Enum | Struct;
/**
* Guards
*/
export function isClassFunction(page: WikiPage): page is ClassFunction {
return page.type === 'classfunc';
}
export function isLibraryFunction(page: WikiPage): page is LibraryFunction {
return page.type === 'libraryfunc';
}
export function isHookFunction(page: WikiPage): page is HookFunction {
return page.type === 'hook';
}
export function isPanelFunction(page: WikiPage): page is PanelFunction {
return page.type === 'panelfunc';
}
export function isPanel(page: WikiPage): page is Panel {
return page.type === 'panel';
}
export function isEnum(page: WikiPage): page is Enum {
return page.type === 'enum';
}
export function isStruct(page: WikiPage): page is Struct {
return page.type === 'struct';
}
/**
* Scraper
*/
export class WikiPageMarkupScraper extends Scraper<WikiPage> {
/**
* @param response The response from the page
* @param content The content of the request
*
* @returns A list containing only the scraped page
*/
public getScrapeCallback(): ScrapeCallback<WikiPage> {
return (response: Response, content: string): WikiPage[] => {
|
const page = deserializeXml<WikiPage | null>(content, ($) => {
|
const isEnum = $('enum').length > 0;
const isStruct = $('structure').length > 0;
const isFunction = $('function').length > 0;
const isPanel = $('panel').length > 0;
const mainElement = $(isEnum ? 'enum' : isStruct ? 'struct' : isPanel ? 'panel' : 'function');
const address = response.url.split('/').pop()!.split('?')[0];
if (isEnum) {
const items = $('items item').map(function () {
const $el = $(this);
return <EnumValue>{
key: $el.attr('key')!,
value: $el.attr('value')!,
description: $el.text()
};
}).get();
return <Enum>{
type: 'enum',
name: address,
address: address,
description: $('description').text(),
realm: $('realm').text() as Realm,
items
};
} else if (isStruct) {
const fields = $('fields item').map(function () {
const $el = $(this);
return <StructField>{
name: $el.attr('name')!,
type: $el.attr('type')!,
default: $el.attr('default'),
description: $el.text()
};
}).get();
return <Struct>{
type: 'struct',
name: address,
address: address,
description: $('description').text(),
realm: $('realm').text() as Realm,
fields
};
} else if (isPanel) {
return <Panel>{
type: 'panel',
name: address,
address: address,
description: $('description').text(),
realm: $('realm').text() as Realm,
parent: $('parent').text()
};
} else if (isFunction) {
const isClassFunction = mainElement.attr('type') === 'classfunc';
const isLibraryFunction = mainElement.attr('type') === 'libraryfunc';
const isHookFunction = mainElement.attr('type') === 'hook';
const isPanelFunction = mainElement.attr('type') === 'panelfunc';
const arguments_ = $('args arg').map(function() {
const $el = $(this);
const argument = <FunctionArgument> {
name: $el.attr('name')!,
type: $el.attr('type')!,
description: $el.text()
};
if ($el.attr('default'))
argument.default = $el.attr('default')!;
return argument;
}).get();
const returns = $('rets ret').map(function() {
const $el = $(this);
return <FunctionReturn> {
name: $el.attr('name')!,
type: $el.attr('type')!,
description: $el.text()
};
}).get();
const base = <Function> {
type: mainElement.attr('type')!,
parent: mainElement.attr('parent')!,
name: mainElement.attr('name')!,
address: address,
description: $('description:first').text(),
realm: $('realm:first').text() as Realm,
arguments: arguments_,
returns
};
if (isClassFunction) {
return <ClassFunction> {
...base,
type: 'classfunc'
};
} else if (isLibraryFunction) {
if (base.parent === 'Global') {
base.parent = '_G';
(<LibraryFunction>base).dontDefineParent = true;
}
return <LibraryFunction> {
...base,
type: 'libraryfunc'
};
} else if (isHookFunction) {
return <HookFunction> {
...base,
type: 'hook',
isHook: 'yes'
};
} else if (isPanelFunction) {
return <PanelFunction> {
...base,
type: 'panelfunc',
isPanelFunction: 'yes'
};
}
}
return null;
});
if (!page)
return [];
page.url = response.url.replace(/\?format=text$/, '');
return [page];
};
}
}
|
src/scrapers/wiki-page-markup-scraper.ts
|
luttje-glua-api-snippets-9f40376
|
[
{
"filename": "src/scrapers/wiki-history-scraper.ts",
"retrieved_chunk": " * Scrapes a wiki history page for information on wiki changes\n * \n * @param response The response from the page\n * @param content The content of the request\n * \n * @returns A list containing only the scraped page\n */\n public getScrapeCallback(): ScrapeCallback<WikiHistoryPage> {\n const baseScrapeCallback = super.getScrapeCallback();\n return async (response: Response, content: string): Promise<WikiHistoryPage[]> => {",
"score": 0.9028290510177612
},
{
"filename": "src/scrapers/page-traverse-scraper.ts",
"retrieved_chunk": " * \n * @param response The response from the page\n * @param content The content of the request\n * \n * @returns A list containing only the scraped page\n */\n public getScrapeCallback(): ScrapeCallback<T> {\n return (response: Response, content: string): T[] => {\n const results: T[] = [];\n const url = response.url;",
"score": 0.8897448778152466
},
{
"filename": "src/scrapers/json-scraper.ts",
"retrieved_chunk": "import { ScrapeCallback, Scraper } from './scraper.js';\nexport class JsonScraper<T extends object = object> extends Scraper<T> {\n /**\n * @param response The response from the page\n * @param content The content of the request\n * \n * @returns A list containing only the scraped page\n */\n public getScrapeCallback(): ScrapeCallback<T> {\n return JsonScraper.makeScrapeCallback<T>();",
"score": 0.8849522471427917
},
{
"filename": "src/scrapers/wiki-history-scraper.ts",
"retrieved_chunk": " const pages = await baseScrapeCallback(response, content);\n if (pages.length === 0)\n return [];\n // There is only one page per response\n const page = pages[0];\n const $ = cheerio.load(content);\n const changeElements = $('table.changelist > tbody > .entry');\n if (!changeElements)\n return [page];\n for (const changeElement of changeElements) {",
"score": 0.8417693376541138
},
{
"filename": "src/scrapers/wiki-history-scraper.ts",
"retrieved_chunk": "import { Page, PageTraverseScraper } from './page-traverse-scraper.js';\nimport { ScrapeCallback } from './scraper.js';\nimport * as cheerio from 'cheerio';\nexport interface WikiHistory {\n dateTime: Date;\n change: string;\n user: string;\n url: string;\n}\nexport class WikiHistoryPage extends Page {",
"score": 0.8296225070953369
}
] |
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": 0.830459475517273
},
{
"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": 0.8284660577774048
},
{
"filename": "src/chat_gpt.ts",
"retrieved_chunk": " for (let i = 0; i < maxRetries; i++) {\n try {\n const completion = await openai.createChatCompletion({\n model: model,\n messages: messages,\n });\n return (completion.data!.choices[0]!.message?.content || \"\").trim();\n } catch (error: any) {\n if (error.response && (error.response.status === 429 || (error.response.status >= 500 && error.response.status < 600))) {\n const resetMs = parseInt(error.response.headers['x-ratelimit-reset-requests']) || 1000;",
"score": 0.822539746761322
},
{
"filename": "src/types.ts",
"retrieved_chunk": "export interface GolemTarget {\n dependencies: string[];\n prompt: string;\n model?: string; // Add this line\n task_generation_prompt?: string; // Add this line\n [key: string]: string[] | string | undefined;\n}\nexport type GolemFile = {\n default: string[];\n} & {",
"score": 0.7591139674186707
},
{
"filename": "src/golem.ts",
"retrieved_chunk": " const golemFilePath = argv.golemFile as string;\n // console.log(golemFilePath);\n // Add this line to create the .golem/ directory\n createGolemCacheDir();\n // Read the Golem file content\n const golemFileContent = fs.readFileSync(golemFilePath, 'utf8');\n const golemFile = parseGolemFile(golemFileContent);\n console.log(golemFile);\n // Execute the default target with an empty context\n await executeTarget('default', golemFile, golemFilePath, new Map());",
"score": 0.7550027370452881
}
] |
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/scrapers/wiki-history-scraper.ts",
"retrieved_chunk": " const pages = await baseScrapeCallback(response, content);\n if (pages.length === 0)\n return [];\n // There is only one page per response\n const page = pages[0];\n const $ = cheerio.load(content);\n const changeElements = $('table.changelist > tbody > .entry');\n if (!changeElements)\n return [page];\n for (const changeElement of changeElements) {",
"score": 0.8155045509338379
},
{
"filename": "src/scrapers/wiki-page-markup-scraper.ts",
"retrieved_chunk": " } else if (isFunction) {\n const isClassFunction = mainElement.attr('type') === 'classfunc';\n const isLibraryFunction = mainElement.attr('type') === 'libraryfunc';\n const isHookFunction = mainElement.attr('type') === 'hook';\n const isPanelFunction = mainElement.attr('type') === 'panelfunc';\n const arguments_ = $('args arg').map(function() {\n const $el = $(this);\n const argument = <FunctionArgument> {\n name: $el.attr('name')!,\n type: $el.attr('type')!,",
"score": 0.7819483280181885
},
{
"filename": "src/scrapers/wiki-page-markup-scraper.ts",
"retrieved_chunk": " type: $el.attr('type')!,\n description: $el.text()\n };\n }).get();\n const base = <Function> {\n type: mainElement.attr('type')!,\n parent: mainElement.attr('parent')!,\n name: mainElement.attr('name')!,\n address: address,\n description: $('description:first').text(),",
"score": 0.7789833545684814
},
{
"filename": "src/utils/xml.ts",
"retrieved_chunk": "import * as cheerio from 'cheerio';\nexport function deserializeXml<T extends object | null>(xml: string, deserializer: ($: cheerio.CheerioAPI) => T): T {\n const $ = cheerio.load(xml, { xmlMode: true });\n return deserializer($);\n}",
"score": 0.7738111019134521
},
{
"filename": "src/scrapers/page-traverse-scraper.ts",
"retrieved_chunk": " if (this.childPageFilter && !this.childPageFilter(absoluteUrl))\n continue;\n page.childUrls.add(absoluteUrl);\n }\n results.push(page);\n return results;\n };\n }\n}",
"score": 0.7678765058517456
}
] |
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": 0.8583518266677856
},
{
"filename": "src/cli-scraper.ts",
"retrieved_chunk": " return;\n const api = writer.writePages(pageMarkups);\n let fileName = pageIndex.address;\n let moduleName = fileName;\n if (fileName.includes('.') || fileName.includes(':') || fileName.includes('/')) {\n [moduleName, fileName] = fileName.split(/[:.\\/]/, 2);\n }\n // Make sure modules like Entity and ENTITY are placed in the same file.\n moduleName = moduleName.toLowerCase();\n const moduleFile = path.join(baseDirectory, moduleName);",
"score": 0.8460521697998047
},
{
"filename": "src/scrapers/wiki-page-markup-scraper.ts",
"retrieved_chunk": " parent: string;\n};\nexport type WikiPage = ClassFunction | LibraryFunction | HookFunction | PanelFunction | Panel | Enum | Struct;\n/**\n * Guards\n */\nexport function isClassFunction(page: WikiPage): page is ClassFunction {\n return page.type === 'classfunc';\n}\nexport function isLibraryFunction(page: WikiPage): page is LibraryFunction {",
"score": 0.8289405107498169
},
{
"filename": "src/scrapers/wiki-page-markup-scraper.ts",
"retrieved_chunk": " ...base,\n type: 'hook',\n isHook: 'yes'\n };\n } else if (isPanelFunction) {\n return <PanelFunction> {\n ...base,\n type: 'panelfunc',\n isPanelFunction: 'yes'\n };",
"score": 0.8242533802986145
},
{
"filename": "src/cli-scraper.ts",
"retrieved_chunk": " if (!fs.existsSync(`${moduleFile}.lua`))\n fs.writeFileSync(`${moduleFile}.lua`, '---@meta\\n\\n');\n if (!fs.existsSync(moduleFile))\n fs.mkdirSync(moduleFile, { recursive: true });\n fileName = fileName.replace(/[^a-z0-9]/gi, '_').toLowerCase();\n // Lua API\n fs.appendFileSync(path.join(baseDirectory, `${moduleName}.lua`), api);\n // JSON data\n const json = JSON.stringify(pageMarkups, null, 2);\n fs.writeFileSync(path.join(baseDirectory, moduleName, `${fileName}.json`), json);",
"score": 0.8169212341308594
}
] |
typescript
|
if (isPanel(page))
return this.writePanel(page);
|
import { ScrapeCallback, Scraper } from './scraper.js';
import { deserializeXml } from '../utils/xml.js';
export type WikiFunctionType = 'panelfunc' | 'classfunc' | 'libraryfunc' | 'hook';
export type Realm = 'Menu' | 'Client' | 'Server' | 'Shared' | 'Client and menu';
export type CommonWikiProperties = {
type: WikiFunctionType | 'enum' | 'struct' | 'panel';
address: string;
name: string;
description: string;
realm: Realm;
url: string;
}
export type WikiIdentifier = {
name: string;
type: string;
description?: string;
};
export type FunctionArgument = WikiIdentifier & {
default?: string;
};
export type FunctionReturn = WikiIdentifier & {};
export type Function = CommonWikiProperties & {
parent: string;
arguments?: FunctionArgument[];
returns?: FunctionReturn[];
};
export type ClassFunction = Function & {};
export type LibraryFunction = Function & {
type: 'libraryfunc';
dontDefineParent?: boolean;
};
export type HookFunction = Function & {
type: 'hook';
isHook: 'yes';
};
export type PanelFunction = Function & {
type: 'panelfunc';
isPanelFunction: 'yes';
};
export type EnumValue = {
key: string;
value: string;
description: string;
};
export type Enum = CommonWikiProperties & {
type: 'enum';
items: EnumValue[];
};
export type StructField = {
name: string;
type: string;
default?: any;
description: string;
};
export type Struct = CommonWikiProperties & {
type: 'struct';
fields: StructField[];
};
export type Panel = CommonWikiProperties & {
type: 'panel';
parent: string;
};
export type WikiPage = ClassFunction | LibraryFunction | HookFunction | PanelFunction | Panel | Enum | Struct;
/**
* Guards
*/
export function isClassFunction(page: WikiPage): page is ClassFunction {
return page.type === 'classfunc';
}
export function isLibraryFunction(page: WikiPage): page is LibraryFunction {
return page.type === 'libraryfunc';
}
export function isHookFunction(page: WikiPage): page is HookFunction {
return page.type === 'hook';
}
export function isPanelFunction(page: WikiPage): page is PanelFunction {
return page.type === 'panelfunc';
}
export function isPanel(page: WikiPage): page is Panel {
return page.type === 'panel';
}
export function isEnum(page: WikiPage): page is Enum {
return page.type === 'enum';
}
export function isStruct(page: WikiPage): page is Struct {
return page.type === 'struct';
}
/**
* Scraper
*/
export class WikiPageMarkupScraper extends
|
Scraper<WikiPage> {
|
/**
* @param response The response from the page
* @param content The content of the request
*
* @returns A list containing only the scraped page
*/
public getScrapeCallback(): ScrapeCallback<WikiPage> {
return (response: Response, content: string): WikiPage[] => {
const page = deserializeXml<WikiPage | null>(content, ($) => {
const isEnum = $('enum').length > 0;
const isStruct = $('structure').length > 0;
const isFunction = $('function').length > 0;
const isPanel = $('panel').length > 0;
const mainElement = $(isEnum ? 'enum' : isStruct ? 'struct' : isPanel ? 'panel' : 'function');
const address = response.url.split('/').pop()!.split('?')[0];
if (isEnum) {
const items = $('items item').map(function () {
const $el = $(this);
return <EnumValue>{
key: $el.attr('key')!,
value: $el.attr('value')!,
description: $el.text()
};
}).get();
return <Enum>{
type: 'enum',
name: address,
address: address,
description: $('description').text(),
realm: $('realm').text() as Realm,
items
};
} else if (isStruct) {
const fields = $('fields item').map(function () {
const $el = $(this);
return <StructField>{
name: $el.attr('name')!,
type: $el.attr('type')!,
default: $el.attr('default'),
description: $el.text()
};
}).get();
return <Struct>{
type: 'struct',
name: address,
address: address,
description: $('description').text(),
realm: $('realm').text() as Realm,
fields
};
} else if (isPanel) {
return <Panel>{
type: 'panel',
name: address,
address: address,
description: $('description').text(),
realm: $('realm').text() as Realm,
parent: $('parent').text()
};
} else if (isFunction) {
const isClassFunction = mainElement.attr('type') === 'classfunc';
const isLibraryFunction = mainElement.attr('type') === 'libraryfunc';
const isHookFunction = mainElement.attr('type') === 'hook';
const isPanelFunction = mainElement.attr('type') === 'panelfunc';
const arguments_ = $('args arg').map(function() {
const $el = $(this);
const argument = <FunctionArgument> {
name: $el.attr('name')!,
type: $el.attr('type')!,
description: $el.text()
};
if ($el.attr('default'))
argument.default = $el.attr('default')!;
return argument;
}).get();
const returns = $('rets ret').map(function() {
const $el = $(this);
return <FunctionReturn> {
name: $el.attr('name')!,
type: $el.attr('type')!,
description: $el.text()
};
}).get();
const base = <Function> {
type: mainElement.attr('type')!,
parent: mainElement.attr('parent')!,
name: mainElement.attr('name')!,
address: address,
description: $('description:first').text(),
realm: $('realm:first').text() as Realm,
arguments: arguments_,
returns
};
if (isClassFunction) {
return <ClassFunction> {
...base,
type: 'classfunc'
};
} else if (isLibraryFunction) {
if (base.parent === 'Global') {
base.parent = '_G';
(<LibraryFunction>base).dontDefineParent = true;
}
return <LibraryFunction> {
...base,
type: 'libraryfunc'
};
} else if (isHookFunction) {
return <HookFunction> {
...base,
type: 'hook',
isHook: 'yes'
};
} else if (isPanelFunction) {
return <PanelFunction> {
...base,
type: 'panelfunc',
isPanelFunction: 'yes'
};
}
}
return null;
});
if (!page)
return [];
page.url = response.url.replace(/\?format=text$/, '');
return [page];
};
}
}
|
src/scrapers/wiki-page-markup-scraper.ts
|
luttje-glua-api-snippets-9f40376
|
[
{
"filename": "src/scrapers/wiki-page-list-scraper.ts",
"retrieved_chunk": "import { JsonScraper } from './json-scraper.js';\nexport type WikiPageIndexObject = {\n address: string;\n updateCount: number;\n viewCount: number;\n}\nexport class WikiPageListScraper extends JsonScraper<WikiPageIndexObject> {}",
"score": 0.8502095341682434
},
{
"filename": "src/scrapers/wiki-history-scraper.ts",
"retrieved_chunk": "import { Page, PageTraverseScraper } from './page-traverse-scraper.js';\nimport { ScrapeCallback } from './scraper.js';\nimport * as cheerio from 'cheerio';\nexport interface WikiHistory {\n dateTime: Date;\n change: string;\n user: string;\n url: string;\n}\nexport class WikiHistoryPage extends Page {",
"score": 0.8460687398910522
},
{
"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": 0.824928343296051
},
{
"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": 0.8224440813064575
},
{
"filename": "src/scrapers/wiki-history-scraper.ts",
"retrieved_chunk": " public history: WikiHistory[] = [];\n constructor(url: string, title: string) {\n super(url, title);\n }\n}\nexport class WikiHistoryPageScraper extends PageTraverseScraper<WikiHistoryPage> {\n constructor(baseUrl: string) {\n super(baseUrl, (url: string, title: string) => new WikiHistoryPage(url, title));\n }\n /**",
"score": 0.8175444602966309
}
] |
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/scrapers/wiki-page-markup-scraper.ts",
"retrieved_chunk": " const isEnum = $('enum').length > 0;\n const isStruct = $('structure').length > 0;\n const isFunction = $('function').length > 0;\n const isPanel = $('panel').length > 0;\n const mainElement = $(isEnum ? 'enum' : isStruct ? 'struct' : isPanel ? 'panel' : 'function');\n const address = response.url.split('/').pop()!.split('?')[0];\n if (isEnum) {\n const items = $('items item').map(function () {\n const $el = $(this);\n return <EnumValue>{",
"score": 0.8174684643745422
},
{
"filename": "src/scrapers/wiki-page-markup-scraper.ts",
"retrieved_chunk": "};\nexport type HookFunction = Function & {\n type: 'hook';\n isHook: 'yes';\n};\nexport type PanelFunction = Function & {\n type: 'panelfunc';\n isPanelFunction: 'yes';\n};\nexport type EnumValue = {",
"score": 0.8144251704216003
},
{
"filename": "src/scrapers/wiki-page-markup-scraper.ts",
"retrieved_chunk": " key: string;\n value: string;\n description: string;\n};\nexport type Enum = CommonWikiProperties & {\n type: 'enum';\n items: EnumValue[];\n};\nexport type StructField = {\n name: string;",
"score": 0.7847121357917786
},
{
"filename": "src/scrapers/wiki-page-markup-scraper.ts",
"retrieved_chunk": " } else if (isFunction) {\n const isClassFunction = mainElement.attr('type') === 'classfunc';\n const isLibraryFunction = mainElement.attr('type') === 'libraryfunc';\n const isHookFunction = mainElement.attr('type') === 'hook';\n const isPanelFunction = mainElement.attr('type') === 'panelfunc';\n const arguments_ = $('args arg').map(function() {\n const $el = $(this);\n const argument = <FunctionArgument> {\n name: $el.attr('name')!,\n type: $el.attr('type')!,",
"score": 0.7845082879066467
},
{
"filename": "src/scrapers/wiki-page-markup-scraper.ts",
"retrieved_chunk": " ...base,\n type: 'hook',\n isHook: 'yes'\n };\n } else if (isPanelFunction) {\n return <PanelFunction> {\n ...base,\n type: 'panelfunc',\n isPanelFunction: 'yes'\n };",
"score": 0.7779809236526489
}
] |
typescript
|
const isContainedInTable = _enum.items[0]?.key.includes('.') ?? false;
|
import { ScrapeCallback, Scraper } from './scraper.js';
import { deserializeXml } from '../utils/xml.js';
export type WikiFunctionType = 'panelfunc' | 'classfunc' | 'libraryfunc' | 'hook';
export type Realm = 'Menu' | 'Client' | 'Server' | 'Shared' | 'Client and menu';
export type CommonWikiProperties = {
type: WikiFunctionType | 'enum' | 'struct' | 'panel';
address: string;
name: string;
description: string;
realm: Realm;
url: string;
}
export type WikiIdentifier = {
name: string;
type: string;
description?: string;
};
export type FunctionArgument = WikiIdentifier & {
default?: string;
};
export type FunctionReturn = WikiIdentifier & {};
export type Function = CommonWikiProperties & {
parent: string;
arguments?: FunctionArgument[];
returns?: FunctionReturn[];
};
export type ClassFunction = Function & {};
export type LibraryFunction = Function & {
type: 'libraryfunc';
dontDefineParent?: boolean;
};
export type HookFunction = Function & {
type: 'hook';
isHook: 'yes';
};
export type PanelFunction = Function & {
type: 'panelfunc';
isPanelFunction: 'yes';
};
export type EnumValue = {
key: string;
value: string;
description: string;
};
export type Enum = CommonWikiProperties & {
type: 'enum';
items: EnumValue[];
};
export type StructField = {
name: string;
type: string;
default?: any;
description: string;
};
export type Struct = CommonWikiProperties & {
type: 'struct';
fields: StructField[];
};
export type Panel = CommonWikiProperties & {
type: 'panel';
parent: string;
};
export type WikiPage = ClassFunction | LibraryFunction | HookFunction | PanelFunction | Panel | Enum | Struct;
/**
* Guards
*/
export function isClassFunction(page: WikiPage): page is ClassFunction {
return page.type === 'classfunc';
}
export function isLibraryFunction(page: WikiPage): page is LibraryFunction {
return page.type === 'libraryfunc';
}
export function isHookFunction(page: WikiPage): page is HookFunction {
return page.type === 'hook';
}
export function isPanelFunction(page: WikiPage): page is PanelFunction {
return page.type === 'panelfunc';
}
export function isPanel(page: WikiPage): page is Panel {
return page.type === 'panel';
}
export function isEnum(page: WikiPage): page is Enum {
return page.type === 'enum';
}
export function isStruct(page: WikiPage): page is Struct {
return page.type === 'struct';
}
/**
* Scraper
*/
export
|
class WikiPageMarkupScraper extends Scraper<WikiPage> {
|
/**
* @param response The response from the page
* @param content The content of the request
*
* @returns A list containing only the scraped page
*/
public getScrapeCallback(): ScrapeCallback<WikiPage> {
return (response: Response, content: string): WikiPage[] => {
const page = deserializeXml<WikiPage | null>(content, ($) => {
const isEnum = $('enum').length > 0;
const isStruct = $('structure').length > 0;
const isFunction = $('function').length > 0;
const isPanel = $('panel').length > 0;
const mainElement = $(isEnum ? 'enum' : isStruct ? 'struct' : isPanel ? 'panel' : 'function');
const address = response.url.split('/').pop()!.split('?')[0];
if (isEnum) {
const items = $('items item').map(function () {
const $el = $(this);
return <EnumValue>{
key: $el.attr('key')!,
value: $el.attr('value')!,
description: $el.text()
};
}).get();
return <Enum>{
type: 'enum',
name: address,
address: address,
description: $('description').text(),
realm: $('realm').text() as Realm,
items
};
} else if (isStruct) {
const fields = $('fields item').map(function () {
const $el = $(this);
return <StructField>{
name: $el.attr('name')!,
type: $el.attr('type')!,
default: $el.attr('default'),
description: $el.text()
};
}).get();
return <Struct>{
type: 'struct',
name: address,
address: address,
description: $('description').text(),
realm: $('realm').text() as Realm,
fields
};
} else if (isPanel) {
return <Panel>{
type: 'panel',
name: address,
address: address,
description: $('description').text(),
realm: $('realm').text() as Realm,
parent: $('parent').text()
};
} else if (isFunction) {
const isClassFunction = mainElement.attr('type') === 'classfunc';
const isLibraryFunction = mainElement.attr('type') === 'libraryfunc';
const isHookFunction = mainElement.attr('type') === 'hook';
const isPanelFunction = mainElement.attr('type') === 'panelfunc';
const arguments_ = $('args arg').map(function() {
const $el = $(this);
const argument = <FunctionArgument> {
name: $el.attr('name')!,
type: $el.attr('type')!,
description: $el.text()
};
if ($el.attr('default'))
argument.default = $el.attr('default')!;
return argument;
}).get();
const returns = $('rets ret').map(function() {
const $el = $(this);
return <FunctionReturn> {
name: $el.attr('name')!,
type: $el.attr('type')!,
description: $el.text()
};
}).get();
const base = <Function> {
type: mainElement.attr('type')!,
parent: mainElement.attr('parent')!,
name: mainElement.attr('name')!,
address: address,
description: $('description:first').text(),
realm: $('realm:first').text() as Realm,
arguments: arguments_,
returns
};
if (isClassFunction) {
return <ClassFunction> {
...base,
type: 'classfunc'
};
} else if (isLibraryFunction) {
if (base.parent === 'Global') {
base.parent = '_G';
(<LibraryFunction>base).dontDefineParent = true;
}
return <LibraryFunction> {
...base,
type: 'libraryfunc'
};
} else if (isHookFunction) {
return <HookFunction> {
...base,
type: 'hook',
isHook: 'yes'
};
} else if (isPanelFunction) {
return <PanelFunction> {
...base,
type: 'panelfunc',
isPanelFunction: 'yes'
};
}
}
return null;
});
if (!page)
return [];
page.url = response.url.replace(/\?format=text$/, '');
return [page];
};
}
}
|
src/scrapers/wiki-page-markup-scraper.ts
|
luttje-glua-api-snippets-9f40376
|
[
{
"filename": "src/scrapers/wiki-page-list-scraper.ts",
"retrieved_chunk": "import { JsonScraper } from './json-scraper.js';\nexport type WikiPageIndexObject = {\n address: string;\n updateCount: number;\n viewCount: number;\n}\nexport class WikiPageListScraper extends JsonScraper<WikiPageIndexObject> {}",
"score": 0.8496049642562866
},
{
"filename": "src/scrapers/wiki-history-scraper.ts",
"retrieved_chunk": "import { Page, PageTraverseScraper } from './page-traverse-scraper.js';\nimport { ScrapeCallback } from './scraper.js';\nimport * as cheerio from 'cheerio';\nexport interface WikiHistory {\n dateTime: Date;\n change: string;\n user: string;\n url: string;\n}\nexport class WikiHistoryPage extends Page {",
"score": 0.8450355529785156
},
{
"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": 0.8271328210830688
},
{
"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": 0.825940728187561
},
{
"filename": "src/scrapers/wiki-history-scraper.ts",
"retrieved_chunk": " public history: WikiHistory[] = [];\n constructor(url: string, title: string) {\n super(url, title);\n }\n}\nexport class WikiHistoryPageScraper extends PageTraverseScraper<WikiHistoryPage> {\n constructor(baseUrl: string) {\n super(baseUrl, (url: string, title: string) => new WikiHistoryPage(url, title));\n }\n /**",
"score": 0.8163002133369446
}
] |
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": 0.8132529258728027
},
{
"filename": "src/scrapers/wiki-page-markup-scraper.ts",
"retrieved_chunk": " realm: $('realm:first').text() as Realm,\n arguments: arguments_,\n returns\n };\n if (isClassFunction) {\n return <ClassFunction> {\n ...base,\n type: 'classfunc'\n };\n } else if (isLibraryFunction) {",
"score": 0.8083304166793823
},
{
"filename": "src/scrapers/wiki-page-markup-scraper.ts",
"retrieved_chunk": "export type FunctionReturn = WikiIdentifier & {};\nexport type Function = CommonWikiProperties & {\n parent: string;\n arguments?: FunctionArgument[];\n returns?: FunctionReturn[];\n};\nexport type ClassFunction = Function & {};\nexport type LibraryFunction = Function & {\n type: 'libraryfunc';\n dontDefineParent?: boolean;",
"score": 0.7961181998252869
},
{
"filename": "src/scrapers/wiki-page-markup-scraper.ts",
"retrieved_chunk": " } else if (isFunction) {\n const isClassFunction = mainElement.attr('type') === 'classfunc';\n const isLibraryFunction = mainElement.attr('type') === 'libraryfunc';\n const isHookFunction = mainElement.attr('type') === 'hook';\n const isPanelFunction = mainElement.attr('type') === 'panelfunc';\n const arguments_ = $('args arg').map(function() {\n const $el = $(this);\n const argument = <FunctionArgument> {\n name: $el.attr('name')!,\n type: $el.attr('type')!,",
"score": 0.7843483686447144
},
{
"filename": "src/cli-scraper.ts",
"retrieved_chunk": " if (!fs.existsSync(`${moduleFile}.lua`))\n fs.writeFileSync(`${moduleFile}.lua`, '---@meta\\n\\n');\n if (!fs.existsSync(moduleFile))\n fs.mkdirSync(moduleFile, { recursive: true });\n fileName = fileName.replace(/[^a-z0-9]/gi, '_').toLowerCase();\n // Lua API\n fs.appendFileSync(path.join(baseDirectory, `${moduleName}.lua`), api);\n // JSON data\n const json = JSON.stringify(pageMarkups, null, 2);\n fs.writeFileSync(path.join(baseDirectory, moduleName, `${fileName}.json`), json);",
"score": 0.7840530872344971
}
] |
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/wiki-history-scraper.ts",
"retrieved_chunk": " * Scrapes a wiki history page for information on wiki changes\n * \n * @param response The response from the page\n * @param content The content of the request\n * \n * @returns A list containing only the scraped page\n */\n public getScrapeCallback(): ScrapeCallback<WikiHistoryPage> {\n const baseScrapeCallback = super.getScrapeCallback();\n return async (response: Response, content: string): Promise<WikiHistoryPage[]> => {",
"score": 0.9152942895889282
},
{
"filename": "src/scrapers/page-traverse-scraper.ts",
"retrieved_chunk": " * \n * @param response The response from the page\n * @param content The content of the request\n * \n * @returns A list containing only the scraped page\n */\n public getScrapeCallback(): ScrapeCallback<T> {\n return (response: Response, content: string): T[] => {\n const results: T[] = [];\n const url = response.url;",
"score": 0.8967058658599854
},
{
"filename": "src/scrapers/json-scraper.ts",
"retrieved_chunk": "import { ScrapeCallback, Scraper } from './scraper.js';\nexport class JsonScraper<T extends object = object> extends Scraper<T> {\n /**\n * @param response The response from the page\n * @param content The content of the request\n * \n * @returns A list containing only the scraped page\n */\n public getScrapeCallback(): ScrapeCallback<T> {\n return JsonScraper.makeScrapeCallback<T>();",
"score": 0.8887556195259094
},
{
"filename": "src/scrapers/wiki-page-list-scraper.ts",
"retrieved_chunk": "import { JsonScraper } from './json-scraper.js';\nexport type WikiPageIndexObject = {\n address: string;\n updateCount: number;\n viewCount: number;\n}\nexport class WikiPageListScraper extends JsonScraper<WikiPageIndexObject> {}",
"score": 0.816999614238739
},
{
"filename": "src/scrapers/wiki-history-scraper.ts",
"retrieved_chunk": "import { Page, PageTraverseScraper } from './page-traverse-scraper.js';\nimport { ScrapeCallback } from './scraper.js';\nimport * as cheerio from 'cheerio';\nexport interface WikiHistory {\n dateTime: Date;\n change: string;\n user: string;\n url: string;\n}\nexport class WikiHistoryPage extends Page {",
"score": 0.8153631687164307
}
] |
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": 0.8708968162536621
},
{
"filename": "src/scrapers/page-traverse-scraper.ts",
"retrieved_chunk": "import { Scrapeable, TraverseScraper } from './traverse-scraper.js';\nimport { decodeEntities } from './decode-entities.js';\nimport { ScrapeCallback } from './scraper.js';\nexport class Page implements Scrapeable {\n public url: string;\n public title: string;\n public childUrls: Set<string> = new Set();\n constructor(url: string, title: string) {\n this.url = url;\n this.title = title;",
"score": 0.8384217619895935
},
{
"filename": "src/scrapers/page-traverse-scraper.ts",
"retrieved_chunk": " }\n}\nexport class PageTraverseScraper<T extends Page = Page> extends TraverseScraper<T> {\n private readonly factory: (url: string, title: string) => T;\n constructor(baseUrl: string, factory?: (url: string, title: string) => T) {\n super(baseUrl);\n this.factory = factory ?? ((url: string, title: string) => new Page(url, title) as T);\n }\n /**\n * Scrapes a page for its URL and title, and returns a list of child URLs",
"score": 0.8318277597427368
},
{
"filename": "src/scrapers/page-traverse-scraper.ts",
"retrieved_chunk": " if (this.childPageFilter && !this.childPageFilter(absoluteUrl))\n continue;\n page.childUrls.add(absoluteUrl);\n }\n results.push(page);\n return results;\n };\n }\n}",
"score": 0.827082633972168
},
{
"filename": "src/scrapers/page-traverse-scraper.ts",
"retrieved_chunk": " const title = decodeEntities(content.match(/<title>(.*?)<\\/title>/)?.[1] || '');\n const page = this.factory(url, title);\n const links = content.match(/<a\\s+(?:[^>]*?\\s+)?href=([\"'])([\\s\\S]*?)\\1(?:[^>]*?\\s+)?>(?:[\\s\\S]*?<\\/a>)?/gi)\n ?.map(link => link.replace(/\\n/g, ''))\n ?.map(link => link.match(/href=([\"'])([\\s\\S]*?)\\1/i)?.[2] || '') || [];\n for (let link of links) {\n link = decodeEntities(link);\n let absoluteUrl = link.startsWith('http') ? link : new URL(link, url).toString();\n if (page.childUrls.has(absoluteUrl))\n continue;",
"score": 0.815414309501648
}
] |
typescript
|
(url: string, callback?: ScrapeCallback<T>): Promise<void> {
|
import { Scrapeable, TraverseScraper } from './traverse-scraper.js';
import { ScrapeCallback } from './scraper.js';
import * as cheerio from 'cheerio';
import "reflect-metadata";
const tableColumnMetadataKey = Symbol("tableColumn");
export type TableColumnDefinition = {
propertyKey: string | symbol,
columnName: string,
typeConverter: (value: string) => any
};
export function tableColumn(columnName: string): PropertyDecorator {
return (target: object, propertyKey: string | symbol) => {
const existingColumns: TableColumnDefinition[] = Reflect.getMetadata(tableColumnMetadataKey, target) || [];
const propertyType = Reflect.getMetadata("design:type", target, propertyKey);
existingColumns.push({
propertyKey,
columnName,
typeConverter: (value: string) => {
switch (propertyType) {
case String:
return value;
case Number:
return Number(value);
case Boolean:
return Boolean(value);
default:
return value;
}
}
});
Reflect.defineMetadata(tableColumnMetadataKey, existingColumns, target);
};
}
export function getTableColumns(target: object): TableColumnDefinition[] {
return Reflect.getMetadata(tableColumnMetadataKey, target) || [];
}
export class Row<T> {
constructor(public data: T) { }
}
export class Table<T> implements Scrapeable {
public url: string;
public childUrls: Set<string> = new Set();
constructor(url: string, public rows: Row<T>[] = []) {
this.url = url;
}
public addRow(row: Row<T>) {
this.rows.push(row);
}
}
export class TableScraper<T
|
extends object> extends TraverseScraper<Table<T>> {
|
constructor(baseUrl: string, private readonly factory: () => T) {
super(baseUrl);
}
public getScrapeCallback(): ScrapeCallback<Table<T>> {
return (response: Response, content: string): Table<T>[] => {
const results: Table<T>[] = [];
const $ = cheerio.load(content);
const tables = $('table');
for (const table of tables) {
const tableResult = this.fromTableElement($, table);
if (tableResult)
results.push(tableResult);
}
return results;
};
}
private fromTableElement($: cheerio.CheerioAPI, tableElement: cheerio.Element): Table<T> | null {
const tableResult = new Table<T>(this.baseUrl);
let headingRows = $(tableElement).find('thead > tr');
let shouldTrimHeadings = false;
if (headingRows.length === 0) {
headingRows = $(tableElement).find('tbody > tr:first-child');
shouldTrimHeadings = true;
}
let headings : cheerio.Element[] | undefined;
if (headingRows.length > 0)
headings = $(headingRows[0]).find('th').toArray();
if (!headings || headings.length === 0)
throw new Error('No headings found in table');
let rows = $(tableElement).find('tbody > tr').toArray();
if (rows.length === 0)
rows = $(tableElement).find('tr').toArray();
if (shouldTrimHeadings)
rows = rows.slice(headingRows.length);
let isEmpty = true;
for (const row of rows) {
const rowResult = this.fromRowElement($, row, headings);
if (rowResult === null)
continue;
tableResult.addRow(rowResult);
isEmpty = false;
}
if (isEmpty)
return null;
return tableResult;
}
private fromRowElement($: cheerio.CheerioAPI, rowElement: cheerio.Element, headings: cheerio.Element[]): Row<T> | null {
const cells = $(rowElement).find('td').toArray();
const rowResult = this.factory();
const allTableColumns = getTableColumns(rowResult);
let isEmpty = true;
for (let i = 0; i < cells.length; i++) {
const cell = cells[i];
const heading = headings[i];
if (!heading)
continue;
const headingText = $(heading).text();
if (!headingText)
continue;
let tableColumnDefinition = allTableColumns.find(column => column.columnName === headingText);
if (!tableColumnDefinition) {
const properties = Object.getOwnPropertyNames(rowResult);
const propertyKey = properties.find(property => property.toLowerCase() === headingText.toLowerCase());
if (!propertyKey)
continue;
tableColumnDefinition = {
propertyKey,
columnName: headingText,
typeConverter: (value: string) => value
};
}
const cellText = $(cell).text();
if (!cellText)
continue;
(rowResult as any)[tableColumnDefinition.propertyKey] = tableColumnDefinition.typeConverter(cellText);
isEmpty = false;
}
if (isEmpty)
return null;
return new Row<T>(rowResult);
}
}
|
src/scrapers/table-scraper.ts
|
luttje-glua-api-snippets-9f40376
|
[
{
"filename": "src/scrapers/traverse-scraper.ts",
"retrieved_chunk": "import { Scraper, ScrapeCallback } from './scraper.js';\nexport interface Scrapeable {\n childUrls: Set<string>;\n}\nexport class TraverseScraper<T extends Scrapeable> extends Scraper<T> {\n protected readonly traversedUrls: Set<string> = new Set();\n protected childPageFilter?: (url: string) => boolean;\n public setChildPageFilter(filter: (url: string) => boolean): void {\n this.childPageFilter = filter;\n }",
"score": 0.8768327236175537
},
{
"filename": "src/scrapers/page-traverse-scraper.ts",
"retrieved_chunk": "import { Scrapeable, TraverseScraper } from './traverse-scraper.js';\nimport { decodeEntities } from './decode-entities.js';\nimport { ScrapeCallback } from './scraper.js';\nexport class Page implements Scrapeable {\n public url: string;\n public title: string;\n public childUrls: Set<string> = new Set();\n constructor(url: string, title: string) {\n this.url = url;\n this.title = title;",
"score": 0.8533541560173035
},
{
"filename": "src/scrapers/page-traverse-scraper.ts",
"retrieved_chunk": " }\n}\nexport class PageTraverseScraper<T extends Page = Page> extends TraverseScraper<T> {\n private readonly factory: (url: string, title: string) => T;\n constructor(baseUrl: string, factory?: (url: string, title: string) => T) {\n super(baseUrl);\n this.factory = factory ?? ((url: string, title: string) => new Page(url, title) as T);\n }\n /**\n * Scrapes a page for its URL and title, and returns a list of child URLs",
"score": 0.8332610130310059
},
{
"filename": "src/scrapers/scraper.ts",
"retrieved_chunk": "export class Scraper<T extends ScrapeResult> extends TypedEventEmitter<ScraperEvents<T>> {\n protected retryOptions: RequestInitWithRetry = {};\n constructor(\n protected readonly baseUrl: string,\n protected readonly scrapeCallback?: ScrapeCallback<T>\n ) { \n super();\n }\n public getScrapeCallback(): ScrapeCallback<T> {\n return this.scrapeCallback || ((_: Response, __: string): T[] => []);",
"score": 0.818970799446106
},
{
"filename": "src/scrapers/wiki-history-scraper.ts",
"retrieved_chunk": " public history: WikiHistory[] = [];\n constructor(url: string, title: string) {\n super(url, title);\n }\n}\nexport class WikiHistoryPageScraper extends PageTraverseScraper<WikiHistoryPage> {\n constructor(baseUrl: string) {\n super(baseUrl, (url: string, title: string) => new WikiHistoryPage(url, title));\n }\n /**",
"score": 0.8110437393188477
}
] |
typescript
|
extends object> extends TraverseScraper<Table<T>> {
|
import { Scraper, ScrapeCallback } from './scraper.js';
export interface Scrapeable {
childUrls: Set<string>;
}
export class TraverseScraper<T extends Scrapeable> extends Scraper<T> {
protected readonly traversedUrls: Set<string> = new Set();
protected childPageFilter?: (url: string) => boolean;
public setChildPageFilter(filter: (url: string) => boolean): void {
this.childPageFilter = filter;
}
/**
* Override scraping so we traverse all child URLs of the first scraped page
*/
public async scrape(): Promise<void> {
const callback = this.getScrapeCallback();
await this.traverse(this.baseUrl, callback.bind(this));
}
protected getTraverseUrl(url: string): string | false {
if (!url.startsWith(this.baseUrl))
return false;
if (url.endsWith('/'))
url = url.substring(0, url.length - 1);
if (url.includes('#'))
url = url.substring(0, url.indexOf('#'));
if (this.traversedUrls.has(url))
return false;
if (this.childPageFilter && !this.childPageFilter(url))
return false;
return url;
}
public async traverse(url: string, callback?: ScrapeCallback<T>): Promise<void> {
if (!callback)
callback = this.getScrapeCallback();
const urlsToTraverse: string[] = [url];
while (urlsToTraverse.length > 0) {
let currentUrl = urlsToTraverse.shift()!;
let url = this.getTraverseUrl(currentUrl);
if (!url)
continue;
const currentResults
|
= await this.visitOne(url, callback);
|
this.traversedUrls.add(url);
for (const result of currentResults) {
for (const childUrl of result.childUrls) {
const traverseUrl = this.getTraverseUrl(childUrl);
if (traverseUrl && !urlsToTraverse.includes(traverseUrl))
urlsToTraverse.push(traverseUrl);
}
}
}
}
}
|
src/scrapers/traverse-scraper.ts
|
luttje-glua-api-snippets-9f40376
|
[
{
"filename": "src/scrapers/scraper.ts",
"retrieved_chunk": " }\n public async visitOne(url: string, callback?: ScrapeCallback<T>): Promise<T[]> {\n if (!callback)\n callback = this.getScrapeCallback();\n if (!!process.env.VERBOSE_LOGGING)\n console.debug(`Scraping ${url}...`);\n this.emit('beforescrape', url);\n let response;\n let content;\n try {",
"score": 0.9122405052185059
},
{
"filename": "src/scrapers/scraper.ts",
"retrieved_chunk": " response = await fetch(url, this.retryOptions);\n content = await response.text();\n } catch (e) {\n console.warn(`Error fetching ${url}: ${e}`);\n return [];\n }\n const scrapedResults = await callback(response, content);\n this.emit('scraped', url, scrapedResults);\n return scrapedResults;\n }",
"score": 0.871872067451477
},
{
"filename": "src/scrapers/scraper.ts",
"retrieved_chunk": " }\n public setRetryOptions(options: RequestInitWithRetry): void {\n this.retryOptions = options;\n }\n /**\n * Scrapes the base url and has the callback process the response\n */\n public async scrape(): Promise<void> {\n const callback = this.getScrapeCallback();\n await this.visitOne(this.baseUrl, callback);",
"score": 0.849016547203064
},
{
"filename": "src/scrapers/page-traverse-scraper.ts",
"retrieved_chunk": " }\n}\nexport class PageTraverseScraper<T extends Page = Page> extends TraverseScraper<T> {\n private readonly factory: (url: string, title: string) => T;\n constructor(baseUrl: string, factory?: (url: string, title: string) => T) {\n super(baseUrl);\n this.factory = factory ?? ((url: string, title: string) => new Page(url, title) as T);\n }\n /**\n * Scrapes a page for its URL and title, and returns a list of child URLs",
"score": 0.8304620981216431
},
{
"filename": "src/scrapers/collector.ts",
"retrieved_chunk": "import { Scraper, ScrapeResult } from \"./scraper.js\";\nexport async function scrapeAndCollect<T extends ScrapeResult>(scraper: Scraper<T>) {\n const collected: T[] = [];\n scraper.on(\"scraped\", (url: string, results: T[]) => {\n collected.push(...results);\n });\n await scraper.scrape();\n return collected;\n}",
"score": 0.8283389210700989
}
] |
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": 0.800044596195221
},
{
"filename": "src/scrapers/wiki-page-markup-scraper.ts",
"retrieved_chunk": " description: $el.text()\n };\n if ($el.attr('default'))\n argument.default = $el.attr('default')!;\n return argument;\n }).get();\n const returns = $('rets ret').map(function() {\n const $el = $(this);\n return <FunctionReturn> {\n name: $el.attr('name')!,",
"score": 0.7972303032875061
},
{
"filename": "src/cli-scraper.ts",
"retrieved_chunk": " if (!fs.existsSync(`${moduleFile}.lua`))\n fs.writeFileSync(`${moduleFile}.lua`, '---@meta\\n\\n');\n if (!fs.existsSync(moduleFile))\n fs.mkdirSync(moduleFile, { recursive: true });\n fileName = fileName.replace(/[^a-z0-9]/gi, '_').toLowerCase();\n // Lua API\n fs.appendFileSync(path.join(baseDirectory, `${moduleName}.lua`), api);\n // JSON data\n const json = JSON.stringify(pageMarkups, null, 2);\n fs.writeFileSync(path.join(baseDirectory, moduleName, `${fileName}.json`), json);",
"score": 0.7826370596885681
},
{
"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": 0.7805397510528564
},
{
"filename": "src/scrapers/wiki-page-markup-scraper.ts",
"retrieved_chunk": " realm: $('realm:first').text() as Realm,\n arguments: arguments_,\n returns\n };\n if (isClassFunction) {\n return <ClassFunction> {\n ...base,\n type: 'classfunc'\n };\n } else if (isLibraryFunction) {",
"score": 0.7746621370315552
}
] |
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/scrapers/wiki-page-list-scraper.ts",
"retrieved_chunk": "import { JsonScraper } from './json-scraper.js';\nexport type WikiPageIndexObject = {\n address: string;\n updateCount: number;\n viewCount: number;\n}\nexport class WikiPageListScraper extends JsonScraper<WikiPageIndexObject> {}",
"score": 0.8532710075378418
},
{
"filename": "src/scrapers/wiki-history-scraper.ts",
"retrieved_chunk": "import { Page, PageTraverseScraper } from './page-traverse-scraper.js';\nimport { ScrapeCallback } from './scraper.js';\nimport * as cheerio from 'cheerio';\nexport interface WikiHistory {\n dateTime: Date;\n change: string;\n user: string;\n url: string;\n}\nexport class WikiHistoryPage extends Page {",
"score": 0.8504365682601929
},
{
"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": 0.844848096370697
},
{
"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": 0.8283827304840088
},
{
"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": 0.815941572189331
}
] |
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": " const isEnum = $('enum').length > 0;\n const isStruct = $('structure').length > 0;\n const isFunction = $('function').length > 0;\n const isPanel = $('panel').length > 0;\n const mainElement = $(isEnum ? 'enum' : isStruct ? 'struct' : isPanel ? 'panel' : 'function');\n const address = response.url.split('/').pop()!.split('?')[0];\n if (isEnum) {\n const items = $('items item').map(function () {\n const $el = $(this);\n return <EnumValue>{",
"score": 0.8129086494445801
},
{
"filename": "src/scrapers/wiki-page-markup-scraper.ts",
"retrieved_chunk": " key: string;\n value: string;\n description: string;\n};\nexport type Enum = CommonWikiProperties & {\n type: 'enum';\n items: EnumValue[];\n};\nexport type StructField = {\n name: string;",
"score": 0.8078691959381104
},
{
"filename": "src/cli-scraper.ts",
"retrieved_chunk": " if (!fs.existsSync(`${moduleFile}.lua`))\n fs.writeFileSync(`${moduleFile}.lua`, '---@meta\\n\\n');\n if (!fs.existsSync(moduleFile))\n fs.mkdirSync(moduleFile, { recursive: true });\n fileName = fileName.replace(/[^a-z0-9]/gi, '_').toLowerCase();\n // Lua API\n fs.appendFileSync(path.join(baseDirectory, `${moduleName}.lua`), api);\n // JSON data\n const json = JSON.stringify(pageMarkups, null, 2);\n fs.writeFileSync(path.join(baseDirectory, moduleName, `${fileName}.json`), json);",
"score": 0.7814146280288696
},
{
"filename": "src/scrapers/wiki-page-markup-scraper.ts",
"retrieved_chunk": " realm: $('realm').text() as Realm,\n items\n };\n } else if (isStruct) {\n const fields = $('fields item').map(function () {\n const $el = $(this);\n return <StructField>{\n name: $el.attr('name')!,\n type: $el.attr('type')!,\n default: $el.attr('default'),",
"score": 0.7680531740188599
},
{
"filename": "src/scrapers/table-scraper.ts",
"retrieved_chunk": "export function tableColumn(columnName: string): PropertyDecorator {\n return (target: object, propertyKey: string | symbol) => {\n const existingColumns: TableColumnDefinition[] = Reflect.getMetadata(tableColumnMetadataKey, target) || [];\n const propertyType = Reflect.getMetadata(\"design:type\", target, propertyKey);\n existingColumns.push({\n propertyKey,\n columnName,\n typeConverter: (value: string) => {\n switch (propertyType) {\n case String:",
"score": 0.767474353313446
}
] |
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": 0.9174654483795166
},
{
"filename": "src/scrapers/wiki-history-scraper.ts",
"retrieved_chunk": " * Scrapes a wiki history page for information on wiki changes\n * \n * @param response The response from the page\n * @param content The content of the request\n * \n * @returns A list containing only the scraped page\n */\n public getScrapeCallback(): ScrapeCallback<WikiHistoryPage> {\n const baseScrapeCallback = super.getScrapeCallback();\n return async (response: Response, content: string): Promise<WikiHistoryPage[]> => {",
"score": 0.9125957489013672
},
{
"filename": "src/scrapers/json-scraper.ts",
"retrieved_chunk": "import { ScrapeCallback, Scraper } from './scraper.js';\nexport class JsonScraper<T extends object = object> extends Scraper<T> {\n /**\n * @param response The response from the page\n * @param content The content of the request\n * \n * @returns A list containing only the scraped page\n */\n public getScrapeCallback(): ScrapeCallback<T> {\n return JsonScraper.makeScrapeCallback<T>();",
"score": 0.8753566145896912
},
{
"filename": "src/scrapers/wiki-history-scraper.ts",
"retrieved_chunk": " const pages = await baseScrapeCallback(response, content);\n if (pages.length === 0)\n return [];\n // There is only one page per response\n const page = pages[0];\n const $ = cheerio.load(content);\n const changeElements = $('table.changelist > tbody > .entry');\n if (!changeElements)\n return [page];\n for (const changeElement of changeElements) {",
"score": 0.8465597629547119
},
{
"filename": "src/scrapers/json-scraper.ts",
"retrieved_chunk": " }\n public static makeScrapeCallback<T extends object = object>(): ScrapeCallback<T> {\n return (response: Response, content: string): T[] => {\n return JSON.parse(content);\n };\n }\n}",
"score": 0.8194745779037476
}
] |
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": " })\n }\n if (cookies.length) {\n setBadgeText(accountName.slice(0, 2))\n } else {\n setBadgeText('...')\n }\n}\nasync function remove(accountName: string) {\n await storage.update<Accounts>('accounts', (accounts) => {",
"score": 0.8735595941543579
},
{
"filename": "src/shared.ts",
"retrieved_chunk": " return false\n }\n if (urlMatchesAnyRule(url, rules)) {\n return false\n }\n return true\n}\nexport async function removeAccount(account: string) {\n await browser.runtime.sendMessage({ type: 'removeAccount', account })\n}",
"score": 0.8733657002449036
},
{
"filename": "src/content/index.ts",
"retrieved_chunk": " ? `/login?return_to=${encodeURIComponent(window.location.href)}`\n : '/login'\n}\nasync function switchAccount(account: string) {\n await browser.runtime.sendMessage({ type: 'switchAccount', account })\n const autoSwitchRules = await getAutoSwitchRules()\n if (isNormalGitHubUrl(window.location.href, autoSwitchRules)) {\n window.location.reload()\n } else {\n window.location.href = '/'",
"score": 0.8580809831619263
},
{
"filename": "src/services/account.ts",
"retrieved_chunk": "async function switchTo(accountName: string) {\n await cookie.clear()\n const account = await find(accountName)\n const cookies = account?.cookies || []\n for (const cookie of cookies) {\n const { hostOnly, domain, session, ...rest } = cookie\n await browser.cookies.set({\n url: 'https://github.com',\n domain: hostOnly ? undefined : domain,\n ...rest,",
"score": 0.8567454218864441
},
{
"filename": "src/content/index.ts",
"retrieved_chunk": " }\n const res: GetAccountsResponse = await browser.runtime.sendMessage({\n type: 'getAccounts',\n } as GetAccountsMessage)\n if (!res?.success) {\n return\n }\n const { data: accounts } = res\n const addAccountButton = document.getElementById(ADD_ACCOUNT_BUTTON_ID)!\n for (const account of accounts) {",
"score": 0.8557066321372986
}
] |
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/popup/components/Accounts.tsx",
"retrieved_chunk": " title={`Remove ${account.name}`}\n onClick={() => handleRemove(account.name)}\n >\n <IconButton color=\"warning\">\n <Close />\n </IconButton>\n </Tooltip>\n </ListItemSecondaryAction>\n </ListItem>\n ))}",
"score": 0.8729751110076904
},
{
"filename": "src/content/index.ts",
"retrieved_chunk": " if (account === currentAccount) {\n continue\n }\n const accountId = `${ACCOUNT_ITEM_CLASS}-${account}`\n if (!document.getElementById(accountId) && addAccountButton) {\n const accountWrapper = createAccountItem(account)\n addAccountButton.parentElement?.insertBefore(accountWrapper, addAccountButton)\n }\n }\n}",
"score": 0.8578433990478516
},
{
"filename": "src/content/index.ts",
"retrieved_chunk": " if (!document.getElementById(ADD_ACCOUNT_BUTTON_ID)) {\n // Add the \"Add another account\" menu item and a divider\n const fragment = createElement('fragment', {\n children: [\n createAddAccountLink(),\n createDivider(),\n ],\n })\n // Insert the elements before the logoutForm\n logoutForm.parentElement?.insertBefore(fragment, logoutForm)",
"score": 0.8459718823432922
},
{
"filename": "src/content/index.ts",
"retrieved_chunk": " const closestTarget = target.closest(`.${ACCOUNT_ITEM_CLASS}`) as HTMLElement\n const { account } = closestTarget.dataset\n switchAccount(account!)\n } else if (target.closest(`.${ACCOUNT_REMOVE_CLASS}`)) {\n // remove account\n const btn = target.closest(`.${ACCOUNT_REMOVE_CLASS}`) as HTMLElement\n const { account } = btn.dataset\n removeAccount(account!).then(() => {\n btn.parentElement?.remove()\n })",
"score": 0.8390732407569885
},
{
"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": 0.836760401725769
}
] |
typescript
|
createRemoveIcon(),
}),
]
})
}
|
import { Close, Login, PersonAdd } from '@mui/icons-material'
import {
Alert,
Avatar,
Badge,
Box,
Button,
IconButton,
List,
ListItem,
ListItemAvatar,
ListItemSecondaryAction,
ListItemText,
Tooltip,
styled,
} from '@mui/material'
import { useEffect, useState } from 'react'
import browser, { Tabs } from 'webextension-polyfill'
import accountService, { Account } from '../../services/account'
import cookie from '../../services/cookie'
import rule from '../../services/rule'
import { isGitHubUrl, isNormalGitHubUrl, removeAccount } from '../../shared'
const StyledBadge = styled(Badge)(({ theme }) => ({
'& .MuiBadge-badge': {
backgroundColor: '#44b700',
color: '#44b700',
boxShadow: `0 0 0 2px ${theme.palette.background.paper}`,
'&::after': {
position: 'absolute',
top: 0,
left: 0,
width: '100%',
height: '100%',
borderRadius: '50%',
animation: 'ripple 1.2s infinite ease-in-out',
border: '1px solid currentColor',
content: '""',
},
},
'@keyframes ripple': {
'0%': {
transform: 'scale(.8)',
opacity: 1,
},
'100%': {
transform: 'scale(2.4)',
opacity: 0,
},
},
}))
function GitHubAvatar({ account }: { account: Account }) {
const { name, active } = account
const avatarUrl = account.avatarUrl ?? `https://github.com/${name}.png?size=100`
const avatar = <Avatar src={avatarUrl} />
if (active) {
return (
<StyledBadge
overlap="circular"
anchorOrigin={{ vertical: 'bottom', horizontal: 'right' }}
variant="dot"
>
{avatar}
</StyledBadge>
)
}
return avatar
}
async function getCurrentTab(): Promise<Tabs.Tab | undefined> {
const queryOptions = { active: true, lastFocusedWindow: true }
// `tab` will either be a `tabs.Tab` instance or `undefined`.
const [tab] = await browser.tabs.query(queryOptions)
return tab
}
export default function Accounts() {
const [accounts, setAccounts] = useState<Account[]>([])
useEffect(() => {
accountService.getAll().then(setAccounts)
}, [])
async function handleLogin() {
await cookie.clear()
const tab = await getCurrentTab()
const rules = await rule.getAll()
if (isNormalGitHubUrl(tab?.url, rules)) {
await browser.tabs.update(tab?.id!, {
url: `https://github.com/login?return_to=${encodeURIComponent(tab?.url ?? '')}`,
})
} else if (
|
isGitHubUrl(tab?.url)) {
|
await browser.tabs.update(tab?.id!, { url: 'https://github.com/login' })
} else {
await browser.tabs.create({ url: 'https://github.com/login' })
}
window.close()
}
async function handleSwitch(username: string) {
await accountService.switchTo(username)
const tab = await getCurrentTab()
const rules = await rule.getAll()
// If the current tab is a normal GitHub page, reload it.
if (isNormalGitHubUrl(tab?.url, rules)) {
await browser.tabs.reload(tab?.id!)
} else if (isGitHubUrl(tab?.url)) {
await browser.tabs.update(tab?.id!, { url: 'https://github.com' })
} else {
await browser.tabs.create({ url: 'https://github.com' })
}
window.close()
}
async function handleRemove(accountName: string) {
await removeAccount(accountName)
setAccounts(accounts.filter((account) => account.name !== accountName))
}
return (
<Box>
<Alert severity="info" sx={{ mb: 2 }}>
You can manage your logged in accounts here.
</Alert>
<Box sx={{ mb: 1 }}>
<List dense disablePadding>
{accounts.map((account, i) => (
<ListItem key={account.name} disableGutters divider={i !== accounts.length - 1}>
<ListItemAvatar>
<GitHubAvatar account={account} />
</ListItemAvatar>
<ListItemText
primary={account.name}
secondary={account.expiresAt && `Expires at ${account.expiresAt.toLocaleString()}`}
/>
<ListItemSecondaryAction>
<Tooltip title={`Switch to ${account.name}`}>
<span>
<IconButton
color="primary"
disabled={account.active}
onClick={() => handleSwitch(account.name)}
>
<Login />
</IconButton>
</span>
</Tooltip>
<Tooltip
title={`Remove ${account.name}`}
onClick={() => handleRemove(account.name)}
>
<IconButton color="warning">
<Close />
</IconButton>
</Tooltip>
</ListItemSecondaryAction>
</ListItem>
))}
</List>
</Box>
<Button
variant="contained"
sx={{ textTransform: 'none' }}
startIcon={<PersonAdd />}
onClick={handleLogin}
>
Login Another Account
</Button>
</Box>
)
}
|
src/popup/components/Accounts.tsx
|
yuezk-github-account-switcher-36b3c11
|
[
{
"filename": "src/content/index.ts",
"retrieved_chunk": " ? `/login?return_to=${encodeURIComponent(window.location.href)}`\n : '/login'\n}\nasync function switchAccount(account: string) {\n await browser.runtime.sendMessage({ type: 'switchAccount', account })\n const autoSwitchRules = await getAutoSwitchRules()\n if (isNormalGitHubUrl(window.location.href, autoSwitchRules)) {\n window.location.reload()\n } else {\n window.location.href = '/'",
"score": 0.8706310987472534
},
{
"filename": "src/content/index.ts",
"retrieved_chunk": "async function getAutoSwitchRules() {\n const res: GetAutoSwitchRulesResponse = await browser.runtime.sendMessage({\n type: 'getAutoSwitchRules',\n } as GetAutoSwitchRulesMessage)\n return res?.success ? res.data : []\n}\nasync function addAccount() {\n await browser.runtime.sendMessage({ type: 'clearCookies' } as ClearCookiesMessage)\n const autoSwitchRules = await getAutoSwitchRules()\n window.location.href = isNormalGitHubUrl(window.location.href, autoSwitchRules)",
"score": 0.8615986108779907
},
{
"filename": "src/services/account.ts",
"retrieved_chunk": "async function switchTo(accountName: string) {\n await cookie.clear()\n const account = await find(accountName)\n const cookies = account?.cookies || []\n for (const cookie of cookies) {\n const { hostOnly, domain, session, ...rest } = cookie\n await browser.cookies.set({\n url: 'https://github.com',\n domain: hostOnly ? undefined : domain,\n ...rest,",
"score": 0.8458574414253235
},
{
"filename": "src/content/index.ts",
"retrieved_chunk": "import browser from 'webextension-polyfill'\nimport { isNormalGitHubUrl, removeAccount } from '../shared'\nimport {\n ClearCookiesMessage,\n GetAccountsMessage,\n GetAccountsResponse,\n GetAutoSwitchRulesMessage,\n GetAutoSwitchRulesResponse,\n} from '../types'\nimport './index.css'",
"score": 0.8287062644958496
},
{
"filename": "src/shared.ts",
"retrieved_chunk": " return false\n }\n if (urlMatchesAnyRule(url, rules)) {\n return false\n }\n return true\n}\nexport async function removeAccount(account: string) {\n await browser.runtime.sendMessage({ type: 'removeAccount', account })\n}",
"score": 0.8234723806381226
}
] |
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": " })\n }\n if (cookies.length) {\n setBadgeText(accountName.slice(0, 2))\n } else {\n setBadgeText('...')\n }\n}\nasync function remove(accountName: string) {\n await storage.update<Accounts>('accounts', (accounts) => {",
"score": 0.8444503545761108
},
{
"filename": "src/shared.ts",
"retrieved_chunk": " return false\n }\n if (urlMatchesAnyRule(url, rules)) {\n return false\n }\n return true\n}\nexport async function removeAccount(account: string) {\n await browser.runtime.sendMessage({ type: 'removeAccount', account })\n}",
"score": 0.8168821930885315
},
{
"filename": "src/popup/components/Accounts.tsx",
"retrieved_chunk": " const [tab] = await browser.tabs.query(queryOptions)\n return tab\n}\nexport default function Accounts() {\n const [accounts, setAccounts] = useState<Account[]>([])\n useEffect(() => {\n accountService.getAll().then(setAccounts)\n }, [])\n async function handleLogin() {\n await cookie.clear()",
"score": 0.8103337287902832
},
{
"filename": "src/content/index.ts",
"retrieved_chunk": "import browser from 'webextension-polyfill'\nimport { isNormalGitHubUrl, removeAccount } from '../shared'\nimport {\n ClearCookiesMessage,\n GetAccountsMessage,\n GetAccountsResponse,\n GetAutoSwitchRulesMessage,\n GetAutoSwitchRulesResponse,\n} from '../types'\nimport './index.css'",
"score": 0.8057467937469482
},
{
"filename": "src/content/index.ts",
"retrieved_chunk": " }\n const res: GetAccountsResponse = await browser.runtime.sendMessage({\n type: 'getAccounts',\n } as GetAccountsMessage)\n if (!res?.success) {\n return\n }\n const { data: accounts } = res\n const addAccountButton = document.getElementById(ADD_ACCOUNT_BUTTON_ID)!\n for (const account of accounts) {",
"score": 0.8051315546035767
}
] |
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": " 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": 0.8467932343482971
},
{
"filename": "src/content/ui.ts",
"retrieved_chunk": " class: `dropdown-item ${ADD_ACCOUNT_BUTTON_ID}`,\n children: 'Add another account'\n })\n },\n createAccountItem(account: string) {\n const accountId = `${ACCOUNT_ITEM_CLASS}-${account}`\n return createElement('div', {\n id: accountId,\n class: 'gh-account-switcher__account-wrapper',\n children: [",
"score": 0.8434951305389404
},
{
"filename": "src/content/ui.ts",
"retrieved_chunk": " createElement('a', {\n class: `ActionListContent ${ADD_ACCOUNT_BUTTON_ID}`,\n href: '/login',\n children: [\n createElement('span', {\n class: 'ActionListItem-label',\n children: 'Add another account'\n })\n ]\n })",
"score": 0.8427437543869019
},
{
"filename": "src/content/ui.ts",
"retrieved_chunk": " ]\n }),\n createElement('button', {\n title: 'Remove account',\n 'data-account': account,\n class: `btn-link color-fg-danger ${ACCOUNT_REMOVE_CLASS}`,\n children: createRemoveIcon(),\n })\n ]\n })",
"score": 0.8370927572250366
},
{
"filename": "src/content/ui.ts",
"retrieved_chunk": " ]\n })\n },\n createAccountItem(account: string) {\n const accountId = `${ACCOUNT_ITEM_CLASS}-${account}`\n return createElement('li', {\n id: accountId,\n class: 'ActionListItem',\n children: [\n createElement('button', {",
"score": 0.8314045667648315
}
] |
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/background/index.ts",
"retrieved_chunk": " listenMessage()\n if (!browser.declarativeNetRequest) {\n interceptRequests()\n }\n /*\n chrome.declarativeNetRequest.onRuleMatchedDebug.addListener((info) => {\n console.info('onRuleMatchedDebug', info)\n })*/\n}\ninit()",
"score": 0.8228026628494263
},
{
"filename": "src/content/injected.ts",
"retrieved_chunk": "function init() {\n patchRequest()\n patchFetch()\n}\ninit()",
"score": 0.803313136100769
},
{
"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": 0.7997340559959412
},
{
"filename": "src/background/index.ts",
"retrieved_chunk": "import browser, { DeclarativeNetRequest } from 'webextension-polyfill'\nimport accountService from '../services/account'\nimport { setBadgeText } from '../services/badge'\nimport cookie from '../services/cookie'\nimport ruleService from '../services/rule'\nimport { RequestMessage, Response } from '../types'\nconst RESOURCE_TYPES: DeclarativeNetRequest.ResourceType[] = [\n 'main_frame',\n 'sub_frame',\n 'csp_report',",
"score": 0.7975805997848511
},
{
"filename": "src/shared.ts",
"retrieved_chunk": " return false\n }\n if (urlMatchesAnyRule(url, rules)) {\n return false\n }\n return true\n}\nexport async function removeAccount(account: string) {\n await browser.runtime.sendMessage({ type: 'removeAccount', account })\n}",
"score": 0.7958208322525024
}
] |
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": 0.8715931177139282
},
{
"filename": "src/content/ui.ts",
"retrieved_chunk": " createElement('a', {\n class: `ActionListContent ${ADD_ACCOUNT_BUTTON_ID}`,\n href: '/login',\n children: [\n createElement('span', {\n class: 'ActionListItem-label',\n children: 'Add another account'\n })\n ]\n })",
"score": 0.8567525744438171
},
{
"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": 0.8515833616256714
},
{
"filename": "src/content/ui.ts",
"retrieved_chunk": " ]\n })\n },\n createAccountItem(account: string) {\n const accountId = `${ACCOUNT_ITEM_CLASS}-${account}`\n return createElement('li', {\n id: accountId,\n class: 'ActionListItem',\n children: [\n createElement('button', {",
"score": 0.8454810380935669
},
{
"filename": "src/content/ui.ts",
"retrieved_chunk": " createDivider() {\n return createElement('li', {\n class: 'ActionList-sectionDivider'\n })\n },\n createAddAccountLink() {\n return createElement('li', {\n id: ADD_ACCOUNT_BUTTON_ID,\n class: 'ActionListItem',\n children: [",
"score": 0.8383822441101074
}
] |
typescript
|
const accountWrapper = createAccountItem(account)
addAccountButton.parentElement?.insertBefore(accountWrapper, addAccountButton)
}
|
import browser from 'webextension-polyfill'
import { isNormalGitHubUrl, removeAccount } from '../shared'
import {
ClearCookiesMessage,
GetAccountsMessage,
GetAccountsResponse,
GetAutoSwitchRulesMessage,
GetAutoSwitchRulesResponse,
} from '../types'
import './index.css'
// Script that will be injected in the main page
import { createElement } from './createElement'
import injectedScript from './injected?script&module'
import { ACCOUNT_ITEM_CLASS, ACCOUNT_REMOVE_CLASS, ADD_ACCOUNT_BUTTON_ID, createAccountItem, createAddAccountLink, createDivider } from './ui'
async function addSwitchUserMenu(logoutForm: HTMLFormElement) {
const currentAccount = document.querySelector<HTMLMetaElement>('meta[name="user-login"]')?.content
if (!currentAccount) {
console.info('no current account found')
return
}
if (!document.getElementById(ADD_ACCOUNT_BUTTON_ID)) {
// Add the "Add another account" menu item and a divider
const fragment = createElement('fragment', {
children: [
createAddAccountLink(),
createDivider(),
],
})
// Insert the elements before the logoutForm
logoutForm.parentElement?.insertBefore(fragment, logoutForm)
}
const res: GetAccountsResponse = await browser.runtime.sendMessage({
type: 'getAccounts',
} as GetAccountsMessage)
if (!res?.success) {
return
}
const { data: accounts } = res
const addAccountButton = document.getElementById(ADD_ACCOUNT_BUTTON_ID)!
for (const account of accounts) {
if (account === currentAccount) {
continue
}
const accountId = `${ACCOUNT_ITEM_CLASS}-${account}`
if (!document.getElementById(accountId) && addAccountButton) {
const accountWrapper = createAccountItem(account)
addAccountButton.parentElement?.insertBefore(accountWrapper, addAccountButton)
}
}
}
async function getAutoSwitchRules() {
const res: GetAutoSwitchRulesResponse = await browser.runtime.sendMessage({
type: 'getAutoSwitchRules',
} as GetAutoSwitchRulesMessage)
return res?.success ? res.data : []
}
async function addAccount() {
await browser.runtime.sendMessage({ type: 'clearCookies' } as ClearCookiesMessage)
const autoSwitchRules = await getAutoSwitchRules()
window.location.href = isNormalGitHubUrl(window.location.href, autoSwitchRules)
? `/login?return_to=${encodeURIComponent(window.location.href)}`
: '/login'
}
async function switchAccount(account: string) {
await browser.runtime.sendMessage({ type: 'switchAccount', account })
const autoSwitchRules = await getAutoSwitchRules()
if (isNormalGitHubUrl(window.location.href, autoSwitchRules)) {
window.location.reload()
} else {
window.location.href = '/'
}
}
function injectScript() {
const script = document.createElement('script')
script.src = browser.runtime.getURL(injectedScript)
script.type = 'module'
document.head.prepend(script)
}
function ready(fn: () => void) {
if (document.readyState !== 'loading') {
fn()
return
}
document.addEventListener('DOMContentLoaded', fn)
}
function watchDom() {
new MutationObserver((mutations) => {
for (const mutation of mutations) {
const isOpen =
mutation.type === 'attributes' &&
mutation.attributeName === 'open' &&
mutation.target instanceof HTMLElement &&
mutation.target.hasAttribute('open')
if (isOpen || (mutation.type === 'childList' && mutation.target instanceof HTMLElement)) {
// Find the logout form on GitHub page or Gist page
const logoutForm = mutation.target.querySelector<HTMLFormElement>(
'.js-loggout-form, #user-links .logout-form, user-drawer-side-panel nav-list .ActionListItem:last-child',
)
if (logoutForm) {
addSwitchUserMenu(logoutForm)
}
}
}
}).observe(document.documentElement, {
childList: true,
subtree: true,
attributes: true,
})
}
async function init() {
injectScript()
ready(watchDom)
document.addEventListener('click', (event) => {
const target = event.target as HTMLElement
if (target.closest(`.${ADD_ACCOUNT_BUTTON_ID}`)) {
// add another account
event.preventDefault()
addAccount()
} else if (target.closest(`.${ACCOUNT_ITEM_CLASS}`)) {
// switch to account
const closestTarget = target.closest(`.${ACCOUNT_ITEM_CLASS}`) as HTMLElement
const { account } = closestTarget.dataset
switchAccount(account!)
}
|
else if (target.closest(`.${ACCOUNT_REMOVE_CLASS}`)) {
|
// remove account
const btn = target.closest(`.${ACCOUNT_REMOVE_CLASS}`) as HTMLElement
const { account } = btn.dataset
removeAccount(account!).then(() => {
btn.parentElement?.remove()
})
}
})
}
init()
|
src/content/index.ts
|
yuezk-github-account-switcher-36b3c11
|
[
{
"filename": "src/content/ui.ts",
"retrieved_chunk": " 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": 0.8471823930740356
},
{
"filename": "src/popup/components/Accounts.tsx",
"retrieved_chunk": " } else if (isGitHubUrl(tab?.url)) {\n await browser.tabs.update(tab?.id!, { url: 'https://github.com' })\n } else {\n await browser.tabs.create({ url: 'https://github.com' })\n }\n window.close()\n }\n async function handleRemove(accountName: string) {\n await removeAccount(accountName)\n setAccounts(accounts.filter((account) => account.name !== accountName))",
"score": 0.8385009169578552
},
{
"filename": "src/content/ui.ts",
"retrieved_chunk": " class: `dropdown-item ${ADD_ACCOUNT_BUTTON_ID}`,\n children: 'Add another account'\n })\n },\n createAccountItem(account: string) {\n const accountId = `${ACCOUNT_ITEM_CLASS}-${account}`\n return createElement('div', {\n id: accountId,\n class: 'gh-account-switcher__account-wrapper',\n children: [",
"score": 0.8349842429161072
},
{
"filename": "src/content/ui.ts",
"retrieved_chunk": " ]\n })\n },\n createAccountItem(account: string) {\n const accountId = `${ACCOUNT_ITEM_CLASS}-${account}`\n return createElement('li', {\n id: accountId,\n class: 'ActionListItem',\n children: [\n createElement('button', {",
"score": 0.8241984248161316
},
{
"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": 0.8225884437561035
}
] |
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/shared.ts",
"retrieved_chunk": " return false\n }\n if (urlMatchesAnyRule(url, rules)) {\n return false\n }\n return true\n}\nexport async function removeAccount(account: string) {\n await browser.runtime.sendMessage({ type: 'removeAccount', account })\n}",
"score": 0.8695598840713501
},
{
"filename": "src/content/index.ts",
"retrieved_chunk": "async function getAutoSwitchRules() {\n const res: GetAutoSwitchRulesResponse = await browser.runtime.sendMessage({\n type: 'getAutoSwitchRules',\n } as GetAutoSwitchRulesMessage)\n return res?.success ? res.data : []\n}\nasync function addAccount() {\n await browser.runtime.sendMessage({ type: 'clearCookies' } as ClearCookiesMessage)\n const autoSwitchRules = await getAutoSwitchRules()\n window.location.href = isNormalGitHubUrl(window.location.href, autoSwitchRules)",
"score": 0.8510768413543701
},
{
"filename": "src/types.ts",
"retrieved_chunk": "export type RemoveAccountMessage = Message<'removeAccount', { account: string }>\nexport type RemoveAccountResponse = Response\nexport type GetAutoSwitchRulesMessage = Message<'getAutoSwitchRules'>\nexport type GetAutoSwitchRulesResponse = Response<Rule[]>\nexport type RequestMessage =\n | GetAccountsMessage\n | ClearCookiesMessage\n | SwitchAccountMessage\n | RemoveAccountMessage\n | GetAutoSwitchRulesMessage",
"score": 0.8442047238349915
},
{
"filename": "src/content/index.ts",
"retrieved_chunk": " }\n const res: GetAccountsResponse = await browser.runtime.sendMessage({\n type: 'getAccounts',\n } as GetAccountsMessage)\n if (!res?.success) {\n return\n }\n const { data: accounts } = res\n const addAccountButton = document.getElementById(ADD_ACCOUNT_BUTTON_ID)!\n for (const account of accounts) {",
"score": 0.8407704830169678
},
{
"filename": "src/content/index.ts",
"retrieved_chunk": "import browser from 'webextension-polyfill'\nimport { isNormalGitHubUrl, removeAccount } from '../shared'\nimport {\n ClearCookiesMessage,\n GetAccountsMessage,\n GetAccountsResponse,\n GetAutoSwitchRulesMessage,\n GetAutoSwitchRulesResponse,\n} from '../types'\nimport './index.css'",
"score": 0.8306077122688293
}
] |
typescript
|
async (request: RequestMessage, _sender): Promise<Response<unknown>> => {
|
import browser, { DeclarativeNetRequest } from 'webextension-polyfill'
import accountService from '../services/account'
import { setBadgeText } from '../services/badge'
import cookie from '../services/cookie'
import ruleService from '../services/rule'
import { RequestMessage, Response } from '../types'
const RESOURCE_TYPES: DeclarativeNetRequest.ResourceType[] = [
'main_frame',
'sub_frame',
'csp_report',
'websocket',
'xmlhttprequest',
]
async function syncAccounts() {
const usernameCookie = await cookie.get('dotcom_user')
const sessionCookie = await cookie.get('user_session')
if (!usernameCookie || !sessionCookie) {
return
}
const { value: account } = usernameCookie
if (!account) {
return
}
await accountService.upsert(account, await cookie.getAll())
const accounts = await accountService.getAll()
console.info('synced accounts', accounts)
await updateDynamicRequestRules()
const res = await fetch(`https://github.com/${account}.png?size=100`)
if (res.status === 200) {
accountService.saveAvatar(account, res.url)
}
await setBadgeText(account.slice(0, 2))
}
async function removeAccount(accountName: string) {
await accountService.remove(accountName)
await updateDynamicRequestRules()
}
async function buildCookieValue(accountName: string): Promise<string | null> {
const account = await accountService.find(accountName)
const cookies = account?.cookies || []
if (!cookies.length) {
return null
}
return cookies
.map((cookie) => `${cookie.name}=${cookie.value}`)
.concat(`__account__=${accountName}`)
.join('; ')
}
async function buildAddRules(): Promise<DeclarativeNetRequest.Rule[]> {
const requestRules: DeclarativeNetRequest.Rule[] = []
const autoSwitchRules =
|
await ruleService.getAll()
for (const [index, rule] of autoSwitchRules.entries()) {
|
const cookieValue = await buildCookieValue(rule.account)
if (!cookieValue) {
continue
}
requestRules.push({
id: index + 1,
priority: 1,
action: {
type: 'modifyHeaders',
requestHeaders: [
{
header: 'Cookie',
operation: 'set',
value: cookieValue,
},
],
},
condition: {
regexFilter: `${rule.urlPattern}|__account__=${rule.account}`,
resourceTypes: RESOURCE_TYPES,
},
})
}
return requestRules
}
async function updateDynamicRequestRules() {
if (!browser.declarativeNetRequest) {
return
}
const existingRules = await browser.declarativeNetRequest.getDynamicRules()
const removeRuleIds = existingRules.map((rule) => rule.id)
const addRules = await buildAddRules()
await browser.declarativeNetRequest.updateDynamicRules({
removeRuleIds,
addRules,
})
const rules = await browser.declarativeNetRequest.getDynamicRules()
console.info('Current dynamic rules:', rules)
}
// Watch the requests, if the main_frame url matches any of the auto switch rules, switch to the account
function watchAutoSwitchRequests() {
browser.webRequest.onBeforeRequest.addListener(
(details) => {
ruleService.getAll().then((autoSwitchRules) => {
for (const rule of autoSwitchRules) {
if (new RegExp(rule.urlPattern).test(details.url)) {
console.info('onBeforeRequest: found an auto switch rule for url', details.url, rule)
return accountService.switchTo(rule.account)
}
}
})
},
{
urls: ['https://github.com/*'],
types: ['main_frame'],
},
)
}
function watchCookies() {
browser.cookies.onChanged.addListener(async (changeInfo) => {
const { cookie, removed } = changeInfo
// Ignore other cookies
if (cookie.name !== 'dotcom_user') {
return
}
if (removed) {
if (cookie.name === 'dotcom_user') {
console.info('dotcom_user cookie removed')
await setBadgeText('...')
}
return
}
console.info('New dotcom_user cookie', cookie.value)
await syncAccounts()
})
}
function handleMessage(message: RequestMessage) {
const { type } = message
switch (type) {
case 'getAccounts':
return accountService.getAllNames()
case 'switchAccount':
return accountService.switchTo(message.account)
case 'removeAccount':
return removeAccount(message.account)
case 'clearCookies':
return cookie.clear()
case 'getAutoSwitchRules':
return ruleService.getAll()
}
}
function listenMessage() {
browser.runtime.onMessage.addListener(
async (request: RequestMessage, _sender): Promise<Response<unknown>> => {
try {
const data = await handleMessage(request)
return { success: true, data }
} catch (error: unknown) {
return { success: false, error: error as Error }
}
},
)
}
function interceptRequests() {
browser.webRequest.onBeforeSendHeaders.addListener(
async (details) => {
if (!details.requestHeaders) {
return { requestHeaders: details.requestHeaders }
}
const autoSwitchRules = await ruleService.getAll()
for (const rule of autoSwitchRules) {
const urlPattern = `${rule.urlPattern}|__account__=${rule.account}`
if (new RegExp(urlPattern).test(details.url)) {
const cookieValue = await buildCookieValue(rule.account)
if (cookieValue) {
for (const header of details.requestHeaders) {
if (header.name.toLowerCase() === 'cookie') {
header.value = cookieValue
}
}
}
console.info('interceptRequests: found an auto switch rule for url', details.url, rule)
return { requestHeaders: details.requestHeaders }
}
}
return { requestHeaders: details.requestHeaders }
},
{
urls: ['https://github.com/*'],
types: RESOURCE_TYPES,
},
['blocking', 'requestHeaders'],
)
}
async function init() {
await syncAccounts()
watchAutoSwitchRequests()
watchCookies()
listenMessage()
if (!browser.declarativeNetRequest) {
interceptRequests()
}
/*
chrome.declarativeNetRequest.onRuleMatchedDebug.addListener((info) => {
console.info('onRuleMatchedDebug', info)
})*/
}
init()
|
src/background/index.ts
|
yuezk-github-account-switcher-36b3c11
|
[
{
"filename": "src/content/index.ts",
"retrieved_chunk": "async function getAutoSwitchRules() {\n const res: GetAutoSwitchRulesResponse = await browser.runtime.sendMessage({\n type: 'getAutoSwitchRules',\n } as GetAutoSwitchRulesMessage)\n return res?.success ? res.data : []\n}\nasync function addAccount() {\n await browser.runtime.sendMessage({ type: 'clearCookies' } as ClearCookiesMessage)\n const autoSwitchRules = await getAutoSwitchRules()\n window.location.href = isNormalGitHubUrl(window.location.href, autoSwitchRules)",
"score": 0.8647446632385254
},
{
"filename": "src/services/account.ts",
"retrieved_chunk": " expiresAt?: Date\n}\ntype Accounts = Record<string, Cookie[]>\nasync function getAll(): Promise<Account[]> {\n const accounts = await storage.get<Accounts>('accounts')\n if (!accounts) {\n return []\n }\n const currentAccount = await browser.cookies.get({\n url: 'https://github.com',",
"score": 0.823571503162384
},
{
"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": 0.82231205701828
},
{
"filename": "src/services/rule.ts",
"retrieved_chunk": "import storage from './storage'\nexport type Rule = {\n id: number\n urlPattern: string\n account: string\n}\nasync function getAll(): Promise<Rule[]> {\n const rules = await storage.get<Rule[]>('rules')\n return rules || []\n}",
"score": 0.8139007091522217
},
{
"filename": "src/services/account.ts",
"retrieved_chunk": " name: 'dotcom_user',\n })\n const avatarUrls = await storage.get<Record<string, string>>('avatars')\n return Object.entries(accounts).map(([name, cookies]) => {\n const userSessionCookie = cookies.find(({ name }) => name === 'user_session')\n return {\n name,\n cookies,\n active: currentAccount?.value === name,\n avatarUrl: avatarUrls?.[name],",
"score": 0.8081665635108948
}
] |
typescript
|
await ruleService.getAll()
for (const [index, rule] of autoSwitchRules.entries()) {
|
import { Close, Login, PersonAdd } from '@mui/icons-material'
import {
Alert,
Avatar,
Badge,
Box,
Button,
IconButton,
List,
ListItem,
ListItemAvatar,
ListItemSecondaryAction,
ListItemText,
Tooltip,
styled,
} from '@mui/material'
import { useEffect, useState } from 'react'
import browser, { Tabs } from 'webextension-polyfill'
import accountService, { Account } from '../../services/account'
import cookie from '../../services/cookie'
import rule from '../../services/rule'
import { isGitHubUrl, isNormalGitHubUrl, removeAccount } from '../../shared'
const StyledBadge = styled(Badge)(({ theme }) => ({
'& .MuiBadge-badge': {
backgroundColor: '#44b700',
color: '#44b700',
boxShadow: `0 0 0 2px ${theme.palette.background.paper}`,
'&::after': {
position: 'absolute',
top: 0,
left: 0,
width: '100%',
height: '100%',
borderRadius: '50%',
animation: 'ripple 1.2s infinite ease-in-out',
border: '1px solid currentColor',
content: '""',
},
},
'@keyframes ripple': {
'0%': {
transform: 'scale(.8)',
opacity: 1,
},
'100%': {
transform: 'scale(2.4)',
opacity: 0,
},
},
}))
function GitHubAvatar({ account }: { account: Account }) {
const { name, active } = account
const avatarUrl = account.avatarUrl ?? `https://github.com/${name}.png?size=100`
const avatar = <Avatar src={avatarUrl} />
if (active) {
return (
<StyledBadge
overlap="circular"
anchorOrigin={{ vertical: 'bottom', horizontal: 'right' }}
variant="dot"
>
{avatar}
</StyledBadge>
)
}
return avatar
}
async function getCurrentTab(): Promise<Tabs.Tab | undefined> {
const queryOptions = { active: true, lastFocusedWindow: true }
// `tab` will either be a `tabs.Tab` instance or `undefined`.
const [tab] = await browser.tabs.query(queryOptions)
return tab
}
export default function Accounts() {
const [accounts, setAccounts] = useState<Account[]>([])
useEffect(() => {
accountService.getAll().then(setAccounts)
}, [])
async function handleLogin() {
await cookie.clear()
const tab = await getCurrentTab()
|
const rules = await rule.getAll()
if (isNormalGitHubUrl(tab?.url, rules)) {
|
await browser.tabs.update(tab?.id!, {
url: `https://github.com/login?return_to=${encodeURIComponent(tab?.url ?? '')}`,
})
} else if (isGitHubUrl(tab?.url)) {
await browser.tabs.update(tab?.id!, { url: 'https://github.com/login' })
} else {
await browser.tabs.create({ url: 'https://github.com/login' })
}
window.close()
}
async function handleSwitch(username: string) {
await accountService.switchTo(username)
const tab = await getCurrentTab()
const rules = await rule.getAll()
// If the current tab is a normal GitHub page, reload it.
if (isNormalGitHubUrl(tab?.url, rules)) {
await browser.tabs.reload(tab?.id!)
} else if (isGitHubUrl(tab?.url)) {
await browser.tabs.update(tab?.id!, { url: 'https://github.com' })
} else {
await browser.tabs.create({ url: 'https://github.com' })
}
window.close()
}
async function handleRemove(accountName: string) {
await removeAccount(accountName)
setAccounts(accounts.filter((account) => account.name !== accountName))
}
return (
<Box>
<Alert severity="info" sx={{ mb: 2 }}>
You can manage your logged in accounts here.
</Alert>
<Box sx={{ mb: 1 }}>
<List dense disablePadding>
{accounts.map((account, i) => (
<ListItem key={account.name} disableGutters divider={i !== accounts.length - 1}>
<ListItemAvatar>
<GitHubAvatar account={account} />
</ListItemAvatar>
<ListItemText
primary={account.name}
secondary={account.expiresAt && `Expires at ${account.expiresAt.toLocaleString()}`}
/>
<ListItemSecondaryAction>
<Tooltip title={`Switch to ${account.name}`}>
<span>
<IconButton
color="primary"
disabled={account.active}
onClick={() => handleSwitch(account.name)}
>
<Login />
</IconButton>
</span>
</Tooltip>
<Tooltip
title={`Remove ${account.name}`}
onClick={() => handleRemove(account.name)}
>
<IconButton color="warning">
<Close />
</IconButton>
</Tooltip>
</ListItemSecondaryAction>
</ListItem>
))}
</List>
</Box>
<Button
variant="contained"
sx={{ textTransform: 'none' }}
startIcon={<PersonAdd />}
onClick={handleLogin}
>
Login Another Account
</Button>
</Box>
)
}
|
src/popup/components/Accounts.tsx
|
yuezk-github-account-switcher-36b3c11
|
[
{
"filename": "src/services/account.ts",
"retrieved_chunk": " expiresAt?: Date\n}\ntype Accounts = Record<string, Cookie[]>\nasync function getAll(): Promise<Account[]> {\n const accounts = await storage.get<Accounts>('accounts')\n if (!accounts) {\n return []\n }\n const currentAccount = await browser.cookies.get({\n url: 'https://github.com',",
"score": 0.8789029121398926
},
{
"filename": "src/content/index.ts",
"retrieved_chunk": "async function getAutoSwitchRules() {\n const res: GetAutoSwitchRulesResponse = await browser.runtime.sendMessage({\n type: 'getAutoSwitchRules',\n } as GetAutoSwitchRulesMessage)\n return res?.success ? res.data : []\n}\nasync function addAccount() {\n await browser.runtime.sendMessage({ type: 'clearCookies' } as ClearCookiesMessage)\n const autoSwitchRules = await getAutoSwitchRules()\n window.location.href = isNormalGitHubUrl(window.location.href, autoSwitchRules)",
"score": 0.873818039894104
},
{
"filename": "src/background/index.ts",
"retrieved_chunk": " if (!account) {\n return\n }\n await accountService.upsert(account, await cookie.getAll())\n const accounts = await accountService.getAll()\n console.info('synced accounts', accounts)\n await updateDynamicRequestRules()\n const res = await fetch(`https://github.com/${account}.png?size=100`)\n if (res.status === 200) {\n accountService.saveAvatar(account, res.url)",
"score": 0.866890013217926
},
{
"filename": "src/background/index.ts",
"retrieved_chunk": " 'websocket',\n 'xmlhttprequest',\n]\nasync function syncAccounts() {\n const usernameCookie = await cookie.get('dotcom_user')\n const sessionCookie = await cookie.get('user_session')\n if (!usernameCookie || !sessionCookie) {\n return\n }\n const { value: account } = usernameCookie",
"score": 0.8574173450469971
},
{
"filename": "src/content/index.ts",
"retrieved_chunk": " ? `/login?return_to=${encodeURIComponent(window.location.href)}`\n : '/login'\n}\nasync function switchAccount(account: string) {\n await browser.runtime.sendMessage({ type: 'switchAccount', account })\n const autoSwitchRules = await getAutoSwitchRules()\n if (isNormalGitHubUrl(window.location.href, autoSwitchRules)) {\n window.location.reload()\n } else {\n window.location.href = '/'",
"score": 0.8518552780151367
}
] |
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/services/account.ts",
"retrieved_chunk": " expiresAt?: Date\n}\ntype Accounts = Record<string, Cookie[]>\nasync function getAll(): Promise<Account[]> {\n const accounts = await storage.get<Accounts>('accounts')\n if (!accounts) {\n return []\n }\n const currentAccount = await browser.cookies.get({\n url: 'https://github.com',",
"score": 0.8789029121398926
},
{
"filename": "src/content/index.ts",
"retrieved_chunk": "async function getAutoSwitchRules() {\n const res: GetAutoSwitchRulesResponse = await browser.runtime.sendMessage({\n type: 'getAutoSwitchRules',\n } as GetAutoSwitchRulesMessage)\n return res?.success ? res.data : []\n}\nasync function addAccount() {\n await browser.runtime.sendMessage({ type: 'clearCookies' } as ClearCookiesMessage)\n const autoSwitchRules = await getAutoSwitchRules()\n window.location.href = isNormalGitHubUrl(window.location.href, autoSwitchRules)",
"score": 0.873818039894104
},
{
"filename": "src/background/index.ts",
"retrieved_chunk": " if (!account) {\n return\n }\n await accountService.upsert(account, await cookie.getAll())\n const accounts = await accountService.getAll()\n console.info('synced accounts', accounts)\n await updateDynamicRequestRules()\n const res = await fetch(`https://github.com/${account}.png?size=100`)\n if (res.status === 200) {\n accountService.saveAvatar(account, res.url)",
"score": 0.866890013217926
},
{
"filename": "src/background/index.ts",
"retrieved_chunk": " 'websocket',\n 'xmlhttprequest',\n]\nasync function syncAccounts() {\n const usernameCookie = await cookie.get('dotcom_user')\n const sessionCookie = await cookie.get('user_session')\n if (!usernameCookie || !sessionCookie) {\n return\n }\n const { value: account } = usernameCookie",
"score": 0.8574173450469971
},
{
"filename": "src/content/index.ts",
"retrieved_chunk": " ? `/login?return_to=${encodeURIComponent(window.location.href)}`\n : '/login'\n}\nasync function switchAccount(account: string) {\n await browser.runtime.sendMessage({ type: 'switchAccount', account })\n const autoSwitchRules = await getAutoSwitchRules()\n if (isNormalGitHubUrl(window.location.href, autoSwitchRules)) {\n window.location.reload()\n } else {\n window.location.href = '/'",
"score": 0.8518552780151367
}
] |
typescript
|
if (isNormalGitHubUrl(tab?.url, rules)) {
|
import browser, { DeclarativeNetRequest } from 'webextension-polyfill'
import accountService from '../services/account'
import { setBadgeText } from '../services/badge'
import cookie from '../services/cookie'
import ruleService from '../services/rule'
import { RequestMessage, Response } from '../types'
const RESOURCE_TYPES: DeclarativeNetRequest.ResourceType[] = [
'main_frame',
'sub_frame',
'csp_report',
'websocket',
'xmlhttprequest',
]
async function syncAccounts() {
const usernameCookie = await cookie.get('dotcom_user')
const sessionCookie = await cookie.get('user_session')
if (!usernameCookie || !sessionCookie) {
return
}
const { value: account } = usernameCookie
if (!account) {
return
}
await accountService.upsert(account, await cookie.getAll())
const accounts = await accountService.getAll()
console.info('synced accounts', accounts)
await updateDynamicRequestRules()
const res = await fetch(`https://github.com/${account}.png?size=100`)
if (res.status === 200) {
accountService.saveAvatar(account, res.url)
}
await setBadgeText(account.slice(0, 2))
}
async function removeAccount(accountName: string) {
await accountService.remove(accountName)
await updateDynamicRequestRules()
}
async function buildCookieValue(accountName: string): Promise<string | null> {
const account = await accountService.find(accountName)
const cookies = account?.cookies || []
if (!cookies.length) {
return null
}
return cookies
.map((cookie) => `${cookie.name}=${cookie.value}`)
.concat(`__account__=${accountName}`)
.join('; ')
}
async function buildAddRules(): Promise<DeclarativeNetRequest.Rule[]> {
const requestRules: DeclarativeNetRequest.Rule[] = []
|
const autoSwitchRules = await ruleService.getAll()
for (const [index, rule] of autoSwitchRules.entries()) {
|
const cookieValue = await buildCookieValue(rule.account)
if (!cookieValue) {
continue
}
requestRules.push({
id: index + 1,
priority: 1,
action: {
type: 'modifyHeaders',
requestHeaders: [
{
header: 'Cookie',
operation: 'set',
value: cookieValue,
},
],
},
condition: {
regexFilter: `${rule.urlPattern}|__account__=${rule.account}`,
resourceTypes: RESOURCE_TYPES,
},
})
}
return requestRules
}
async function updateDynamicRequestRules() {
if (!browser.declarativeNetRequest) {
return
}
const existingRules = await browser.declarativeNetRequest.getDynamicRules()
const removeRuleIds = existingRules.map((rule) => rule.id)
const addRules = await buildAddRules()
await browser.declarativeNetRequest.updateDynamicRules({
removeRuleIds,
addRules,
})
const rules = await browser.declarativeNetRequest.getDynamicRules()
console.info('Current dynamic rules:', rules)
}
// Watch the requests, if the main_frame url matches any of the auto switch rules, switch to the account
function watchAutoSwitchRequests() {
browser.webRequest.onBeforeRequest.addListener(
(details) => {
ruleService.getAll().then((autoSwitchRules) => {
for (const rule of autoSwitchRules) {
if (new RegExp(rule.urlPattern).test(details.url)) {
console.info('onBeforeRequest: found an auto switch rule for url', details.url, rule)
return accountService.switchTo(rule.account)
}
}
})
},
{
urls: ['https://github.com/*'],
types: ['main_frame'],
},
)
}
function watchCookies() {
browser.cookies.onChanged.addListener(async (changeInfo) => {
const { cookie, removed } = changeInfo
// Ignore other cookies
if (cookie.name !== 'dotcom_user') {
return
}
if (removed) {
if (cookie.name === 'dotcom_user') {
console.info('dotcom_user cookie removed')
await setBadgeText('...')
}
return
}
console.info('New dotcom_user cookie', cookie.value)
await syncAccounts()
})
}
function handleMessage(message: RequestMessage) {
const { type } = message
switch (type) {
case 'getAccounts':
return accountService.getAllNames()
case 'switchAccount':
return accountService.switchTo(message.account)
case 'removeAccount':
return removeAccount(message.account)
case 'clearCookies':
return cookie.clear()
case 'getAutoSwitchRules':
return ruleService.getAll()
}
}
function listenMessage() {
browser.runtime.onMessage.addListener(
async (request: RequestMessage, _sender): Promise<Response<unknown>> => {
try {
const data = await handleMessage(request)
return { success: true, data }
} catch (error: unknown) {
return { success: false, error: error as Error }
}
},
)
}
function interceptRequests() {
browser.webRequest.onBeforeSendHeaders.addListener(
async (details) => {
if (!details.requestHeaders) {
return { requestHeaders: details.requestHeaders }
}
const autoSwitchRules = await ruleService.getAll()
for (const rule of autoSwitchRules) {
const urlPattern = `${rule.urlPattern}|__account__=${rule.account}`
if (new RegExp(urlPattern).test(details.url)) {
const cookieValue = await buildCookieValue(rule.account)
if (cookieValue) {
for (const header of details.requestHeaders) {
if (header.name.toLowerCase() === 'cookie') {
header.value = cookieValue
}
}
}
console.info('interceptRequests: found an auto switch rule for url', details.url, rule)
return { requestHeaders: details.requestHeaders }
}
}
return { requestHeaders: details.requestHeaders }
},
{
urls: ['https://github.com/*'],
types: RESOURCE_TYPES,
},
['blocking', 'requestHeaders'],
)
}
async function init() {
await syncAccounts()
watchAutoSwitchRequests()
watchCookies()
listenMessage()
if (!browser.declarativeNetRequest) {
interceptRequests()
}
/*
chrome.declarativeNetRequest.onRuleMatchedDebug.addListener((info) => {
console.info('onRuleMatchedDebug', info)
})*/
}
init()
|
src/background/index.ts
|
yuezk-github-account-switcher-36b3c11
|
[
{
"filename": "src/content/index.ts",
"retrieved_chunk": "async function getAutoSwitchRules() {\n const res: GetAutoSwitchRulesResponse = await browser.runtime.sendMessage({\n type: 'getAutoSwitchRules',\n } as GetAutoSwitchRulesMessage)\n return res?.success ? res.data : []\n}\nasync function addAccount() {\n await browser.runtime.sendMessage({ type: 'clearCookies' } as ClearCookiesMessage)\n const autoSwitchRules = await getAutoSwitchRules()\n window.location.href = isNormalGitHubUrl(window.location.href, autoSwitchRules)",
"score": 0.8712290525436401
},
{
"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": 0.829779863357544
},
{
"filename": "src/services/account.ts",
"retrieved_chunk": " expiresAt?: Date\n}\ntype Accounts = Record<string, Cookie[]>\nasync function getAll(): Promise<Account[]> {\n const accounts = await storage.get<Accounts>('accounts')\n if (!accounts) {\n return []\n }\n const currentAccount = await browser.cookies.get({\n url: 'https://github.com',",
"score": 0.8286352157592773
},
{
"filename": "src/services/rule.ts",
"retrieved_chunk": "import storage from './storage'\nexport type Rule = {\n id: number\n urlPattern: string\n account: string\n}\nasync function getAll(): Promise<Rule[]> {\n const rules = await storage.get<Rule[]>('rules')\n return rules || []\n}",
"score": 0.8252438306808472
},
{
"filename": "src/services/account.ts",
"retrieved_chunk": " name: 'dotcom_user',\n })\n const avatarUrls = await storage.get<Record<string, string>>('avatars')\n return Object.entries(accounts).map(([name, cookies]) => {\n const userSessionCookie = cookies.find(({ name }) => name === 'user_session')\n return {\n name,\n cookies,\n active: currentAccount?.value === name,\n avatarUrl: avatarUrls?.[name],",
"score": 0.8158637881278992
}
] |
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/content/index.ts",
"retrieved_chunk": "async function getAutoSwitchRules() {\n const res: GetAutoSwitchRulesResponse = await browser.runtime.sendMessage({\n type: 'getAutoSwitchRules',\n } as GetAutoSwitchRulesMessage)\n return res?.success ? res.data : []\n}\nasync function addAccount() {\n await browser.runtime.sendMessage({ type: 'clearCookies' } as ClearCookiesMessage)\n const autoSwitchRules = await getAutoSwitchRules()\n window.location.href = isNormalGitHubUrl(window.location.href, autoSwitchRules)",
"score": 0.8890459537506104
},
{
"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": 0.8298985958099365
},
{
"filename": "src/popup/components/Accounts.tsx",
"retrieved_chunk": " }\n window.close()\n }\n async function handleSwitch(username: string) {\n await accountService.switchTo(username)\n const tab = await getCurrentTab()\n const rules = await rule.getAll()\n // If the current tab is a normal GitHub page, reload it.\n if (isNormalGitHubUrl(tab?.url, rules)) {\n await browser.tabs.reload(tab?.id!)",
"score": 0.8247339725494385
},
{
"filename": "src/content/index.ts",
"retrieved_chunk": " ? `/login?return_to=${encodeURIComponent(window.location.href)}`\n : '/login'\n}\nasync function switchAccount(account: string) {\n await browser.runtime.sendMessage({ type: 'switchAccount', account })\n const autoSwitchRules = await getAutoSwitchRules()\n if (isNormalGitHubUrl(window.location.href, autoSwitchRules)) {\n window.location.reload()\n } else {\n window.location.href = '/'",
"score": 0.8165155649185181
},
{
"filename": "src/content/index.ts",
"retrieved_chunk": "import browser from 'webextension-polyfill'\nimport { isNormalGitHubUrl, removeAccount } from '../shared'\nimport {\n ClearCookiesMessage,\n GetAccountsMessage,\n GetAccountsResponse,\n GetAutoSwitchRulesMessage,\n GetAutoSwitchRulesResponse,\n} from '../types'\nimport './index.css'",
"score": 0.8103786706924438
}
] |
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": " 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": 0.8388383984565735
},
{
"filename": "src/popup/components/RuleItem.tsx",
"retrieved_chunk": " />\n </Box>\n <Box width={150} flexShrink={0}>\n <TextField\n size=\"medium\"\n variant=\"standard\"\n fullWidth\n placeholder=\"GitHub account\"\n error={!!accountValidation}\n helperText={accountValidation}",
"score": 0.8183436989784241
},
{
"filename": "src/popup/components/Header.tsx",
"retrieved_chunk": "import { GitHub } from '@mui/icons-material'\nimport { Avatar, Container, IconButton, Typography } from '@mui/material'\nimport { useState } from 'react'\nimport logo from '../../assets/logo.png'\nexport default function Header() {\n const [active, setActive] = useState(false)\n function handleClick() {\n setActive(!active)\n }\n return (",
"score": 0.7988630533218384
},
{
"filename": "src/popup/components/Header.tsx",
"retrieved_chunk": " >\n <GitHub />\n </IconButton>\n </Container>\n )\n}",
"score": 0.798572301864624
},
{
"filename": "src/content/ui.ts",
"retrieved_chunk": " title: 'Remove account',\n class: `btn-link ${ACCOUNT_REMOVE_CLASS}`,\n 'data-account': account,\n children: createRemoveIcon(),\n }),\n ]\n })\n }\n}\nconst newLook = {",
"score": 0.7983894944190979
}
] |
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": 0.9185463786125183
},
{
"filename": "src/services/account.ts",
"retrieved_chunk": "async function find(accountName: string): Promise<Account | undefined> {\n const accounts = await getAll()\n return accounts.find((account) => account.name === accountName)\n}\nasync function upsert(accountName: string, cookies: Cookie[]) {\n await storage.update<Accounts>('accounts', (accounts = {}) => {\n accounts[accountName] = cookies\n return accounts\n })\n}",
"score": 0.8697918057441711
},
{
"filename": "src/services/account.ts",
"retrieved_chunk": "async function switchTo(accountName: string) {\n await cookie.clear()\n const account = await find(accountName)\n const cookies = account?.cookies || []\n for (const cookie of cookies) {\n const { hostOnly, domain, session, ...rest } = cookie\n await browser.cookies.set({\n url: 'https://github.com',\n domain: hostOnly ? undefined : domain,\n ...rest,",
"score": 0.8585535287857056
},
{
"filename": "src/services/account.ts",
"retrieved_chunk": " expiresAt?: Date\n}\ntype Accounts = Record<string, Cookie[]>\nasync function getAll(): Promise<Account[]> {\n const accounts = await storage.get<Accounts>('accounts')\n if (!accounts) {\n return []\n }\n const currentAccount = await browser.cookies.get({\n url: 'https://github.com',",
"score": 0.8412632346153259
},
{
"filename": "src/popup/components/Accounts.tsx",
"retrieved_chunk": " const [tab] = await browser.tabs.query(queryOptions)\n return tab\n}\nexport default function Accounts() {\n const [accounts, setAccounts] = useState<Account[]>([])\n useEffect(() => {\n accountService.getAll().then(setAccounts)\n }, [])\n async function handleLogin() {\n await cookie.clear()",
"score": 0.8327682018280029
}
] |
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": 0.8371597528457642
},
{
"filename": "src/popup/components/Settings.tsx",
"retrieved_chunk": " value=\"accounts\"\n sx={{ textTransform: 'none', minHeight: 50 }}\n />\n <Tab\n icon={<Rule />}\n iconPosition=\"start\"\n label=\"Auto Switch Rules\"\n value=\"rules\"\n sx={{ textTransform: 'none', minHeight: 50 }}\n />",
"score": 0.8370859622955322
},
{
"filename": "src/services/rule.ts",
"retrieved_chunk": "async function add(rule: Rule) {\n await storage.update<Rule[]>('rules', (rules = []) => {\n return [...rules, rule]\n })\n}\nasync function update(rule: Rule) {\n await storage.update<Rule[]>('rules', (rules = []) => {\n return rules.map((r) => (r.id === rule.id ? rule : r))\n })\n}",
"score": 0.8148998022079468
},
{
"filename": "src/popup/components/Accounts.tsx",
"retrieved_chunk": " }\n return (\n <Box>\n <Alert severity=\"info\" sx={{ mb: 2 }}>\n You can manage your logged in accounts here.\n </Alert>\n <Box sx={{ mb: 1 }}>\n <List dense disablePadding>\n {accounts.map((account, i) => (\n <ListItem key={account.name} disableGutters divider={i !== accounts.length - 1}>",
"score": 0.8039862513542175
},
{
"filename": "src/popup/components/RuleItem.tsx",
"retrieved_chunk": " value={rule.account}\n onChange={handleAccountChange}\n disabled={!isEditing}\n />\n </Box>\n <Box display=\"flex\" flexShrink={0}>\n {!isEditing && (\n <Tooltip title=\"Edit\">\n <IconButton size=\"small\" color=\"primary\" onClick={handleEdit}>\n <Edit />",
"score": 0.8031781315803528
}
] |
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/popup/components/Accounts.tsx",
"retrieved_chunk": " const [tab] = await browser.tabs.query(queryOptions)\n return tab\n}\nexport default function Accounts() {\n const [accounts, setAccounts] = useState<Account[]>([])\n useEffect(() => {\n accountService.getAll().then(setAccounts)\n }, [])\n async function handleLogin() {\n await cookie.clear()",
"score": 0.8153611421585083
},
{
"filename": "src/content/index.ts",
"retrieved_chunk": " }\n const res: GetAccountsResponse = await browser.runtime.sendMessage({\n type: 'getAccounts',\n } as GetAccountsMessage)\n if (!res?.success) {\n return\n }\n const { data: accounts } = res\n const addAccountButton = document.getElementById(ADD_ACCOUNT_BUTTON_ID)!\n for (const account of accounts) {",
"score": 0.813178300857544
},
{
"filename": "src/services/account.ts",
"retrieved_chunk": "async function switchTo(accountName: string) {\n await cookie.clear()\n const account = await find(accountName)\n const cookies = account?.cookies || []\n for (const cookie of cookies) {\n const { hostOnly, domain, session, ...rest } = cookie\n await browser.cookies.set({\n url: 'https://github.com',\n domain: hostOnly ? undefined : domain,\n ...rest,",
"score": 0.8049142956733704
},
{
"filename": "src/content/index.ts",
"retrieved_chunk": " ? `/login?return_to=${encodeURIComponent(window.location.href)}`\n : '/login'\n}\nasync function switchAccount(account: string) {\n await browser.runtime.sendMessage({ type: 'switchAccount', account })\n const autoSwitchRules = await getAutoSwitchRules()\n if (isNormalGitHubUrl(window.location.href, autoSwitchRules)) {\n window.location.reload()\n } else {\n window.location.href = '/'",
"score": 0.8039137721061707
},
{
"filename": "src/shared.ts",
"retrieved_chunk": " return false\n }\n if (urlMatchesAnyRule(url, rules)) {\n return false\n }\n return true\n}\nexport async function removeAccount(account: string) {\n await browser.runtime.sendMessage({ type: 'removeAccount', account })\n}",
"score": 0.8028912544250488
}
] |
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/background/index.ts",
"retrieved_chunk": " listenMessage()\n if (!browser.declarativeNetRequest) {\n interceptRequests()\n }\n /*\n chrome.declarativeNetRequest.onRuleMatchedDebug.addListener((info) => {\n console.info('onRuleMatchedDebug', info)\n })*/\n}\ninit()",
"score": 0.8197476863861084
},
{
"filename": "src/content/injected.ts",
"retrieved_chunk": "function init() {\n patchRequest()\n patchFetch()\n}\ninit()",
"score": 0.7996965646743774
},
{
"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": 0.7936373949050903
},
{
"filename": "src/background/index.ts",
"retrieved_chunk": " }\n }\n })\n },\n {\n urls: ['https://github.com/*'],\n types: ['main_frame'],\n },\n )\n}",
"score": 0.7914613485336304
},
{
"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": 0.7905524373054504
}
] |
typescript
|
script.src = browser.runtime.getURL(injectedScript)
script.type = 'module'
document.head.prepend(script)
}
|
import browser, { Cookies } from 'webextension-polyfill'
import { setBadgeText } from './badge'
import cookie from './cookie'
import storage from './storage'
type Cookie = Cookies.Cookie
export type Account = {
name: string
cookies: Cookie[]
active: boolean
avatarUrl?: string
expiresAt?: Date
}
type Accounts = Record<string, Cookie[]>
async function getAll(): Promise<Account[]> {
const accounts = await storage.get<Accounts>('accounts')
if (!accounts) {
return []
}
const currentAccount = await browser.cookies.get({
url: 'https://github.com',
name: 'dotcom_user',
})
const avatarUrls = await storage.get<Record<string, string>>('avatars')
return Object.entries(accounts).map(([name, cookies]) => {
const userSessionCookie = cookies.find(({ name }) => name === 'user_session')
return {
name,
cookies,
active: currentAccount?.value === name,
avatarUrl: avatarUrls?.[name],
expiresAt: userSessionCookie?.expirationDate
? new Date(userSessionCookie.expirationDate * 1000)
: undefined,
}
})
}
async function getAllNames(): Promise<string[]> {
const accounts = await getAll()
return accounts.map(({ name }) => name)
}
async function find(accountName: string): Promise<Account | undefined> {
const accounts = await getAll()
return accounts.find((account) => account.name === accountName)
}
async function upsert(accountName: string, cookies: Cookie[]) {
await storage.update<Accounts>('accounts', (accounts = {}) => {
accounts[accountName] = cookies
return accounts
})
}
async function switchTo(accountName: string) {
await cookie.clear()
const account = await find(accountName)
const cookies = account?.cookies || []
for (const cookie of cookies) {
const { hostOnly, domain, session, ...rest } = cookie
await browser.cookies.set({
url: 'https://github.com',
domain: hostOnly ? undefined : domain,
...rest,
})
}
if (cookies.length) {
setBadgeText(accountName.slice(0, 2))
} else {
setBadgeText('...')
}
}
async function remove(accountName: string) {
await storage.update
|
<Accounts>('accounts', (accounts) => {
|
if (!accounts) {
return
}
delete accounts[accountName]
return accounts
})
}
async function saveAvatar(accountName: string, avatarUrl: string) {
await storage.update<Record<string, string>>('avatars', (avatars = {}) => {
avatars[accountName] = avatarUrl
return avatars
})
}
export default {
getAll,
getAllNames,
find,
upsert,
switchTo,
remove,
saveAvatar,
}
|
src/services/account.ts
|
yuezk-github-account-switcher-36b3c11
|
[
{
"filename": "src/background/index.ts",
"retrieved_chunk": " }\n await setBadgeText(account.slice(0, 2))\n}\nasync function removeAccount(accountName: string) {\n await accountService.remove(accountName)\n await updateDynamicRequestRules()\n}\nasync function buildCookieValue(accountName: string): Promise<string | null> {\n const account = await accountService.find(accountName)\n const cookies = account?.cookies || []",
"score": 0.9209814071655273
},
{
"filename": "src/popup/components/Accounts.tsx",
"retrieved_chunk": " } else if (isGitHubUrl(tab?.url)) {\n await browser.tabs.update(tab?.id!, { url: 'https://github.com' })\n } else {\n await browser.tabs.create({ url: 'https://github.com' })\n }\n window.close()\n }\n async function handleRemove(accountName: string) {\n await removeAccount(accountName)\n setAccounts(accounts.filter((account) => account.name !== accountName))",
"score": 0.8615032434463501
},
{
"filename": "src/background/index.ts",
"retrieved_chunk": " if (!account) {\n return\n }\n await accountService.upsert(account, await cookie.getAll())\n const accounts = await accountService.getAll()\n console.info('synced accounts', accounts)\n await updateDynamicRequestRules()\n const res = await fetch(`https://github.com/${account}.png?size=100`)\n if (res.status === 200) {\n accountService.saveAvatar(account, res.url)",
"score": 0.8450615406036377
},
{
"filename": "src/shared.ts",
"retrieved_chunk": " return false\n }\n if (urlMatchesAnyRule(url, rules)) {\n return false\n }\n return true\n}\nexport async function removeAccount(account: string) {\n await browser.runtime.sendMessage({ type: 'removeAccount', account })\n}",
"score": 0.8356145024299622
},
{
"filename": "src/popup/components/Accounts.tsx",
"retrieved_chunk": " const [tab] = await browser.tabs.query(queryOptions)\n return tab\n}\nexport default function Accounts() {\n const [accounts, setAccounts] = useState<Account[]>([])\n useEffect(() => {\n accountService.getAll().then(setAccounts)\n }, [])\n async function handleLogin() {\n await cookie.clear()",
"score": 0.8352539539337158
}
] |
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/background/index.ts",
"retrieved_chunk": " urls: ['https://github.com/*'],\n types: RESOURCE_TYPES,\n },\n ['blocking', 'requestHeaders'],\n )\n}\nasync function init() {\n await syncAccounts()\n watchAutoSwitchRequests()\n watchCookies()",
"score": 0.8493566513061523
},
{
"filename": "src/content/ui.ts",
"retrieved_chunk": " createElement('a', {\n class: `ActionListContent ${ADD_ACCOUNT_BUTTON_ID}`,\n href: '/login',\n children: [\n createElement('span', {\n class: 'ActionListItem-label',\n children: 'Add another account'\n })\n ]\n })",
"score": 0.8282766342163086
},
{
"filename": "src/popup/components/Accounts.tsx",
"retrieved_chunk": " const [tab] = await browser.tabs.query(queryOptions)\n return tab\n}\nexport default function Accounts() {\n const [accounts, setAccounts] = useState<Account[]>([])\n useEffect(() => {\n accountService.getAll().then(setAccounts)\n }, [])\n async function handleLogin() {\n await cookie.clear()",
"score": 0.8214787244796753
},
{
"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": 0.8184901475906372
},
{
"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": 0.8145900964736938
}
] |
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/types.ts",
"retrieved_chunk": "export type RemoveAccountMessage = Message<'removeAccount', { account: string }>\nexport type RemoveAccountResponse = Response\nexport type GetAutoSwitchRulesMessage = Message<'getAutoSwitchRules'>\nexport type GetAutoSwitchRulesResponse = Response<Rule[]>\nexport type RequestMessage =\n | GetAccountsMessage\n | ClearCookiesMessage\n | SwitchAccountMessage\n | RemoveAccountMessage\n | GetAutoSwitchRulesMessage",
"score": 0.8707626461982727
},
{
"filename": "src/types.ts",
"retrieved_chunk": "import { Rule } from './services/rule'\ntype Message<T extends string, P = {}> = { type: T } & P\ntype ErrorResponse = { success: false; error: Error }\nexport type Response<T = void> = { success: true; data: T } | ErrorResponse\nexport type GetAccountsMessage = Message<'getAccounts'>\nexport type GetAccountsResponse = Response<string[]>\nexport type SwitchAccountMessage = Message<'switchAccount', { account: string }>\nexport type SwitchAccountResponse = Response\nexport type ClearCookiesMessage = Message<'clearCookies'>\nexport type ClearCookiesResponse = Response",
"score": 0.8483946323394775
},
{
"filename": "src/content/index.ts",
"retrieved_chunk": "async function getAutoSwitchRules() {\n const res: GetAutoSwitchRulesResponse = await browser.runtime.sendMessage({\n type: 'getAutoSwitchRules',\n } as GetAutoSwitchRulesMessage)\n return res?.success ? res.data : []\n}\nasync function addAccount() {\n await browser.runtime.sendMessage({ type: 'clearCookies' } as ClearCookiesMessage)\n const autoSwitchRules = await getAutoSwitchRules()\n window.location.href = isNormalGitHubUrl(window.location.href, autoSwitchRules)",
"score": 0.8429328203201294
},
{
"filename": "src/content/index.ts",
"retrieved_chunk": " ? `/login?return_to=${encodeURIComponent(window.location.href)}`\n : '/login'\n}\nasync function switchAccount(account: string) {\n await browser.runtime.sendMessage({ type: 'switchAccount', account })\n const autoSwitchRules = await getAutoSwitchRules()\n if (isNormalGitHubUrl(window.location.href, autoSwitchRules)) {\n window.location.reload()\n } else {\n window.location.href = '/'",
"score": 0.833104133605957
},
{
"filename": "src/services/account.ts",
"retrieved_chunk": "async function switchTo(accountName: string) {\n await cookie.clear()\n const account = await find(accountName)\n const cookies = account?.cookies || []\n for (const cookie of cookies) {\n const { hostOnly, domain, session, ...rest } = cookie\n await browser.cookies.set({\n url: 'https://github.com',\n domain: hostOnly ? undefined : domain,\n ...rest,",
"score": 0.8188782930374146
}
] |
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/content/index.ts",
"retrieved_chunk": "async function getAutoSwitchRules() {\n const res: GetAutoSwitchRulesResponse = await browser.runtime.sendMessage({\n type: 'getAutoSwitchRules',\n } as GetAutoSwitchRulesMessage)\n return res?.success ? res.data : []\n}\nasync function addAccount() {\n await browser.runtime.sendMessage({ type: 'clearCookies' } as ClearCookiesMessage)\n const autoSwitchRules = await getAutoSwitchRules()\n window.location.href = isNormalGitHubUrl(window.location.href, autoSwitchRules)",
"score": 0.8768367171287537
},
{
"filename": "src/background/index.ts",
"retrieved_chunk": " if (!account) {\n return\n }\n await accountService.upsert(account, await cookie.getAll())\n const accounts = await accountService.getAll()\n console.info('synced accounts', accounts)\n await updateDynamicRequestRules()\n const res = await fetch(`https://github.com/${account}.png?size=100`)\n if (res.status === 200) {\n accountService.saveAvatar(account, res.url)",
"score": 0.8758609294891357
},
{
"filename": "src/services/account.ts",
"retrieved_chunk": " expiresAt?: Date\n}\ntype Accounts = Record<string, Cookie[]>\nasync function getAll(): Promise<Account[]> {\n const accounts = await storage.get<Accounts>('accounts')\n if (!accounts) {\n return []\n }\n const currentAccount = await browser.cookies.get({\n url: 'https://github.com',",
"score": 0.8688070774078369
},
{
"filename": "src/content/index.ts",
"retrieved_chunk": " ? `/login?return_to=${encodeURIComponent(window.location.href)}`\n : '/login'\n}\nasync function switchAccount(account: string) {\n await browser.runtime.sendMessage({ type: 'switchAccount', account })\n const autoSwitchRules = await getAutoSwitchRules()\n if (isNormalGitHubUrl(window.location.href, autoSwitchRules)) {\n window.location.reload()\n } else {\n window.location.href = '/'",
"score": 0.8556935787200928
},
{
"filename": "src/background/index.ts",
"retrieved_chunk": " 'websocket',\n 'xmlhttprequest',\n]\nasync function syncAccounts() {\n const usernameCookie = await cookie.get('dotcom_user')\n const sessionCookie = await cookie.get('user_session')\n if (!usernameCookie || !sessionCookie) {\n return\n }\n const { value: account } = usernameCookie",
"score": 0.8518005609512329
}
] |
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/popup/components/Accounts.tsx",
"retrieved_chunk": " title={`Remove ${account.name}`}\n onClick={() => handleRemove(account.name)}\n >\n <IconButton color=\"warning\">\n <Close />\n </IconButton>\n </Tooltip>\n </ListItemSecondaryAction>\n </ListItem>\n ))}",
"score": 0.8636086583137512
},
{
"filename": "src/content/index.ts",
"retrieved_chunk": " if (account === currentAccount) {\n continue\n }\n const accountId = `${ACCOUNT_ITEM_CLASS}-${account}`\n if (!document.getElementById(accountId) && addAccountButton) {\n const accountWrapper = createAccountItem(account)\n addAccountButton.parentElement?.insertBefore(accountWrapper, addAccountButton)\n }\n }\n}",
"score": 0.851982593536377
},
{
"filename": "src/content/index.ts",
"retrieved_chunk": " if (!document.getElementById(ADD_ACCOUNT_BUTTON_ID)) {\n // Add the \"Add another account\" menu item and a divider\n const fragment = createElement('fragment', {\n children: [\n createAddAccountLink(),\n createDivider(),\n ],\n })\n // Insert the elements before the logoutForm\n logoutForm.parentElement?.insertBefore(fragment, logoutForm)",
"score": 0.8382054567337036
},
{
"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": 0.8322848081588745
},
{
"filename": "src/content/index.ts",
"retrieved_chunk": " const closestTarget = target.closest(`.${ACCOUNT_ITEM_CLASS}`) as HTMLElement\n const { account } = closestTarget.dataset\n switchAccount(account!)\n } else if (target.closest(`.${ACCOUNT_REMOVE_CLASS}`)) {\n // remove account\n const btn = target.closest(`.${ACCOUNT_REMOVE_CLASS}`) as HTMLElement\n const { account } = btn.dataset\n removeAccount(account!).then(() => {\n btn.parentElement?.remove()\n })",
"score": 0.8320719003677368
}
] |
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/popup/components/RuleItem.tsx",
"retrieved_chunk": " />\n </Box>\n <Box width={150} flexShrink={0}>\n <TextField\n size=\"medium\"\n variant=\"standard\"\n fullWidth\n placeholder=\"GitHub account\"\n error={!!accountValidation}\n helperText={accountValidation}",
"score": 0.8157804012298584
},
{
"filename": "src/content/ui.ts",
"retrieved_chunk": " ]\n }),\n createElement('button', {\n title: 'Remove account',\n 'data-account': account,\n class: `btn-link color-fg-danger ${ACCOUNT_REMOVE_CLASS}`,\n children: createRemoveIcon(),\n })\n ]\n })",
"score": 0.8110504746437073
},
{
"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": 0.8018190860748291
},
{
"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": 0.8003643751144409
},
{
"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": 0.7999134659767151
}
] |
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": 0.8395911455154419
},
{
"filename": "src/popup/components/Settings.tsx",
"retrieved_chunk": " value=\"accounts\"\n sx={{ textTransform: 'none', minHeight: 50 }}\n />\n <Tab\n icon={<Rule />}\n iconPosition=\"start\"\n label=\"Auto Switch Rules\"\n value=\"rules\"\n sx={{ textTransform: 'none', minHeight: 50 }}\n />",
"score": 0.8273426294326782
},
{
"filename": "src/services/rule.ts",
"retrieved_chunk": "async function add(rule: Rule) {\n await storage.update<Rule[]>('rules', (rules = []) => {\n return [...rules, rule]\n })\n}\nasync function update(rule: Rule) {\n await storage.update<Rule[]>('rules', (rules = []) => {\n return rules.map((r) => (r.id === rule.id ? rule : r))\n })\n}",
"score": 0.81929612159729
},
{
"filename": "src/popup/components/RuleItem.tsx",
"retrieved_chunk": " value={rule.account}\n onChange={handleAccountChange}\n disabled={!isEditing}\n />\n </Box>\n <Box display=\"flex\" flexShrink={0}>\n {!isEditing && (\n <Tooltip title=\"Edit\">\n <IconButton size=\"small\" color=\"primary\" onClick={handleEdit}>\n <Edit />",
"score": 0.8064174056053162
},
{
"filename": "src/popup/components/Accounts.tsx",
"retrieved_chunk": " }\n return (\n <Box>\n <Alert severity=\"info\" sx={{ mb: 2 }}>\n You can manage your logged in accounts here.\n </Alert>\n <Box sx={{ mb: 1 }}>\n <List dense disablePadding>\n {accounts.map((account, i) => (\n <ListItem key={account.name} disableGutters divider={i !== accounts.length - 1}>",
"score": 0.8045554757118225
}
] |
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": 0.8747598528862
},
{
"filename": "src/content/index.ts",
"retrieved_chunk": "async function getAutoSwitchRules() {\n const res: GetAutoSwitchRulesResponse = await browser.runtime.sendMessage({\n type: 'getAutoSwitchRules',\n } as GetAutoSwitchRulesMessage)\n return res?.success ? res.data : []\n}\nasync function addAccount() {\n await browser.runtime.sendMessage({ type: 'clearCookies' } as ClearCookiesMessage)\n const autoSwitchRules = await getAutoSwitchRules()\n window.location.href = isNormalGitHubUrl(window.location.href, autoSwitchRules)",
"score": 0.8744975328445435
},
{
"filename": "src/services/account.ts",
"retrieved_chunk": " expiresAt?: Date\n}\ntype Accounts = Record<string, Cookie[]>\nasync function getAll(): Promise<Account[]> {\n const accounts = await storage.get<Accounts>('accounts')\n if (!accounts) {\n return []\n }\n const currentAccount = await browser.cookies.get({\n url: 'https://github.com',",
"score": 0.8690502643585205
},
{
"filename": "src/content/index.ts",
"retrieved_chunk": " ? `/login?return_to=${encodeURIComponent(window.location.href)}`\n : '/login'\n}\nasync function switchAccount(account: string) {\n await browser.runtime.sendMessage({ type: 'switchAccount', account })\n const autoSwitchRules = await getAutoSwitchRules()\n if (isNormalGitHubUrl(window.location.href, autoSwitchRules)) {\n window.location.reload()\n } else {\n window.location.href = '/'",
"score": 0.8527964353561401
},
{
"filename": "src/background/index.ts",
"retrieved_chunk": " 'websocket',\n 'xmlhttprequest',\n]\nasync function syncAccounts() {\n const usernameCookie = await cookie.get('dotcom_user')\n const sessionCookie = await cookie.get('user_session')\n if (!usernameCookie || !sessionCookie) {\n return\n }\n const { value: account } = usernameCookie",
"score": 0.8505089282989502
}
] |
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/popup/components/Header.tsx",
"retrieved_chunk": "import { GitHub } from '@mui/icons-material'\nimport { Avatar, Container, IconButton, Typography } from '@mui/material'\nimport { useState } from 'react'\nimport logo from '../../assets/logo.png'\nexport default function Header() {\n const [active, setActive] = useState(false)\n function handleClick() {\n setActive(!active)\n }\n return (",
"score": 0.8423207998275757
},
{
"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": 0.8333738446235657
},
{
"filename": "src/services/account.ts",
"retrieved_chunk": " if (!accounts) {\n return\n }\n delete accounts[accountName]\n return accounts\n })\n}\nasync function saveAvatar(accountName: string, avatarUrl: string) {\n await storage.update<Record<string, string>>('avatars', (avatars = {}) => {\n avatars[accountName] = avatarUrl",
"score": 0.8222081661224365
},
{
"filename": "src/background/index.ts",
"retrieved_chunk": " if (!account) {\n return\n }\n await accountService.upsert(account, await cookie.getAll())\n const accounts = await accountService.getAll()\n console.info('synced accounts', accounts)\n await updateDynamicRequestRules()\n const res = await fetch(`https://github.com/${account}.png?size=100`)\n if (res.status === 200) {\n accountService.saveAvatar(account, res.url)",
"score": 0.820745050907135
},
{
"filename": "src/popup/components/RuleItem.tsx",
"retrieved_chunk": " />\n </Box>\n <Box width={150} flexShrink={0}>\n <TextField\n size=\"medium\"\n variant=\"standard\"\n fullWidth\n placeholder=\"GitHub account\"\n error={!!accountValidation}\n helperText={accountValidation}",
"score": 0.8190524578094482
}
] |
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/content/index.ts",
"retrieved_chunk": " ? `/login?return_to=${encodeURIComponent(window.location.href)}`\n : '/login'\n}\nasync function switchAccount(account: string) {\n await browser.runtime.sendMessage({ type: 'switchAccount', account })\n const autoSwitchRules = await getAutoSwitchRules()\n if (isNormalGitHubUrl(window.location.href, autoSwitchRules)) {\n window.location.reload()\n } else {\n window.location.href = '/'",
"score": 0.8685494661331177
},
{
"filename": "src/content/index.ts",
"retrieved_chunk": "async function getAutoSwitchRules() {\n const res: GetAutoSwitchRulesResponse = await browser.runtime.sendMessage({\n type: 'getAutoSwitchRules',\n } as GetAutoSwitchRulesMessage)\n return res?.success ? res.data : []\n}\nasync function addAccount() {\n await browser.runtime.sendMessage({ type: 'clearCookies' } as ClearCookiesMessage)\n const autoSwitchRules = await getAutoSwitchRules()\n window.location.href = isNormalGitHubUrl(window.location.href, autoSwitchRules)",
"score": 0.8609907627105713
},
{
"filename": "src/services/account.ts",
"retrieved_chunk": "async function switchTo(accountName: string) {\n await cookie.clear()\n const account = await find(accountName)\n const cookies = account?.cookies || []\n for (const cookie of cookies) {\n const { hostOnly, domain, session, ...rest } = cookie\n await browser.cookies.set({\n url: 'https://github.com',\n domain: hostOnly ? undefined : domain,\n ...rest,",
"score": 0.844255805015564
},
{
"filename": "src/content/index.ts",
"retrieved_chunk": "import browser from 'webextension-polyfill'\nimport { isNormalGitHubUrl, removeAccount } from '../shared'\nimport {\n ClearCookiesMessage,\n GetAccountsMessage,\n GetAccountsResponse,\n GetAutoSwitchRulesMessage,\n GetAutoSwitchRulesResponse,\n} from '../types'\nimport './index.css'",
"score": 0.8277670741081238
},
{
"filename": "src/shared.ts",
"retrieved_chunk": " return false\n }\n if (urlMatchesAnyRule(url, rules)) {\n return false\n }\n return true\n}\nexport async function removeAccount(account: string) {\n await browser.runtime.sendMessage({ type: 'removeAccount', account })\n}",
"score": 0.8236589431762695
}
] |
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/content/index.ts",
"retrieved_chunk": " }\n const res: GetAccountsResponse = await browser.runtime.sendMessage({\n type: 'getAccounts',\n } as GetAccountsMessage)\n if (!res?.success) {\n return\n }\n const { data: accounts } = res\n const addAccountButton = document.getElementById(ADD_ACCOUNT_BUTTON_ID)!\n for (const account of accounts) {",
"score": 0.8672498464584351
},
{
"filename": "src/services/account.ts",
"retrieved_chunk": " expiresAt?: Date\n}\ntype Accounts = Record<string, Cookie[]>\nasync function getAll(): Promise<Account[]> {\n const accounts = await storage.get<Accounts>('accounts')\n if (!accounts) {\n return []\n }\n const currentAccount = await browser.cookies.get({\n url: 'https://github.com',",
"score": 0.8560168743133545
},
{
"filename": "src/background/index.ts",
"retrieved_chunk": " 'websocket',\n 'xmlhttprequest',\n]\nasync function syncAccounts() {\n const usernameCookie = await cookie.get('dotcom_user')\n const sessionCookie = await cookie.get('user_session')\n if (!usernameCookie || !sessionCookie) {\n return\n }\n const { value: account } = usernameCookie",
"score": 0.8496577143669128
},
{
"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": 0.8347968459129333
},
{
"filename": "src/background/index.ts",
"retrieved_chunk": " if (!account) {\n return\n }\n await accountService.upsert(account, await cookie.getAll())\n const accounts = await accountService.getAll()\n console.info('synced accounts', accounts)\n await updateDynamicRequestRules()\n const res = await fetch(`https://github.com/${account}.png?size=100`)\n if (res.status === 200) {\n accountService.saveAvatar(account, res.url)",
"score": 0.8333508968353271
}
] |
typescript
|
.getAll().then(setAccounts)
}, [])
async function handleLogin() {
|
import type { GeneralOptions } from '../../typings/General'
import { isAuthenticated } from '../../helpers/isAuthenticated'
import fs from 'fs'
import path from 'path'
import {
extractCodeFromFile,
extractCodeFromString
} from '../../helpers/extractCode'
import { config } from '../../helpers/authSystem'
import { openAIChat } from '../../helpers/openAIChat'
import { red, yellow, green } from 'kleur/colors'
export const generateTestAction = async (options: GeneralOptions) => {
const componentName = options[Object.keys(options)[0]]
const componentPath = options[Object.keys(options)[1]]
const testLibrary = options[Object.keys(options)[2]]
const componentExtension = path.extname(componentPath)
// verify authentication
const isAuth = await isAuthenticated()
if (!isAuth) return
if (!componentName || !componentPath) {
return console.log(
red(`\nYou did not enter the expected component name or path!`),
yellow(
`\n* use --component or -c to declare component name\n* use --path or -p to declare component path\nuse --library or -l to declare the desired test library`
)
)
}
// read the contents of the component file
const componentCode = extractCodeFromFile(componentPath)
if (!componentCode) {
return console.log(
red(`\nI didn't find your component. Check the path and try again!`),
yellow(`\nexample path: ./src/components/MyComponent/index.tsx`)
)
}
// generate test code
const params = {
text: `Create the code with test (containing all necessary imports) in ${
testLibrary ? testLibrary : 'Jest'
} in code form based on the following component:\n${componentCode}`,
method: 'POST',
key: config.apiKey
}
const openAIChatResponse
|
= await openAIChat(params)
const testCode = extractCodeFromString(openAIChatResponse.data)
if (!testCode) {
|
return console.log(
red(
`\nUnable to generate a test. Check the component code and try again!`
)
)
}
// get component folder path
const componentFolderPath = componentPath.split('/').slice(0, -1).join('/')
// save the test code to a new file
const testFilePath = `${componentFolderPath}/${componentName}.test${componentExtension}`
fs.writeFileSync(testFilePath, testCode)
console.log(
green(`\nTest generated successfully in: ${testFilePath}`),
yellow(
`\nif you don't like the generated test, you can run the command again to generate another one over the previous one`
)
)
}
|
src/commands/generateTest/generateTestAction.ts
|
zonixlab-zonix-e7c108a
|
[
{
"filename": "src/commands/auth/authAction.ts",
"retrieved_chunk": " )\n }\n const params = {\n text: `Hello!`,\n method: 'POST',\n key\n }\n const openAIChatResponse = await openAIChat(params)\n if (openAIChatResponse.error) {\n return console.log(",
"score": 0.8847527503967285
},
{
"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": 0.8698529601097107
},
{
"filename": "src/commands/hello/helloAction.ts",
"retrieved_chunk": " if (!isAuth) return\n const params = {\n text: `Return me a random greeting from movies, cartoons or series`,\n method: 'POST',\n key: config.apiKey\n }\n const openAIChatResponse = await openAIChat(params)\n return console.log(\n green(`\\n${openAIChatResponse.data}`),\n yellow(`\\nuse --name or -n to declare your name and get a greeting`)",
"score": 0.8364801406860352
},
{
"filename": "src/helpers/openAIChat.ts",
"retrieved_chunk": "import axios, { AxiosError } from 'axios'\nimport type { OpenAIChatProps } from '../typings/OpenAI'\nexport const openAIChat = async ({ text, method, key }: OpenAIChatProps) => {\n try {\n const chatBody = {\n model: 'gpt-3.5-turbo',\n messages: [\n {\n role: 'user',\n content: text",
"score": 0.8351610898971558
},
{
"filename": "src/helpers/openAIChat.ts",
"retrieved_chunk": " }\n ]\n }\n const response = await axios(`https://api.openai.com/v1/chat/completions`, {\n method,\n headers: {\n 'Content-Type': 'application/json',\n Authorization: `Bearer ${key}`\n },\n data: JSON.stringify(chatBody)",
"score": 0.8221840262413025
}
] |
typescript
|
= await openAIChat(params)
const testCode = extractCodeFromString(openAIChatResponse.data)
if (!testCode) {
|
import browser, { Cookies } from 'webextension-polyfill'
import { setBadgeText } from './badge'
import cookie from './cookie'
import storage from './storage'
type Cookie = Cookies.Cookie
export type Account = {
name: string
cookies: Cookie[]
active: boolean
avatarUrl?: string
expiresAt?: Date
}
type Accounts = Record<string, Cookie[]>
async function getAll(): Promise<Account[]> {
const accounts = await storage.get<Accounts>('accounts')
if (!accounts) {
return []
}
const currentAccount = await browser.cookies.get({
url: 'https://github.com',
name: 'dotcom_user',
})
const avatarUrls = await storage.get<Record<string, string>>('avatars')
return Object.entries(accounts).map(([name, cookies]) => {
const userSessionCookie = cookies.find(({ name }) => name === 'user_session')
return {
name,
cookies,
active: currentAccount?.value === name,
avatarUrl: avatarUrls?.[name],
expiresAt: userSessionCookie?.expirationDate
? new Date(userSessionCookie.expirationDate * 1000)
: undefined,
}
})
}
async function getAllNames(): Promise<string[]> {
const accounts = await getAll()
return accounts.map(({ name }) => name)
}
async function find(accountName: string): Promise<Account | undefined> {
const accounts = await getAll()
return accounts.find((account) => account.name === accountName)
}
async function upsert(accountName: string, cookies: Cookie[]) {
await storage.update<Accounts>('accounts', (accounts = {}) => {
accounts[accountName] = cookies
return accounts
})
}
async function switchTo(accountName: string) {
await cookie.clear()
const account = await find(accountName)
const cookies = account?.cookies || []
for (const cookie of cookies) {
const { hostOnly, domain, session, ...rest } = cookie
await browser.cookies.set({
url: 'https://github.com',
domain: hostOnly ? undefined : domain,
...rest,
})
}
if (cookies.length) {
setBadgeText(accountName.slice(0, 2))
} else {
setBadgeText('...')
}
}
async function remove(accountName: string) {
|
await storage.update<Accounts>('accounts', (accounts) => {
|
if (!accounts) {
return
}
delete accounts[accountName]
return accounts
})
}
async function saveAvatar(accountName: string, avatarUrl: string) {
await storage.update<Record<string, string>>('avatars', (avatars = {}) => {
avatars[accountName] = avatarUrl
return avatars
})
}
export default {
getAll,
getAllNames,
find,
upsert,
switchTo,
remove,
saveAvatar,
}
|
src/services/account.ts
|
yuezk-github-account-switcher-36b3c11
|
[
{
"filename": "src/background/index.ts",
"retrieved_chunk": " }\n await setBadgeText(account.slice(0, 2))\n}\nasync function removeAccount(accountName: string) {\n await accountService.remove(accountName)\n await updateDynamicRequestRules()\n}\nasync function buildCookieValue(accountName: string): Promise<string | null> {\n const account = await accountService.find(accountName)\n const cookies = account?.cookies || []",
"score": 0.9188395738601685
},
{
"filename": "src/popup/components/Accounts.tsx",
"retrieved_chunk": " } else if (isGitHubUrl(tab?.url)) {\n await browser.tabs.update(tab?.id!, { url: 'https://github.com' })\n } else {\n await browser.tabs.create({ url: 'https://github.com' })\n }\n window.close()\n }\n async function handleRemove(accountName: string) {\n await removeAccount(accountName)\n setAccounts(accounts.filter((account) => account.name !== accountName))",
"score": 0.8622457981109619
},
{
"filename": "src/background/index.ts",
"retrieved_chunk": " if (!account) {\n return\n }\n await accountService.upsert(account, await cookie.getAll())\n const accounts = await accountService.getAll()\n console.info('synced accounts', accounts)\n await updateDynamicRequestRules()\n const res = await fetch(`https://github.com/${account}.png?size=100`)\n if (res.status === 200) {\n accountService.saveAvatar(account, res.url)",
"score": 0.8460684418678284
},
{
"filename": "src/shared.ts",
"retrieved_chunk": " return false\n }\n if (urlMatchesAnyRule(url, rules)) {\n return false\n }\n return true\n}\nexport async function removeAccount(account: string) {\n await browser.runtime.sendMessage({ type: 'removeAccount', account })\n}",
"score": 0.8370774984359741
},
{
"filename": "src/popup/components/Accounts.tsx",
"retrieved_chunk": " const [tab] = await browser.tabs.query(queryOptions)\n return tab\n}\nexport default function Accounts() {\n const [accounts, setAccounts] = useState<Account[]>([])\n useEffect(() => {\n accountService.getAll().then(setAccounts)\n }, [])\n async function handleLogin() {\n await cookie.clear()",
"score": 0.8354265093803406
}
] |
typescript
|
await storage.update<Accounts>('accounts', (accounts) => {
|
import browser, { Cookies } from 'webextension-polyfill'
import { setBadgeText } from './badge'
import cookie from './cookie'
import storage from './storage'
type Cookie = Cookies.Cookie
export type Account = {
name: string
cookies: Cookie[]
active: boolean
avatarUrl?: string
expiresAt?: Date
}
type Accounts = Record<string, Cookie[]>
async function getAll(): Promise<Account[]> {
const accounts = await storage.get<Accounts>('accounts')
if (!accounts) {
return []
}
const currentAccount = await browser.cookies.get({
url: 'https://github.com',
name: 'dotcom_user',
})
const avatarUrls = await storage.get<Record<string, string>>('avatars')
return Object.entries(accounts).map(([name, cookies]) => {
const userSessionCookie = cookies.find(({ name }) => name === 'user_session')
return {
name,
cookies,
active: currentAccount?.value === name,
avatarUrl: avatarUrls?.[name],
expiresAt: userSessionCookie?.expirationDate
? new Date(userSessionCookie.expirationDate * 1000)
: undefined,
}
})
}
async function getAllNames(): Promise<string[]> {
const accounts = await getAll()
return accounts.map(({ name }) => name)
}
async function find(accountName: string): Promise<Account | undefined> {
const accounts = await getAll()
return accounts.find((account) => account.name === accountName)
}
async function upsert(accountName: string, cookies: Cookie[]) {
|
await storage.update<Accounts>('accounts', (accounts = {}) => {
|
accounts[accountName] = cookies
return accounts
})
}
async function switchTo(accountName: string) {
await cookie.clear()
const account = await find(accountName)
const cookies = account?.cookies || []
for (const cookie of cookies) {
const { hostOnly, domain, session, ...rest } = cookie
await browser.cookies.set({
url: 'https://github.com',
domain: hostOnly ? undefined : domain,
...rest,
})
}
if (cookies.length) {
setBadgeText(accountName.slice(0, 2))
} else {
setBadgeText('...')
}
}
async function remove(accountName: string) {
await storage.update<Accounts>('accounts', (accounts) => {
if (!accounts) {
return
}
delete accounts[accountName]
return accounts
})
}
async function saveAvatar(accountName: string, avatarUrl: string) {
await storage.update<Record<string, string>>('avatars', (avatars = {}) => {
avatars[accountName] = avatarUrl
return avatars
})
}
export default {
getAll,
getAllNames,
find,
upsert,
switchTo,
remove,
saveAvatar,
}
|
src/services/account.ts
|
yuezk-github-account-switcher-36b3c11
|
[
{
"filename": "src/background/index.ts",
"retrieved_chunk": " }\n await setBadgeText(account.slice(0, 2))\n}\nasync function removeAccount(accountName: string) {\n await accountService.remove(accountName)\n await updateDynamicRequestRules()\n}\nasync function buildCookieValue(accountName: string): Promise<string | null> {\n const account = await accountService.find(accountName)\n const cookies = account?.cookies || []",
"score": 0.879752516746521
},
{
"filename": "src/background/index.ts",
"retrieved_chunk": " if (!account) {\n return\n }\n await accountService.upsert(account, await cookie.getAll())\n const accounts = await accountService.getAll()\n console.info('synced accounts', accounts)\n await updateDynamicRequestRules()\n const res = await fetch(`https://github.com/${account}.png?size=100`)\n if (res.status === 200) {\n accountService.saveAvatar(account, res.url)",
"score": 0.8603782653808594
},
{
"filename": "src/background/index.ts",
"retrieved_chunk": " 'websocket',\n 'xmlhttprequest',\n]\nasync function syncAccounts() {\n const usernameCookie = await cookie.get('dotcom_user')\n const sessionCookie = await cookie.get('user_session')\n if (!usernameCookie || !sessionCookie) {\n return\n }\n const { value: account } = usernameCookie",
"score": 0.8464173078536987
},
{
"filename": "src/popup/components/Accounts.tsx",
"retrieved_chunk": " const [tab] = await browser.tabs.query(queryOptions)\n return tab\n}\nexport default function Accounts() {\n const [accounts, setAccounts] = useState<Account[]>([])\n useEffect(() => {\n accountService.getAll().then(setAccounts)\n }, [])\n async function handleLogin() {\n await cookie.clear()",
"score": 0.8419386148452759
},
{
"filename": "src/services/cookie.ts",
"retrieved_chunk": "import browser from 'webextension-polyfill'\nconst COOKIE_URL = 'https://github.com'\nasync function get(name: string) {\n return browser.cookies.get({ url: COOKIE_URL, name })\n}\nasync function getAll() {\n return browser.cookies.getAll({ url: COOKIE_URL })\n}\nasync function clear() {\n const cookies = await getAll()",
"score": 0.8349406719207764
}
] |
typescript
|
await storage.update<Accounts>('accounts', (accounts = {}) => {
|
import browser, { Cookies } from 'webextension-polyfill'
import { setBadgeText } from './badge'
import cookie from './cookie'
import storage from './storage'
type Cookie = Cookies.Cookie
export type Account = {
name: string
cookies: Cookie[]
active: boolean
avatarUrl?: string
expiresAt?: Date
}
type Accounts = Record<string, Cookie[]>
async function getAll(): Promise<Account[]> {
const accounts = await storage.get<Accounts>('accounts')
if (!accounts) {
return []
}
const currentAccount = await browser.cookies.get({
url: 'https://github.com',
name: 'dotcom_user',
})
const avatarUrls = await storage.get<Record<string, string>>('avatars')
return Object.entries(accounts).map(([name, cookies]) => {
const userSessionCookie = cookies.find(({ name }) => name === 'user_session')
return {
name,
cookies,
active: currentAccount?.value === name,
avatarUrl: avatarUrls?.[name],
expiresAt: userSessionCookie?.expirationDate
? new Date(userSessionCookie.expirationDate * 1000)
: undefined,
}
})
}
async function getAllNames(): Promise<string[]> {
const accounts = await getAll()
return accounts.map(({ name }) => name)
}
async function find(accountName: string): Promise<Account | undefined> {
const accounts = await getAll()
return accounts.find((account) => account.name === accountName)
}
async function upsert(accountName: string, cookies: Cookie[]) {
await storage.update<Accounts>('accounts', (accounts = {}) => {
accounts[accountName] = cookies
return accounts
})
}
async function switchTo(accountName: string) {
await cookie.
|
clear()
const account = await find(accountName)
const cookies = account?.cookies || []
for (const cookie of cookies) {
|
const { hostOnly, domain, session, ...rest } = cookie
await browser.cookies.set({
url: 'https://github.com',
domain: hostOnly ? undefined : domain,
...rest,
})
}
if (cookies.length) {
setBadgeText(accountName.slice(0, 2))
} else {
setBadgeText('...')
}
}
async function remove(accountName: string) {
await storage.update<Accounts>('accounts', (accounts) => {
if (!accounts) {
return
}
delete accounts[accountName]
return accounts
})
}
async function saveAvatar(accountName: string, avatarUrl: string) {
await storage.update<Record<string, string>>('avatars', (avatars = {}) => {
avatars[accountName] = avatarUrl
return avatars
})
}
export default {
getAll,
getAllNames,
find,
upsert,
switchTo,
remove,
saveAvatar,
}
|
src/services/account.ts
|
yuezk-github-account-switcher-36b3c11
|
[
{
"filename": "src/background/index.ts",
"retrieved_chunk": " }\n await setBadgeText(account.slice(0, 2))\n}\nasync function removeAccount(accountName: string) {\n await accountService.remove(accountName)\n await updateDynamicRequestRules()\n}\nasync function buildCookieValue(accountName: string): Promise<string | null> {\n const account = await accountService.find(accountName)\n const cookies = account?.cookies || []",
"score": 0.8767253160476685
},
{
"filename": "src/popup/components/Accounts.tsx",
"retrieved_chunk": " const [tab] = await browser.tabs.query(queryOptions)\n return tab\n}\nexport default function Accounts() {\n const [accounts, setAccounts] = useState<Account[]>([])\n useEffect(() => {\n accountService.getAll().then(setAccounts)\n }, [])\n async function handleLogin() {\n await cookie.clear()",
"score": 0.8501737117767334
},
{
"filename": "src/background/index.ts",
"retrieved_chunk": " 'websocket',\n 'xmlhttprequest',\n]\nasync function syncAccounts() {\n const usernameCookie = await cookie.get('dotcom_user')\n const sessionCookie = await cookie.get('user_session')\n if (!usernameCookie || !sessionCookie) {\n return\n }\n const { value: account } = usernameCookie",
"score": 0.8427298069000244
},
{
"filename": "src/content/index.ts",
"retrieved_chunk": " ? `/login?return_to=${encodeURIComponent(window.location.href)}`\n : '/login'\n}\nasync function switchAccount(account: string) {\n await browser.runtime.sendMessage({ type: 'switchAccount', account })\n const autoSwitchRules = await getAutoSwitchRules()\n if (isNormalGitHubUrl(window.location.href, autoSwitchRules)) {\n window.location.reload()\n } else {\n window.location.href = '/'",
"score": 0.83890700340271
},
{
"filename": "src/background/index.ts",
"retrieved_chunk": " if (!account) {\n return\n }\n await accountService.upsert(account, await cookie.getAll())\n const accounts = await accountService.getAll()\n console.info('synced accounts', accounts)\n await updateDynamicRequestRules()\n const res = await fetch(`https://github.com/${account}.png?size=100`)\n if (res.status === 200) {\n accountService.saveAvatar(account, res.url)",
"score": 0.8358727097511292
}
] |
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/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": 0.8506383895874023
},
{
"filename": "src/popup/components/Accounts.tsx",
"retrieved_chunk": " } else if (isGitHubUrl(tab?.url)) {\n await browser.tabs.update(tab?.id!, { url: 'https://github.com' })\n } else {\n await browser.tabs.create({ url: 'https://github.com' })\n }\n window.close()\n }\n async function handleRemove(accountName: string) {\n await removeAccount(accountName)\n setAccounts(accounts.filter((account) => account.name !== accountName))",
"score": 0.8378911018371582
},
{
"filename": "src/content/ui.ts",
"retrieved_chunk": " class: `dropdown-item ${ADD_ACCOUNT_BUTTON_ID}`,\n children: 'Add another account'\n })\n },\n createAccountItem(account: string) {\n const accountId = `${ACCOUNT_ITEM_CLASS}-${account}`\n return createElement('div', {\n id: accountId,\n class: 'gh-account-switcher__account-wrapper',\n children: [",
"score": 0.8346335887908936
},
{
"filename": "src/content/ui.ts",
"retrieved_chunk": " ]\n })\n },\n createAccountItem(account: string) {\n const accountId = `${ACCOUNT_ITEM_CLASS}-${account}`\n return createElement('li', {\n id: accountId,\n class: 'ActionListItem',\n children: [\n createElement('button', {",
"score": 0.8249548673629761
},
{
"filename": "src/content/ui.ts",
"retrieved_chunk": " ]\n }),\n createElement('button', {\n title: 'Remove account',\n 'data-account': account,\n class: `btn-link color-fg-danger ${ACCOUNT_REMOVE_CLASS}`,\n children: createRemoveIcon(),\n })\n ]\n })",
"score": 0.8246028423309326
}
] |
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/marching_cubes.ts",
"retrieved_chunk": " computeVoxelValuesWgsl + \"\\n\" + computeNumVertsWgsl, \"compute_num_verts.wgsl\");\n let computeVertices = await compileShader(device,\n computeVoxelValuesWgsl + \"\\n\" + computeVerticesWgsl, \"compute_vertices.wgsl\");\n // Bind group layout for the volume parameters, shared by all pipelines in group 0\n let volumeInfoBGLayout = device.createBindGroupLayout({\n entries: [\n {\n binding: 0,\n visibility: GPUShaderStage.COMPUTE,\n texture: {",
"score": 0.8321371078491211
},
{
"filename": "src/marching_cubes.ts",
"retrieved_chunk": " ]\n });\n mc.#volumeInfoBG = device.createBindGroup({\n layout: volumeInfoBGLayout,\n entries: [\n {\n binding: 0,\n resource: mc.#volume.texture.createView(),\n },\n {",
"score": 0.8310520648956299
},
{
"filename": "src/marching_cubes.ts",
"retrieved_chunk": " });\n mc.#computeVerticesPipeline = device.createComputePipeline({\n layout: device.createPipelineLayout({\n bindGroupLayouts: [\n volumeInfoBGLayout,\n computeVerticesBGLayout,\n pushConstantsBGLayout\n ]\n }),\n compute: {",
"score": 0.8307549953460693
},
{
"filename": "src/volume.ts",
"retrieved_chunk": " }\n async upload(device: GPUDevice)\n {\n this.#texture = device.createTexture({\n size: this.#dimensions,\n format: voxelTypeToTextureType(this.#dataType),\n dimension: \"3d\",\n usage: GPUTextureUsage.TEXTURE_BINDING | GPUTextureUsage.COPY_DST\n });\n // TODO: might need to chunk the upload to support very large volumes?",
"score": 0.8306565284729004
},
{
"filename": "src/marching_cubes.ts",
"retrieved_chunk": " }\n private async computeActiveVoxels()\n {\n let dispatchSize = [\n Math.ceil(this.#volume.dualGridDims[0] / 4),\n Math.ceil(this.#volume.dualGridDims[1] / 4),\n Math.ceil(this.#volume.dualGridDims[2] / 2)\n ];\n let activeVoxelOffsets = this.#device.createBuffer({\n size: this.#voxelActive.size,",
"score": 0.8287583589553833
}
] |
typescript
|
fillSelector(volumePicker, volumes);
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.