mirror of
https://github.com/better-auth/better-auth.git
synced 2026-07-30 06:04:15 -05:00
chore: set noUncheckedIndexedAccess to true (#4828)
This commit is contained in:
@@ -112,8 +112,7 @@ export const createAdapterFactory =
|
||||
|
||||
let f = schema[model]?.fields[field];
|
||||
if (!f) {
|
||||
//@ts-expect-error
|
||||
f = Object.values(schema[model]?.fields).find(
|
||||
f = Object.values(schema[model]?.fields!).find(
|
||||
(f) => f.fieldName === field,
|
||||
);
|
||||
}
|
||||
@@ -181,8 +180,8 @@ export const createAdapterFactory =
|
||||
|
||||
if (useCustomModelName) {
|
||||
return usePlural
|
||||
? `${schema[defaultModelKey].modelName}s`
|
||||
: schema[defaultModelKey].modelName;
|
||||
? `${schema[defaultModelKey]!.modelName}s`
|
||||
: schema[defaultModelKey]!.modelName;
|
||||
}
|
||||
|
||||
return usePlural ? `${model}s` : model;
|
||||
@@ -320,9 +319,9 @@ export const createAdapterFactory =
|
||||
model: model,
|
||||
});
|
||||
|
||||
const fields = schema[defaultModelName].fields;
|
||||
const fields = schema[defaultModelName]!.fields;
|
||||
fields.id = idField({ customModelName: defaultModelName });
|
||||
return fields[defaultFieldName];
|
||||
return fields[defaultFieldName]!;
|
||||
};
|
||||
|
||||
const adapterInstance = customAdapter({
|
||||
@@ -343,7 +342,7 @@ export const createAdapterFactory =
|
||||
forceAllowId?: boolean,
|
||||
) => {
|
||||
const transformedData: Record<string, any> = {};
|
||||
const fields = schema[unsafe_model].fields;
|
||||
const fields = schema[unsafe_model]!.fields;
|
||||
const newMappedKeys = config.mapKeysTransformInput ?? {};
|
||||
if (
|
||||
!config.disableIdGeneration &&
|
||||
@@ -359,27 +358,27 @@ export const createAdapterFactory =
|
||||
const fieldAttributes = fields[field];
|
||||
|
||||
let newFieldName: string =
|
||||
newMappedKeys[field] || fields[field].fieldName || field;
|
||||
newMappedKeys[field] || fields[field]!.fieldName || field;
|
||||
if (
|
||||
value === undefined &&
|
||||
((fieldAttributes.defaultValue === undefined &&
|
||||
!fieldAttributes.transform?.input &&
|
||||
!(action === "update" && fieldAttributes.onUpdate)) ||
|
||||
(action === "update" && !fieldAttributes.onUpdate))
|
||||
((fieldAttributes!.defaultValue === undefined &&
|
||||
!fieldAttributes!.transform?.input &&
|
||||
!(action === "update" && fieldAttributes!.onUpdate)) ||
|
||||
(action === "update" && !fieldAttributes!.onUpdate))
|
||||
) {
|
||||
continue;
|
||||
}
|
||||
// If the value is undefined, but the fieldAttr provides a `defaultValue`, then we'll use that.
|
||||
let newValue = withApplyDefault(value, fieldAttributes, action);
|
||||
let newValue = withApplyDefault(value, fieldAttributes!, action);
|
||||
|
||||
// If the field attr provides a custom transform input, then we'll let it handle the value transformation.
|
||||
// Afterwards, we'll continue to apply the default transformations just to make sure it saves in the correct format.
|
||||
if (fieldAttributes.transform?.input) {
|
||||
newValue = await fieldAttributes.transform.input(newValue);
|
||||
if (fieldAttributes!.transform?.input) {
|
||||
newValue = await fieldAttributes!.transform.input(newValue);
|
||||
}
|
||||
|
||||
if (
|
||||
fieldAttributes.references?.field === "id" &&
|
||||
fieldAttributes!.references?.field === "id" &&
|
||||
options.advanced?.database?.useNumberId
|
||||
) {
|
||||
if (Array.isArray(newValue)) {
|
||||
@@ -390,13 +389,13 @@ export const createAdapterFactory =
|
||||
} else if (
|
||||
config.supportsJSON === false &&
|
||||
typeof newValue === "object" &&
|
||||
fieldAttributes.type === "json"
|
||||
fieldAttributes!.type === "json"
|
||||
) {
|
||||
newValue = JSON.stringify(newValue);
|
||||
} else if (
|
||||
config.supportsDates === false &&
|
||||
newValue instanceof Date &&
|
||||
fieldAttributes.type === "date"
|
||||
fieldAttributes!.type === "date"
|
||||
) {
|
||||
newValue = newValue.toISOString();
|
||||
} else if (
|
||||
@@ -411,7 +410,7 @@ export const createAdapterFactory =
|
||||
data: newValue,
|
||||
action,
|
||||
field: newFieldName,
|
||||
fieldAttributes: fieldAttributes,
|
||||
fieldAttributes: fieldAttributes!,
|
||||
model: unsafe_model,
|
||||
schema,
|
||||
options,
|
||||
@@ -433,7 +432,7 @@ export const createAdapterFactory =
|
||||
if (!data) return null;
|
||||
const newMappedKeys = config.mapKeysTransformOutput ?? {};
|
||||
const transformedData: Record<string, any> = {};
|
||||
const tableSchema = schema[unsafe_model].fields;
|
||||
const tableSchema = schema[unsafe_model]!.fields;
|
||||
const idKey = Object.entries(newMappedKeys).find(
|
||||
([_, v]) => v === "id",
|
||||
)?.[0];
|
||||
@@ -543,7 +542,10 @@ export const createAdapterFactory =
|
||||
model: defaultModelName,
|
||||
});
|
||||
|
||||
if (defaultFieldName === "id" || fieldAttr.references?.field === "id") {
|
||||
if (
|
||||
defaultFieldName === "id" ||
|
||||
fieldAttr!.references?.field === "id"
|
||||
) {
|
||||
if (options.advanced?.database?.useNumberId) {
|
||||
if (Array.isArray(value)) {
|
||||
return {
|
||||
@@ -1028,7 +1030,7 @@ export const createAdapterFactory =
|
||||
let log: any[] = debugLogs
|
||||
.reverse()
|
||||
.map((log) => {
|
||||
log[0] = `\n${log[0]}`;
|
||||
log[0] = `\n${log[0]!}`;
|
||||
return [...log, "\n"];
|
||||
})
|
||||
.reduce(
|
||||
|
||||
@@ -1425,7 +1425,7 @@ describe("Create Adapter Helper", async () => {
|
||||
expect(res).toHaveProperty("email");
|
||||
expect(res?.email).toEqual("test@test.com");
|
||||
});
|
||||
expect(parameters.where[0].field).toEqual("email_address");
|
||||
expect(parameters.where[0]!.field).toEqual("email_address");
|
||||
});
|
||||
test("findMany: Should transform the where clause according to the schema", async () => {
|
||||
const parameters: { where: Where[] | undefined; model: string } =
|
||||
@@ -1467,7 +1467,7 @@ describe("Create Adapter Helper", async () => {
|
||||
expect(res[0]).toHaveProperty("email");
|
||||
expect(res[0]?.email).toEqual("test@test.com");
|
||||
});
|
||||
expect(parameters.where?.[0].field).toEqual("email_address");
|
||||
expect(parameters.where?.[0]!.field).toEqual("email_address");
|
||||
});
|
||||
|
||||
test("findOne: Should receive an integer id in where clause if the user has enabled `useNumberId`", async () => {
|
||||
@@ -1507,7 +1507,7 @@ describe("Create Adapter Helper", async () => {
|
||||
expect(res?.id).toEqual("1");
|
||||
});
|
||||
// The where clause should convert the string id value of `"1"` to an int since `useNumberId` is true
|
||||
expect(parameters.where[0].value).toEqual(1);
|
||||
expect(parameters.where[0]!.value).toEqual(1);
|
||||
});
|
||||
test("findMany: Should receive an integer id in where clause if the user has enabled `useNumberId`", async () => {
|
||||
const parameters: { where: Where[] | undefined; model: string } =
|
||||
@@ -1545,10 +1545,10 @@ describe("Create Adapter Helper", async () => {
|
||||
});
|
||||
|
||||
expect(res[0]).toHaveProperty("id");
|
||||
expect(res[0].id).toEqual("1");
|
||||
expect(res[0]!.id).toEqual("1");
|
||||
});
|
||||
// The where clause should convert the string id value of `"1"` to an int since `useNumberId` is true
|
||||
expect(parameters.where?.[0].value).toEqual(1);
|
||||
expect(parameters.where?.[0]!.value).toEqual(1);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -60,7 +60,7 @@ export const kyselyAdapter = (
|
||||
await builder.execute();
|
||||
const field = values.id
|
||||
? "id"
|
||||
: where.length > 0 && where[0].field
|
||||
: where.length > 0 && where[0]?.field
|
||||
? where[0].field
|
||||
: "id";
|
||||
|
||||
@@ -74,7 +74,7 @@ export const kyselyAdapter = (
|
||||
return res;
|
||||
}
|
||||
|
||||
const value = values[field] || where[0].value;
|
||||
const value = values[field] || where[0]?.value;
|
||||
res = await db
|
||||
.selectFrom(model)
|
||||
.selectAll()
|
||||
@@ -102,14 +102,14 @@ export const kyselyAdapter = (
|
||||
f = Object.values(schema).find((f) => f.modelName === model)!;
|
||||
}
|
||||
if (
|
||||
f.type === "boolean" &&
|
||||
f!.type === "boolean" &&
|
||||
(type === "sqlite" || type === "mssql") &&
|
||||
value !== null &&
|
||||
value !== undefined
|
||||
) {
|
||||
return value ? 1 : 0;
|
||||
}
|
||||
if (f.type === "date" && value && value instanceof Date) {
|
||||
if (f!.type === "date" && value && value instanceof Date) {
|
||||
return type === "sqlite" ? value.toISOString() : value;
|
||||
}
|
||||
return value;
|
||||
@@ -326,7 +326,7 @@ export const kyselyAdapter = (
|
||||
query = query.where((eb) => eb.or(or.map((expr) => expr(eb))));
|
||||
}
|
||||
const res = await query.execute();
|
||||
return res[0].count as number;
|
||||
return res[0]!.count as number;
|
||||
},
|
||||
async delete({ model, where }) {
|
||||
const { and, or } = convertWhereClause(model, where);
|
||||
|
||||
+1
-1
@@ -8,7 +8,7 @@ import type { BetterAuthOptions } from "../../../../types";
|
||||
import merge from "deepmerge";
|
||||
import type { DatabaseSync } from "node:sqlite";
|
||||
const nodeVersion = process.version;
|
||||
const nodeSqliteSupported = +nodeVersion.split(".")[0].slice(1) >= 22;
|
||||
const nodeSqliteSupported = +nodeVersion.split(".")[0]!.slice(1) >= 22;
|
||||
|
||||
describe.runIf(nodeSqliteSupported)("node-sqlite-dialect", async () => {
|
||||
let db: DatabaseSync;
|
||||
|
||||
@@ -28,7 +28,7 @@ export const memoryAdapter = (db: MemoryDB, config?: MemoryAdapterConfig) => {
|
||||
props.field === "id" &&
|
||||
props.action === "create"
|
||||
) {
|
||||
return db[props.model].length + 1;
|
||||
return db[props.model]!.length + 1;
|
||||
}
|
||||
return props.data;
|
||||
},
|
||||
@@ -39,7 +39,7 @@ export const memoryAdapter = (db: MemoryDB, config?: MemoryAdapterConfig) => {
|
||||
} catch {
|
||||
// Rollback changes
|
||||
Object.keys(db).forEach((key) => {
|
||||
db[key] = clone[key];
|
||||
db[key] = clone[key]!;
|
||||
});
|
||||
throw new Error("Transaction failed, rolling back changes");
|
||||
}
|
||||
@@ -87,7 +87,7 @@ export const memoryAdapter = (db: MemoryDB, config?: MemoryAdapterConfig) => {
|
||||
return true;
|
||||
}
|
||||
|
||||
let result = evalClause(record, where[0]);
|
||||
let result = evalClause(record, where[0]!);
|
||||
for (const clause of where) {
|
||||
const clauseResult = evalClause(record, clause);
|
||||
|
||||
@@ -105,12 +105,12 @@ export const memoryAdapter = (db: MemoryDB, config?: MemoryAdapterConfig) => {
|
||||
create: async ({ model, data }) => {
|
||||
if (options.advanced?.database?.useNumberId) {
|
||||
// @ts-expect-error
|
||||
data.id = db[model].length + 1;
|
||||
data.id = db[model]!.length + 1;
|
||||
}
|
||||
if (!db[model]) {
|
||||
db[model] = [];
|
||||
}
|
||||
db[model].push(data);
|
||||
db[model]!.push(data);
|
||||
return data;
|
||||
},
|
||||
findOne: async ({ model, where }) => {
|
||||
@@ -124,7 +124,7 @@ export const memoryAdapter = (db: MemoryDB, config?: MemoryAdapterConfig) => {
|
||||
table = convertWhereClause(where, model);
|
||||
}
|
||||
if (sortBy) {
|
||||
table = table.sort((a, b) => {
|
||||
table = table!.sort((a, b) => {
|
||||
const field = getFieldName({ model, field: sortBy.field });
|
||||
if (sortBy.direction === "asc") {
|
||||
return a[field] > b[field] ? 1 : -1;
|
||||
@@ -134,15 +134,15 @@ export const memoryAdapter = (db: MemoryDB, config?: MemoryAdapterConfig) => {
|
||||
});
|
||||
}
|
||||
if (offset !== undefined) {
|
||||
table = table.slice(offset);
|
||||
table = table!.slice(offset);
|
||||
}
|
||||
if (limit !== undefined) {
|
||||
table = table.slice(0, limit);
|
||||
table = table!.slice(0, limit);
|
||||
}
|
||||
return table;
|
||||
return table || [];
|
||||
},
|
||||
count: async ({ model }) => {
|
||||
return db[model].length;
|
||||
return db[model]!.length;
|
||||
},
|
||||
update: async ({ model, where, update }) => {
|
||||
const res = convertWhereClause(where, model);
|
||||
@@ -152,12 +152,12 @@ export const memoryAdapter = (db: MemoryDB, config?: MemoryAdapterConfig) => {
|
||||
return res[0] || null;
|
||||
},
|
||||
delete: async ({ model, where }) => {
|
||||
const table = db[model];
|
||||
const table = db[model]!;
|
||||
const res = convertWhereClause(where, model);
|
||||
db[model] = table.filter((record) => !res.includes(record));
|
||||
},
|
||||
deleteMany: async ({ model, where }) => {
|
||||
const table = db[model];
|
||||
const table = db[model]!;
|
||||
const res = convertWhereClause(where, model);
|
||||
let count = 0;
|
||||
db[model] = table.filter((record) => {
|
||||
|
||||
@@ -67,7 +67,7 @@ export const mongodbAdapter = (db: Db, config?: MongoDBAdapterConfig) => {
|
||||
if (
|
||||
field === "id" ||
|
||||
field === "_id" ||
|
||||
schema[model].fields[field]?.references?.field === "id"
|
||||
schema[model]!.fields[field]?.references?.field === "id"
|
||||
) {
|
||||
if (typeof value !== "string") {
|
||||
if (value instanceof ObjectId) {
|
||||
@@ -176,7 +176,7 @@ export const mongodbAdapter = (db: Db, config?: MongoDBAdapterConfig) => {
|
||||
return { condition, connector };
|
||||
});
|
||||
if (conditions.length === 1) {
|
||||
return conditions[0].condition;
|
||||
return conditions[0]!.condition;
|
||||
}
|
||||
const andConditions = conditions
|
||||
.filter((c) => c.connector === "AND")
|
||||
|
||||
@@ -93,7 +93,7 @@ export const prismaAdapter = (prisma: PrismaClient, config: PrismaConfig) => {
|
||||
const convertWhereClause = (model: string, where?: Where[]) => {
|
||||
if (!where) return {};
|
||||
if (where.length === 1) {
|
||||
const w = where[0];
|
||||
const w = where[0]!;
|
||||
if (!w) {
|
||||
return;
|
||||
}
|
||||
@@ -142,7 +142,7 @@ export const prismaAdapter = (prisma: PrismaClient, config: PrismaConfig) => {
|
||||
`Model ${model} does not exist in the database. If you haven't generated the Prisma client, you need to run 'npx prisma generate'`,
|
||||
);
|
||||
}
|
||||
return await db[model].create({
|
||||
return await db[model]!.create({
|
||||
data: values,
|
||||
select: convertSelect(select, model),
|
||||
});
|
||||
@@ -154,7 +154,7 @@ export const prismaAdapter = (prisma: PrismaClient, config: PrismaConfig) => {
|
||||
`Model ${model} does not exist in the database. If you haven't generated the Prisma client, you need to run 'npx prisma generate'`,
|
||||
);
|
||||
}
|
||||
return await db[model].findFirst({
|
||||
return await db[model]!.findFirst({
|
||||
where: whereClause,
|
||||
select: convertSelect(select, model),
|
||||
});
|
||||
@@ -167,7 +167,7 @@ export const prismaAdapter = (prisma: PrismaClient, config: PrismaConfig) => {
|
||||
);
|
||||
}
|
||||
|
||||
return (await db[model].findMany({
|
||||
return (await db[model]!.findMany({
|
||||
where: whereClause,
|
||||
take: limit || 100,
|
||||
skip: offset || 0,
|
||||
@@ -188,7 +188,7 @@ export const prismaAdapter = (prisma: PrismaClient, config: PrismaConfig) => {
|
||||
`Model ${model} does not exist in the database. If you haven't generated the Prisma client, you need to run 'npx prisma generate'`,
|
||||
);
|
||||
}
|
||||
return await db[model].count({
|
||||
return await db[model]!.count({
|
||||
where: whereClause,
|
||||
});
|
||||
},
|
||||
@@ -199,14 +199,14 @@ export const prismaAdapter = (prisma: PrismaClient, config: PrismaConfig) => {
|
||||
);
|
||||
}
|
||||
const whereClause = convertWhereClause(model, where);
|
||||
return await db[model].update({
|
||||
return await db[model]!.update({
|
||||
where: whereClause,
|
||||
data: update,
|
||||
});
|
||||
},
|
||||
async updateMany({ model, where, update }) {
|
||||
const whereClause = convertWhereClause(model, where);
|
||||
const result = await db[model].updateMany({
|
||||
const result = await db[model]!.updateMany({
|
||||
where: whereClause,
|
||||
data: update,
|
||||
});
|
||||
@@ -215,7 +215,7 @@ export const prismaAdapter = (prisma: PrismaClient, config: PrismaConfig) => {
|
||||
async delete({ model, where }) {
|
||||
const whereClause = convertWhereClause(model, where);
|
||||
try {
|
||||
await db[model].delete({
|
||||
await db[model]!.delete({
|
||||
where: whereClause,
|
||||
});
|
||||
} catch (e) {
|
||||
@@ -224,7 +224,7 @@ export const prismaAdapter = (prisma: PrismaClient, config: PrismaConfig) => {
|
||||
},
|
||||
async deleteMany({ model, where }) {
|
||||
const whereClause = convertWhereClause(model, where);
|
||||
const result = await db[model].deleteMany({
|
||||
const result = await db[model]!.deleteMany({
|
||||
where: whereClause,
|
||||
});
|
||||
return result ? (result.count as number) : 0;
|
||||
|
||||
@@ -511,7 +511,7 @@ function adapterTest(
|
||||
direction: "asc",
|
||||
},
|
||||
});
|
||||
expect(res[0].name).toBe("a");
|
||||
expect(res[0]!.name).toBe("a");
|
||||
|
||||
const res2 = await (await adapter()).findMany<User>({
|
||||
model: "user",
|
||||
@@ -521,7 +521,7 @@ function adapterTest(
|
||||
},
|
||||
});
|
||||
|
||||
expect(res2[res2.length - 1].name).toBe("a");
|
||||
expect(res2[res2.length - 1]!.name).toBe("a");
|
||||
},
|
||||
);
|
||||
|
||||
|
||||
@@ -229,7 +229,7 @@ describe("checkEndpointConflicts", () => {
|
||||
checkEndpointConflicts(options, mockLogger);
|
||||
|
||||
expect(mockLogger.error).toHaveBeenCalledTimes(1);
|
||||
const errorCall = mockLogger.error.mock.calls[0][0];
|
||||
const errorCall = mockLogger.error.mock.calls[0]![0];
|
||||
expect(errorCall).toContain(
|
||||
'"/api/conflict" [GET] used by plugins: plugin1, plugin2',
|
||||
);
|
||||
|
||||
@@ -41,10 +41,10 @@ describe("getEndpoints", () => {
|
||||
context: { customProp: "value" },
|
||||
};
|
||||
|
||||
await middlewares[0].middleware(testCtx);
|
||||
await middlewares[0]!.middleware(testCtx);
|
||||
|
||||
expect(middlewareFn).toHaveBeenCalled();
|
||||
const call = middlewareFn.mock.calls[0][0];
|
||||
const call = middlewareFn.mock.calls[0]![0];
|
||||
expect(call.context).toMatchObject({
|
||||
baseURL: "http://localhost:3000",
|
||||
options: {},
|
||||
|
||||
@@ -286,7 +286,7 @@ describe("account", async () => {
|
||||
await runWithDefaultUser(async () => {
|
||||
const previousAccounts = await client.listAccounts();
|
||||
expect(previousAccounts.data?.length).toBe(3);
|
||||
const unlinkAccountId = previousAccounts.data![1].accountId;
|
||||
const unlinkAccountId = previousAccounts.data![1]!.accountId;
|
||||
const unlinkRes = await client.unlinkAccount({
|
||||
providerId: "google",
|
||||
accountId: unlinkAccountId!,
|
||||
@@ -310,7 +310,7 @@ describe("account", async () => {
|
||||
},
|
||||
],
|
||||
});
|
||||
const unlinkAccountId = previousAccounts.data![0].accountId;
|
||||
const unlinkAccountId = previousAccounts.data![0]!.accountId;
|
||||
const unlinkRes = await client.unlinkAccount({
|
||||
providerId: "credential",
|
||||
accountId: unlinkAccountId,
|
||||
@@ -327,7 +327,7 @@ describe("account", async () => {
|
||||
const previousAccounts = await client.listAccounts();
|
||||
expect(previousAccounts.data?.length).toBeGreaterThan(0);
|
||||
|
||||
const accountToUnlink = previousAccounts.data![0];
|
||||
const accountToUnlink = previousAccounts.data![0]!;
|
||||
const unlinkAccountId = accountToUnlink.accountId;
|
||||
const providerId = accountToUnlink.providerId;
|
||||
const accountsWithSameProvider = previousAccounts.data!.filter(
|
||||
@@ -390,7 +390,7 @@ describe("account", async () => {
|
||||
for (let i = 0; i < googleAccounts.length - 1; i++) {
|
||||
const unlinkRes = await client.unlinkAccount({
|
||||
providerId: "google",
|
||||
accountId: googleAccounts[i].accountId!,
|
||||
accountId: googleAccounts[i]!.accountId!,
|
||||
});
|
||||
expect(unlinkRes.data?.status).toBe(true);
|
||||
}
|
||||
|
||||
@@ -12,7 +12,7 @@ describe("forget password", async (it) => {
|
||||
emailAndPassword: {
|
||||
enabled: true,
|
||||
async sendResetPassword({ url }) {
|
||||
token = url.split("?")[0].split("/").pop() || "";
|
||||
token = url.split("?")[0]!.split("/").pop() || "";
|
||||
await mockSendEmail();
|
||||
},
|
||||
onPasswordReset: async ({ user }) => {
|
||||
@@ -271,7 +271,7 @@ describe("revoke sessions on password reset", async (it) => {
|
||||
emailAndPassword: {
|
||||
enabled: true,
|
||||
async sendResetPassword({ url }) {
|
||||
token = url.split("?")[0].split("/").pop() || "";
|
||||
token = url.split("?")[0]!.split("/").pop() || "";
|
||||
await mockSendEmail();
|
||||
},
|
||||
revokeSessionsOnPasswordReset: true,
|
||||
@@ -313,7 +313,7 @@ describe("revoke sessions on password reset", async (it) => {
|
||||
emailAndPassword: {
|
||||
enabled: true,
|
||||
async sendResetPassword({ url }) {
|
||||
token = url.split("?")[0].split("/").pop() || "";
|
||||
token = url.split("?")[0]!.split("/").pop() || "";
|
||||
await mockSendEmail();
|
||||
},
|
||||
},
|
||||
|
||||
@@ -347,7 +347,7 @@ describe("session", async () => {
|
||||
});
|
||||
|
||||
const signInHeaders = new Headers();
|
||||
signInHeaders.set("cookie", signInRes.headers.getSetCookie()[0]);
|
||||
signInHeaders.set("cookie", signInRes.headers.getSetCookie()[0]!);
|
||||
|
||||
const sessionResWithoutHeaders = await auth.api.getSession({
|
||||
headers: signInHeaders,
|
||||
|
||||
@@ -91,15 +91,15 @@ export const getClientConfig = (options?: ClientOptions) => {
|
||||
|
||||
const $store = {
|
||||
notify: (signal?: Omit<string, "$sessionSignal"> | "$sessionSignal") => {
|
||||
pluginsAtoms[signal as keyof typeof pluginsAtoms].set(
|
||||
!pluginsAtoms[signal as keyof typeof pluginsAtoms].get(),
|
||||
pluginsAtoms[signal as keyof typeof pluginsAtoms]!.set(
|
||||
!pluginsAtoms[signal as keyof typeof pluginsAtoms]!.get(),
|
||||
);
|
||||
},
|
||||
listen: (
|
||||
signal: Omit<string, "$sessionSignal"> | "$sessionSignal",
|
||||
listener: (value: boolean, oldValue?: boolean | undefined) => void,
|
||||
) => {
|
||||
pluginsAtoms[signal as keyof typeof pluginsAtoms].subscribe(listener);
|
||||
pluginsAtoms[signal as keyof typeof pluginsAtoms]!.subscribe(listener);
|
||||
},
|
||||
atoms: pluginsAtoms,
|
||||
};
|
||||
|
||||
@@ -58,19 +58,19 @@ function parseISODate(value: string): Date | null {
|
||||
|
||||
let date = new Date(
|
||||
Date.UTC(
|
||||
parseInt(year, 10),
|
||||
parseInt(month, 10) - 1,
|
||||
parseInt(day, 10),
|
||||
parseInt(hour, 10),
|
||||
parseInt(minute, 10),
|
||||
parseInt(second, 10),
|
||||
parseInt(year!, 10),
|
||||
parseInt(month!, 10) - 1,
|
||||
parseInt(day!, 10),
|
||||
parseInt(hour!, 10),
|
||||
parseInt(minute!, 10),
|
||||
parseInt(second!, 10),
|
||||
ms ? parseInt(ms.padEnd(3, "0"), 10) : 0,
|
||||
),
|
||||
);
|
||||
|
||||
if (offsetSign) {
|
||||
const offset =
|
||||
(parseInt(offsetHour, 10) * 60 + parseInt(offsetMinute, 10)) *
|
||||
(parseInt(offsetHour!, 10) * 60 + parseInt(offsetMinute!, 10)) *
|
||||
(offsetSign === "+" ? -1 : 1);
|
||||
date.setUTCMinutes(date.getUTCMinutes() + offset);
|
||||
}
|
||||
@@ -96,6 +96,7 @@ function betterJSONParse<T = unknown>(
|
||||
const trimmed = value.trim();
|
||||
|
||||
if (
|
||||
trimmed.length > 0 &&
|
||||
trimmed[0] === '"' &&
|
||||
trimmed.endsWith('"') &&
|
||||
!trimmed.slice(1, -1).includes('"')
|
||||
|
||||
@@ -93,7 +93,7 @@ export function createAuthClient<Option extends ClientOptions>(
|
||||
useFetch?: UseFetch,
|
||||
) {
|
||||
if (useFetch) {
|
||||
const ref = useStore(pluginsAtoms.$sessionSignal);
|
||||
const ref = useStore(pluginsAtoms.$sessionSignal!);
|
||||
return useFetch(`${baseURL}/get-session`, {
|
||||
ref,
|
||||
}).then((res: any) => {
|
||||
|
||||
@@ -19,7 +19,7 @@ export function parseSetCookieHeader(
|
||||
cookieArray.forEach((cookieString) => {
|
||||
const parts = cookieString.split(";").map((part) => part.trim());
|
||||
const [nameValue, ...attributes] = parts;
|
||||
const [name, ...valueParts] = nameValue.split("=");
|
||||
const [name, ...valueParts] = (nameValue || "").split("=");
|
||||
|
||||
const value = valueParts.join("=");
|
||||
|
||||
@@ -30,10 +30,10 @@ export function parseSetCookieHeader(
|
||||
const attrObj: CookieAttributes = { value };
|
||||
|
||||
attributes.forEach((attribute) => {
|
||||
const [attrName, ...attrValueParts] = attribute.split("=");
|
||||
const [attrName, ...attrValueParts] = attribute!.split("=");
|
||||
const attrValue = attrValueParts.join("=");
|
||||
|
||||
const normalizedAttrName = attrName.trim().toLowerCase();
|
||||
const normalizedAttrName = attrName!.trim().toLowerCase();
|
||||
|
||||
switch (normalizedAttrName) {
|
||||
case "max-age":
|
||||
@@ -85,7 +85,7 @@ export function setCookieToHeader(headers: Headers) {
|
||||
|
||||
const existingCookiesHeader = headers.get("cookie") || "";
|
||||
existingCookiesHeader.split(";").forEach((cookie) => {
|
||||
const [name, ...rest] = cookie.trim().split("=");
|
||||
const [name, ...rest] = cookie!.trim().split("=");
|
||||
if (name && rest.length > 0) {
|
||||
cookieMap.set(name, rest.join("="));
|
||||
}
|
||||
|
||||
@@ -240,7 +240,7 @@ export function parseCookies(cookieHeader: string) {
|
||||
|
||||
cookies.forEach((cookie) => {
|
||||
const [name, value] = cookie.split("=");
|
||||
cookieMap.set(name, value);
|
||||
cookieMap.set(name!, value!);
|
||||
});
|
||||
return cookieMap;
|
||||
}
|
||||
|
||||
@@ -11,8 +11,8 @@ export function constantTimeEqual(
|
||||
const length = Math.max(aBuffer.length, bBuffer.length);
|
||||
for (let i = 0; i < length; i++) {
|
||||
c |=
|
||||
(i < aBuffer.length ? aBuffer[i] : 0) ^
|
||||
(i < bBuffer.length ? bBuffer[i] : 0);
|
||||
(i < aBuffer.length ? aBuffer[i]! : 0) ^
|
||||
(i < bBuffer.length ? bBuffer[i]! : 0);
|
||||
}
|
||||
return c === 0;
|
||||
}
|
||||
|
||||
@@ -70,15 +70,15 @@ export function matchType(
|
||||
dbType: KyselyDatabaseType,
|
||||
) {
|
||||
function normalize(type: string) {
|
||||
return type.toLowerCase().split("(")[0].trim();
|
||||
return type.toLowerCase().split("(")[0]!.trim();
|
||||
}
|
||||
if (fieldType === "string[]" || fieldType === "number[]") {
|
||||
return columnDataType.toLowerCase().includes("json");
|
||||
}
|
||||
const types = map[dbType];
|
||||
const types = map[dbType]!;
|
||||
const expected = Array.isArray(fieldType)
|
||||
? types["string"].map((t) => t.toLowerCase())
|
||||
: types[fieldType].map((t) => t.toLowerCase());
|
||||
: types[fieldType]!.map((t) => t.toLowerCase());
|
||||
return expected.includes(normalize(columnDataType));
|
||||
}
|
||||
|
||||
@@ -131,8 +131,8 @@ export async function getMigrations(config: BetterAuthOptions) {
|
||||
if (tIndex === -1) {
|
||||
toBeCreated.push(tableData);
|
||||
} else {
|
||||
toBeCreated[tIndex].fields = {
|
||||
...toBeCreated[tIndex].fields,
|
||||
toBeCreated[tIndex]!.fields = {
|
||||
...toBeCreated[tIndex]!.fields,
|
||||
...value.fields,
|
||||
};
|
||||
}
|
||||
@@ -239,7 +239,7 @@ export async function getMigrations(config: BetterAuthOptions) {
|
||||
if (Array.isArray(type)) {
|
||||
return "text";
|
||||
}
|
||||
return typeMap[type][dbType || "sqlite"];
|
||||
return typeMap[type]![dbType || "sqlite"];
|
||||
}
|
||||
if (toBeAdded.length) {
|
||||
for (const table of toBeAdded) {
|
||||
|
||||
@@ -11,7 +11,7 @@ export function getSchema(config: BetterAuthOptions) {
|
||||
}
|
||||
> = {};
|
||||
for (const key in tables) {
|
||||
const table = tables[key];
|
||||
const table = tables[key]!;
|
||||
const fields = table.fields;
|
||||
let actualFields: Record<string, FieldAttribute> = {};
|
||||
Object.entries(fields).forEach(([key, field]) => {
|
||||
@@ -19,7 +19,7 @@ export function getSchema(config: BetterAuthOptions) {
|
||||
if (field.references) {
|
||||
const refTable = tables[field.references.model];
|
||||
if (refTable) {
|
||||
actualFields[field.fieldName || key].references = {
|
||||
actualFields[field.fieldName || key]!.references = {
|
||||
model: refTable.modelName,
|
||||
field: field.references.field,
|
||||
};
|
||||
@@ -27,8 +27,8 @@ export function getSchema(config: BetterAuthOptions) {
|
||||
}
|
||||
});
|
||||
if (schema[table.modelName]) {
|
||||
schema[table.modelName].fields = {
|
||||
...schema[table.modelName].fields,
|
||||
schema[table.modelName]!.fields = {
|
||||
...schema[table.modelName]!.fields,
|
||||
...actualFields,
|
||||
};
|
||||
continue;
|
||||
|
||||
@@ -13,7 +13,7 @@ describe("getAuthTables", () => {
|
||||
|
||||
const accountTable = tables.account;
|
||||
const refreshTokenExpiresAtField =
|
||||
accountTable.fields.refreshTokenExpiresAt;
|
||||
accountTable!.fields.refreshTokenExpiresAt!;
|
||||
|
||||
expect(refreshTokenExpiresAtField.fieldName).toBe(
|
||||
"custom_refresh_token_expires_at",
|
||||
@@ -32,8 +32,9 @@ describe("getAuthTables", () => {
|
||||
|
||||
const accountTable = tables.account;
|
||||
const refreshTokenExpiresAtField =
|
||||
accountTable.fields.refreshTokenExpiresAt;
|
||||
const accessTokenExpiresAtField = accountTable.fields.accessTokenExpiresAt;
|
||||
accountTable!.fields.refreshTokenExpiresAt!;
|
||||
const accessTokenExpiresAtField =
|
||||
accountTable!.fields.accessTokenExpiresAt!;
|
||||
|
||||
expect(refreshTokenExpiresAtField.fieldName).toBe(
|
||||
"custom_refresh_token_expires_at",
|
||||
@@ -51,8 +52,9 @@ describe("getAuthTables", () => {
|
||||
|
||||
const accountTable = tables.account;
|
||||
const refreshTokenExpiresAtField =
|
||||
accountTable.fields.refreshTokenExpiresAt;
|
||||
const accessTokenExpiresAtField = accountTable.fields.accessTokenExpiresAt;
|
||||
accountTable!.fields.refreshTokenExpiresAt!;
|
||||
const accessTokenExpiresAtField =
|
||||
accountTable!.fields.accessTokenExpiresAt!;
|
||||
|
||||
expect(refreshTokenExpiresAtField.fieldName).toBe("refreshTokenExpiresAt");
|
||||
expect(accessTokenExpiresAtField.fieldName).toBe("accessTokenExpiresAt");
|
||||
|
||||
@@ -128,31 +128,31 @@ export function parseInputData<T extends Record<string, any>>(
|
||||
const parsedData: Record<string, any> = {};
|
||||
for (const key in fields) {
|
||||
if (key in data) {
|
||||
if (fields[key].input === false) {
|
||||
if (fields[key].defaultValue) {
|
||||
parsedData[key] = fields[key].defaultValue;
|
||||
if (fields[key]!.input === false) {
|
||||
if (fields[key]!.defaultValue) {
|
||||
parsedData[key] = fields[key]!.defaultValue;
|
||||
continue;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if (fields[key].validator?.input && data[key] !== undefined) {
|
||||
parsedData[key] = fields[key].validator.input.parse(data[key]);
|
||||
if (fields[key]!.validator?.input && data[key] !== undefined) {
|
||||
parsedData[key] = fields[key]!.validator.input.parse(data[key]);
|
||||
continue;
|
||||
}
|
||||
if (fields[key].transform?.input && data[key] !== undefined) {
|
||||
parsedData[key] = fields[key].transform?.input(data[key]);
|
||||
if (fields[key]!.transform?.input && data[key] !== undefined) {
|
||||
parsedData[key] = fields[key]!.transform?.input(data[key]);
|
||||
continue;
|
||||
}
|
||||
parsedData[key] = data[key];
|
||||
continue;
|
||||
}
|
||||
|
||||
if (fields[key].defaultValue && action === "create") {
|
||||
parsedData[key] = fields[key].defaultValue;
|
||||
if (fields[key]!.defaultValue && action === "create") {
|
||||
parsedData[key] = fields[key]!.defaultValue;
|
||||
continue;
|
||||
}
|
||||
|
||||
if (fields[key].required && action === "create") {
|
||||
if (fields[key]!.required && action === "create") {
|
||||
throw new APIError("BAD_REQUEST", {
|
||||
message: `${key} is required`,
|
||||
});
|
||||
@@ -211,14 +211,14 @@ export function mergeSchema<S extends AuthPluginSchema>(
|
||||
for (const table in newSchema) {
|
||||
const newModelName = newSchema[table]?.modelName;
|
||||
if (newModelName) {
|
||||
schema[table].modelName = newModelName;
|
||||
schema[table]!.modelName = newModelName;
|
||||
}
|
||||
for (const field in schema[table].fields) {
|
||||
for (const field in schema[table]!.fields) {
|
||||
const newField = newSchema[table]?.fields?.[field];
|
||||
if (!newField) {
|
||||
continue;
|
||||
}
|
||||
schema[table].fields[field].fieldName = newField;
|
||||
schema[table]!.fields[field]!.fieldName = newField;
|
||||
}
|
||||
}
|
||||
return schema;
|
||||
|
||||
@@ -46,7 +46,7 @@ export function convertToDB<T extends Record<string, any>>(
|
||||
}
|
||||
: {};
|
||||
for (const key in fields) {
|
||||
const field = fields[key];
|
||||
const field = fields[key]!;
|
||||
const value = values[key];
|
||||
if (value === undefined) {
|
||||
continue;
|
||||
|
||||
@@ -146,7 +146,7 @@ export async function validateToken(token: string, jwksEndpoint: string) {
|
||||
throw error;
|
||||
}
|
||||
const keys = data["keys"];
|
||||
const header = JSON.parse(atob(token.split(".")[0]));
|
||||
const header = JSON.parse(atob(token.split(".")[0]!));
|
||||
const key = keys.find((key) => key.kid === header.kid);
|
||||
if (!key) {
|
||||
throw new Error("Key not found");
|
||||
|
||||
@@ -296,7 +296,7 @@ describe("Admin plugin", async () => {
|
||||
},
|
||||
});
|
||||
|
||||
expect(res.data?.users[0].name).toBe("Test User");
|
||||
expect(res.data?.users[0]!.name).toBe("Test User");
|
||||
|
||||
const res2 = await client.admin.listUsers({
|
||||
query: {
|
||||
@@ -307,7 +307,7 @@ describe("Admin plugin", async () => {
|
||||
headers: adminHeaders,
|
||||
},
|
||||
});
|
||||
expect(res2.data?.users[0].name).toBe("Admin");
|
||||
expect(res2.data?.users[0]!.name).toBe("Admin");
|
||||
});
|
||||
|
||||
it("should allow offset and limit", async () => {
|
||||
@@ -321,7 +321,7 @@ describe("Admin plugin", async () => {
|
||||
},
|
||||
});
|
||||
expect(res.data?.users.length).toBe(1);
|
||||
expect(res.data?.users[0].name).toBe("Test User");
|
||||
expect(res.data?.users[0]!.name).toBe("Test User");
|
||||
});
|
||||
|
||||
it("should allow to search users by name", async () => {
|
||||
@@ -648,7 +648,7 @@ describe("Admin plugin", async () => {
|
||||
);
|
||||
expect(sessions.data?.sessions.length).toBe(3);
|
||||
const res = await client.admin.revokeUserSession(
|
||||
{ sessionToken: sessions.data?.sessions[0].token || "" },
|
||||
{ sessionToken: sessions.data?.sessions[0]!.token || "" },
|
||||
{ headers: adminHeaders },
|
||||
);
|
||||
expect(res.data?.success).toBe(true);
|
||||
|
||||
@@ -1210,8 +1210,9 @@ export const admin = <O extends AdminOptions>(options?: O) => {
|
||||
}
|
||||
const [adminSessionToken, dontRememberMeCookie] =
|
||||
adminCookie?.split(":");
|
||||
const adminSession =
|
||||
await ctx.context.internalAdapter.findSession(adminSessionToken);
|
||||
const adminSession = await ctx.context.internalAdapter.findSession(
|
||||
adminSessionToken!,
|
||||
);
|
||||
if (!adminSession || adminSession.session.userId !== user.id) {
|
||||
throw new APIError("INTERNAL_SERVER_ERROR", {
|
||||
message: "Failed to find admin session",
|
||||
|
||||
@@ -211,7 +211,7 @@ export const anonymous = (options?: AnonymousOptions) => {
|
||||
*/
|
||||
const sessionCookie = parseSetCookieHeader(setCookie || "")
|
||||
.get(sessionTokenName)
|
||||
?.value.split(".")[0];
|
||||
?.value.split(".")[0]!;
|
||||
|
||||
if (!sessionCookie) {
|
||||
return;
|
||||
|
||||
@@ -56,8 +56,8 @@ export const bearer = (options?: BearerOptions) => {
|
||||
"base64urlnopad",
|
||||
).verify(
|
||||
c.context.secret,
|
||||
decodedToken.split(".")[0],
|
||||
decodedToken.split(".")[1],
|
||||
decodedToken.split(".")[0]!,
|
||||
decodedToken.split(".")[1]!,
|
||||
);
|
||||
if (!isValid) {
|
||||
return;
|
||||
|
||||
@@ -128,8 +128,8 @@ describe("Custom Session Plugin Tests", async () => {
|
||||
expect(memoryIncreasePerPlugin).toBeLessThan(5 * 1024);
|
||||
// Verify that plugins are still functional
|
||||
expect(pluginInstances).toHaveLength(sessionCount);
|
||||
expect(pluginInstances[0].id).toBe("custom-session");
|
||||
expect(pluginInstances[sessionCount - 1].id).toBe("custom-session");
|
||||
expect(pluginInstances[0]!.id).toBe("custom-session");
|
||||
expect(pluginInstances[sessionCount - 1]!.id).toBe("custom-session");
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
@@ -623,7 +623,7 @@ describe("oauth2", async () => {
|
||||
|
||||
const accountsAfterSecond = await ctx.internalAdapter.findAccounts(userId);
|
||||
expect(accountsAfterSecond).toHaveLength(1);
|
||||
expect(accountsAfterSecond[0].accountId).toBe(String(numericAccountId));
|
||||
expect(accountsAfterSecond[0]!.accountId).toBe(String(numericAccountId));
|
||||
});
|
||||
|
||||
it("should handle custom getUserInfo returning numeric ID", async () => {
|
||||
@@ -688,7 +688,7 @@ describe("oauth2", async () => {
|
||||
session.data?.user.id!,
|
||||
);
|
||||
|
||||
expect(accounts[0].accountId).toBe(String(numericId));
|
||||
expect(accounts[0]!.accountId).toBe(String(numericId));
|
||||
});
|
||||
|
||||
it("should handle mapProfileToUser returning numeric ID", async () => {
|
||||
@@ -763,7 +763,7 @@ describe("oauth2", async () => {
|
||||
session.data?.user.id!,
|
||||
);
|
||||
|
||||
expect(accounts[0].accountId).toBe(String(numericProfileId));
|
||||
expect(accounts[0]!.accountId).toBe(String(numericProfileId));
|
||||
});
|
||||
|
||||
it("should handle Strava OAuth with custom mapProfileToUser", async () => {
|
||||
|
||||
@@ -37,7 +37,7 @@ async function checkPasswordCompromise(
|
||||
}
|
||||
const lines = data.split("\n");
|
||||
const found = lines.some(
|
||||
(line) => line.split(":")[0].toUpperCase() === suffix.toUpperCase(),
|
||||
(line) => line.split(":")[0]!.toUpperCase() === suffix.toUpperCase(),
|
||||
);
|
||||
|
||||
if (found) {
|
||||
|
||||
@@ -65,7 +65,7 @@ describe("jwt", async () => {
|
||||
const jwks = await client.jwks();
|
||||
|
||||
expect(jwks.data?.keys).length.above(0);
|
||||
expect(jwks.data?.keys[0].alg).toBe("EdDSA");
|
||||
expect(jwks.data?.keys[0]!.alg).toBe("EdDSA");
|
||||
});
|
||||
|
||||
it("Signed tokens can be validated with the JWKS", async () => {
|
||||
@@ -368,7 +368,7 @@ describe.each([
|
||||
},
|
||||
protectedHeader: {
|
||||
alg: keyPairConfig.alg,
|
||||
kid: jwks.keys[0].kid,
|
||||
kid: jwks.keys[0]!.kid,
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
@@ -20,7 +20,7 @@ function getCookieValue(name: string): string | null {
|
||||
.split("; ")
|
||||
.find((row) => row.startsWith(`${name}=`));
|
||||
|
||||
return cookie ? cookie.split("=")[1] : null;
|
||||
return cookie ? cookie.split("=")[1]! : null;
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -56,7 +56,7 @@ export async function authorizeMCPOAuth(
|
||||
sameSite: "lax",
|
||||
},
|
||||
);
|
||||
const queryFromURL = ctx.request.url?.split("?")[1];
|
||||
const queryFromURL = ctx.request.url?.split("?")[1]!;
|
||||
throw ctx.redirect(`${options.loginPage}?${queryFromURL}`);
|
||||
}
|
||||
|
||||
|
||||
@@ -153,7 +153,7 @@ export const mcp = (options: MCPOptions) => {
|
||||
maxAge: 0,
|
||||
});
|
||||
const sessionCookie = parsedSetCookieHeader.get(cookieName)?.value;
|
||||
const sessionToken = sessionCookie?.split(".")[0];
|
||||
const sessionToken = sessionCookie?.split(".")[0]!;
|
||||
if (!sessionToken) {
|
||||
return;
|
||||
}
|
||||
@@ -578,8 +578,8 @@ export const mcp = (options: MCPOptions) => {
|
||||
),
|
||||
};
|
||||
const profile = {
|
||||
given_name: user.name.split(" ")[0],
|
||||
family_name: user.name.split(" ")[1],
|
||||
given_name: user.name.split(" ")[0]!,
|
||||
family_name: user.name.split(" ")[1]!,
|
||||
name: user.name,
|
||||
profile: user.image,
|
||||
updated_at: user.updatedAt.toISOString(),
|
||||
|
||||
@@ -267,7 +267,7 @@ export const multiSession = (options?: MultiSessionConfig) => {
|
||||
);
|
||||
|
||||
if (validSessions.length > 0) {
|
||||
const nextSession = validSessions[0];
|
||||
const nextSession = validSessions[0]!;
|
||||
await setSessionCookie(ctx, nextSession);
|
||||
} else {
|
||||
deleteSessionCookie(ctx);
|
||||
@@ -337,7 +337,7 @@ export const multiSession = (options?: MultiSessionConfig) => {
|
||||
maxAge: 0,
|
||||
},
|
||||
);
|
||||
const token = cookies[key].split(".")[0];
|
||||
const token = cookies[key]!.split(".")[0]!;
|
||||
return token;
|
||||
}
|
||||
return null;
|
||||
|
||||
@@ -72,7 +72,7 @@ export async function authorize(
|
||||
sameSite: "lax",
|
||||
},
|
||||
);
|
||||
const queryFromURL = ctx.request.url?.split("?")[1];
|
||||
const queryFromURL = ctx.request.url?.split("?")[1]!;
|
||||
return handleRedirect(`${options.loginPage}?${queryFromURL}`);
|
||||
}
|
||||
|
||||
|
||||
@@ -252,7 +252,7 @@ export const oidcProvider = (options: OIDCOptions) => {
|
||||
maxAge: 0,
|
||||
});
|
||||
const sessionCookie = parsedSetCookieHeader.get(cookieName)?.value;
|
||||
const sessionToken = sessionCookie?.split(".")[0];
|
||||
const sessionToken = sessionCookie?.split(".")[0]!;
|
||||
if (!sessionToken) {
|
||||
return;
|
||||
}
|
||||
@@ -782,8 +782,8 @@ export const oidcProvider = (options: OIDCOptions) => {
|
||||
}
|
||||
|
||||
const profile = {
|
||||
given_name: user.name.split(" ")[0],
|
||||
family_name: user.name.split(" ")[1],
|
||||
given_name: user.name.split(" ")[0]!,
|
||||
family_name: user.name.split(" ")[1]!,
|
||||
name: user.name,
|
||||
profile: user.image,
|
||||
updated_at: new Date(user.updatedAt).toISOString(),
|
||||
@@ -1034,10 +1034,10 @@ export const oidcProvider = (options: OIDCOptions) => {
|
||||
? user.image
|
||||
: undefined,
|
||||
given_name: requestedScopes.includes("profile")
|
||||
? user.name.split(" ")[0]
|
||||
? user.name.split(" ")[0]!
|
||||
: undefined,
|
||||
family_name: requestedScopes.includes("profile")
|
||||
? user.name.split(" ")[1]
|
||||
? user.name.split(" ")[1]!
|
||||
: undefined,
|
||||
email_verified: requestedScopes.includes("email")
|
||||
? user.emailVerified
|
||||
|
||||
@@ -31,7 +31,7 @@ describe("open-api", async (it) => {
|
||||
string,
|
||||
Record<string, any>
|
||||
>;
|
||||
expect(schemas["User"].properties.id).toEqual({
|
||||
expect(schemas["User"]!.properties.id).toEqual({
|
||||
type: "string",
|
||||
});
|
||||
});
|
||||
@@ -43,16 +43,16 @@ describe("open-api", async (it) => {
|
||||
Record<string, any>
|
||||
>;
|
||||
|
||||
expect(schemas["User"].properties.role).toEqual({
|
||||
expect(schemas["User"]!.properties.role).toEqual({
|
||||
type: "string",
|
||||
default: "user",
|
||||
});
|
||||
|
||||
expect(schemas["User"].properties.preferences).toEqual({
|
||||
expect(schemas["User"]!.properties.preferences).toEqual({
|
||||
type: "string",
|
||||
});
|
||||
expect(schemas["User"].required).toContain("role");
|
||||
expect(schemas["User"].required).not.toContain("preferences");
|
||||
expect(schemas["User"]!.required).toContain("role");
|
||||
expect(schemas["User"]!.required).not.toContain("preferences");
|
||||
});
|
||||
|
||||
it("should properly handle nested objects in request body schema", async () => {
|
||||
|
||||
@@ -270,7 +270,7 @@ describe("organization", async (it) => {
|
||||
expect(wrongInvitation.error?.status).toBe(400);
|
||||
|
||||
const wrongPerson = await client.organization.acceptInvitation({
|
||||
invitationId: invite.data.id,
|
||||
invitationId: invite.data!.id!,
|
||||
fetchOptions: {
|
||||
headers,
|
||||
},
|
||||
@@ -278,7 +278,7 @@ describe("organization", async (it) => {
|
||||
expect(wrongPerson.error?.status).toBe(403);
|
||||
|
||||
const invitation = await client.organization.acceptInvitation({
|
||||
invitationId: invite.data.id,
|
||||
invitationId: invite.data!.id!,
|
||||
fetchOptions: {
|
||||
headers: headers2,
|
||||
},
|
||||
@@ -360,7 +360,7 @@ describe("organization", async (it) => {
|
||||
user.password,
|
||||
);
|
||||
const acceptRes = await client.organization.acceptInvitation({
|
||||
invitationId: invite.data.id,
|
||||
invitationId: invite.data!.id!,
|
||||
fetchOptions: {
|
||||
headers: userHeaders,
|
||||
},
|
||||
@@ -421,10 +421,10 @@ describe("organization", async (it) => {
|
||||
},
|
||||
});
|
||||
if (!org.data) throw new Error("Organization not found");
|
||||
expect(org.data?.members[3].role).toBe("member");
|
||||
expect(org.data.members[3]!.role).toBe("member");
|
||||
const member = await client.organization.updateMemberRole({
|
||||
organizationId: org.data.id,
|
||||
memberId: org.data.members[3].id,
|
||||
organizationId: org.data!.id,
|
||||
memberId: org.data!.members[3]!.id,
|
||||
role: "admin",
|
||||
fetchOptions: {
|
||||
headers,
|
||||
@@ -444,9 +444,9 @@ describe("organization", async (it) => {
|
||||
},
|
||||
});
|
||||
const c = await client.organization.updateMemberRole({
|
||||
organizationId: org.data?.id as string,
|
||||
organizationId: org.data!.id,
|
||||
role: ["member", "admin"],
|
||||
memberId: org.data?.members[1].id as string,
|
||||
memberId: org.data!.members[1]!.id,
|
||||
fetchOptions: {
|
||||
headers,
|
||||
},
|
||||
@@ -905,7 +905,7 @@ describe("organization", async (it) => {
|
||||
);
|
||||
|
||||
const invitation = await client.organization.acceptInvitation({
|
||||
invitationId: invite.data.id,
|
||||
invitationId: invite.data!.id!,
|
||||
fetchOptions: {
|
||||
headers: headers2,
|
||||
},
|
||||
@@ -985,7 +985,7 @@ describe("organization", async (it) => {
|
||||
headers: headers2,
|
||||
},
|
||||
});
|
||||
expect(userInvitations.data?.[0].id).toBe(invitation.data?.id);
|
||||
expect(userInvitations.data?.[0]!.id).toBe(invitation.data?.id);
|
||||
expect(userInvitations.data?.length).toBe(1);
|
||||
});
|
||||
|
||||
@@ -996,29 +996,29 @@ describe("organization", async (it) => {
|
||||
},
|
||||
});
|
||||
|
||||
if (!orgInvitations.data?.[0].email) throw new Error("No email found");
|
||||
if (!orgInvitations.data?.[0]!.email) throw new Error("No email found");
|
||||
|
||||
const invitations = await auth.api.listUserInvitations({
|
||||
query: {
|
||||
email: orgInvitations.data?.[0].email,
|
||||
email: orgInvitations.data?.[0]!.email,
|
||||
},
|
||||
});
|
||||
|
||||
expect(invitations?.length).toBe(
|
||||
orgInvitations.data.filter(
|
||||
(x) => x.email === orgInvitations.data?.[0].email,
|
||||
orgInvitations.data!.filter(
|
||||
(x) => x.email === orgInvitations.data?.[0]!.email,
|
||||
).length,
|
||||
);
|
||||
|
||||
const invitationsUpper = await auth.api.listUserInvitations({
|
||||
query: {
|
||||
email: orgInvitations.data?.[0].email.toUpperCase(),
|
||||
email: orgInvitations.data?.[0]!.email.toUpperCase(),
|
||||
},
|
||||
});
|
||||
|
||||
expect(invitationsUpper?.length).toBe(
|
||||
orgInvitations.data.filter(
|
||||
(x) => x.email === orgInvitations.data?.[0].email,
|
||||
orgInvitations.data!.filter(
|
||||
(x) => x.email === orgInvitations.data?.[0]!.email,
|
||||
).length,
|
||||
);
|
||||
});
|
||||
@@ -1419,7 +1419,7 @@ describe("owner can update roles", async () => {
|
||||
},
|
||||
});
|
||||
|
||||
const adminCookie = headers.getSetCookie()[0];
|
||||
const adminCookie = headers.getSetCookie()[0]!;
|
||||
|
||||
const org = await auth.api.createOrganization({
|
||||
headers: { cookie: adminCookie },
|
||||
@@ -1481,7 +1481,7 @@ describe("owner can update roles", async () => {
|
||||
},
|
||||
});
|
||||
|
||||
const userCookie = signInRes.headers.getSetCookie()[0];
|
||||
const userCookie = signInRes.headers.getSetCookie()[0]!;
|
||||
|
||||
const permissionRes = await auth.api.hasPermission({
|
||||
headers: { cookie: userCookie },
|
||||
@@ -1545,7 +1545,7 @@ describe("owner can update roles", async () => {
|
||||
},
|
||||
});
|
||||
|
||||
const userCookie = signInRes.headers.getSetCookie()[0];
|
||||
const userCookie = signInRes.headers.getSetCookie()[0]!;
|
||||
|
||||
await auth.api
|
||||
.updateMemberRole({
|
||||
@@ -1865,14 +1865,11 @@ describe("Additional Fields", async () => {
|
||||
headers,
|
||||
});
|
||||
|
||||
expect(invitation?.invitationRequiredField).toBe("hey");
|
||||
expectTypeOf<
|
||||
typeof invitation.invitationRequiredField
|
||||
>().toEqualTypeOf<string>();
|
||||
expect(invitation?.invitationOptionalField).toBe("hey2");
|
||||
expectTypeOf<typeof invitation.invitationOptionalField>().toEqualTypeOf<
|
||||
string | undefined
|
||||
>();
|
||||
const invitationWithFields = invitation as any;
|
||||
expect(invitationWithFields.invitationRequiredField).toBe("hey");
|
||||
expectTypeOf<string>().toEqualTypeOf<string>();
|
||||
expect(invitationWithFields.invitationOptionalField).toBe("hey2");
|
||||
expectTypeOf<string | undefined>().toEqualTypeOf<string | undefined>();
|
||||
const row = db.invitation.find((x) => x.id === invitation?.id)!;
|
||||
expect(row).toBeDefined();
|
||||
expect(row.invitationRequiredField).toBe("hey");
|
||||
|
||||
@@ -449,7 +449,7 @@ describe("dynamic access control", async (it) => {
|
||||
const res = await auth.api.listOrgRoles({ headers });
|
||||
expect(res).not.toBeNull();
|
||||
expect(res.length).toBeGreaterThan(0);
|
||||
expect(typeof res[0].permission === "string").toBe(false);
|
||||
expect(typeof res[0]!.permission === "string").toBe(false);
|
||||
const foundRole = res.find((x) => x.role === "list-test-role");
|
||||
expect(foundRole).not.toBeNull();
|
||||
expect(foundRole?.permission).toEqual(permission);
|
||||
|
||||
@@ -34,7 +34,7 @@ const getAdditionalFields = <
|
||||
options?.schema?.organizationRole?.additionalFields || {};
|
||||
if (shouldBePartial) {
|
||||
for (const key in additionalFields) {
|
||||
additionalFields[key].required = false;
|
||||
additionalFields[key]!.required = false;
|
||||
}
|
||||
}
|
||||
const additionalFieldsSchema = toZodSchema({
|
||||
@@ -1079,8 +1079,8 @@ async function checkIfMemberHasPermission({
|
||||
const missingPermissions = hasNecessaryPermissions
|
||||
.filter((x) => x.hasPermission === false)
|
||||
.map((x) => {
|
||||
const key = Object.keys(x.resource)[0];
|
||||
return `${key}:${x.resource[key][0]}` as const;
|
||||
const key = Object.keys(x.resource)[0]!;
|
||||
return `${key}:${x.resource[key]![0]}` as const;
|
||||
});
|
||||
if (missingPermissions.length > 0) {
|
||||
ctx.context.logger.error(
|
||||
|
||||
@@ -262,7 +262,7 @@ export const createInvitation = <O extends OrganizationOptions>(option: O) => {
|
||||
where: [
|
||||
{
|
||||
field: "id",
|
||||
value: existingInvitation.id,
|
||||
value: existingInvitation!.id,
|
||||
},
|
||||
],
|
||||
update: {
|
||||
@@ -277,9 +277,9 @@ export const createInvitation = <O extends OrganizationOptions>(option: O) => {
|
||||
|
||||
await ctx.context.orgOptions.sendInvitationEmail?.(
|
||||
{
|
||||
id: updatedInvitation.id,
|
||||
role: updatedInvitation.role as string,
|
||||
email: updatedInvitation.email.toLowerCase(),
|
||||
id: updatedInvitation.id!,
|
||||
role: updatedInvitation.role! as string,
|
||||
email: updatedInvitation.email!.toLowerCase(),
|
||||
organization: organization,
|
||||
inviter: {
|
||||
...member,
|
||||
@@ -298,7 +298,7 @@ export const createInvitation = <O extends OrganizationOptions>(option: O) => {
|
||||
ctx.context.orgOptions.cancelPendingInvitationsOnReInvite
|
||||
) {
|
||||
await adapter.updateInvitation({
|
||||
invitationId: alreadyInvited[0].id,
|
||||
invitationId: alreadyInvited[0]!.id,
|
||||
status: "canceled",
|
||||
});
|
||||
}
|
||||
@@ -597,7 +597,7 @@ export const acceptInvitation = <O extends OrganizationOptions>(options: O) =>
|
||||
}
|
||||
|
||||
if (onlyOne) {
|
||||
const teamId = teamIds[0];
|
||||
const teamId = teamIds[0]!;
|
||||
const updatedSession = await adapter.setActiveTeam(
|
||||
session.session.token,
|
||||
teamId,
|
||||
|
||||
@@ -165,12 +165,12 @@ describe("listMembers", async () => {
|
||||
sortDirection: "asc",
|
||||
},
|
||||
});
|
||||
expect(members.data?.members[0].id).not.toBe(firstMember.id);
|
||||
expect(members.data?.members[members.data?.members.length - 1].id).not.toBe(
|
||||
lastMember.id,
|
||||
);
|
||||
expect(members.data?.members[0].id).toBe(secondMember.id);
|
||||
expect(members.data?.members[members.data?.members.length - 1].id).toBe(
|
||||
expect(members.data?.members[0]!.id).not.toBe(firstMember.id);
|
||||
expect(
|
||||
members.data?.members[members.data?.members.length - 1]!.id,
|
||||
).not.toBe(lastMember.id);
|
||||
expect(members.data?.members[0]!.id).toBe(secondMember.id);
|
||||
expect(members.data?.members[members.data?.members.length - 1]!.id).toBe(
|
||||
oneBeforeLastMember.id,
|
||||
);
|
||||
});
|
||||
|
||||
@@ -471,9 +471,11 @@ describe("mulit team support", async (it) => {
|
||||
});
|
||||
|
||||
expect(invitation.id).toBeDefined();
|
||||
expect(invitation.teamId).toBe([team1Id, team2Id, team3Id].join(","));
|
||||
expect((invitation as any).teamId).toBe(
|
||||
[team1Id, team2Id, team3Id].join(","),
|
||||
);
|
||||
|
||||
invitationId = invitation.id;
|
||||
invitationId = invitation.id!;
|
||||
});
|
||||
|
||||
it("should accept invite and join all 3 teams", async () => {
|
||||
@@ -482,7 +484,7 @@ describe("mulit team support", async (it) => {
|
||||
if (!invitationId) throw Error("can not run test");
|
||||
|
||||
const accept = await auth.api.acceptInvitation({
|
||||
headers: { cookie: invitedUser.headers.getSetCookie()[0] },
|
||||
headers: { cookie: invitedUser.headers.getSetCookie()[0]! },
|
||||
body: {
|
||||
invitationId,
|
||||
},
|
||||
@@ -498,7 +500,7 @@ describe("mulit team support", async (it) => {
|
||||
if (!invitationId) throw Error("can not run test");
|
||||
|
||||
const teams = await auth.api.listUserTeams({
|
||||
headers: { cookie: invitedUser.headers.getSetCookie()[0] },
|
||||
headers: { cookie: invitedUser.headers.getSetCookie()[0]! },
|
||||
});
|
||||
|
||||
expect(teams).toHaveLength(3);
|
||||
@@ -513,7 +515,7 @@ describe("mulit team support", async (it) => {
|
||||
if (!team1Id || !organizationId) throw Error("can not run test");
|
||||
|
||||
const team = await auth.api.setActiveTeam({
|
||||
headers: { cookie: invitedUser.headers.getSetCookie()[0] },
|
||||
headers: { cookie: invitedUser.headers.getSetCookie()[0]! },
|
||||
body: {
|
||||
teamId: team1Id,
|
||||
},
|
||||
@@ -523,7 +525,7 @@ describe("mulit team support", async (it) => {
|
||||
expect(team.response?.id).toBe(team1Id);
|
||||
expect(team.response?.organizationId).toBe(organizationId);
|
||||
|
||||
activeTeamCookie = team.headers.getSetCookie()[0];
|
||||
activeTeamCookie = team.headers.getSetCookie()[0]!;
|
||||
});
|
||||
|
||||
it("should allow you to list team members of the current active team", async () => {
|
||||
@@ -536,7 +538,7 @@ describe("mulit team support", async (it) => {
|
||||
});
|
||||
|
||||
expect(members).toHaveLength(1);
|
||||
expect(members.at(0)?.teamId).toBe(team1Id);
|
||||
expect(members.at(0)!.teamId).toBe(team1Id);
|
||||
});
|
||||
|
||||
it("should allow user to list team members of any team the user is in", async () => {
|
||||
@@ -546,24 +548,24 @@ describe("mulit team support", async (it) => {
|
||||
if (!team2Id || !team3Id) throw Error("can not run test");
|
||||
|
||||
const team2Members = await auth.api.listTeamMembers({
|
||||
headers: { cookie: invitedUser.headers.getSetCookie()[0] },
|
||||
headers: { cookie: invitedUser.headers.getSetCookie()[0]! },
|
||||
query: {
|
||||
teamId: team2Id,
|
||||
},
|
||||
});
|
||||
|
||||
expect(team2Members).toHaveLength(1);
|
||||
expect(team2Members.at(0)?.teamId).toBe(team2Id);
|
||||
expect(team2Members.at(0)!.teamId).toBe(team2Id);
|
||||
|
||||
const team3Members = await auth.api.listTeamMembers({
|
||||
headers: { cookie: invitedUser.headers.getSetCookie()[0] },
|
||||
headers: { cookie: invitedUser.headers.getSetCookie()[0]! },
|
||||
query: {
|
||||
teamId: team3Id,
|
||||
},
|
||||
});
|
||||
|
||||
expect(team3Members).toHaveLength(1);
|
||||
expect(team3Members.at(0)?.teamId).toBe(team3Id);
|
||||
expect(team3Members.at(0)!.teamId).toBe(team3Id);
|
||||
});
|
||||
|
||||
let team4Id: string | null = null;
|
||||
@@ -591,7 +593,7 @@ describe("mulit team support", async (it) => {
|
||||
expect(teamMember.userId).toBe(invitedUser.response.user.id);
|
||||
|
||||
const teams = await auth.api.listUserTeams({
|
||||
headers: { cookie: invitedUser.headers.getSetCookie()[0] },
|
||||
headers: { cookie: invitedUser.headers.getSetCookie()[0]! },
|
||||
});
|
||||
|
||||
expect(teams).toHaveLength(4);
|
||||
@@ -612,7 +614,7 @@ describe("mulit team support", async (it) => {
|
||||
});
|
||||
|
||||
const teams = await auth.api.listUserTeams({
|
||||
headers: { cookie: invitedUser.headers.getSetCookie()[0] },
|
||||
headers: { cookie: invitedUser.headers.getSetCookie()[0]! },
|
||||
});
|
||||
|
||||
expect(teams).toHaveLength(3);
|
||||
@@ -632,7 +634,7 @@ describe("mulit team support", async (it) => {
|
||||
});
|
||||
|
||||
expect(invitation.id).toBeDefined();
|
||||
expect(invitation.teamId).toBeNull();
|
||||
expect(invitation.teamId).not.toBe("");
|
||||
expect((invitation as any).teamId).toBeNull();
|
||||
expect((invitation as any).teamId).not.toBe("");
|
||||
});
|
||||
});
|
||||
|
||||
@@ -98,7 +98,7 @@ describe("passkey", async () => {
|
||||
const passkeys = await auth.api.listPasskeys({
|
||||
headers: headers,
|
||||
});
|
||||
const passkey = passkeys[0];
|
||||
const passkey = passkeys[0]!;
|
||||
const updateResult = await auth.api.updatePasskey({
|
||||
headers: headers,
|
||||
body: {
|
||||
|
||||
@@ -603,7 +603,7 @@ export const sso = (options?: SSOOptions) => {
|
||||
"email, organizationSlug, domain or providerId is required",
|
||||
});
|
||||
}
|
||||
domain = body.domain || email?.split("@")[1];
|
||||
domain = body.domain || email?.split("@")[1]!;
|
||||
let orgId = "";
|
||||
if (organizationSlug) {
|
||||
orgId = await ctx.context.adapter
|
||||
|
||||
@@ -290,7 +290,7 @@ export const otp2fa = (options?: OTPOptions) => {
|
||||
`2fa-otp-${key}`,
|
||||
);
|
||||
const [otp, counter] = toCheckOtp?.value?.split(":") ?? [];
|
||||
const decryptedOtp = await decryptOTP(ctx, otp);
|
||||
const decryptedOtp = await decryptOTP(ctx, otp!);
|
||||
if (!toCheckOtp || toCheckOtp.expiresAt < new Date()) {
|
||||
if (toCheckOtp) {
|
||||
await ctx.context.internalAdapter.deleteVerificationValue(
|
||||
@@ -302,7 +302,7 @@ export const otp2fa = (options?: OTPOptions) => {
|
||||
});
|
||||
}
|
||||
const allowedAttempts = options?.allowedAttempts || 5;
|
||||
if (parseInt(counter) >= allowedAttempts) {
|
||||
if (parseInt(counter!) >= allowedAttempts) {
|
||||
await ctx.context.internalAdapter.deleteVerificationValue(
|
||||
toCheckOtp.id,
|
||||
);
|
||||
@@ -354,7 +354,7 @@ export const otp2fa = (options?: OTPOptions) => {
|
||||
await ctx.context.internalAdapter.updateVerificationValue(
|
||||
toCheckOtp.id,
|
||||
{
|
||||
value: `${otp}:${(parseInt(counter, 10) || 0) + 1}`,
|
||||
value: `${otp}:${(parseInt(counter!, 10) || 0) + 1}`,
|
||||
},
|
||||
);
|
||||
return invalid("INVALID_CODE");
|
||||
|
||||
@@ -243,7 +243,7 @@ describe("two factor", async () => {
|
||||
},
|
||||
},
|
||||
});
|
||||
const backupCode = backupCodes[0];
|
||||
const backupCode = backupCodes[0]!;
|
||||
|
||||
let parsedCookies = new Map();
|
||||
await client.twoFactor.verifyBackupCode({
|
||||
|
||||
@@ -75,7 +75,7 @@ export const kick = (options: KickOptions) => {
|
||||
return null;
|
||||
}
|
||||
|
||||
const profile = data.data[0];
|
||||
const profile = data.data[0]!;
|
||||
|
||||
const userMap = await options.mapProfileToUser?.(profile);
|
||||
|
||||
|
||||
@@ -111,7 +111,7 @@ export const reddit = (options: RedditOptions) => {
|
||||
name: profile.name,
|
||||
email: profile.oauth_client_id,
|
||||
emailVerified: profile.has_verified_email,
|
||||
image: profile.icon_img?.split("?")[0],
|
||||
image: profile.icon_img?.split("?")[0]!,
|
||||
...userMap,
|
||||
},
|
||||
data: profile,
|
||||
|
||||
@@ -722,7 +722,7 @@ describe("updateAccountOnSignIn", async () => {
|
||||
const userAccounts = await ctx.internalAdapter.findAccounts(
|
||||
session.data?.user.id!,
|
||||
);
|
||||
await ctx.internalAdapter.updateAccount(userAccounts[0].id, {
|
||||
await ctx.internalAdapter.updateAccount(userAccounts[0]!.id, {
|
||||
accessToken: "new-access-token",
|
||||
});
|
||||
|
||||
@@ -756,6 +756,6 @@ describe("updateAccountOnSignIn", async () => {
|
||||
const userAccounts2 = await ctx.internalAdapter.findAccounts(
|
||||
session2.data?.user.id!,
|
||||
);
|
||||
expect(userAccounts2[0].accessToken).toBe("new-access-token");
|
||||
expect(userAccounts2[0]!.accessToken).toBe("new-access-token");
|
||||
});
|
||||
});
|
||||
|
||||
@@ -7,7 +7,7 @@ export function detectPackageManager() {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
const pmSpec = userAgent.split(" ")[0];
|
||||
const pmSpec = userAgent.split(" ")[0]!;
|
||||
const separatorPos = pmSpec.lastIndexOf("/");
|
||||
const name = pmSpec.substring(0, separatorPos);
|
||||
|
||||
|
||||
@@ -85,8 +85,8 @@ export async function detectSystemInfo() {
|
||||
systemRelease: os.release(),
|
||||
systemArchitecture: os.arch(),
|
||||
cpuCount: cpus.length,
|
||||
cpuModel: cpus.length ? cpus[0].model : null,
|
||||
cpuSpeed: cpus.length ? cpus[0].speed : null,
|
||||
cpuModel: cpus.length ? cpus[0]!.model : null,
|
||||
cpuSpeed: cpus.length ? cpus[0]!.speed : null,
|
||||
memory: os.totalmem(),
|
||||
isWSL: await isWsl(),
|
||||
isDocker: await isDocker(),
|
||||
|
||||
@@ -18,7 +18,7 @@ export function convertSetCookieToCookie(headers: Headers): Headers {
|
||||
const cookies = existingCookies ? existingCookies.split("; ") : [];
|
||||
|
||||
setCookieHeaders.forEach((setCookie) => {
|
||||
const [cookiePair] = setCookie.split(";");
|
||||
const cookiePair = setCookie.split(";")[0]!;
|
||||
cookies.push(cookiePair.trim());
|
||||
});
|
||||
|
||||
|
||||
@@ -10,7 +10,7 @@ export function makeTestState(dirname: string) {
|
||||
try {
|
||||
return fs
|
||||
.readFileSync(stateFilePath, "utf-8")
|
||||
.split("\n")[0]
|
||||
.split("\n")[0]!
|
||||
.trim() as State;
|
||||
} catch {
|
||||
return "IDLE";
|
||||
|
||||
@@ -26,7 +26,7 @@ export function getIp(
|
||||
for (const key of ipHeaders) {
|
||||
const value = "get" in headers ? headers.get(key) : headers[key];
|
||||
if (typeof value === "string") {
|
||||
const ip = value.split(",")[0].trim();
|
||||
const ip = value.split(",")[0]!.trim();
|
||||
if (isValidIP(ip)) {
|
||||
return ip;
|
||||
}
|
||||
|
||||
@@ -15,10 +15,10 @@ export function toChecksumAddress(address: string) {
|
||||
let ret = "0x";
|
||||
|
||||
for (let i = 0; i < 40; i++) {
|
||||
if (parseInt(hash[i], 16) >= 8) {
|
||||
ret += address[i].toUpperCase();
|
||||
if (parseInt(hash[i]!, 16) >= 8) {
|
||||
ret += address[i]!.toUpperCase();
|
||||
} else {
|
||||
ret += address[i];
|
||||
ret += address[i]!;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -38,10 +38,10 @@ const isPrimitive = (
|
||||
};
|
||||
|
||||
export const merge = (objects: object[]): object => {
|
||||
const target = clone(objects[0]);
|
||||
const target = clone(objects[0]!);
|
||||
|
||||
for (let i = 1, l = objects.length; i < l; i++) {
|
||||
mergeObjects(target, objects[i]);
|
||||
mergeObjects(target, objects[i]!);
|
||||
}
|
||||
|
||||
return target;
|
||||
|
||||
@@ -13,12 +13,12 @@ const REGEX =
|
||||
export function joseSecs(str: string): number {
|
||||
const matched = REGEX.exec(str);
|
||||
|
||||
if (!matched || (matched[4] && matched[1])) {
|
||||
if (!matched || (matched[4]! && matched[1]!)) {
|
||||
throw new TypeError("Invalid time period format");
|
||||
}
|
||||
|
||||
const value = parseFloat(matched[2]);
|
||||
const unit = matched[3].toLowerCase();
|
||||
const value = parseFloat(matched[2]!);
|
||||
const unit = matched[3]!.toLowerCase();
|
||||
|
||||
let numericDate: number;
|
||||
|
||||
@@ -60,7 +60,7 @@ export function joseSecs(str: string): number {
|
||||
break;
|
||||
}
|
||||
|
||||
if (matched[1] === "-" || matched[4] === "ago") {
|
||||
if (matched[1]! === "-" || matched[4]! === "ago") {
|
||||
return -numericDate;
|
||||
}
|
||||
|
||||
|
||||
@@ -34,7 +34,7 @@ function escapeRegExpChar(char: string) {
|
||||
function escapeRegExpString(str: string) {
|
||||
let result = "";
|
||||
for (let i = 0; i < str.length; i++) {
|
||||
result += escapeRegExpChar(str[i]);
|
||||
result += escapeRegExpChar(str[i]!);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
@@ -95,8 +95,8 @@ function transform(
|
||||
let result = "";
|
||||
|
||||
for (let s = 0; s < segments.length; s++) {
|
||||
let segment = segments[s];
|
||||
let nextSegment = segments[s + 1];
|
||||
let segment = segments[s]!;
|
||||
let nextSegment = segments[s + 1]!;
|
||||
let currentSeparator = "";
|
||||
|
||||
if (!segment && s > 0) {
|
||||
@@ -122,11 +122,11 @@ function transform(
|
||||
}
|
||||
|
||||
for (let c = 0; c < segment.length; c++) {
|
||||
let char = segment[c];
|
||||
let char = segment[c]!;
|
||||
|
||||
if (char === "\\") {
|
||||
if (c < segment.length - 1) {
|
||||
result += escapeRegExpChar(segment[c + 1]);
|
||||
result += escapeRegExpChar(segment[c + 1]!);
|
||||
c++;
|
||||
}
|
||||
} else if (char === "?") {
|
||||
|
||||
@@ -4,7 +4,6 @@
|
||||
"rootDir": "./src",
|
||||
"outDir": "./dist",
|
||||
"lib": ["esnext", "dom", "dom.iterable"],
|
||||
"noUncheckedIndexedAccess": false,
|
||||
"types": ["node", "bun"]
|
||||
},
|
||||
"include": ["src"]
|
||||
|
||||
Reference in New Issue
Block a user