Openverse is a search engine for openly-licensed media. This monorepo includes all application code.
Convert 6 utils to TypeScript (#1023)
Dhruv Bhanushali49b54b55b4ff
diff --git a/.eslintrc.js b/.eslintrc.jsindex 8811be90a..2fe6ad08d 100644--- a/.eslintrc.js+++ b/.eslintrc.js@@ -18,7 +18,13 @@ module.exports = {'plugin:@intlify/vue-i18n/recommended',],// required to lint *.vue files- plugins: ['@typescript-eslint', 'vue', 'vuejs-accessibility', 'unicorn'],+ plugins: [+ '@typescript-eslint',+ 'eslint-plugin-tsdoc',+ 'vue',+ 'vuejs-accessibility',+ 'unicorn',+ ],// add your custom rules hererules: {semi: [2, 'never'],@@ -75,6 +81,14 @@ module.exports = {'@typescript-eslint/ban-ts-comment': ['warn'],'@typescript-eslint/no-var-requires': ['warn'],},+ overrides: [+ {+ files: ['*.ts'],+ rules: {+ 'tsdoc/syntax': 'warn',+ },+ },+ ],settings: {'vue-i18n': {localeDir: './src/locales/*.{json}',diff --git a/Dockerfile b/Dockerfileindex a7293f580..d21b469aa 100644--- a/Dockerfile+++ b/Dockerfile@@ -76,7 +76,7 @@ COPY pnpm-lock.yaml .COPY .npmrc .# copy the nuxt configuration file-COPY --from=builder /usr/app/nuxt.config.js .+COPY --from=builder /usr/app/nuxt.config.ts .# copy distribution directory with the static contentCOPY --from=builder /usr/app/.nuxt /usr/app/.nuxt@@ -106,4 +106,3 @@ EXPOSE 8443# run the application in static modeENTRYPOINT ["pnpm", "run", "start"]-diff --git a/nuxt-template-overrides/README.md b/nuxt-template-overrides/README.mdindex c6118be9e..99ed3da0c 100644--- a/nuxt-template-overrides/README.md+++ b/nuxt-template-overrides/README.md@@ -1,6 +1,6 @@# Nuxt vue-app template overrides-Due to a CSS ordering bug that we haven't been able to find any other solutions for, we've had to override the Nuxt templates for the `App.js` and `index.js` files to prevent any Vue components from being imported before the static CSS assets in the `nuxt.config.js`.+Due to a CSS ordering bug that we haven't been able to find any other solutions for, we've had to override the Nuxt templates for the `App.js` and `index.js` files to prevent any Vue components from being imported before the static CSS assets in the `nuxt.config.ts`.## Described changesdiff --git a/nuxt.config.js b/nuxt.config.tssimilarity index 93%rename from nuxt.config.jsrename to nuxt.config.tsindex 2d8a524d5..f91a8ebbf 100644--- a/nuxt.config.js+++ b/nuxt.config.ts@@ -1,9 +1,13 @@+import type { NuxtConfig } from '@nuxt/types'+import pkg from './package.json'import locales from './src/locales/scripts/valid-locales.json'+import { VIEWPORTS } from './src/constants/screens'-import { dev } from './src/utils/dev'++import { isProd } from './src/utils/node-env'+import { sentryConfig } from './src/utils/sentry-config'import { env } from './src/utils/env'-import { sentry } from './src/utils/sentry-config'/*** The default metadata for the site. Can be extended and/or overwritten per page. And even in components!@@ -51,6 +55,7 @@ const meta = [if (process.env.NODE_ENV === 'production') {meta.push({+ // @ts-expect-error: 'http-equiv' isn't allowed here by Nuxt'http-equiv': 'Content-Security-Policy',content: 'upgrade-insecure-requests',})@@ -99,7 +104,7 @@ const head = {],}-export default {+const config: NuxtConfig = {// eslint-disable-next-line no-undefversion: pkg.version, // used to purge cache :)cache: {@@ -116,9 +121,9 @@ export default {router: {middleware: 'middleware',},- components: {- dirs: [{ path: '~/components', extensions: ['vue'], pathPrefix: false }],- },+ components: [+ { path: '~/components', extensions: ['vue'], pathPrefix: false },+ ],plugins: [{ src: '~/plugins/url-change.js' },{ src: '~/plugins/migration-notice.js' },@@ -134,7 +139,7 @@ export default {],head,env,- dev,+ dev: !isProd,buildModules: ['@nuxt/typescript-build','@nuxtjs/composition-api/module',@@ -195,7 +200,7 @@ export default {* {@link https://github.com/nuxt-community/redirect-module#usage}*/redirect: [{ from: '^/photos/(.*)$', to: '/image/$1', statusCode: 301 }],- sentry,+ sentry: sentryConfig,build: {templates: [{@@ -245,3 +250,5 @@ export default {},},}++export default configdiff --git a/package.json b/package.jsonindex e314d3d43..c5f198085 100644--- a/package.json+++ b/package.json@@ -27,8 +27,8 @@"e2e:ci": "start-server-and-test run-server http://localhost:8443 test:e2e","generate-e2e-tests": "playwright codegen localhost:8443/","types": "tsc --noEmit",- "lint": "eslint --ext .js,.vue --ignore-path .gitignore --ignore-path .eslintignore .",- "lintfix": "eslint --fix --ext .js,.vue --ignore-path .gitignore --ignore-path .eslintignore .",+ "lint": "eslint --ext .js,.ts,.vue --ignore-path .gitignore --ignore-path .eslintignore .",+ "lintfix": "eslint --fix --ext .js,.ts,.vue --ignore-path .gitignore --ignore-path .eslintignore .","format": "prettier --write .","format:test": "prettier --check .","vue-i18n-check": "vue-i18n-extract report --vueFiles './src/**/*.?(js|vue)' --languageFiles './src/locales/*.?(json)'",@@ -108,6 +108,7 @@"eslint-config-prettier": "^8.1.0","eslint-loader": "^4.0.2","eslint-plugin-prettier": "^3.3.1",+ "eslint-plugin-tsdoc": "^0.2.14","eslint-plugin-unicorn": "^35.0.0","eslint-plugin-vue": "^7.8.0","eslint-plugin-vuejs-accessibility": "^0.6.1",diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex 9f43c662a..44ef92e8b 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -46,6 +46,7 @@ specifiers:eslint-config-prettier: ^8.1.0eslint-loader: ^4.0.2eslint-plugin-prettier: ^3.3.1+ eslint-plugin-tsdoc: ^0.2.14eslint-plugin-unicorn: ^35.0.0eslint-plugin-vue: ^7.8.0eslint-plugin-vuejs-accessibility: ^0.6.1@@ -157,6 +158,7 @@ devDependencies:eslint-config-prettier: [email protected]eslint-loader: [email protected]eslint-plugin-prettier: 3.4.1_6e6a25a49a944db0fa38418c3ba4bc86+ eslint-plugin-tsdoc: 0.2.14eslint-plugin-unicorn: [email protected]eslint-plugin-vue: [email protected]eslint-plugin-vuejs-accessibility: [email protected]@@ -3095,6 +3097,19 @@ packages:resolution: {integrity: sha512-H1rQc1ZOHANWBvPcW+JpGwr+juXSxM8Q8YCkm3GhZd8REu1fHR3z99CErO1p9pkcfcxZnMdIZdIsXkOHY0NilA==}dev: true+ /@microsoft/tsdoc-config/0.15.2:+ resolution: {integrity: sha512-mK19b2wJHSdNf8znXSMYVShAHktVr/ib0Ck2FA3lsVBSEhSI/TfXT7DJQkAYgcztTuwazGcg58ZjYdk0hTCVrA==}+ dependencies:+ '@microsoft/tsdoc': 0.13.2+ ajv: 6.12.6+ jju: 1.4.0+ resolve: 1.19.0+ dev: true++ /@microsoft/tsdoc/0.13.2:+ resolution: {integrity: sha512-WrHvO8PDL8wd8T2+zBGKrMwVL5IyzR3ryWUsl0PXgEV0QHup4mTLi0QcATefGI6Gx9Anu7vthPyyyLpY0EpiQg==}+ dev: true+/@mrmlnc/readdir-enhanced/2.2.1:resolution: {integrity: sha512-bPHp6Ji8b41szTOcaP63VlnbbO5Ny6dwAATtY6JTjh5N2OLrb5Qk/Th5cRkRQhkWCt+EJsYrNB0MiL+Gpn6e3g==}engines: {node: '>=4'}@@ -9508,6 +9523,13 @@ packages:prettier-linter-helpers: 1.0.0dev: true+ /eslint-plugin-tsdoc/0.2.14:+ resolution: {integrity: sha512-fJ3fnZRsdIoBZgzkQjv8vAj6NeeOoFkTfgosj6mKsFjX70QV256sA/wq+y/R2+OL4L8E79VVaVWrPeZnKNe8Ng==}+ dependencies:+ '@microsoft/tsdoc': 0.13.2+ '@microsoft/tsdoc-config': 0.15.2+ dev: true+/eslint-plugin-unicorn/[email protected]:resolution: {integrity: sha512-FHsaO68tDPQILfs/mGF8eSISJp8RswR4FpUuBDnueK2wyEHC6zmsc9WxjYyldXoIsBuVmru6jQyFCbCWPoW/KQ==}engines: {node: '>=12'}@@ -12309,6 +12331,10 @@ packages:resolution: {integrity: sha512-TdcJywkQtcwLxogc4rSMAi479G2eDPzfW0fLySks7TPhgZZ4s/tM6stnzayIh3gS/db3zExWJyUx4cNWrwAmoQ==}hasBin: true+ /jju/1.4.0:+ resolution: {integrity: sha1-o6vicYryQaKykE+EpiWXDzia4yo=}+ dev: true+/joi/17.5.0:resolution: {integrity: sha512-R7hR50COp7StzLnDi4ywOXHrBrgNXuUUfJWIR5lPY5Bm/pOD3jZaTwpluUXVLRWcoWZxkrHBBJ5hLxgnlehbdw==}dependencies:@@ -16066,6 +16092,13 @@ packages:resolution: {integrity: sha1-LGN/53yJOv0qZj/iGqkIAGjiBSo=}deprecated: https://github.com/lydell/resolve-url#deprecated+ /resolve/1.19.0:+ resolution: {integrity: sha512-rArEXAgsBG4UgRGcynxWIWKFvh/XZCcS8UJdHhwy91zwAvCZIbcs+vAbflgBnNjYMs/i/i+/Ux6IZhML1yPvxg==}+ dependencies:+ is-core-module: 2.8.0+ path-parse: 1.0.7+ dev: true+/resolve/1.20.0:resolution: {integrity: sha512-wENBPt4ySzg4ybFQW2TT1zMQucPK95HSh/nq2CFTZVOGut2+pQvSsgtda4d26YrYcr067wjbmzOG8byDPBX63A==}dependencies:diff --git a/src/components/SketchFabViewer.vue b/src/components/SketchFabViewer.vueindex 38ef9d440..41dcd8054 100644--- a/src/components/SketchFabViewer.vue+++ b/src/components/SketchFabViewer.vue@@ -16,6 +16,7 @@<script>import loadScript from '~/utils/load-script'+import { log } from '~/utils/console'const sketchfabUrl ='https://static.sketchfab.com/api/sketchfab-viewer-1.10.1.js'@@ -34,11 +35,11 @@ export default {success: (api) => {api.addEventListener('viewerready', () => {this.loading = false- console.log('LOADED!')+ log('LOADED!')})},error: () => {- console.log('Viewer error')+ log('Viewer error')},},loading: true,diff --git a/src/components/VButton.vue b/src/components/VButton.vueindex 47c5c51bd..584626a3f 100644--- a/src/components/VButton.vue+++ b/src/components/VButton.vue@@ -31,7 +31,7 @@ import {computed,} from '@nuxtjs/composition-api'import VLink from '~/components/VLink.vue'-import { warn } from '@/utils/warn'+import { warn } from '~/utils/console'/*** A button component that behaves just like a regular HTML `button` elementdiff --git a/src/components/VIcon/VIcon.vue b/src/components/VIcon/VIcon.vueindex ec3b8d1a5..3984e377c 100644--- a/src/components/VIcon/VIcon.vue+++ b/src/components/VIcon/VIcon.vue@@ -12,6 +12,8 @@</template><script>+import { isTest } from '~/utils/node-env'+/*** Displays the given icon in a 24px × 24px square.*/@@ -33,7 +35,7 @@ export default {/*** In `jest` our icons get transformed to Vue components*/- type: process.env.NODE_ENV === 'test' ? Object : String,+ type: isTest ? Object : String,required: true,},/**diff --git a/src/components/VItemGroup/VItem.vue b/src/components/VItemGroup/VItem.vueindex 5b4eab33b..20a501290 100644--- a/src/components/VItemGroup/VItem.vue+++ b/src/components/VItemGroup/VItem.vue@@ -74,7 +74,7 @@ import {VItemGroupFocusContextKey,} from './VItemGroup.vue'import { VPopoverContentContextKey } from '~/components/VPopover/VPopoverContent.vue'-import { warn } from '~/utils/warn'+import { warn } from '~/utils/console'export default defineComponent({name: 'VItem',diff --git a/src/components/VModal/VMobileModalContent.vue b/src/components/VModal/VMobileModalContent.vueindex 3ef2a03ba..715616134 100644--- a/src/components/VModal/VMobileModalContent.vue+++ b/src/components/VModal/VMobileModalContent.vue@@ -45,7 +45,7 @@import { defineComponent, toRefs, ref } from '@nuxtjs/composition-api'import { FocusTrap } from 'focus-trap-vue'import { useDialogContent } from '~/composables/use-dialog-content'-import { warn } from '~/utils/warn'+import { warn } from '~/utils/console'import closeIcon from '~/assets/icons/close.svg'diff --git a/src/components/VModal/VModalContent.vue b/src/components/VModal/VModalContent.vueindex f63a2f7aa..f9946a17f 100644--- a/src/components/VModal/VModalContent.vue+++ b/src/components/VModal/VModalContent.vue@@ -42,7 +42,7 @@ import { defineComponent, toRefs, ref } from '@nuxtjs/composition-api'import { FocusTrap } from 'focus-trap-vue'import VTeleport from '~/components/VTeleport/VTeleport'import { useDialogContent } from '~/composables/use-dialog-content'-import { warn } from '~/utils/warn'+import { warn } from '~/utils/console'import VButton from '~/components/VButton.vue'import VIcon from '~/components/VIcon/VIcon.vue'import closeIcon from '~/assets/icons/close.svg'diff --git a/src/components/VPopover/VPopoverContent.vue b/src/components/VPopover/VPopoverContent.vueindex 2ac3eee7c..017030cbe 100644--- a/src/components/VPopover/VPopoverContent.vue+++ b/src/components/VPopover/VPopoverContent.vue@@ -21,7 +21,7 @@<script>import { defineComponent, toRefs, ref, provide } from '@nuxtjs/composition-api'import { usePopoverContent } from '~/composables/use-popover-content'-import { warn } from '~/utils/warn'+import { warn } from '~/utils/console'import { propTypes } from './VPopoverContent.types'diff --git a/src/components/VPopover/meta/VPopover.stories.js b/src/components/VPopover/meta/VPopover.stories.jsindex 79236a064..71f63ac92 100644--- a/src/components/VPopover/meta/VPopover.stories.js+++ b/src/components/VPopover/meta/VPopover.stories.js@@ -2,6 +2,8 @@ import VPopover from '~/components/VPopover/VPopover.vue'import VButton from '~/components/VButton'import { placements as popoverPlacements } from '@popperjs/core'+import { log } from '~/utils/console'+export default {component: VPopover,title: 'Components/VPopover',@@ -37,8 +39,8 @@ const SinglePopoverStory = (args, { argTypes }) => ({`,components: { VPopover, VButton },setup() {- const onOpen = () => console.log('opened!')- const onClose = () => console.log('closed!')+ const onOpen = () => log('opened!')+ const onClose = () => log('closed!')return { onOpen, onClose }},diff --git a/src/components/VTeleport/VTeleportTarget.vue b/src/components/VTeleport/VTeleportTarget.vueindex 978c52b37..8e3408b24 100644--- a/src/components/VTeleport/VTeleportTarget.vue+++ b/src/components/VTeleport/VTeleportTarget.vue@@ -1,7 +1,7 @@<script>import { defineComponent } from '@nuxtjs/composition-api'import { targets } from './meta/targets'-import { warn } from '~/utils/warn'+import { warn } from '~/utils/console'export default defineComponent({name: 'VTeleportTarget',diff --git a/src/components/meta/DropdownButton.stories.js b/src/components/meta/DropdownButton.stories.jsindex 3fc437acf..96e8d3205 100644--- a/src/components/meta/DropdownButton.stories.js+++ b/src/components/meta/DropdownButton.stories.js@@ -1,5 +1,7 @@import DropdownButton from '~/components/DropdownButton'+import { log } from '~/utils/console'+export default {title: 'Components/DropdownButton',component: DropdownButton,@@ -41,13 +43,13 @@ export const Default = (args, { argTypes }) => ({},computed: {activeItem() {- console.log(this)+ log(this)return this.items.find((item) => item.active)},},methods: {onClick(event) {- console.log(event)+ log(event)alert('clicked!')},setActive(toActivate) {diff --git a/src/composables/use-focus-on-show.js b/src/composables/use-focus-on-show.jsindex 6eb34945c..fbc9c2549 100644--- a/src/composables/use-focus-on-show.js+++ b/src/composables/use-focus-on-show.js@@ -3,7 +3,7 @@ import { getFirstTabbableIn } from 'reakit-utils/tabbable'import { hasFocusWithin } from 'reakit-utils/hasFocusWithin'import { ensureFocus } from 'reakit-utils/ensureFocus'-import { warn } from '~/utils/warn'+import { warn } from '~/utils/console'export const noFocusableElementWarning ="It's recommended to have at least one tabbable element inside dialog. The dialog element has been automatically focused. If this is the intended behavior, pass `tabIndex={0}` to the dialog element to disable this warning."diff --git a/src/data/api-service.js b/src/data/api-service.jsindex b9795e52d..0be6edf7c 100644--- a/src/data/api-service.js+++ b/src/data/api-service.js@@ -1,5 +1,5 @@import axios from 'axios'-import { warn } from '~/utils/warn'+import { warn } from '~/utils/console'import { AUDIO, IMAGE } from '~/constants/media'const DEFAULT_REQUEST_TIMEOUT = 30000diff --git a/src/locales/scripts/get-validated-locales.js b/src/locales/scripts/get-validated-locales.jsindex 3d0292cf2..a5de99f1c 100644--- a/src/locales/scripts/get-validated-locales.js+++ b/src/locales/scripts/get-validated-locales.js@@ -10,8 +10,8 @@ const { addFetchedTranslationStatus } = require('./get-translations-status')/*** Returns a list of locale objects with at least one translated string* @returns {{- * translated: import('./types').i18nLocaleProps[],- * untranslated: import('./types').i18nLocaleProps[]+ * translated: import('./types').I18nLocaleProps[],+ * untranslated: import('./types').I18nLocaleProps[]* }}*/const getValidatedLocales = async () => {diff --git a/src/locales/scripts/types.d.ts b/src/locales/scripts/types.d.tsindex 13f2fbc66..4f522a5f8 100644--- a/src/locales/scripts/types.d.ts+++ b/src/locales/scripts/types.d.ts@@ -1,3 +1,9 @@-/**- * @typedef {{ code: string, wpLocale?: string, file?: string, iso?: string, name: string, dir?: string, translated?: number }} i18nLocaleProps- */+export interface I18nLocaleProps {+ code: string+ name: string+ wpLocale?: string+ file?: string+ iso?: string+ dir?: string+ translated?: number+}diff --git a/src/store/index.js b/src/store/index.jsindex ad837e167..3c0b63398 100644--- a/src/store/index.js+++ b/src/store/index.js@@ -1,12 +1,14 @@import { FETCH_MEDIA_PROVIDERS } from '~/constants/action-types'import { PROVIDER } from '~/constants/store-modules'+import { warn } from '~/utils/console'+export const actions = {async nuxtServerInit({ dispatch }) {try {await dispatch(`${PROVIDER}/${FETCH_MEDIA_PROVIDERS}`)} catch (error) {- console.warn("Couldn't fetch media providers")+ warn("Couldn't fetch media providers")}},}diff --git a/src/store/provider.js b/src/store/provider.jsindex 1e6a8c6b8..71e40f632 100644--- a/src/store/provider.js+++ b/src/store/provider.js@@ -14,6 +14,7 @@ import {} from '~/constants/mutation-types'import { capital } from 'case'import { SEARCH } from '~/constants/store-modules'+import { warn } from '~/utils/console'const AudioProviderService = MediaProviderService(AUDIO)const ImageProviderService = MediaProviderService(IMAGE)@@ -70,7 +71,7 @@ export const createActions = (services) => ({sortedProviders = sortProviders(data)}).catch((error) => {- console.warn(+ warn(`Error getting ${mediaType} providers: ${error}. Will use saved provider data instead.`)commit(SET_PROVIDER_FETCH_ERROR, { mediaType, error: true })diff --git a/src/store/types.ts b/src/store/types.tsindex a259ea5f0..73333d61c 100644--- a/src/store/types.ts+++ b/src/store/types.ts@@ -149,8 +149,9 @@ export interface ActiveMediaState {status: 'ejected' | 'playing' | 'paused' // 'ejected' means player is closed}-export interface MediaStoreResult<T extends FrontendMediaType>- extends MediaResult<Record<MediaDetail['id'], T>> {}+export type MediaStoreResult<T extends FrontendMediaType> = MediaResult<+ Record<MediaDetail['id'], T>+>export interface MediaState {results: {diff --git a/src/store/usage-data.js b/src/store/usage-data.jsindex a1ba17049..b87eef548 100644--- a/src/store/usage-data.js+++ b/src/store/usage-data.js@@ -4,9 +4,11 @@ import {SEND_DETAIL_PAGE_EVENT,SEND_SEARCH_RATING_EVENT,} from '~/constants/usage-data-analytics-types'-import stringToBoolean from '~/utils/string-to-boolean'+import UsageDataService from '~/data/usage-data-service'-import { sentry as sentryConfig } from '~/utils/sentry-config'++import { stringToBoolean } from '~/utils/string-to-boolean'+import { sentryConfig } from '~/utils/sentry-config'const disabled = !stringToBoolean(process.env.enableInternalAnalytics)diff --git a/src/utils/console.ts b/src/utils/console.tsnew file mode 100644index 000000000..253f51f64--- /dev/null+++ b/src/utils/console.ts@@ -0,0 +1,11 @@+import { isProd } from '~/utils/node-env'++export const getLogger = (level: 'log' | 'warn' | 'error') =>+ isProd+ ? () => {+ // do nothing+ }+ : console[level]++export const warn = getLogger('warn')+export const log = getLogger('log')diff --git a/src/utils/decode-data.js b/src/utils/decode-data.jsdeleted file mode 100644index 5f36e4535..000000000--- a/src/utils/decode-data.js+++ /dev/null@@ -1,23 +0,0 @@-/**- * decodes some edge cases of Unicode characters with an extra \- * See test cases for some examples- * @param {string} [data]- */-export default function decodeData(data) {- if (data) {- try {- const regexASCII = /\\x([\d\w]{2})/gi- const ascii = data.replace(regexASCII, (_, grp) =>- String.fromCharCode(parseInt(grp, 16))- )- const regexUni = /\\u([\d\w]{4})/gi- const uni = ascii.replace(regexUni, (_, grp) =>- String.fromCharCode(parseInt(grp, 16))- )- return decodeURI(uni)- } catch (e) {- return data- }- }- return ''-}diff --git a/src/utils/decode-data.ts b/src/utils/decode-data.tsnew file mode 100644index 000000000..121c6a8ea--- /dev/null+++ b/src/utils/decode-data.ts@@ -0,0 +1,22 @@+/**+ * Decodes some edge cases where ASCII/Unicode characters with escape sequences+ * have escaped backslashes, which prevents them from rendering. This function+ * replaces them with the relevant character.+ *+ * @param data - the string to unescape so that it can be rendered+ */+export const decodeData = (data = ''): string => {+ if (!data) return ''++ try {+ const regexes = [/\\x([\d\w]{2})/gi, /\\u([\d\w]{4})/gi]+ regexes.forEach((regex) => {+ data = data.replace(regex, (_, grp) =>+ String.fromCharCode(parseInt(grp, 16))+ )+ })+ return decodeURI(data)+ } catch (e) {+ return data+ }+}diff --git a/src/utils/decode-media-data.js b/src/utils/decode-media-data.jsindex 70f7c1625..cfbc0cd7c 100644--- a/src/utils/decode-media-data.js+++ b/src/utils/decode-media-data.js@@ -1,4 +1,4 @@-import decodeData from '~/utils/decode-data'+import { decodeData } from '~/utils/decode-data'import { IMAGE } from '~/constants/media'/**diff --git a/src/utils/dev.js b/src/utils/dev.jsdeleted file mode 100644index 11d9b7fc5..000000000--- a/src/utils/dev.js+++ /dev/null@@ -1 +0,0 @@-export const dev = process.env.NODE_ENV !== 'production'diff --git a/src/utils/env.js b/src/utils/env.tssimilarity index 65%rename from src/utils/env.jsrename to src/utils/env.tsindex 304ac8111..efce30e53 100644--- a/src/utils/env.js+++ b/src/utils/env.ts@@ -1,6 +1,3 @@-// Use relative import to resolve during nuxt runtime-import stringToBoolean from './string-to-boolean'-/*** Default environment variables are set on this key. Defaults are fallbacks to existing env vars.* All boolean values should be designed to be false by default.@@ -9,7 +6,5 @@ export const env = {apiUrl: process.env.API_URL ?? 'https://api.openverse.engineering/v1/',filterStorageKey: 'openverse-filter-visibility',notificationStorageKey: 'openverse-show-notification',- enableInternalAnalytics: stringToBoolean(- process.env.ENABLE_INTERNAL_ANALYTICS- ),-}+ enableInternalAnalytics: process.env.ENABLE_INTERNAL_ANALYTICS ?? 'false',+} as constdiff --git a/src/utils/local.js b/src/utils/local.jsindex 30d84bb61..a7725e31d 100644--- a/src/utils/local.js+++ b/src/utils/local.js@@ -1,4 +1,5 @@// Small wrapper for localstorage to protect against SSR and permissions+import { warn } from '~/utils/console'const localStorageExists = () => process.client && window.localStorage !== null@@ -11,7 +12,7 @@ const local = {return localStorageExists() ? localStorage.getItem(...args) : null} catch (e) {// Probably a `SecurityError`- console.warn('`localStorage` access denied', e)+ warn('`localStorage` access denied', e)return null}},@@ -24,7 +25,7 @@ const local = {if (localStorageExists()) localStorage.setItem(...args)} catch (e) {// Probably a `SecurityError`- console.warn('`localStorage` access denied', e)+ warn('`localStorage` access denied', e)}},}diff --git a/src/utils/node-env.ts b/src/utils/node-env.tsnew file mode 100644index 000000000..3a14c9ae3--- /dev/null+++ b/src/utils/node-env.ts@@ -0,0 +1,3 @@+export const isDev: boolean = process.env.NODE_ENV === 'development'+export const isTest: boolean = process.env.NODE_ENV === 'test'+export const isProd: boolean = process.env.NODE_ENV === 'production'diff --git a/src/utils/resampling.js b/src/utils/resampling.tssimilarity index 62%rename from src/utils/resampling.jsrename to src/utils/resampling.tsindex c0ca4e9f4..26d825a46 100644--- a/src/utils/resampling.js+++ b/src/utils/resampling.ts@@ -2,23 +2,22 @@* Resizes a given array to consist of more elements than provided. This uses* linear interpolation to fill in the gaps.*- * @param data {number[]} the list of data points to interpolate- * @param threshold {number} the number of expected data points from the array- * @returns {number[]} the array with the required number of points+ * @param data - the list of data points to interpolate+ * @param threshold - the number of expected data points from the array+ * @returns the array with the required number of points*/-export let upsampleArray = (data, threshold) => {- let linearInterpolate = function (before, after, atPoint) {- return before + (after - before) * atPoint- }+export const upsampleArray = (data: number[], threshold: number): number[] => {+ const linearInterpolate = (before: number, after: number, atPoint: number) =>+ before + (after - before) * atPoint- let newData = []- let springFactor = (data.length - 1) / (threshold - 1)+ const newData = []+ const springFactor = (data.length - 1) / (threshold - 1)newData[0] = data[0] // for new allocationfor (let i = 1; i < threshold - 1; i++) {- let tmp = i * springFactor- let before = Math.floor(tmp).toFixed()- let after = Math.ceil(tmp).toFixed()- let atPoint = tmp - before+ const tmp = i * springFactor+ const before = Math.floor(tmp)+ const after = Math.ceil(tmp)+ const atPoint = tmp - beforenewData[i] = linearInterpolate(data[before], data[after], atPoint)}newData[threshold - 1] = data[data.length - 1] // for new allocation@@ -26,23 +25,23 @@ export let upsampleArray = (data, threshold) => {}/**- * Resizes a given array to consist of less elements than provided. This uses+ * Resizes a given array to consist of fewer elements than provided. This uses* the Largest Triangle Three Buckets algorithm by Sveinn Steinarsson.** @see {@link https://github.com/sveinn-steinarsson/flot-downsample}*- * @param data {number[]} the list of data points to interpolate- * @param threshold {number} the number of expected data points from the array- * @returns {number[]} the array with the required number of points+ * @param data - the list of data points to interpolate+ * @param threshold - the number of expected data points from the array+ * @returns the array with the required number of points*/-export const downsampleArray = (data, threshold) => {- let dataLength = data.length+export const downsampleArray = (data: number[], threshold: number) => {+ const dataLength = data.length- let sampled = []+ const sampled = []let sampled_index = 0// Bucket size, except first and last point- let every = (dataLength - 2) / (threshold - 2)+ const every = (dataLength - 2) / (threshold - 2)let a = 0let max_area_point, max_area, area, next_a@@ -56,7 +55,7 @@ export const downsampleArray = (data, threshold) => {let avg_range_end = Math.floor((i + 2) * every) + 1avg_range_end = avg_range_end < dataLength ? avg_range_end : dataLength- let avg_range_length = avg_range_end - avg_range_start+ const avg_range_length = avg_range_end - avg_range_startfor (; avg_range_start < avg_range_end; avg_range_start++) {avg_x += avg_range_start@@ -67,13 +66,16 @@ export const downsampleArray = (data, threshold) => {// Get the range for this bucketlet range_offs = Math.floor(i * every) + 1- let range_to = Math.floor((i + 1) * every) + 1+ const range_to = Math.floor((i + 1) * every) + 1- let point_a_x = a- let point_a_y = data[a]+ const point_a_x = a+ const point_a_y = data[a]max_area = area = -1+ max_area_point = 0+ next_a = 0+for (; range_offs < range_to; range_offs++) {// Calculate triangle area over three bucketsarea =diff --git a/src/utils/send-message.js b/src/utils/send-message.jsindex 155fd3272..1354ec130 100644--- a/src/utils/send-message.js+++ b/src/utils/send-message.js@@ -1,4 +1,4 @@-import { dev } from '~/utils/dev'+import { isProd } from '~/utils/node-env'// TODO: set correct targetOrigin of the parent windowconst TARGET_ORIGIN = '*'@@ -11,7 +11,7 @@ const TARGET_ORIGIN = '*'* @param {'resize'|'changeUrl'} message.type - event that triggers the message* @param {any} message.value - the value of event*/-export const sendWindowMessage = ({ debug = dev, ...message }) => {+export const sendWindowMessage = ({ debug = !isProd, ...message }) => {if (window.parent !== window) {window.parent.postMessage({ debug, ...message }, TARGET_ORIGIN)}diff --git a/src/utils/sentry-config.js b/src/utils/sentry-config.jsdeleted file mode 100644index 2512b7d80..000000000--- a/src/utils/sentry-config.js+++ /dev/null@@ -1,8 +0,0 @@-export const sentry = {- dsn:- process.env.SENTRY_DSN ||- 'https://[email protected]/5799642',- disabled: process.env.NODE_ENV === 'development',- environment: process.env.NODE_ENV,- lazy: true,-}diff --git a/src/utils/sentry-config.ts b/src/utils/sentry-config.tsnew file mode 100644index 000000000..990956835--- /dev/null+++ b/src/utils/sentry-config.ts@@ -0,0 +1,16 @@+import type { ModuleConfiguration } from '@nuxtjs/sentry'++import { isProd } from './node-env'++/**+ * Get the Sentry configuration based on the current environment.+ * @param isDisabled - whether to disable Sentry+ * @returns the Sentry configuration to use+ */+export const sentryConfig: ModuleConfiguration = {+ dsn:+ process.env.SENTRY_DSN ||+ 'https://[email protected]/5799642',+ disabled: !isProd,+ lazy: true,+}diff --git a/src/utils/string-to-boolean.js b/src/utils/string-to-boolean.jsdeleted file mode 100644index 156e77aa4..000000000--- a/src/utils/string-to-boolean.js+++ /dev/null@@ -1,24 +0,0 @@-function stringToBoolean(string) {- // In case the string is already a boolean, bail and return the boolean.- // This isn't *awesome*, but sometimes .env vars are auto-cast to booleans- // and this will catch that.- if (typeof string === 'boolean') return string-- if (string && typeof string === 'string') {- switch (string.toLowerCase().trim()) {- case 'true':- case 'yes':- case '1':- return true- case 'false':- case 'no':- case '0':- case null:- return false- default:- return Boolean(string)- }- } else return false-}--export default stringToBooleandiff --git a/src/utils/string-to-boolean.ts b/src/utils/string-to-boolean.tsnew file mode 100644index 000000000..1fdf26853--- /dev/null+++ b/src/utils/string-to-boolean.ts@@ -0,0 +1,32 @@+/**+ * Convert the given value, string or boolean, to a boolean value by casting+ * - `'true'`, `'yes'` and `'1'` to true+ * - `'false'`, `'no'` and `'0'` to false+ *+ * Any other string will be cast to boolean using the default JavaScript+ * truthy-falsy logic.+ *+ * @param value - the value to cast+ * @returns the boolean-equivalent value of the given string or boolean+ */+export const stringToBoolean = (value: string | boolean): boolean => {+ // In case the string is already a boolean, return as-is.+ // If `.env` vars are auto-cast to booleans, this will catch that.+ if (typeof value === 'boolean') return value++ if (!value) return false++ value = value.toLowerCase().trim()+ switch (value) {+ case 'true':+ case 'yes':+ case '1':+ return true+ case 'false':+ case 'no':+ case '0':+ return false+ default:+ return Boolean(value)+ }+}diff --git a/src/utils/warn.js b/src/utils/warn.jsdeleted file mode 100644index d509fc6f6..000000000--- a/src/utils/warn.js+++ /dev/null@@ -1,6 +0,0 @@-export const warn =- process.env.NODE_ENV !== 'production'- ? console.warn- : () => {- /* silence warnings in production */- }diff --git a/test/unit/specs/components/v-button.spec.js b/test/unit/specs/components/v-button.spec.jsindex 2d11723e9..2a8a0561b 100644--- a/test/unit/specs/components/v-button.spec.js+++ b/test/unit/specs/components/v-button.spec.js@@ -1,9 +1,9 @@import { render, screen } from '@testing-library/vue'import VButton from '~/components/VButton.vue'-import { warn } from '~/utils/warn'+import { warn } from '~/utils/console'-jest.mock('~/utils/warn', () => ({ warn: jest.fn() }))+jest.mock('~/utils/console', () => ({ warn: jest.fn(), log: jest.fn() }))const nextTick = () => new Promise((r) => setTimeout(r, 0))/**diff --git a/test/unit/specs/components/v-logo-loader.spec.js b/test/unit/specs/components/v-logo-loader.spec.jsindex 52d38e8e6..8cc61a81c 100644--- a/test/unit/specs/components/v-logo-loader.spec.js+++ b/test/unit/specs/components/v-logo-loader.spec.js@@ -2,8 +2,9 @@ import { render, screen } from '@testing-library/vue'import VLogoLoader from '~/components/VLogoLoader/VLogoLoader.vue'import { useReducedMotion } from '~/composables/use-media-query'-jest.mock('~/utils/warn', () => ({+jest.mock('~/utils/console', () => ({warn: jest.fn(),+ log: jest.fn(),}))jest.mock('~/composables/use-media-query', () => ({diff --git a/test/unit/specs/components/v-popover.spec.js b/test/unit/specs/components/v-popover.spec.jsindex 63e110e40..2c1fdb537 100644--- a/test/unit/specs/components/v-popover.spec.js+++ b/test/unit/specs/components/v-popover.spec.js@@ -4,9 +4,9 @@ import userEvent from '@testing-library/user-event'import VButton from '~/components/VButton.vue'import VPopover from '~/components/VPopover/VPopover.vue'import { noFocusableElementWarning } from '~/composables/use-focus-on-show'-import { warn } from '~/utils/warn'+import { warn } from '~/utils/console'-jest.mock('~/utils/warn', () => ({+jest.mock('~/utils/console', () => ({warn: jest.fn(),}))diff --git a/test/unit/specs/utils/decode-data.spec.js b/test/unit/specs/utils/decode-data.spec.jsindex 7a5b4ed73..4de26cc8e 100644--- a/test/unit/specs/utils/decode-data.spec.js+++ b/test/unit/specs/utils/decode-data.spec.js@@ -1,4 +1,4 @@-import decodeData from '~/utils/decode-data'+import { decodeData } from '~/utils/decode-data'describe('decodeData', () => {it('returns empty string for empty string', () => {@@ -16,7 +16,7 @@ describe('decodeData', () => {it('returns decoded ASCII hexacode strings', () => {const data = 's\\xe9'- expect(decodeData(data)).toBe('s\xe9')+ expect(decodeData(data)).toBe('sé')})it('returns decoded unicode strings', () => {diff --git a/test/unit/specs/utils/string-to-boolean.spec.js b/test/unit/specs/utils/string-to-boolean.spec.jsindex bee77faad..9e09367df 100644--- a/test/unit/specs/utils/string-to-boolean.spec.js+++ b/test/unit/specs/utils/string-to-boolean.spec.js@@ -1,15 +1,30 @@-import stringToBoolean from '~/utils/string-to-boolean'+import { stringToBoolean } from '~/utils/string-to-boolean'describe('stringToBoolean', () => {- it('returns true', () => {+ it('returns true for "true", "yes" and "1"', () => {expect(stringToBoolean('true')).toBe(true)expect(stringToBoolean('yes')).toBe(true)expect(stringToBoolean('1')).toBe(true)})- it('returns false', () => {+ it('returns false for "false", "no" and "0"', () => {expect(stringToBoolean('false')).toBe(false)expect(stringToBoolean('no')).toBe(false)expect(stringToBoolean('0')).toBe(false)})++ it('returns booleans as-is', () => {+ expect(stringToBoolean(true)).toBe(true)+ expect(stringToBoolean(false)).toBe(false)+ })++ it('converts null-ish values to false', () => {+ expect(stringToBoolean(null)).toBe(false)+ expect(stringToBoolean(undefined)).toBe(false)+ })++ it('handles other strings', () => {+ expect(stringToBoolean('any content')).toBe(true)+ expect(stringToBoolean('')).toBe(false)+ })})diff --git a/tsconfig.json b/tsconfig.jsonindex d4457abc2..0fe0108a5 100644--- a/tsconfig.json+++ b/tsconfig.json@@ -33,7 +33,7 @@"baseUrl": "."},"include": [- "src/**/*.ts",+ "**/*.ts","src/composables/types.js","src/composables/use-event-listener-outside.js","src/composables/use-active-audio.js",@@ -46,12 +46,10 @@"src/data/api-service.js","src/data/usage-data-service.js","src/store/user.js",- "src/utils/decode-data.js","src/utils/decode-media-data.js","src/utils/deep-freeze.js","src/utils/key-codes.js",- "src/utils/local.js",- "src/utils/warn.js"+ "src/utils/local.js"],"exclude": ["node_modules"]}