Skip to content

Commit

Permalink
fix failing tests
Browse files Browse the repository at this point in the history
  • Loading branch information
brandon-schabel committed Aug 6, 2024
1 parent e083aec commit fa6292a
Show file tree
Hide file tree
Showing 15 changed files with 119 additions and 91 deletions.
5 changes: 2 additions & 3 deletions auth/oauth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -71,10 +71,9 @@ export const initProvider: OAuthProviderInitializer = ({ clientId, authReqUrl, r
if (response.error) {
console.error('Error fetching token:', response.error)
throw new Error(response.error)
} else {
console.log('Access Token:', response.accessToken)
return response
}

return response
})
},
}
Expand Down
11 changes: 11 additions & 0 deletions biome.json
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,17 @@
"trailingCommas": "es5"
}
},
"linter": {
"rules": {
"suspicious": {
"noExplicitAny": "off"
},
"style": {
"useTemplate": "off"
}
},
"ignore": ["*.test.ts"]
},
"files": {
"ignore": ["node_modules", "dist", "build", "*.min.js", "*.d.ts", ".vscode"]
}
Expand Down
29 changes: 13 additions & 16 deletions cli/cli-utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -79,22 +79,18 @@ export function parseArgument(
}

export async function parseCliArgs(): Promise<ParsedArgs> {
try {
const args = getArguments()
const parsedArgs: ParsedArgs = {}
const args = getArguments()
const parsedArgs: ParsedArgs = {}

for (let i = 0; i < args.length; i++) {
const { key, value } = parseArgument(args[i], args[i + 1])
for (let i = 0; i < args.length; i++) {
const { key, value } = parseArgument(args[i], args[i + 1])

if (key) {
parsedArgs[key] = value
}
if (key) {
parsedArgs[key] = value
}

return parsedArgs
} catch (error) {
throw error
}

return parsedArgs
}

export const getAdditionalPrompt = () =>
Expand All @@ -112,6 +108,7 @@ export const getAdditionalPrompt = () =>
export const chooseActions = async (actionsConfig: Record<string, any>): Promise<Array<keyof typeof actionsConfig>> => {
cliLog('\nChoose actions (separated by commas):')
const actions = Object.keys(actionsConfig)

actions.forEach((action, index) => {
cliLog(`${index + 1}. ${action}`)
})
Expand All @@ -128,14 +125,14 @@ export const chooseActions = async (actionsConfig: Record<string, any>): Promise
})
})

const selectedIndexes = actionIndexes.split(',').map((index) => parseInt(index.trim()) - 1)
const selectedIndexes = actionIndexes.split(',').map((index) => Number.parseInt(index.trim()) - 1)

const validSelection = selectedIndexes.every((index) => index >= 0 && index < actions.length)

if (validSelection) {
return selectedIndexes.map((index) => actions[index] as keyof typeof actionsConfig)
} else {
cliLog('Invalid input, please try again.')
return chooseActions(actionsConfig)
}

cliLog('Invalid input, please try again.')
return chooseActions(actionsConfig)
}
32 changes: 10 additions & 22 deletions cli/create-cli-factory.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,40 +25,28 @@ export function createCliFactory<DataT, E extends BaseError<DataT>>({
})

const processInput = async () => {
try {
const commandLineArgs = await parseCliArgs()
const commandLineArgs = await parseCliArgs()

const userInput = await getUserInput()
const userInput = await getUserInput()

// Handle user input and command line arguments...
return { commandLineArgs, userInput }
} catch (error) {
throw error
}
// Handle user input and command line arguments...
return { commandLineArgs, userInput }
}

const executeActions = async () => {
try {
const additionalPrompt = await getAdditionalPrompt()
const additionalPrompt = await getAdditionalPrompt()

const chosenActions = await chooseActions(actionsConfig)
const chosenActions = await chooseActions(actionsConfig)

// Execute chosen actions...
// Execute chosen actions...

return { additionalPrompt, chosenActions }
} catch (error) {
throw error
}
return { additionalPrompt, chosenActions }
}

const handleFiles = ({ filePath, fileContent }: { filePath: string; fileContent: string }) => {
try {
factory.directoryExists({ path: filePath })
factory.directoryExists({ path: filePath })

factory.createFile(filePath, fileContent)
} catch (error) {
throw error
}
factory.createFile(filePath, fileContent)
}

return {
Expand Down
10 changes: 8 additions & 2 deletions cookies/cookie-utils.test.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,16 @@
import { afterEach, describe, expect, it } from 'bun:test'
import { parseCookieData, retrieveRawCookieValue, stringifyCookieData } from './cookie-utils'

declare var document: {
cookie: any
// declare var document: {
// cookie: any
// }
const mockDocument = {
cookie: '',
}

// Mock global document
global.document = mockDocument as any

describe('Cookie Helpers', () => {
describe('parseCookieData', () => {
it('should parse JSON string to object', () => {
Expand Down
18 changes: 9 additions & 9 deletions cookies/cookie-utils.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import type { CookieOptions } from './cookie-types'

declare var document: {
declare const document: {
cookie: any
}

Expand All @@ -19,9 +19,9 @@ export const parseCookieData = <T = string>(data: string | null): T | null => {
export const stringifyCookieData = <T>(data: T): string => {
if (typeof data === 'string') {
return data
} else {
return JSON.stringify(data)
}

return JSON.stringify(data)
}

export const retrieveRawCookieValue = (name: string): string | null => {
Expand Down Expand Up @@ -55,11 +55,11 @@ export const encodeCookie = <T>(cookieKey: string, value: T, options: CookieOpti
}

if (options.secure) {
cookieString += `; secure`
cookieString += '; secure'
}

if (options.httpOnly) {
cookieString += `; httpOnly`
cookieString += '; httpOnly'
}

return cookieString
Expand All @@ -73,10 +73,10 @@ export function parseCookies(cookiesString: string) {
const cookies: { [name: string]: string } = {}
const pairs = cookiesString.split(';')

pairs.forEach((pair) => {
const [name, ...rest] = pair.split('=')
cookies[name.trim()] = rest.join('=').trim()
})
for (const pair of pairs) {
const [name, ...value] = pair.split('=')
cookies[name.trim()] = value.join('=').trim()
}

return cookies
}
Expand Down
16 changes: 8 additions & 8 deletions htmlody/css-engine.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -39,11 +39,11 @@ describe('generateCSS', () => {

const result = generateCSS(mockNodeMap)
const expectedCss =
`.flex { display: flex; }\n` +
`.m-1 { margin: 0.25rem; }\n` +
`.w-1/2 { width: 50%; }\n` +
`.h-1/2 { height: 50%; }\n` +
`.p-1 { padding: 0.25rem; }\n`
'.flex { display: flex; }\n' +
'.m-1 { margin: 0.25rem; }\n' +
'.w-1/2 { width: 50%; }\n' +
'.h-1/2 { height: 50%; }\n' +
'.p-1 { padding: 0.25rem; }\n'

expect(result).toEqual(expectedCss)
})
Expand Down Expand Up @@ -136,7 +136,7 @@ describe('generateColorVariables', () => {
it('should generate CSS variables for colors', () => {
const result = generateColorVariables()

expect(result).toContain(`--red-50`)
expect(result).toContain('--red-50')

expect(result).toContain(':root {\n--red-50: #1A0000;')
expect(result).toContain('--slate-300: #4E5A65;')
Expand All @@ -148,10 +148,10 @@ describe('generateShades', () => {
const result = generateShades('red')
expect(result).toHaveLength(10)

result.forEach((shade) => {
for (const shade of result) {
// validate that each shade is a valid hex color
expect(shade).toHaveLength(7)
})
}

expect(result[0][0]).toBe('#') // first shade, first charact
})
Expand Down
20 changes: 10 additions & 10 deletions htmlody/css-engine.ts
Original file line number Diff line number Diff line change
Expand Up @@ -88,10 +88,10 @@ function generateCssSelector(breakpoint: string, className: string): string {
function processClassRecords(classRecords: ResponsiveClassRecord, usedClasses: Set<string>): string | null {
let cssStr = ''

Object.entries(classRecords).forEach(([breakpoint, classRecord]) => {
for (const [breakpoint, classRecord] of Object.entries(classRecords)) {
const classNames = extractClassNames(classRecord)

classNames.forEach((className) => {
for (const className of classNames) {
const fullClassName = breakpoint === '*' ? className : `${breakpoint}_${className}`

if (!usedClasses.has(fullClassName)) {
Expand All @@ -102,8 +102,8 @@ function processClassRecords(classRecords: ResponsiveClassRecord, usedClasses: S
cssStr += `${selector}\n`
}
}
})
})
}
}

if (!cssStr) return null
return cssStr
Expand All @@ -118,10 +118,10 @@ export function processNode(node: JsonTagElNode<ClassRecordAttributes>, usedClas
}

if (node.child) {
Object.values(node.child).forEach((childNode) => {
for (const childNode of Object.values(node.child)) {
const childNodeStr = processNode(childNode, usedClasses)
if (childNodeStr) cssStr += childNodeStr
})
}
}

return cssStr || null
Expand All @@ -135,11 +135,10 @@ export function generateCSS<
const usedClasses = new Set<string>()
let cssStr = ''

Object.values(nodeMap).forEach((node) => {
for (const node of Object.values(nodeMap)) {
const nodeStr = processNode(node, usedClasses)

if (nodeStr) cssStr += nodeStr
})
}

if (!cssStr) return null
return cssStr
Expand Down Expand Up @@ -297,7 +296,8 @@ export function generateShades(color: ColorType): string[] {
// and greater than 1 will lighten it
const factors = [0.1, 0.3, 0.5, 0.7, 0.9, 1, 1.1, 1.3, 1.5, 1.7]
factors.forEach((factor, index) => {
let adjustedColor
let adjustedColor: ReturnType<typeof adjustBrightness> | ReturnType<typeof lightenColor>

if (index < 5) {
// Darken the color for shades 50-400
adjustedColor = adjustBrightness(baseColor, factor)
Expand Down
5 changes: 3 additions & 2 deletions htmlody/htmlody-utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -47,10 +47,11 @@ export function isValidAttributesString(attributesStr: string): boolean {
export function collectClassNames(node: JsonTagElNode, uniqueClassNames: Set<string>) {
if (node.attributes && typeof node.attributes.class === 'string') {
const classList = node.attributes.class.split(' ')
classList.forEach((cls) => uniqueClassNames.add(cls))
for (const cls of classList) {
uniqueClassNames.add(cls)
}
}
}

export const children = (children: JsonTagElNode<CRNode>[]) => {
const returnChildren: JsonHtmlNodeTree = {}

Expand Down
4 changes: 2 additions & 2 deletions htmlody/json-to-html-engine.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -240,7 +240,7 @@ describe('renderNodeToHtml', () => {
id: 'sample-id',
class: 'sample-class',
},
children: {
child: {
span_id1: {
tag: 'span',
content: 'Child Content',
Expand Down Expand Up @@ -293,7 +293,7 @@ describe('createNodeFactory', () => {
id: 'sample-id',
class: 'sample-class',
},
children: {
child: {
span_id1: {
tag: 'span',
content: 'Child Content',
Expand Down
29 changes: 25 additions & 4 deletions htmlody/json-to-html-engine.ts
Original file line number Diff line number Diff line change
Expand Up @@ -168,14 +168,20 @@ const generateTitleNode = (title: string): JsonTagElNode => {
}
}

const generateMetaTagNode = (meta: { name: string; content: string }): JsonTagElNode => {
const generateMetaTagNode = (meta: {
name: string
content: string
}): JsonTagElNode => {
return {
tag: 'meta',
attributes: { name: meta.name, content: meta.content },
}
}

const generateLinkTagNode = (link: { rel: string; href: string }): JsonTagElNode => {
const generateLinkTagNode = (link: {
rel: string
href: string
}): JsonTagElNode => {
return {
tag: 'link',
attributes: { rel: link.rel, href: link.href },
Expand All @@ -189,7 +195,11 @@ const generateStyleTagNode = (content: string): JsonTagElNode => {
}
}

const generateScriptTagNode = (script: { src?: string; type?: string; content: string }): JsonTagElNode => {
const generateScriptTagNode = (script: {
src?: string
type?: string
content: string
}): JsonTagElNode => {
const node: JsonTagElNode = {
tag: 'script',
attributes: {},
Expand Down Expand Up @@ -279,7 +289,18 @@ export const htmlodyBuilder = <
const renderNodeTreeToHtml = (nodeMap: JsonHtmlNodeTree, pluginsOverride?: Plugins): string => {
const activePlugins = pluginsOverride || effectivePlugins
return Object.keys(nodeMap)
.map((id) => renderNodeWithPlugins(nodeMap[id], activePlugins))
.map((id) => {
const node = nodeMap[id]
const childrenHtml = node.child ? renderNodeTreeToHtml(node.child, activePlugins) : ''
return renderNodeWithPlugins(
{
...node,
content: node.content || '', // Remove childrenHtml from here
child: node.child, // Pass child to renderNodeWithPlugins
},
activePlugins
)
})
.join('')
}

Expand Down
Loading

0 comments on commit fa6292a

Please sign in to comment.