Skip to content

Commit

Permalink
feat: Enable and fix all strict type checks
Browse files Browse the repository at this point in the history
  • Loading branch information
andymac4182 committed May 2, 2023
1 parent 03da715 commit c16ee2d
Show file tree
Hide file tree
Showing 19 changed files with 351 additions and 256 deletions.
37 changes: 26 additions & 11 deletions packages/lib/src/AdfProcessing.ts
Expand Up @@ -201,7 +201,9 @@ function applyInlineComments(

newContent.push({
...child,
text: comment.textForComment,
...(comment.textForComment
? { text: comment.textForComment }
: undefined),
marks: [
...(child.marks ? child.marks : []),
{
Expand Down Expand Up @@ -312,6 +314,9 @@ function pickBestMatchForComment(
index++
) {
const possibleSpot = possibleMatchsForInlineComment[index];
if (!possibleSpot) {
continue;
}

const beforeText =
possibleSpot.beforeTextOutsideMyNode +
Expand Down Expand Up @@ -385,6 +390,9 @@ function pickBestMatchForComment(
index++
) {
const possibleSpot = possibleMatchsForInlineComment[index];
if (!possibleSpot) {
continue;
}

const beforeText =
possibleSpot.beforeTextOutsideMyNode +
Expand Down Expand Up @@ -575,14 +583,19 @@ function levenshteinDistance(a: string, b: string): number {
for (let i = 1; i <= a.length; i++) {
for (let j = 1; j <= b.length; j++) {
const cost = a[i - 1] === b[j - 1] ? 0 : 1;
// @ts-expect-error
matrix[i][j] = Math.min(
// @ts-expect-error
matrix[i - 1][j] + 1,
// @ts-expect-error
matrix[i][j - 1] + 1,
// @ts-expect-error
matrix[i - 1][j - 1] + cost
);
}
}

// @ts-expect-error
return matrix[a.length][b.length];
}

Expand All @@ -596,13 +609,13 @@ function extractInlineComments(adf: JSONDocNode) {
node.marks.some(
(mark) =>
mark.type === "annotation" &&
mark.attrs?.annotationType === "inlineComment"
mark.attrs?.["annotationType"] === "inlineComment"
)
) {
const inlineCommentMark = node.marks?.find(
(mark) =>
mark.type === "annotation" &&
mark.attrs?.annotationType === "inlineComment"
mark.attrs?.["annotationType"] === "inlineComment"
);
const beforeNodes: (ADFEntity | undefined)[] = [],
afterNodes: (ADFEntity | undefined)[] = [];
Expand All @@ -615,17 +628,17 @@ function extractInlineComments(adf: JSONDocNode) {
}
});

const beforeText = beforeNodes.reduce((prev, curr, index) => {
const beforeText = beforeNodes.reduce((prev, curr) => {
return prev + curr?.text;
}, "");

const afterText = afterNodes.reduce((prev, curr, index) => {
const afterText = afterNodes.reduce((prev, curr) => {
return prev + curr?.text;
}, "");

const extract: ExtractedInlineComment = {
pluginInternalId: uuidv4(),
inlineCommentId: inlineCommentMark?.attrs?.id,
inlineCommentId: inlineCommentMark?.attrs?.["id"],
textForComment: node.text,
beforeText,
afterText,
Expand All @@ -648,14 +661,15 @@ function processWikilinkToActualLink(
text: (node, _parent) => {
if (
node.marks &&
node.marks[0] &&
node.marks[0].type === "link" &&
node.marks[0].attrs
) {
if (
typeof node.marks[0].attrs.href === "string" &&
node.marks[0].attrs.href.startsWith("wikilink")
typeof node.marks[0].attrs["href"] === "string" &&
node.marks[0].attrs["href"].startsWith("wikilink")
) {
const wikilinkUrl = new URL(node.marks[0].attrs.href);
const wikilinkUrl = new URL(node.marks[0].attrs["href"]);

const pagename =
wikilinkUrl.pathname !== ""
Expand All @@ -665,14 +679,14 @@ function processWikilinkToActualLink(

if (linkPage) {
const confluenceUrl = `${settings.confluenceBaseUrl}/wiki/spaces/${linkPage.spaceKey}/pages/${linkPage.pageId}${wikilinkUrl.hash}`;
node.marks[0].attrs.href = confluenceUrl;
node.marks[0].attrs["href"] = confluenceUrl;
if (
node.text ===
`${wikilinkUrl.pathname}${wikilinkUrl.hash}`
) {
node.type = "inlineCard";
node.attrs = {
url: node.marks[0].attrs.href,
url: node.marks[0].attrs["href"],
};
delete node.marks;
delete node.text;
Expand All @@ -684,6 +698,7 @@ function processWikilinkToActualLink(
return node;
}
}
return;
},
}) as JSONDocNode;
}
Expand Down
38 changes: 22 additions & 16 deletions packages/lib/src/Attachments.ts
Expand Up @@ -27,14 +27,12 @@ export async function uploadBuffer(
const currentFileMd5 = spark.append(fileBuffer).end();
const imageSize = await sizeOf(fileBuffer);

if (
!!currentAttachments[uploadFilename] &&
currentAttachments[uploadFilename].filehash === currentFileMd5
) {
const fileInCurrentAttachments = currentAttachments[uploadFilename];
if (fileInCurrentAttachments?.filehash === currentFileMd5) {
return {
filename: uploadFilename,
id: currentAttachments[uploadFilename].attachmentId,
collection: currentAttachments[uploadFilename].collectionName,
id: fileInCurrentAttachments.attachmentId,
collection: fileInCurrentAttachments.collectionName,
width: imageSize.width ?? 0,
height: imageSize.height ?? 0,
status: "existing",
Expand All @@ -59,10 +57,15 @@ export async function uploadBuffer(
attachmentDetails
);

const attachmentUploadResponse = attachmentResponse.results[0];
if (!attachmentUploadResponse) {
throw new Error("Issue uploading buffer");
}

return {
filename: uploadFilename,
id: attachmentResponse.results[0].extensions.fileId,
collection: `contentId-${attachmentResponse.results[0].container.id}`,
id: attachmentUploadResponse.extensions.fileId,
collection: `contentId-${attachmentUploadResponse.container.id}`,
width: imageSize.width ?? 0,
height: imageSize.height ?? 0,
status: "uploaded",
Expand All @@ -89,14 +92,12 @@ export async function uploadFile(
const imageBuffer = Buffer.from(testing.contents);
const imageSize = await sizeOf(imageBuffer);

if (
!!currentAttachments[uploadFilename] &&
currentAttachments[uploadFilename].filehash === currentFileMd5
) {
const fileInCurrentAttachments = currentAttachments[uploadFilename];
if (fileInCurrentAttachments?.filehash === currentFileMd5) {
return {
filename: fileNameToUpload,
id: currentAttachments[uploadFilename].attachmentId,
collection: currentAttachments[uploadFilename].collectionName,
id: fileInCurrentAttachments.attachmentId,
collection: fileInCurrentAttachments.collectionName,
width: imageSize.width ?? 0,
height: imageSize.height ?? 0,
status: "existing",
Expand All @@ -120,10 +121,15 @@ export async function uploadFile(
attachmentDetails
);

const attachmentUploadResponse = attachmentResponse.results[0];
if (!attachmentUploadResponse) {
throw new Error("Issue uploading image");
}

return {
filename: fileNameToUpload,
id: attachmentResponse.results[0].extensions.fileId,
collection: `contentId-${attachmentResponse.results[0].container.id}`,
id: attachmentUploadResponse.extensions.fileId,
collection: `contentId-${attachmentUploadResponse.container.id}`,
width: imageSize.width ?? 0,
height: imageSize.height ?? 0,
status: "uploaded",
Expand Down
20 changes: 10 additions & 10 deletions packages/lib/src/ConniePageConfig.ts
Expand Up @@ -127,7 +127,7 @@ export const conniePerPageConfig: ConfluencePerPageConfig = {
key: "connie-frontmatter-to-publish",
default: [],
inputType: "array-text",
inputValidator: (value) => {
inputValidator: () => {
return {
valid: true,
errors: [],
Expand Down Expand Up @@ -164,13 +164,13 @@ export const conniePerPageConfig: ConfluencePerPageConfig = {
key: "tags",
default: [],
inputType: "array-text",
inputValidator: (value) => {
inputValidator: () => {
return {
valid: true,
errors: [],
};
},
process: (yamlValue, markdownFile) => {
process: (yamlValue) => {
const tags: string[] = [];
if (Array.isArray(yamlValue)) {
for (const label of yamlValue) {
Expand Down Expand Up @@ -200,7 +200,7 @@ export const conniePerPageConfig: ConfluencePerPageConfig = {
],
};
},
process: (yamlValue, markdownFile) => {
process: (yamlValue) => {
let pageId: string | undefined;
switch (typeof yamlValue) {
case "string":
Expand All @@ -217,7 +217,7 @@ export const conniePerPageConfig: ConfluencePerPageConfig = {
key: "connie-dont-change-parent-page",
default: false,
inputType: "boolean",
inputValidator: (value) => {
inputValidator: () => {
return {
valid: true,
errors: [],
Expand Down Expand Up @@ -277,13 +277,13 @@ export const conniePerPageConfig: ConfluencePerPageConfig = {
alwaysProcess: true,
inputType: "options",
selectOptions: ["page", "blogpost"],
inputValidator: (value) => {
inputValidator: () => {
return {
valid: true,
errors: [],
};
},
process: (yamlValue, markdownFile, alreadyParsed) => {
process: (yamlValue, _markdownFile, alreadyParsed) => {
if (yamlValue !== undefined && typeof yamlValue !== "string") {
return Error(`Provided "connie-content-type" isn't a string.`);
}
Expand Down Expand Up @@ -388,9 +388,9 @@ function validateDate(dateString: string): ValidationResult {
reasons.push("Invalid format");
} else {
const parts = dateString.split("-");
const year = parseInt(parts[0], 10);
const month = parseInt(parts[1], 10) - 1; // Date months are 0-based
const day = parseInt(parts[2], 10);
const year = parseInt(parts[0] ?? "", 10);
const month = parseInt(parts[1] ?? "", 10) - 1; // Date months are 0-based
const day = parseInt(parts[2] ?? "", 10);

if (year < 0 || year > 9999) {
reasons.push("Invalid year");
Expand Down
15 changes: 10 additions & 5 deletions packages/lib/src/MarkdownTransformer/callout.ts
Expand Up @@ -70,12 +70,14 @@ const panelTypeToAttributesMap: Record<string, [string, string][]> = {
],
};

function getPanelAttributes(calloutType: string) {
function getPanelAttributes(calloutType: string): [string, string][] {
const calloutTypeCheck = calloutType.toLowerCase();
if (Object.keys(panelTypeToAttributesMap).includes(calloutTypeCheck)) {
return panelTypeToAttributesMap[calloutTypeCheck];
const toReturn = panelTypeToAttributesMap[calloutTypeCheck];
if (toReturn) {
return toReturn;
}

// @ts-expect-error
return panelTypeToAttributesMap["info"];
}

Expand All @@ -102,6 +104,9 @@ export function panel(state: StateCore): boolean {
while (true) {
const tokenToCheck = allTokens[currentCheck];
currentCheck = currentCheck + 1;
if (!tokenToCheck) {
continue;
}
if (tokenToCheck.type === "blockquote_close") {
break;
}
Expand All @@ -119,7 +124,7 @@ export function panel(state: StateCore): boolean {
continue;
}

const calloutType = check.groups["calloutType"];
const calloutType = check.groups["calloutType"] ?? "info";
const collapseType = check.groups["collapseType"];
const title = check.groups["title"];
calloutStartIndex = currentCheck - 1;
Expand Down Expand Up @@ -161,7 +166,7 @@ export function panel(state: StateCore): boolean {
if (token.children) {
for (let i = 0; i < token.children.length; i++) {
const child = token.children[i];
if (child.content.includes(check[0])) {
if (child && child.content.includes(check[0])) {
child.content = child.content.replace(
check[0],
calloutTitle
Expand Down
11 changes: 6 additions & 5 deletions packages/lib/src/MarkdownTransformer/index.ts
Expand Up @@ -151,25 +151,26 @@ export class MarkdownTransformer implements Transformer<Markdown> {
private markdownParser: MarkdownParser;
constructor(schema: Schema = defaultSchema, tokenizer: MarkdownIt = md) {
// Enable markdown plugins based on schema
if (schema.nodes.panel) {
if (schema.nodes["panel"]) {
tokenizer.use(myTokenizer);
}

tokenizer.use(wikilinksPlugin);

(["nodes", "marks"] as (keyof SchemaMapping)[]).forEach((key) => {
for (const idx in pmSchemaToMdMapping[key]) {
if (schema[key][idx]) {
tokenizer.enable(pmSchemaToMdMapping[key][idx]);
const toEnable = pmSchemaToMdMapping[key][idx];
if (schema[key][idx] && toEnable) {
tokenizer.enable(toEnable);
}
}
});

if (schema.nodes.table) {
if (schema.nodes["table"]) {
tokenizer.use(markdownItTable);
}

if (schema.nodes.media && schema.nodes.mediaSingle) {
if (schema.nodes["media"] && schema.nodes["mediaSingle"]) {
tokenizer.use(markdownItMedia);
}

Expand Down
5 changes: 4 additions & 1 deletion packages/lib/src/MarkdownTransformer/media.ts
Expand Up @@ -136,7 +136,10 @@ function createRule() {
previousToken = arr[cursor];
}

if (validParentTokens.indexOf(previousToken.type) === -1) {
if (
previousToken &&
validParentTokens.indexOf(previousToken.type) === -1
) {
openingTokens.unshift(previousToken);
} else {
cursor++;
Expand Down
6 changes: 5 additions & 1 deletion packages/lib/src/MarkdownTransformer/wikilinks.ts
Expand Up @@ -110,7 +110,11 @@ function findLinkToHeader(
state: StateInline,
start: number,
max: number
): { hashFragment?: string; headerStart: number; headerEnd: number } {
): {
hashFragment: string | undefined;
headerStart: number;
headerEnd: number;
} {
let headerStart = -1,
headerEnd = -1,
found = false,
Expand Down

0 comments on commit c16ee2d

Please sign in to comment.