diff --git a/.prettierrc b/.prettierrc deleted file mode 100644 index 1001eee5..00000000 --- a/.prettierrc +++ /dev/null @@ -1,12 +0,0 @@ -{ - "printWidth": 100, - "tabWidth": 2, - "singleQuote": true, - "trailingComma": "es5", - "semi": false, - "bracketSpacing": true, - "arrowParens": "always", - "quoteProps": "consistent", - "vueIndentScriptAndStyle": false, - "plugins": ["prettier-plugin-organize-imports"] -} diff --git a/.prettierrc.js b/.prettierrc.js new file mode 100644 index 00000000..f725be4a --- /dev/null +++ b/.prettierrc.js @@ -0,0 +1,3 @@ +import prettier from "@cycraft/eslint/prettier" + +export default prettier diff --git a/.vscode/settings.json b/.vscode/settings.json index 46cfbdd0..ace9d281 100644 --- a/.vscode/settings.json +++ b/.vscode/settings.json @@ -25,5 +25,8 @@ "editor.insertSpaces": true, // gitlens "gitlens.defaultTimeFormat": "HH:mm", - "gitlens.codeLens.enabled": false + "gitlens.codeLens.enabled": false, + // auto import with .js extension + "javascript.preferences.importModuleSpecifierEnding": "js", + "typescript.preferences.importModuleSpecifierEnding": "js" } diff --git a/CHANGELOG.md b/CHANGELOG.md index 0d5dfdbc..47d07196 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,13 @@ # CHANGELOG +## v1.0.0 + +##### ESM Only & Node v18+ + +- Magnetar is now ESM only. This means you need to use `import` instead of `require`. +- Magnetar now requires Node v18+. +- `@magnetarjs/plugin-vue2` was removed. + ## v0.4.0 ##### breaking changes @@ -20,7 +28,7 @@ firebase.initializeApp({ }) // initialise PluginFirestore -import { PluginFirestore } from 'magnetar' +import { CreatePlugin as PluginFirestore } from '@magnetarjs/plugin-firestore' const remote = PluginFirestore.CreatePlugin({ firebaseInstance: firebase }) ``` @@ -38,7 +46,7 @@ const firebaseApp = initializeApp({ const db = getFirestore(firebaseApp) // initialise PluginFirestore -import { PluginFirestore } from 'magnetar' +import { CreatePlugin as PluginFirestore } from '@magnetarjs/plugin-firestore' const remote = PluginFirestore.CreatePlugin({ db }) ``` diff --git a/docs/docs-main/hooks-and-events/index.md b/docs/docs-main/hooks-and-events/index.md index fdf6b37c..96e2daeb 100644 --- a/docs/docs-main/hooks-and-events/index.md +++ b/docs/docs-main/hooks-and-events/index.md @@ -90,7 +90,7 @@ export function addUpdatedAt(payload) { And then in the file(s) you define your modules: ```js -import { addCreatedAt, addUpdatedAt } from './helpers' +import { addCreatedAt, addUpdatedAt } from './helpers/index.js' const pokedexModule = magnetar.collection('pokedex', { modifyPayloadOn: { diff --git a/docs/docs-main/plugins/index.md b/docs/docs-main/plugins/index.md index df6a65c2..b63c50ea 100644 --- a/docs/docs-main/plugins/index.md +++ b/docs/docs-main/plugins/index.md @@ -14,7 +14,7 @@ Example setup: ```js -import { PluginFirestore } from 'magnetar' +import { PluginFirestore } from '@magnetarjs/plugin-firestore' import { initializeApp } from 'firebase/app' import { getFirestore } from 'firebase/firestore' @@ -67,7 +67,7 @@ Use the Vue 3 plugin for Vue 3 projects. Example setup: ```js -import { PluginVue3 } from 'magnetar' +import { CreatePlugin as PluginVue3 } from '@magnetarjs/plugin-vue3' function generateRandomId() { return [Math.random(), Math.random(), Math.random()].join('-') @@ -78,27 +78,6 @@ function generateRandomId() { const local = PluginVue3.CreatePlugin({ generateRandomId }) ``` -## Vue 2 - -> documentation WIP - -Use the Vue 2 plugin for Vue 2 projects. - -Example setup: - -```js -import { CreatePlugin as CreatePluginVue2 } from '@magnetarjs/plugin-vue2' -import vue from 'vue' - -function generateRandomId() { - return [Math.random(), Math.random(), Math.random()].join('-') - // you need to provide your own logic - // this function is used when you execute `insert` without specifying an ID -} - -const local = CreatePluginVue2({ vueInstance: vue, generateRandomId }) -``` - ## Simple Store > documentation WIP @@ -108,7 +87,7 @@ The Simple Store has no built-in reactivity. Good for a lightweight solution in Example setup: ```js -import { PluginSimpleStore } from 'magnetar' +import { CreatePlugin as PluginSimpleStore } from '@magnetarjs/plugin-simple-store' function generateRandomId() { return [Math.random(), Math.random(), Math.random()].join('-') diff --git a/docs/docs-main/setup/index.md b/docs/docs-main/setup/index.md index 580267e4..ccb4764e 100644 --- a/docs/docs-main/setup/index.md +++ b/docs/docs-main/setup/index.md @@ -21,7 +21,10 @@ This is a complete setup example which uses: ```javascript import { initializeApp } from 'firebase/app' import { getFirestore, collection, doc } from 'firebase/firestore' -import { PluginFirestore, PluginVue3, Magnetar, logger } from 'magnetar' +import { Magnetar } from '@magnetarjs/core' +import { CreatePlugin as PluginFirestore } from '@magnetarjs/plugin-firestore' +import { CreatePlugin as PluginVue3 } from '@magnetarjs/plugin-vue3' +import { logger } from '@magnetarjs/utils' // --------------------------------------------- // 0. Initialise firebase // --------------------------------------------- diff --git a/eslint.config.js b/eslint.config.js new file mode 100644 index 00000000..6ea0bb0b --- /dev/null +++ b/eslint.config.js @@ -0,0 +1,15 @@ +import config from '@cycraft/eslint/config' + +export default [ + { + ignores: ['**/dist/*'], + }, + ...config, + { + files: ['**/*.js', '**/*.jsx', '**/*.ts', '**/*.tsx'], + rules: { + '@typescript-eslint/no-explicit-any': 'off', + '@typescript-eslint/no-unused-vars': 'off', + }, + }, +] diff --git a/package.json b/package.json index 1f1f42c5..05b1ed03 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,8 @@ { "name": "magnetar-monorepo", "private": true, + "version": "1.0.1", + "type": "module", "workspaces": [ "packages/*" ], @@ -8,55 +10,60 @@ "dev:nuxt-firestore": "pnpm --filter dev-nuxt-firestore dev", "dev:vue3-firestore": "pnpm --filter dev-vue3-firestore dev", "dev:ui": "pnpm --filter @magnetarjs/ui dev", - "dep:del-all": "npm exec --workspaces -- npx rimraf node_modules && npx rimraf node_modules", + "dep:del-all": "npm exec --workspaces -- del-cli node_modules && del-cli node_modules", "dep:update-minor": "ncu --target minor -u && pnpm --parallel exec ncu --target minor -u && echo \"review git changes and install with ni\"", - "dep:update-major": "ncu -u && pnpm --parallel exec ncu -u && echo \"review git changes and install with ni\"", + "dep:update-major": "ncu -ws -u && echo \"review git changes and install with ni\"", "docs:dev": "vitepress dev docs", "docs:build": "vitepress build docs", "docs:deploy": "pnpm docs:build && firebase deploy --only hosting && git add -A && git commit -m \"chore: deploy\"", "docs:serve": "vitepress serve docs", - "build": "pnpm -r build", + "build": "turbo run build", "typecheck": "turbo run typecheck", "build-and-commit": "npm run build && git add -A && git commit -m \"chore: build\"", "build:nuxt-firestore": "pnpm --filter dev-nuxt-firestore build", "generate:nuxt-firestore": "pnpm --filter dev-nuxt-firestore generate", "preview:nuxt-firestore": "pnpm --filter dev-nuxt-firestore preview", - "test": "pnpm test:core && pnpm test:plugin-simple-store && pnpm test:plugin-vue2 && pnpm test:plugin-vue3 && pnpm test:plugin-firestore", - "_test:admin-broken": "pnpm test:core && pnpm test:plugin-simple-store && pnpm test:plugin-vue2 && pnpm test:plugin-vue3 && pnpm test:plugin-firestore-admin", + "test": "turbo run test", + "_test:admin-broken": "pnpm test:core && pnpm test:plugin-simple-store && pnpm test:plugin-vue3 && pnpm test:plugin-firestore-admin", "test:core": "pnpm --filter=@magnetarjs/core test", "test:plugin-firestore": "pnpm --filter=@magnetarjs/plugin-firestore test", "test:plugin-firestore-admin": "pnpm --filter=@magnetarjs/plugin-firestore-admin test", - "test:plugin-firestore:only": "pnpm --filter=@magnetarjs/plugin-firestore run test:only", "test:plugin-simple-store": "pnpm --filter=@magnetarjs/plugin-simple-store test", - "test:plugin-vue2": "pnpm --filter=@magnetarjs/plugin-vue2 test", "test:plugin-vue3": "pnpm --filter=@magnetarjs/plugin-vue3 test", - "lint": "eslint . --ext .js,.jsx,.ts,.tsx", + "prettier:run": "prettier --write \"packages/*/src/**/*.{vue,ts}\" && prettier --write \"docs/**/*.{vue,ts,md}\"", + "lint": "eslint", "release": "pnpm build && bumpp package.json packages/*/package.json --commit --push --tag && pnpm -r publish --access public" }, "devDependencies": { - "@types/node": "^18.19.33", - "@typescript-eslint/eslint-plugin": "^5.62.0", - "@typescript-eslint/parser": "^5.62.0", + "@cycraft/eslint": "^0.3.0", + "@cycraft/run-ts": "^0.0.0", + "@cycraft/tsconfig": "^0.1.2", + "@magnetarjs/core": "workspace:*", + "@magnetarjs/plugin-firestore": "workspace:*", + "@magnetarjs/plugin-vue3": "workspace:*", + "@magnetarjs/test-utils": "workspace:*", + "@vitejs/plugin-vue": "^5.0.5", "@vue/typescript": "^1.8.20", - "ava": "^4.3.3", - "bumpp": "^8.2.1", + "array-shuffle": "^3.0.0", + "browser-env": "^3.3.0", + "bumpp": "^9.4.1", "copyfiles": "^2.4.1", "del-cli": "^5.1.0", "esbuild": "^0.21.4", - "esbuild-register": "^3.5.0", - "eslint": "^8.57.0", - "eslint-config-prettier": "^8.10.0", - "eslint-plugin-tree-shaking": "^1.12.1", - "exec-sh": "^0.4.0", + "execa": "^9.1.0", + "firebase": "^10.12.2", + "firebase-admin": "^12.1.1", "npm-check-updates": "^16.14.20", - "prettier": "^2.8.8", - "prettier-plugin-organize-imports": "^3.2.4", - "rimraf": "^3.0.2", - "tslib": "^2.6.2", - "tsup": "^6.7.0", + "roll-anything": "^3.0.4", + "sass": "^1.77.4", + "tsup": "^8.0.2", "turbo": "^1.13.3", "typescript": "^5.4.5", - "vitepress": "1.2.2" + "vite": "^5.2.12", + "vitepress": "1.2.2", + "vitest": "^1.6.0", + "vue": "^3.4.27", + "vue-tsc": "^2.0.19" }, "author": "Luca Ban - Mesqueeb", "funding": "https://github.com/sponsors/mesqueeb", @@ -70,50 +77,8 @@ "url": "git+https://github.com/cycraft/magnetar.git" }, "engines": { - "node": ">= 14.0.0", - "npm": ">= 7.8.0" + "node": ">=18" }, - "eslintConfig": { - "root": true, - "parser": "@typescript-eslint/parser", - "plugins": [ - "@typescript-eslint", - "tree-shaking" - ], - "ignorePatterns": [ - "node_modules", - "dist", - "/packages/dev-nuxt-firestore", - "/packages/dev-firestore", - "/packages/dev-vue2", - "/packages/dev-vue2-firestore", - "/packages/dev-vue3", - "/packages/dev-vue3-firestore", - "/packages/docs", - "/packages/ui", - "test" - ], - "extends": [ - "eslint:recommended", - "plugin:@typescript-eslint/eslint-recommended", - "plugin:@typescript-eslint/recommended", - "prettier" - ], - "rules": { - "@typescript-eslint/no-unused-vars": "off", - "@typescript-eslint/no-empty-function": "off", - "@typescript-eslint/no-explicit-any": "off", - "@typescript-eslint/ban-ts-ignore": "off", - "tree-shaking/no-side-effects-in-initialization": "error", - "@typescript-eslint/no-non-null-assertion": "off", - "comma-dangle": [ - "warn", - "always-multiline" - ], - "@typescript-eslint/ban-ts-comment": "warn" - } - }, - "version": "0.20.1", "pnpm": { "peerDependencyRules": { "ignoreMissing": [ diff --git a/packages/core/package.json b/packages/core/package.json index 549f624b..fa437f88 100644 --- a/packages/core/package.json +++ b/packages/core/package.json @@ -1,27 +1,23 @@ { "name": "@magnetarjs/core", - "version": "0.20.1", + "version": "1.0.1", + "type": "module", "sideEffects": false, "description": "Magnetar core library.", - "main": "dist/index.js", - "module": "dist/index.mjs", - "types": "dist/index.d.ts", "exports": { - ".": { - "import": "./dist/index.mjs", - "default": "./dist/index.js" - } + ".": "./dist/index.js" + }, + "engines": { + "node": ">=18" }, "files": [ "dist" ], "scripts": { "typecheck": "tsc --noEmit", - "build": "tsup src/index.ts --clean --format esm,cjs --dts", + "build": "del-cli dist && tsc", "dev": "pnpm build --watch", - "test-and-build": "npm run test && npm run build", - "test": "ava", - "test--only": "ava --match='*only:*'" + "test": "vitest run" }, "author": "Luca Ban - Mesqueeb", "funding": "https://github.com/sponsors/mesqueeb", @@ -30,13 +26,10 @@ "dependencies": { "@magnetarjs/types": "workspace:*", "@magnetarjs/utils": "workspace:*", - "getorset-anything": "^0.0.5", - "is-what": "^4.1.16", + "getorset-anything": "^0.1.0", + "is-what": "^5.0.0", "merge-anything": "^5.1.7" }, - "devDependencies": { - "@magnetarjs/test-utils": "workspace:*" - }, "keywords": [ "vuex-easy-firestore", "magnetar", @@ -68,14 +61,5 @@ }, "bugs": { "url": "https://github.com/cycraft/magnetar/issues" - }, - "ava": { - "extensions": [ - "ts" - ], - "require": [ - "esbuild-register" - ], - "timeout": "60s" } } diff --git a/packages/core/src/Collection.ts b/packages/core/src/Collection.ts index 80b47a4f..5d29cd05 100644 --- a/packages/core/src/Collection.ts +++ b/packages/core/src/Collection.ts @@ -22,10 +22,16 @@ import { getCountFromDataStore, getDataFromDataStore, proxify, -} from './helpers/moduleHelpers' -import { HandleFetchPerStoreParams, handleFetchPerStore } from './moduleActions/handleFetchPerStore' -import { handleStreamPerStore } from './moduleActions/handleStreamPerStore' -import { HandleWritePerStoreParams, handleWritePerStore } from './moduleActions/handleWritePerStore' +} from './helpers/moduleHelpers.js' +import { + HandleFetchPerStoreParams, + handleFetchPerStore, +} from './moduleActions/handleFetchPerStore.js' +import { handleStreamPerStore } from './moduleActions/handleStreamPerStore.js' +import { + HandleWritePerStoreParams, + handleWritePerStore, +} from './moduleActions/handleWritePerStore.js' export function createCollectionWithContext( collectionPath: string, @@ -45,7 +51,7 @@ export function createCollectionWithContext( ): CollectionInstance { const { writeLockMap, fetchPromises, cacheStream, streaming, closeStream, closeAllStreams } = streamAndFetchPromises // prettier-ignore - const id = collectionPath.split('/').slice(-1)[0] + const id = collectionPath.split('/').slice(-1)[0] ?? '' const path = collectionPath const doc: DocFn = ((docId: string, _moduleConfig: ModuleConfig = {}) => { @@ -74,7 +80,7 @@ export function createCollectionWithContext( } const insert = handleWritePerStore(writeParams, 'insert') as MagnetarInsertAction //prettier-ignore const _delete = handleWritePerStore(writeParams, 'delete') as MagnetarDeleteAction //prettier-ignore - const fetch = handleFetchPerStore(fetchParams, 'fetch') as MagnetarFetchAction, 'collection'> //prettier-ignore + const fetch = handleFetchPerStore(fetchParams, 'fetch') as MagnetarFetchAction<{ [key: string]: unknown }, 'collection'> //prettier-ignore const fetchCount = handleFetchPerStore(fetchParams, 'fetchCount') as MagnetarFetchCountAction // prettier-ignore const stream = handleStreamPerStore([collectionPath, undefined], moduleConfig, globalConfig, 'write', streaming, cacheStream, writeLockMap) // prettier-ignore diff --git a/packages/core/src/Doc.ts b/packages/core/src/Doc.ts index 2a1959a8..3317d3ab 100644 --- a/packages/core/src/Doc.ts +++ b/packages/core/src/Doc.ts @@ -17,10 +17,16 @@ import { getDataFromDataStore, getExistsFromDataStore, proxify, -} from './helpers/moduleHelpers' -import { HandleFetchPerStoreParams, handleFetchPerStore } from './moduleActions/handleFetchPerStore' -import { handleStreamPerStore } from './moduleActions/handleStreamPerStore' -import { HandleWritePerStoreParams, handleWritePerStore } from './moduleActions/handleWritePerStore' +} from './helpers/moduleHelpers.js' +import { + HandleFetchPerStoreParams, + handleFetchPerStore, +} from './moduleActions/handleFetchPerStore.js' +import { handleStreamPerStore } from './moduleActions/handleStreamPerStore.js' +import { + HandleWritePerStoreParams, + handleWritePerStore, +} from './moduleActions/handleWritePerStore.js' export function createDocWithContext( [collectionPath, docId]: [string, string], @@ -68,7 +74,7 @@ export function createDocWithContext( replace: (handleWritePerStore(writeParams, 'replace') as MagnetarWriteAction), // prettier-ignore deleteProp: (handleWritePerStore(writeParams, 'deleteProp') as MagnetarDeletePropAction), // prettier-ignore delete: (handleWritePerStore(writeParams, 'delete') as MagnetarDeleteAction), // prettier-ignore - fetch: (handleFetchPerStore(fetchParams, 'fetch') as MagnetarFetchAction, 'doc'>), // prettier-ignore + fetch: (handleFetchPerStore(fetchParams, 'fetch') as MagnetarFetchAction<{ [key: string]: unknown }, 'doc'>), // prettier-ignore stream: handleStreamPerStore([collectionPath, docId], moduleConfig, globalConfig, 'write', streaming, cacheStream, writeLockMap), // prettier-ignore } diff --git a/packages/core/src/Magnetar.ts b/packages/core/src/Magnetar.ts index 2b72a651..c8986016 100644 --- a/packages/core/src/Magnetar.ts +++ b/packages/core/src/Magnetar.ts @@ -20,11 +20,11 @@ import { } from '@magnetarjs/types' import { mapGetOrSet } from 'getorset-anything' import { isString } from 'is-what' -import { createCollectionWithContext } from './Collection' -import { createDocWithContext } from './Doc' -import { defaultsGlobalConfig } from './helpers/configHelpers' -import { getCollectionPathDocIdEntry } from './helpers/pathHelpers' -import { throwIfInvalidModulePath } from './helpers/throwFns' +import { createCollectionWithContext } from './Collection.js' +import { createDocWithContext } from './Doc.js' +import { defaultsGlobalConfig } from './helpers/configHelpers.js' +import { getCollectionPathDocIdEntry } from './helpers/pathHelpers.js' +import { throwIfInvalidModulePath } from './helpers/throwFns.js' /** * Creates a magnetar instance. @@ -44,23 +44,23 @@ export function Magnetar(magnetarConfig: GlobalConfig): MagnetarInstance { * the global storage for WriteLock objects * @see {@link WriteLock} */ - const writeLockMap: Map = new Map() // apply type upon get/set + const writeLockMap = new Map() // apply type upon get/set /** * the global storage for closeStream functions */ - const closeStreamFnMap: Map void> = new Map() // apply type upon get/set + const closeStreamFnMap = new Map void>() // apply type upon get/set /** * the global storage for open stream promises */ - const streamingPromiseMap: Map | null> = new Map() // apply type upon get/set + const streamingPromiseMap = new Map | null>() // apply type upon get/set /** * the global storage for fetch promises */ - const fetchPromiseMap: Map = new Map() // apply type upon get/set + const fetchPromiseMap = new Map() // apply type upon get/set /** * the global storage for FetchMetaDataCollection */ - const fetchMetaMap: Map = new Map() + const fetchMetaMap = new Map() // apply type upon get/set async function clearAllData(options?: { exclude?: CollectionName[] }): Promise { for (const collectionName of collectionNames) { @@ -110,14 +110,17 @@ export function Magnetar(magnetarConfig: GlobalConfig): MagnetarInstance { } // grab the stream related functions - function cacheStream(closeStreamFn: () => void, streamingPromise: Promise | null): void { + function cacheStream( + closeStreamFn: () => void, + streamingPromise: Promise | null + ): undefined { closeStreamFnMap.set(pathFilterIdentifier, closeStreamFn) streamingPromiseMap.set(pathFilterIdentifier, streamingPromise) } function streaming(): Promise | null { return streamingPromiseMap.get(pathFilterIdentifier) || null } - function closeStream(): void { + function closeStream(): undefined { const closeStreamFn = closeStreamFnMap.get(pathFilterIdentifier) if (closeStreamFn) { closeStreamFn() @@ -127,10 +130,10 @@ export function Magnetar(magnetarConfig: GlobalConfig): MagnetarInstance { }) } } - function closeAllStreams(): void { + function closeAllStreams(): undefined { for (const [identifier, closeStreamFn] of closeStreamFnMap) { const openStreamPath = identifier.split(MODULE_IDENTIFIER_SPLIT)[0] - if (openStreamPath === modulePath || openStreamPath.startsWith(modulePath + '/')) { + if (openStreamPath === modulePath || openStreamPath?.startsWith(modulePath + '/')) { closeStreamFn() } } @@ -169,7 +172,6 @@ export function Magnetar(magnetarConfig: GlobalConfig): MagnetarInstance { } function collection(modulePath: string, moduleConfig: ModuleConfig = {}): CollectionInstance { - // eslint-disable-next-line @typescript-eslint/no-use-before-define return getModuleInstance(modulePath, moduleConfig, 'collection', doc as DocFn, collection as CollectionFn) as CollectionInstance // prettier-ignore } diff --git a/packages/core/src/helpers/eventHelpers.ts b/packages/core/src/helpers/eventHelpers.ts index 8394c7c9..374bb2ae 100644 --- a/packages/core/src/helpers/eventHelpers.ts +++ b/packages/core/src/helpers/eventHelpers.ts @@ -1,6 +1,6 @@ import type { EventNameFnMap, EventNameFnsMap } from '@magnetarjs/types' -export function getEventNameFnsMap(...onMaps: (EventNameFnMap | void)[]): EventNameFnsMap { +export function getEventNameFnsMap(...onMaps: (EventNameFnMap | undefined)[]): EventNameFnsMap { const _onMaps = onMaps.filter(Boolean) as EventNameFnMap[] const result: EventNameFnsMap = { before: _onMaps.flatMap((on) => on.before ?? []), diff --git a/packages/core/src/helpers/executeOnFns.ts b/packages/core/src/helpers/executeOnFns.ts index d6d94f94..76303df2 100644 --- a/packages/core/src/helpers/executeOnFns.ts +++ b/packages/core/src/helpers/executeOnFns.ts @@ -9,12 +9,12 @@ import type { /** * Executes given function array with given args-array deconstructed, it will always use replace the first param with whatever the response of each function was. */ -export function executeOnFns | string | undefined>(params: { +export function executeOnFns(params: { modifyReadResultFns: (OnAddedFn | OnModifiedFn | OnRemovedFn)[] localStoreFns: (DoOnFetch | OnAddedFn | OnModifiedFn | OnRemovedFn)[] payload: Payload docMetaData: DocMetadata -}): Payload | void { +}): Payload | undefined { const { modifyReadResultFns, localStoreFns, payload, docMetaData } = params let newPayload = payload diff --git a/packages/core/src/helpers/modifyPayload.ts b/packages/core/src/helpers/modifyPayload.ts index 51dbe86c..dfccd4ff 100644 --- a/packages/core/src/helpers/modifyPayload.ts +++ b/packages/core/src/helpers/modifyPayload.ts @@ -1,7 +1,7 @@ import type { ModifyPayloadFnMap, ModifyPayloadFnsMap } from '@magnetarjs/types' export function getModifyPayloadFnsMap( - ...onMaps: (ModifyPayloadFnMap | void)[] + ...onMaps: (ModifyPayloadFnMap | undefined)[] ): Omit { const _onMaps = onMaps.filter(Boolean) as ModifyPayloadFnMap[] const writeFns = _onMaps.flatMap((on) => on.write ?? []) diff --git a/packages/core/src/helpers/modifyReadResponse.ts b/packages/core/src/helpers/modifyReadResponse.ts index 7b5e07fc..ce5354f2 100644 --- a/packages/core/src/helpers/modifyReadResponse.ts +++ b/packages/core/src/helpers/modifyReadResponse.ts @@ -1,7 +1,7 @@ import type { ModifyReadResponseFnMap, ModifyReadResponseFnsMap } from '@magnetarjs/types' export function getModifyReadResponseFnsMap( - ...onMaps: (ModifyReadResponseFnMap | void)[] + ...onMaps: (ModifyReadResponseFnMap | undefined)[] ): ModifyReadResponseFnsMap { const _onMaps = onMaps.filter(Boolean) as ModifyReadResponseFnMap[] const result = { diff --git a/packages/core/src/helpers/moduleHelpers.ts b/packages/core/src/helpers/moduleHelpers.ts index beb4fc64..1e8c3550 100644 --- a/packages/core/src/helpers/moduleHelpers.ts +++ b/packages/core/src/helpers/moduleHelpers.ts @@ -1,6 +1,6 @@ import type { GlobalConfig, ModuleConfig, PluginModuleConfig } from '@magnetarjs/types' import { isFunction, isPlainObject } from 'is-what' -import { throwIfNolocalStoreName } from './throwFns' +import { throwIfNolocalStoreName } from './throwFns.js' /** * Extracts the PluginModuleConfig from the ModuleConfig @@ -31,9 +31,9 @@ export function executeSetupModulePerStore( globalConfigStores: GlobalConfig['stores'], [collectionPath, docId]: [string, string | undefined], moduleConfig: ModuleConfig -): void { +): undefined { for (const storeName in globalConfigStores) { - const { setupModule } = globalConfigStores[storeName] + const { setupModule } = globalConfigStores[storeName] ?? {} if (isFunction(setupModule)) { const pluginModuleConfig = getPluginModuleConfig(moduleConfig, storeName) setupModule({ collectionPath, docId, pluginModuleConfig }) @@ -42,19 +42,19 @@ export function executeSetupModulePerStore( } /** Executes the `getModuleData` function from the store specified as 'localStoreName' */ -export function getDataFromDataStore(moduleConfig: ModuleConfig, globalConfig: GlobalConfig, collectionPath: string): Map> // prettier-ignore +export function getDataFromDataStore(moduleConfig: ModuleConfig, globalConfig: GlobalConfig, collectionPath: string): Map // prettier-ignore /** Executes the `getModuleData` function from the store specified as 'localStoreName' */ -export function getDataFromDataStore(moduleConfig: ModuleConfig, globalConfig: GlobalConfig, collectionPath: string, docId: string): Record // prettier-ignore +export function getDataFromDataStore(moduleConfig: ModuleConfig, globalConfig: GlobalConfig, collectionPath: string, docId: string): { [key: string]: any } // prettier-ignore /** Executes the `getModuleData` function from the store specified as 'localStoreName' */ export function getDataFromDataStore( moduleConfig: ModuleConfig, globalConfig: GlobalConfig, collectionPath: string, docId?: string -): Record | Map> { +): { [key: string]: any } | Map { const localStoreName = globalConfig.localStoreName throwIfNolocalStoreName(localStoreName) - const getModuleData = globalConfig.stores[localStoreName].getModuleData + const getModuleData = globalConfig.stores[localStoreName]?.getModuleData if (!getModuleData) { throw new Error('The data store did not provide a getModuleData function!') } @@ -71,7 +71,7 @@ export function getExistsFromDataStore( ): undefined | 'error' | boolean { const localStoreName = globalConfig.localStoreName throwIfNolocalStoreName(localStoreName) - const getModuleExists = globalConfig.stores[localStoreName].getModuleExists + const getModuleExists = globalConfig.stores[localStoreName]?.getModuleExists if (!getModuleExists) { throw new Error('The data store did not provide a getModuleExists function!') } @@ -87,7 +87,7 @@ export function getCountFromDataStore( ): number { const localStoreName = globalConfig.localStoreName throwIfNolocalStoreName(localStoreName) - const getModuleCount = globalConfig.stores[localStoreName].getModuleCount + const getModuleCount = globalConfig.stores[localStoreName]?.getModuleCount if (!getModuleCount) { throw new Error('The data store did not provide a getModuleCount function!') } @@ -99,18 +99,17 @@ export function getCountFromDataStore( /** * Returns an object as proxy which will execute the given functions upon prop access for the params passed here */ -export function proxify, P extends Record any>>( - target: T, - propExecutionDic: P -): T & { [key in keyof P]: ReturnType } { +export function proxify< + T extends { [key: string]: unknown }, + P extends { [key: string]: () => any }, +>(target: T, propExecutionDic: P): T & { [key in keyof P]: ReturnType } { const dataHandler = { get: function (target: any, key: any, proxyRef: any): any { if (key in propExecutionDic) { - return propExecutionDic[key]() + return propExecutionDic[key]?.() } return Reflect.get(target, key, proxyRef) }, } - // eslint-disable-next-line tree-shaking/no-side-effects-in-initialization return new Proxy(target, dataHandler) } diff --git a/packages/core/src/helpers/pluginHelpers.ts b/packages/core/src/helpers/pluginHelpers.ts index 3f7ccfe8..e6ce3a8b 100644 --- a/packages/core/src/helpers/pluginHelpers.ts +++ b/packages/core/src/helpers/pluginHelpers.ts @@ -13,9 +13,9 @@ import { isArray, isFunction, isNumber, isPlainObject } from 'is-what' export function isDoOnStream(payload: any): payload is DoOnStream { const isNotDoOnStream = !isPlainObject(payload) || - payload.streaming || - payload.stop || - !(payload.added || payload.modified || payload.removed) + payload['streaming'] || + payload['stop'] || + !(payload['added'] || payload['modified'] || payload['removed']) return !isNotDoOnStream } @@ -32,7 +32,7 @@ export function isDoOnFetchCount(payload: any): payload is DoOnFetchCount { * FetchResponse type guard */ export function isFetchCountResponse(payload: any): payload is FetchCountResponse { - return isPlainObject(payload) && isNumber(payload.count) + return isPlainObject(payload) && isNumber(payload['count']) } /** @@ -46,5 +46,5 @@ export function isDoOnFetch(payload: any): payload is DoOnFetch { * FetchResponse type guard */ export function isFetchResponse(payload: any): payload is FetchResponse { - return isPlainObject(payload) && isArray(payload.docs) + return isPlainObject(payload) && isArray(payload['docs']) } diff --git a/packages/core/src/helpers/throwFns.ts b/packages/core/src/helpers/throwFns.ts index 66738eaf..7a58e010 100644 --- a/packages/core/src/helpers/throwFns.ts +++ b/packages/core/src/helpers/throwFns.ts @@ -2,11 +2,11 @@ import type { DoOnStreamFns, StreamResponse } from '@magnetarjs/types' import { isCollectionModule, isDocModule } from '@magnetarjs/utils' import { isFullString } from 'is-what' -export function logError(errorMessage: string): void { +export function logError(errorMessage: string): undefined { console.error('[@magnetarjs error]\n', errorMessage) } -export function logErrorAndThrow(errorMessage: string): void { +export function logErrorAndThrow(errorMessage: string): undefined { logError(errorMessage) throw new Error(errorMessage) } @@ -14,7 +14,7 @@ export function logErrorAndThrow(errorMessage: string): void { export function throwOnIncompleteStreamResponses( streamInfoPerStore: { [storeName: string]: StreamResponse }, doOnStreamFns: DoOnStreamFns -): void { +): undefined { const noStreamLogic = !Object.keys(streamInfoPerStore).length if (noStreamLogic) { const errorMessage = 'None of your store plugins have implemented logic to open a stream.' @@ -28,7 +28,7 @@ export function throwOnIncompleteStreamResponses( } } -export function throwIfNoFnsToExecute(storesToExecute: string[]): void { +export function throwIfNoFnsToExecute(storesToExecute: string[]): undefined { if (storesToExecute.length === 0) { const errorMessage = 'None of your store plugins have implemented this function or you have not defined an executionOrder anywhere.' @@ -36,7 +36,7 @@ export function throwIfNoFnsToExecute(storesToExecute: string[]): void { } } -export function throwIfNolocalStoreName(localStoreName: string): void { +export function throwIfNolocalStoreName(localStoreName: string): undefined { if (isFullString(localStoreName)) return const errorMessage = `No 'localStoreName' provided.` logErrorAndThrow(errorMessage) @@ -45,7 +45,7 @@ export function throwIfNolocalStoreName(localStoreName: string): void { export function throwIfInvalidModulePath( modulePath: string, moduleType: 'collection' | 'doc' -): void { +): undefined { let errorMessage = '' if (moduleType === 'collection') { if (!modulePath) diff --git a/packages/core/src/helpers/writeLockHelpers.ts b/packages/core/src/helpers/writeLockHelpers.ts index 0f471562..bc77da9c 100644 --- a/packages/core/src/helpers/writeLockHelpers.ts +++ b/packages/core/src/helpers/writeLockHelpers.ts @@ -19,11 +19,11 @@ export async function writeLockPromise( */ export async function getDocAfterWritelock(params: { writeLockMap: Map - lastIncomingDocs: Map | undefined; meta: DocMetadata }> + lastIncomingDocs: Map docIdentifier: string - payload: Record | undefined + payload: { [key: string]: unknown } | undefined meta: DocMetadata -}): Promise | undefined; meta: DocMetadata }> { +}): Promise { const { writeLockMap, lastIncomingDocs, docIdentifier, payload, meta } = params // add to lastIncoming map lastIncomingDocs.set(docIdentifier, { payload, meta }) diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts index 25054334..4c80c9be 100644 --- a/packages/core/src/index.ts +++ b/packages/core/src/index.ts @@ -1,3 +1,3 @@ export * from '@magnetarjs/types' -export * from './Magnetar' -export * from './helpers/pathHelpers' +export * from './Magnetar.js' +export * from './helpers/pathHelpers.js' diff --git a/packages/core/src/moduleActions/handleAction.ts b/packages/core/src/moduleActions/handleAction.ts index 2bbf5132..1ab2ae50 100644 --- a/packages/core/src/moduleActions/handleAction.ts +++ b/packages/core/src/moduleActions/handleAction.ts @@ -28,7 +28,7 @@ export async function handleAction(args: { modulePath: string pluginModuleConfig: PluginModuleConfig pluginAction: PluginFetchCountAction | PluginFetchAction | PluginWriteAction | PluginDeletePropAction | PluginDeleteAction | PluginInsertAction // prettier-ignore - payload: void | Record | Record[] | string | string[] + payload: undefined | { [key: string]: unknown } | { [key: string]: unknown }[] | string | string[] actionConfig: ActionConfig eventNameFnsMap: EventNameFnsMap onError: 'revert' | 'continue' | 'stop' @@ -36,7 +36,7 @@ export async function handleAction(args: { stopExecutionAfterAction: (arg?: boolean | 'revert') => void storeName: string }): Promise< - | void + | undefined | string | FetchCountResponse | DoOnFetchCount @@ -75,7 +75,7 @@ export async function handleAction(args: { stopExecutionAfterAction() return } - let result: void | string | FetchCountResponse | DoOnFetchCount | FetchResponse | DoOnFetch | SyncBatch | [string, SyncBatch] // prettier-ignore + let result: undefined | string | FetchCountResponse | DoOnFetchCount | FetchResponse | DoOnFetch | SyncBatch | [string, SyncBatch] // prettier-ignore try { // triggering the action provided by the plugin result = await pluginAction({ diff --git a/packages/core/src/moduleActions/handleFetchPerStore.ts b/packages/core/src/moduleActions/handleFetchPerStore.ts index ebf8163a..f4da1d9b 100644 --- a/packages/core/src/moduleActions/handleFetchPerStore.ts +++ b/packages/core/src/moduleActions/handleFetchPerStore.ts @@ -1,4 +1,3 @@ -/* eslint-disable no-inner-declarations */ import type { ActionConfig, ActionName, @@ -19,20 +18,20 @@ import type { WriteLock, } from '@magnetarjs/types' import { isBoolean, isPromise } from 'is-what' -import { getEventNameFnsMap } from '../helpers/eventHelpers' -import { executeOnFns } from '../helpers/executeOnFns' -import { getModifyPayloadFnsMap } from '../helpers/modifyPayload' -import { getModifyReadResponseFnsMap } from '../helpers/modifyReadResponse' -import { getPluginModuleConfig } from '../helpers/moduleHelpers' -import { getCollectionWriteLocks } from '../helpers/pathHelpers' +import { getEventNameFnsMap } from '../helpers/eventHelpers.js' +import { executeOnFns } from '../helpers/executeOnFns.js' +import { getModifyPayloadFnsMap } from '../helpers/modifyPayload.js' +import { getModifyReadResponseFnsMap } from '../helpers/modifyReadResponse.js' +import { getPluginModuleConfig } from '../helpers/moduleHelpers.js' +import { getCollectionWriteLocks } from '../helpers/pathHelpers.js' import { isDoOnFetch, isDoOnFetchCount, isFetchCountResponse, isFetchResponse, -} from '../helpers/pluginHelpers' -import { throwIfNoFnsToExecute } from '../helpers/throwFns' -import { handleAction } from './handleAction' +} from '../helpers/pluginHelpers.js' +import { throwIfNoFnsToExecute } from '../helpers/throwFns.js' +import { handleAction } from './handleAction.js' export type HandleFetchPerStoreParams = { collectionPath: string @@ -47,7 +46,7 @@ export type HandleFetchPerStoreParams = { } export function handleFetchPerStore< - TActionName extends Extract + TActionName extends Extract, >(sharedParams: HandleFetchPerStoreParams, actionName: TActionName): ActionTernary export function handleFetchPerStore( sharedParams: HandleFetchPerStoreParams, @@ -59,7 +58,7 @@ export function handleFetchPerStore( return function (payload?: any, actionConfig: ActionConfig = {}): Promise { // first of all, check if the same fetch call was just made or not, if so return the same fetch promise early const fetchPromiseKey = JSON.stringify(payload) - const foundFetchPromise = fetchPromises[actionName].get(fetchPromiseKey) + const foundFetchPromise = fetchPromises[actionName]?.get(fetchPromiseKey) // return the same fetch promise early if it's not yet resolved if (actionName === 'fetch' && isPromise(foundFetchPromise)) return foundFetchPromise @@ -107,9 +106,9 @@ export function handleFetchPerStore( ) const storesToExecute: string[] = actionConfig.executionOrder || - (moduleConfig.executionOrder || {})[actionName] || + (actionName === 'fetch' ? (moduleConfig.executionOrder || {})[actionName] : false) || (moduleConfig.executionOrder || {})['read'] || - (globalConfig.executionOrder || {})[actionName] || + (actionName === 'fetch' ? (globalConfig.executionOrder || {})[actionName] : false) || (globalConfig.executionOrder || {})['read'] || [] throwIfNoFnsToExecute(storesToExecute) @@ -126,7 +125,7 @@ export function handleFetchPerStore( /** * The abort mechanism for the entire store chain. When executed in handleAction() it won't go to the next store in executionOrder. */ - function stopExecutionAfterAction(trueOrRevert: StopExecution = true): void { + function stopExecutionAfterAction(trueOrRevert: StopExecution = true): undefined { stopExecution = trueOrRevert } @@ -145,7 +144,7 @@ export function handleFetchPerStore( /** * Fetching on a collection should return a map with just the fetched records for that API call */ - const collectionFetchResult = new Map>() + const collectionFetchResult = new Map() /** * the result of fetchCount */ @@ -156,18 +155,18 @@ export function handleFetchPerStore( * `unknown` in case an error was thrown */ let resultFromPlugin: - | void + | undefined | string | unknown | FetchResponse | SyncBatch | [string, SyncBatch] // handle and await each action in sequence - for (const [i, storeName] of storesToExecute.entries()) { + for (const storeName of storesToExecute.values()) { // a previous iteration stopped the execution: if (stopExecution === true) break // find the action on the plugin - const pluginAction = globalConfig.stores[storeName].actions[actionName] + const pluginAction = globalConfig.stores[storeName]?.actions[actionName] const pluginModuleConfig = getPluginModuleConfig(moduleConfig, storeName) // the plugin action resultFromPlugin = !pluginAction @@ -266,7 +265,7 @@ export function handleFetchPerStore( } }) - fetchPromises[actionName].set(fetchPromiseKey, actionPromise) + fetchPromises[actionName]?.set(fetchPromiseKey, actionPromise) return actionPromise } diff --git a/packages/core/src/moduleActions/handleStream.ts b/packages/core/src/moduleActions/handleStream.ts index c18ae3ab..539d7b89 100644 --- a/packages/core/src/moduleActions/handleStream.ts +++ b/packages/core/src/moduleActions/handleStream.ts @@ -15,7 +15,7 @@ export async function handleStream(args: { docId: string | undefined pluginModuleConfig: PluginModuleConfig pluginAction: PluginStreamAction - payload: Record | void + payload: { [key: string]: unknown } | undefined actionConfig: ActionConfig eventNameFnsMap: EventNameFnsMap actionName: 'stream' diff --git a/packages/core/src/moduleActions/handleStreamPerStore.ts b/packages/core/src/moduleActions/handleStreamPerStore.ts index 977d1869..1bde8165 100644 --- a/packages/core/src/moduleActions/handleStreamPerStore.ts +++ b/packages/core/src/moduleActions/handleStreamPerStore.ts @@ -11,15 +11,15 @@ import type { WriteLock, } from '@magnetarjs/types' import { isPromise } from 'is-what' -import { getEventNameFnsMap } from '../helpers/eventHelpers' -import { executeOnFns } from '../helpers/executeOnFns' -import { getModifyPayloadFnsMap } from '../helpers/modifyPayload' -import { getModifyReadResponseFnsMap } from '../helpers/modifyReadResponse' -import { getPluginModuleConfig } from '../helpers/moduleHelpers' -import { isDoOnStream } from '../helpers/pluginHelpers' -import { throwIfNoFnsToExecute, throwOnIncompleteStreamResponses } from '../helpers/throwFns' -import { getDocAfterWritelock, writeLockPromise } from '../helpers/writeLockHelpers' -import { handleStream } from './handleStream' +import { getEventNameFnsMap } from '../helpers/eventHelpers.js' +import { executeOnFns } from '../helpers/executeOnFns.js' +import { getModifyPayloadFnsMap } from '../helpers/modifyPayload.js' +import { getModifyReadResponseFnsMap } from '../helpers/modifyReadResponse.js' +import { getPluginModuleConfig } from '../helpers/moduleHelpers.js' +import { isDoOnStream } from '../helpers/pluginHelpers.js' +import { throwIfNoFnsToExecute, throwOnIncompleteStreamResponses } from '../helpers/throwFns.js' +import { getDocAfterWritelock, writeLockPromise } from '../helpers/writeLockHelpers.js' +import { handleStream } from './handleStream.js' export function handleStreamPerStore( [collectionPath, docId]: [string, string | undefined], @@ -79,7 +79,7 @@ export function handleStreamPerStore( */ const lastIncomingDocs = new Map< string, - { payload: Record | undefined; meta: DocMetadata } + { payload: { [key: string]: unknown } | undefined; meta: DocMetadata } >() /** @@ -147,7 +147,7 @@ export function handleStreamPerStore( // handle and await each action in sequence for (const storeName of storesToExecute) { // find the action on the plugin - const pluginAction = globalConfig.stores[storeName].actions['stream'] + const pluginAction = globalConfig.stores[storeName]?.actions['stream'] const pluginModuleConfig = getPluginModuleConfig(moduleConfig, storeName) // the plugin action @@ -182,12 +182,12 @@ export function handleStreamPerStore( // create a function to closeStream from the stream of each store const closeStream = (): void => { Object.values(streamInfoPerStore).forEach(({ stop }) => stop()) - cacheStream(() => {}, null) + cacheStream(() => undefined, null) } // handle caching the returned promises const streamPromises = Object.values(streamInfoPerStore).map((res) => res.streaming) // create a single stream promise from multiple stream promises the store plugins return - const streamPromise: Promise = new Promise((resolve, reject) => { + const streamPromise = new Promise((resolve, reject) => { Promise.all(streamPromises) .then(() => { resolve() diff --git a/packages/core/src/moduleActions/handleWritePerStore.ts b/packages/core/src/moduleActions/handleWritePerStore.ts index 7bd80c57..5a386a08 100644 --- a/packages/core/src/moduleActions/handleWritePerStore.ts +++ b/packages/core/src/moduleActions/handleWritePerStore.ts @@ -1,4 +1,3 @@ -/* eslint-disable no-inner-declarations */ import type { ActionConfig, ActionName, @@ -17,11 +16,11 @@ import type { } from '@magnetarjs/types' import { mapGetOrSet } from 'getorset-anything' import { isFullArray, isFullString } from 'is-what' -import { getEventNameFnsMap } from '../helpers/eventHelpers' -import { getModifyPayloadFnsMap } from '../helpers/modifyPayload' -import { getPluginModuleConfig } from '../helpers/moduleHelpers' -import { throwIfNoFnsToExecute } from '../helpers/throwFns' -import { handleAction } from './handleAction' +import { getEventNameFnsMap } from '../helpers/eventHelpers.js' +import { getModifyPayloadFnsMap } from '../helpers/modifyPayload.js' +import { getPluginModuleConfig } from '../helpers/moduleHelpers.js' +import { throwIfNoFnsToExecute } from '../helpers/throwFns.js' +import { handleAction } from './handleAction.js' export type HandleWritePerStoreParams = { collectionPath: string @@ -37,7 +36,7 @@ export function handleWritePerStore< TActionName extends Extract< ActionName, 'insert' | 'merge' | 'assign' | 'replace' | 'deleteProp' | 'delete' - > + >, >(sharedParams: HandleWritePerStoreParams, actionName: TActionName): ActionTernary export function handleWritePerStore( sharedParams: HandleWritePerStoreParams, @@ -57,7 +56,7 @@ export function handleWritePerStore( // set up and/or reset te writeLock for write actions const writeLockId = _docId ? `${collectionPath}/${_docId}` : collectionPath const writeLock = mapGetOrSet(writeLockMap, writeLockId, (): WriteLock => { - return { promise: null, resolve: () => {}, countdown: null } + return { promise: null, resolve: () => undefined, countdown: null } }) // we need to create a promise we'll resolve later to prevent any incoming docs from being written to the local state during this time @@ -65,7 +64,7 @@ export function handleWritePerStore( writeLock.promise = new Promise((resolve) => { writeLock.resolve = () => { resolve() - writeLock.resolve = () => {} + writeLock.resolve = () => undefined writeLock.promise = null if (writeLock.countdown !== null) { clearTimeout(writeLock.countdown) @@ -117,21 +116,21 @@ export function handleWritePerStore( /** * The abort mechanism for the entire store chain. When executed in handleAction() it won't go to the next store in executionOrder. */ - function stopExecutionAfterAction(trueOrRevert: StopExecution = true): void { + function stopExecutionAfterAction(trueOrRevert: StopExecution = true): undefined { stopExecution = trueOrRevert } /** * Fetching on a collection should return a map with just the fetched records for that API call */ - const collectionFetchResult = new Map>() + const collectionFetchResult = new Map() /** * All possible results from the plugins. * `unknown` in case an error was thrown */ let resultFromPlugin: - | void + | undefined | string | unknown | FetchResponse @@ -142,7 +141,7 @@ export function handleWritePerStore( // a previous iteration stopped the execution: if (stopExecution === true) break // find the action on the plugin - const pluginAction = globalConfig.stores[storeName].actions[actionName] + const pluginAction = globalConfig.stores[storeName]?.actions[actionName] const pluginModuleConfig = getPluginModuleConfig(moduleConfig, storeName) // the plugin action resultFromPlugin = !pluginAction @@ -167,17 +166,19 @@ export function handleWritePerStore( const storesToRevert = storesToExecute.slice(0, i) storesToRevert.reverse() for (const storeToRevert of storesToRevert) { - const pluginRevertAction = globalConfig.stores[storeToRevert].revert + const pluginRevertAction = globalConfig.stores[storeToRevert]?.revert const pluginModuleConfig = getPluginModuleConfig(moduleConfig, storeToRevert) - await pluginRevertAction({ - payload, - actionConfig, - collectionPath, - docId, - pluginModuleConfig, - actionName, - error: resultFromPlugin, // in this case the result is the error - }) + if (pluginRevertAction) { + await pluginRevertAction({ + payload, + actionConfig, + collectionPath, + docId, + pluginModuleConfig, + actionName, + error: resultFromPlugin, // in this case the result is the error + }) + } // revert eventFns, handle and await each eventFn in sequence for (const fn of eventNameFnsMap.revert) { await fn({ payload, result: resultFromPlugin, actionName, storeName, collectionPath, docId, path: modulePath, pluginModuleConfig }) // prettier-ignore diff --git a/packages/core/test/external/delete.test.ts b/packages/core/test/external/delete.test.ts index 7d36fa55..461bb4e3 100644 --- a/packages/core/test/external/delete.test.ts +++ b/packages/core/test/external/delete.test.ts @@ -1,57 +1,57 @@ import { pokedex } from '@magnetarjs/test-utils' -import test from 'ava' -import { createMagnetarInstance } from '../helpers/createMagnetarInstance' +import { assert, test } from 'vitest' +import { createMagnetarInstance } from '../helpers/createMagnetarInstance.js' -test('delete (document)', async (t) => { +test('delete (document)', async () => { const { trainerModule } = createMagnetarInstance() - t.deepEqual(trainerModule.data, { age: 10, name: 'Luca' }) + assert.deepEqual(trainerModule.data, { age: 10, name: 'Luca' }) try { await trainerModule.delete() } catch (error) { - t.fail(JSON.stringify(error)) + assert.fail(JSON.stringify(error)) } - t.deepEqual(trainerModule.data, undefined) + assert.deepEqual(trainerModule.data, undefined) }) -test('delete (collection)', async (t) => { +test('delete (collection)', async () => { const { pokedexModule } = createMagnetarInstance() - t.deepEqual(pokedexModule.data.size, 1) - t.deepEqual(pokedexModule.data.get('1'), pokedex(1)) + assert.deepEqual(pokedexModule.data.size, 1) + assert.deepEqual(pokedexModule.data.get('1'), pokedex(1)) try { await pokedexModule.delete('1') } catch (error) { - t.fail(JSON.stringify(error)) + assert.fail(JSON.stringify(error)) } - t.deepEqual(pokedexModule.data.size, 0) - t.deepEqual(pokedexModule.data.get('1'), undefined) + assert.deepEqual(pokedexModule.data.size, 0) + assert.deepEqual(pokedexModule.data.get('1'), undefined) }) -test('revert: delete (local → remote)', async (t) => { +test('revert: delete (local → remote)', async () => { const { trainerModule } = createMagnetarInstance() - t.deepEqual(trainerModule.data, { age: 10, name: 'Luca' }) + assert.deepEqual(trainerModule.data, { age: 10, name: 'Luca' }) try { await trainerModule.delete('remote', { onError: 'revert', executionOrder: ['local', 'remote'] }) // mocks error on delete for remote store mock } catch (error) { - t.truthy(error) + assert.isTrue(!!error) } - t.deepEqual(trainerModule.data, { age: 10, name: 'Luca' }) + assert.deepEqual(trainerModule.data, { age: 10, name: 'Luca' }) }) // todo: for this test to work we need to mock a data pool for the remote plugin mock // test('revert: delete (remote → local)', async t => { // const { trainerModule } = createMagnetarInstance() -// t.deepEqual(trainerModule.data, { age: 10, name: 'Luca' }) +// assert.deepEqual(trainerModule.data, { age: 10, name: 'Luca' }) // try { // await trainerModule.delete('local', { onError: 'revert', executionOrder: ['remote', 'local'] }) // mocks error on delete for remote store mock // } catch (error) { -// t.truthy(error) +// assert.isTrue(!!error) // } -// t.deepEqual(trainerModule.data, { age: 10, name: 'Luca' }) +// assert.deepEqual(trainerModule.data, { age: 10, name: 'Luca' }) // }) diff --git a/packages/core/test/external/deleteProp.test.ts b/packages/core/test/external/deleteProp.test.ts index 50ee62b3..6d4d2bf9 100644 --- a/packages/core/test/external/deleteProp.test.ts +++ b/packages/core/test/external/deleteProp.test.ts @@ -1,95 +1,95 @@ -import test from 'ava' -import { createMagnetarInstance } from '../helpers/createMagnetarInstance' import { pokedex } from '@magnetarjs/test-utils' +import { assert, test } from 'vitest' +import { createMagnetarInstance } from '../helpers/createMagnetarInstance.js' -test('deleteProp', async (t) => { +test('deleteProp', async () => { const { trainerModule } = createMagnetarInstance() const deletePayload = 'age' - t.deepEqual(trainerModule.data, { name: 'Luca', age: 10 }) + assert.deepEqual(trainerModule.data, { name: 'Luca', age: 10 }) try { await trainerModule.deleteProp(deletePayload) } catch (error) { - t.fail(JSON.stringify(error)) + assert.fail(JSON.stringify(error)) } - t.deepEqual(trainerModule.data, { name: 'Luca' }) + assert.deepEqual(trainerModule.data, { name: 'Luca' }) }) -test('deleteProp nested', async (t) => { +test('deleteProp nested', async () => { const { pokedexModule } = createMagnetarInstance() const deletePayload = 'base.HP' - t.deepEqual(pokedexModule.doc('1').data, pokedex(1)) + assert.deepEqual(pokedexModule.doc('1').data, pokedex(1)) try { await pokedexModule.doc('1').deleteProp(deletePayload) } catch (error) { - t.fail(JSON.stringify(error)) + assert.fail(JSON.stringify(error)) } const expected = { id: 1, name: 'Bulbasaur', type: ['Grass', 'Poison'], base: { - 'Attack': 49, - 'Defense': 49, - 'SpAttack': 65, - 'SpDefense': 65, - 'Speed': 45, + Attack: 49, + Defense: 49, + SpAttack: 65, + SpDefense: 65, + Speed: 45, }, } - t.deepEqual(pokedexModule.doc('1').data, expected as any) + assert.deepEqual(pokedexModule.doc('1').data, expected as any) }) -test('deleteProp multiple', async (t) => { +test('deleteProp multiple', async () => { const { pokedexModule } = createMagnetarInstance() const deletePayload = ['base.HP', 'name'] - t.deepEqual(pokedexModule.doc('1').data, pokedex(1)) + assert.deepEqual(pokedexModule.doc('1').data, pokedex(1)) try { await pokedexModule.doc('1').deleteProp(deletePayload) } catch (error) { - t.fail(JSON.stringify(error)) + assert.fail(JSON.stringify(error)) } const expected = { id: 1, type: ['Grass', 'Poison'], base: { - 'Attack': 49, - 'Defense': 49, - 'SpAttack': 65, - 'SpDefense': 65, - 'Speed': 45, + Attack: 49, + Defense: 49, + SpAttack: 65, + SpDefense: 65, + Speed: 45, }, } - t.deepEqual(pokedexModule.doc('1').data, expected as any) + assert.deepEqual(pokedexModule.doc('1').data, expected as any) }) -test('revert: deleteProp', async (t) => { +test('revert: deleteProp', async () => { const { trainerModule } = createMagnetarInstance() const deletePayload = ['age', 'remote'] // this triggers an error on the remote store mock - t.deepEqual(trainerModule.data, { name: 'Luca', age: 10 }) + assert.deepEqual(trainerModule.data, { name: 'Luca', age: 10 }) try { await trainerModule.deleteProp(deletePayload, { onError: 'revert' }) } catch (error) { - t.truthy(error) + assert.isTrue(!!error) } - t.deepEqual(trainerModule.data, { name: 'Luca', age: 10 }) + assert.deepEqual(trainerModule.data, { name: 'Luca', age: 10 }) }) -test('revert: deleteProp nested', async (t) => { +test('revert: deleteProp nested', async () => { const { pokedexModule } = createMagnetarInstance() const deletePayload = ['base.HP', 'remote'] // this triggers an error on the remote store mock - t.deepEqual(pokedexModule.doc('1').data, pokedex(1)) + assert.deepEqual(pokedexModule.doc('1').data, pokedex(1)) try { await pokedexModule.doc('1').deleteProp(deletePayload, { onError: 'revert' }) } catch (error) { - t.truthy(error) + assert.isTrue(!!error) } - t.deepEqual(pokedexModule.doc('1').data, pokedex(1)) + assert.deepEqual(pokedexModule.doc('1').data, pokedex(1)) }) diff --git a/packages/core/test/external/fetch.test.ts b/packages/core/test/external/fetch.test.ts index 3827b7cd..3fe9d669 100644 --- a/packages/core/test/external/fetch.test.ts +++ b/packages/core/test/external/fetch.test.ts @@ -1,70 +1,70 @@ -import test from 'ava' -import { createMagnetarInstance } from '../helpers/createMagnetarInstance' import { pokedex, waitMs } from '@magnetarjs/test-utils' +import { assert, test } from 'vitest' +import { createMagnetarInstance } from '../helpers/createMagnetarInstance.js' -test('fetch (collection)', async (t) => { +test('fetch (collection)', async () => { /// 'fetch' resolves once all stores have given a response with data const { pokedexModule } = createMagnetarInstance() - t.deepEqual(pokedexModule.doc('1').data, pokedex(1)) - t.deepEqual(pokedexModule.doc('136').data, undefined) - t.deepEqual(pokedexModule.data.size, 1) + assert.deepEqual(pokedexModule.doc('1').data, pokedex(1)) + assert.deepEqual(pokedexModule.doc('136').data, undefined) + assert.deepEqual(pokedexModule.data.size, 1) try { await pokedexModule.fetch({ force: true }) } catch (error) { - t.fail(JSON.stringify(error)) + assert.fail(JSON.stringify(error)) } - t.deepEqual(pokedexModule.doc('1').data, pokedex(1)) - t.deepEqual(pokedexModule.doc('136').data, pokedex(136)) - t.deepEqual(pokedexModule.data.size, 151) + assert.deepEqual(pokedexModule.doc('1').data, pokedex(1)) + assert.deepEqual(pokedexModule.doc('136').data, pokedex(136)) + assert.deepEqual(pokedexModule.data.size, 151) }) -test('fetch (collection count)', async (t) => { +test('fetch (collection count)', async () => { /// 'fetch' resolves once all stores have given a response with data const { pokedexModule } = createMagnetarInstance() - t.deepEqual(pokedexModule.doc('1').data, pokedex(1)) - t.deepEqual(pokedexModule.doc('136').data, undefined) - t.deepEqual(pokedexModule.data.size, 1) - t.deepEqual(pokedexModule.count, 1) + assert.deepEqual(pokedexModule.doc('1').data, pokedex(1)) + assert.deepEqual(pokedexModule.doc('136').data, undefined) + assert.deepEqual(pokedexModule.data.size, 1) + assert.deepEqual(pokedexModule.count, 1) try { await pokedexModule.fetchCount() } catch (error) { console.error(error) - t.fail(JSON.stringify(error)) + assert.fail(JSON.stringify(error)) } - t.deepEqual(pokedexModule.doc('1').data, pokedex(1)) - t.deepEqual(pokedexModule.doc('136').data, undefined) - t.deepEqual(pokedexModule.data.size, 1) - t.deepEqual(pokedexModule.count, 151) + assert.deepEqual(pokedexModule.doc('1').data, pokedex(1)) + assert.deepEqual(pokedexModule.doc('136').data, undefined) + assert.deepEqual(pokedexModule.data.size, 1) + assert.deepEqual(pokedexModule.count, 151) }) -test('fetch (document)', async (t) => { +test('fetch (document)', async () => { /// get resolves once all stores have given a response with data const { trainerModule } = createMagnetarInstance() - t.deepEqual(trainerModule.data, { name: 'Luca', age: 10 }) + assert.deepEqual(trainerModule.data, { name: 'Luca', age: 10 }) try { await trainerModule.fetch({ force: true }) } catch (error) { - t.fail(JSON.stringify(error)) + assert.fail(JSON.stringify(error)) } - t.deepEqual(trainerModule.data, { name: 'Luca', age: 10, dream: 'job' }) + assert.deepEqual(trainerModule.data, { name: 'Luca', age: 10, dream: 'job' }) }) -test('fetch (collection) where-filter: ==', async (t) => { +test('fetch (collection) where-filter: ==', async () => { const { pokedexModule } = createMagnetarInstance() try { const queryModuleRef = pokedexModule.where('name', '==', 'Flareon') await queryModuleRef.fetch({ force: true }) const actual = [...queryModuleRef.data.values()] const expected = [pokedex(136)] - t.deepEqual(actual, expected as any) + assert.deepEqual(actual, expected as any) } catch (error) { - t.fail(JSON.stringify(error)) + assert.fail(JSON.stringify(error)) } }) -test('fetch with different where-filters after opening a stream', async (t) => { +test('fetch with different where-filters after opening a stream', async () => { const { pokedexModule } = createMagnetarInstance() try { pokedexModule.where('name', '==', 'Flareon').stream() @@ -73,117 +73,117 @@ test('fetch with different where-filters after opening a stream', async (t) => { await queryModuleRef.fetch({ force: true }) const actual = [...queryModuleRef.data.values()] const expected = [pokedex(136)] - t.deepEqual(actual, expected as any) + assert.deepEqual(actual, expected as any) } catch (error) { - t.fail(JSON.stringify(error)) + assert.fail(JSON.stringify(error)) } }) -test('fetch (collection) where-filter: !=', async (t) => { +test('fetch (collection) where-filter: !=', async () => { const { pokedexModule } = createMagnetarInstance() try { const queryModuleRef = pokedexModule.where('name', '!=', 'Bulbasaur').limit(1) await queryModuleRef.fetch({ force: true }) const actual = [...queryModuleRef.data.values()] const expected = [pokedex(2)] - t.deepEqual(actual, expected as any) + assert.deepEqual(actual, expected as any) } catch (error) { - t.fail(JSON.stringify(error)) + assert.fail(JSON.stringify(error)) } }) -test('fetch (collection) where-filter: == nested', async (t) => { +test('fetch (collection) where-filter: == nested', async () => { const { pokedexModule } = createMagnetarInstance() try { const queryModuleRef = pokedexModule.where('base.HP', '==', 10) await queryModuleRef.fetch({ force: true }) const actual = [...queryModuleRef.data.values()] const expected = [pokedex(50)] - t.deepEqual(actual, expected as any) + assert.deepEqual(actual, expected as any) } catch (error) { - t.fail(JSON.stringify(error)) + assert.fail(JSON.stringify(error)) } }) -test('fetch (collection) where-filter: <', async (t) => { +test('fetch (collection) where-filter: <', async () => { const { pokedexModule } = createMagnetarInstance() try { const queryModuleRef = pokedexModule.where('base.HP', '<', 11) await queryModuleRef.fetch({ force: true }) const actual = [...queryModuleRef.data.values()] const expected = [pokedex(50)] - t.deepEqual(actual, expected as any) + assert.deepEqual(actual, expected as any) } catch (error) { - t.fail(JSON.stringify(error)) + assert.fail(JSON.stringify(error)) } }) -test('fetch (collection) where-filter: <=', async (t) => { +test('fetch (collection) where-filter: <=', async () => { const { pokedexModule } = createMagnetarInstance() try { const queryModuleRef = pokedexModule.where('base.HP', '<=', 10) await queryModuleRef.fetch({ force: true }) const actual = [...queryModuleRef.data.values()] const expected = [pokedex(50)] - t.deepEqual(actual, expected as any) + assert.deepEqual(actual, expected as any) } catch (error) { - t.fail(JSON.stringify(error)) + assert.fail(JSON.stringify(error)) } }) -test('fetch (collection) where-filter: >', async (t) => { +test('fetch (collection) where-filter: >', async () => { const { pokedexModule } = createMagnetarInstance() try { const queryModuleRef = pokedexModule.where('base.HP', '>', 249) await queryModuleRef.fetch({ force: true }) const actual = [...queryModuleRef.data.values()] const expected = [pokedex(113)] - t.deepEqual(actual, expected as any) + assert.deepEqual(actual, expected as any) } catch (error) { - t.fail(JSON.stringify(error)) + assert.fail(JSON.stringify(error)) } }) -test('fetch (collection) where-filter: >=', async (t) => { +test('fetch (collection) where-filter: >=', async () => { const { pokedexModule } = createMagnetarInstance() try { const queryModuleRef = pokedexModule.where('base.HP', '>=', 250) await queryModuleRef.fetch({ force: true }) const actual = [...queryModuleRef.data.values()] const expected = [pokedex(113)] - t.deepEqual(actual, expected as any) + assert.deepEqual(actual, expected as any) } catch (error) { - t.fail(JSON.stringify(error)) + assert.fail(JSON.stringify(error)) } }) -test('fetch (collection) where-filter: array-contains', async (t) => { +test('fetch (collection) where-filter: array-contains', async () => { const { pokedexModule } = createMagnetarInstance() try { const queryModuleRef = pokedexModule.where('type', 'array-contains', 'Steel') await queryModuleRef.fetch({ force: true }) const actual = [...queryModuleRef.data.values()] const expected = [pokedex(81), pokedex(82)] - t.deepEqual(actual, expected as any) + assert.deepEqual(actual, expected as any) } catch (error) { - t.fail(JSON.stringify(error)) + assert.fail(JSON.stringify(error)) } }) -test('fetch (collection) where-filter: in', async (t) => { +test('fetch (collection) where-filter: in', async () => { const { pokedexModule } = createMagnetarInstance() try { const queryModuleRef = pokedexModule.where('name', 'in', ['Vaporeon', 'Jolteon', 'Flareon']) await queryModuleRef.fetch({ force: true }) const actual = [...queryModuleRef.data.values()] const expected = [pokedex(134), pokedex(135), pokedex(136)] - t.deepEqual(actual, expected as any) + assert.deepEqual(actual, expected as any) } catch (error) { - t.fail(JSON.stringify(error)) + assert.fail(JSON.stringify(error)) } }) -test('fetch (collection) where-filter: not-in', async (t) => { +test('fetch (collection) where-filter: not-in', async () => { const { pokedexModule } = createMagnetarInstance() try { const queryModuleRef = pokedexModule @@ -192,13 +192,13 @@ test('fetch (collection) where-filter: not-in', async (t) => { await queryModuleRef.fetch({ force: true }) const actual = [...queryModuleRef.data.values()] const expected = [pokedex(87), pokedex(124), pokedex(131), pokedex(144)] - t.deepEqual(actual, expected as any) + assert.deepEqual(actual, expected as any) } catch (error) { - t.fail(JSON.stringify(error)) + assert.fail(JSON.stringify(error)) } }) -test('fetch (collection) where-filter: array-contains-any', async (t) => { +test('fetch (collection) where-filter: array-contains-any', async () => { const { pokedexModule } = createMagnetarInstance() try { const queryModuleRef = pokedexModule.where('type', 'array-contains-any', ['Steel', 'Ice']) @@ -213,13 +213,13 @@ test('fetch (collection) where-filter: array-contains-any', async (t) => { pokedex(131), pokedex(144), ] - t.deepEqual(actual, expected as any) + assert.deepEqual(actual, expected as any) } catch (error) { - t.fail(JSON.stringify(error)) + assert.fail(JSON.stringify(error)) } }) -test('fetch (collection) compound queries', async (t) => { +test('fetch (collection) compound queries', async () => { const { pokedexModule } = createMagnetarInstance() try { const queryModuleRef = pokedexModule @@ -228,13 +228,13 @@ test('fetch (collection) compound queries', async (t) => { await queryModuleRef.fetch({ force: true }) const actual = [...queryModuleRef.data.values()] const expected = [pokedex(6), pokedex(38), pokedex(78)] - t.deepEqual(actual, expected as any) + assert.deepEqual(actual, expected as any) } catch (error) { - t.fail(JSON.stringify(error)) + assert.fail(JSON.stringify(error)) } }) -test('fetch (collection) orderBy', async (t) => { +test('fetch (collection) orderBy', async () => { const { pokedexModule } = createMagnetarInstance() try { const queryModuleRef = pokedexModule @@ -247,13 +247,13 @@ test('fetch (collection) orderBy', async (t) => { // Charizard 6 const actual = [...queryModuleRef.data.values()] const expected = [pokedex(78), pokedex(38), pokedex(6)] - t.deepEqual(actual, expected as any) + assert.deepEqual(actual, expected as any) } catch (error) { - t.fail(JSON.stringify(error)) + assert.fail(JSON.stringify(error)) } }) -test('fetch (collection) limit', async (t) => { +test('fetch (collection) limit', async () => { const { pokedexModule } = createMagnetarInstance() try { const queryModuleRef = pokedexModule.limit(10) @@ -271,8 +271,8 @@ test('fetch (collection) limit', async (t) => { pokedex(9), pokedex(10), ] - t.deepEqual(actual, expected as any) + assert.deepEqual(actual, expected as any) } catch (error) { - t.fail(JSON.stringify(error)) + assert.fail(JSON.stringify(error)) } }) diff --git a/packages/core/test/external/insert.test.ts b/packages/core/test/external/insert.test.ts index 4a4f8a2f..ea7b4222 100644 --- a/packages/core/test/external/insert.test.ts +++ b/packages/core/test/external/insert.test.ts @@ -1,23 +1,23 @@ import { pokedex, PokedexEntry } from '@magnetarjs/test-utils' import type { DocInstance } from '@magnetarjs/types' -import test from 'ava' -import { createMagnetarInstance } from '../helpers/createMagnetarInstance' +import { assert, test } from 'vitest' +import { createMagnetarInstance } from '../helpers/createMagnetarInstance.js' -test('insert (document)', async (t) => { +test('insert (document)', async () => { const { pokedexModule } = createMagnetarInstance() const payload = pokedex(7) - t.deepEqual(pokedexModule.doc('7').data, undefined) + assert.deepEqual(pokedexModule.doc('7').data, undefined) try { await pokedexModule.doc('7').insert(payload) } catch (error) { - t.fail(JSON.stringify(error)) + assert.fail(JSON.stringify(error)) } - t.deepEqual(pokedexModule.doc('7').data, payload) + assert.deepEqual(pokedexModule.doc('7').data, payload) }) -test('insert (collection) → random ID', async (t) => { +test('insert (collection) → random ID', async () => { const { pokedexModule } = createMagnetarInstance() const payload = pokedex(7) @@ -25,36 +25,36 @@ test('insert (collection) → random ID', async (t) => { try { moduleFromResult = await pokedexModule.insert(payload) } catch (error) { - t.fail(JSON.stringify(error)) + assert.fail(JSON.stringify(error)) return } const newId = moduleFromResult.id - t.deepEqual(pokedexModule.doc(newId).data, payload) + assert.deepEqual(pokedexModule.doc(newId).data, payload) }) -test('revert: insert (document)', async (t) => { +test('revert: insert (document)', async () => { const { pokedexModule } = createMagnetarInstance() const payload = { ...pokedex(7), shouldFail: 'remote' } - t.deepEqual(pokedexModule.doc('7').data, undefined) + assert.deepEqual(pokedexModule.doc('7').data, undefined) try { await pokedexModule.doc('7').insert(payload, { onError: 'revert' }) } catch (error) { - t.truthy(error) + assert.isTrue(!!error) } - t.deepEqual(pokedexModule.doc('7').data, undefined) + assert.deepEqual(pokedexModule.doc('7').data, undefined) }) -test('revert: insert (collection) → random ID', async (t) => { +test('revert: insert (collection) → random ID', async () => { const { pokedexModule } = createMagnetarInstance() const payload = { ...pokedex(7), shouldFail: 'remote' } try { await pokedexModule.insert(payload, { onError: 'revert' }) - t.fail() + assert.fail() } catch (error) { - t.truthy(error) + assert.isTrue(!!error) } - t.deepEqual(pokedexModule.doc('7').data, undefined) + assert.deepEqual(pokedexModule.doc('7').data, undefined) }) diff --git a/packages/core/test/external/mergeAssignReplace.test.ts b/packages/core/test/external/mergeAssignReplace.test.ts index c727a7e3..4b808f64 100644 --- a/packages/core/test/external/mergeAssignReplace.test.ts +++ b/packages/core/test/external/mergeAssignReplace.test.ts @@ -1,16 +1,16 @@ -import test from 'ava' -import { createMagnetarInstance } from '../helpers/createMagnetarInstance' import { pokedex } from '@magnetarjs/test-utils' +import { assert, test } from 'vitest' +import { createMagnetarInstance } from '../helpers/createMagnetarInstance.js' -test('merge', async (t) => { +test('merge', async () => { const { pokedexModule } = createMagnetarInstance() const payload = { base: { HP: 9000 } } - t.deepEqual(pokedexModule.doc('1').data, pokedex(1)) + assert.deepEqual(pokedexModule.doc('1').data, pokedex(1)) try { await pokedexModule.doc('1').merge(payload) } catch (error) { - t.fail(JSON.stringify(error)) + assert.fail(JSON.stringify(error)) } const expected = { @@ -18,26 +18,26 @@ test('merge', async (t) => { name: 'Bulbasaur', type: ['Grass', 'Poison'], base: { - 'HP': 9000, - 'Attack': 49, - 'Defense': 49, - 'SpAttack': 65, - 'SpDefense': 65, - 'Speed': 45, + HP: 9000, + Attack: 49, + Defense: 49, + SpAttack: 65, + SpDefense: 65, + Speed: 45, }, } - t.deepEqual(pokedexModule.doc('1').data, expected as any) + assert.deepEqual(pokedexModule.doc('1').data, expected as any) }) -test('assign', async (t) => { +test('assign', async () => { const { pokedexModule } = createMagnetarInstance() const payload = { base: { HP: 9000 } } - t.deepEqual(pokedexModule.doc('1').data, pokedex(1)) + assert.deepEqual(pokedexModule.doc('1').data, pokedex(1)) try { await pokedexModule.doc('1').assign(payload) } catch (error) { - t.fail(JSON.stringify(error)) + assert.fail(JSON.stringify(error)) } const expected = { @@ -48,65 +48,65 @@ test('assign', async (t) => { HP: 9000, }, } - t.deepEqual(pokedexModule.doc('1').data, expected as any) + assert.deepEqual(pokedexModule.doc('1').data, expected as any) }) -test('replace', async (t) => { +test('replace', async () => { const { pokedexModule } = createMagnetarInstance() const payload = { base: { HP: 9000 } } - t.deepEqual(pokedexModule.doc('1').data, pokedex(1)) + assert.deepEqual(pokedexModule.doc('1').data, pokedex(1)) try { await pokedexModule.doc('1').replace(payload) } catch (error) { - t.fail(JSON.stringify(error)) + assert.fail(JSON.stringify(error)) } const expected = { base: { HP: 9000 } } - t.deepEqual(pokedexModule.doc('1').data, expected as any) + assert.deepEqual(pokedexModule.doc('1').data, expected as any) }) -test('revert: merge', async (t) => { +test('revert: merge', async () => { const { pokedexModule } = createMagnetarInstance() const payload = { base: { HP: 9000 }, shouldFail: 'remote' } - t.deepEqual(pokedexModule.doc('1').data, pokedex(1)) + assert.deepEqual(pokedexModule.doc('1').data, pokedex(1)) try { await pokedexModule.doc('1').merge(payload, { onError: 'revert' }) } catch (error) { - t.truthy(error) + assert.isTrue(!!error) } const expected = pokedex(1) - t.deepEqual(pokedexModule.doc('1').data, expected as any) + assert.deepEqual(pokedexModule.doc('1').data, expected as any) }) -test('revert: assign', async (t) => { +test('revert: assign', async () => { const { pokedexModule } = createMagnetarInstance() const payload = { base: { HP: 9000 }, shouldFail: 'remote' } - t.deepEqual(pokedexModule.doc('1').data, pokedex(1)) + assert.deepEqual(pokedexModule.doc('1').data, pokedex(1)) try { await pokedexModule.doc('1').assign(payload, { onError: 'revert' }) } catch (error) { - t.truthy(error) + assert.isTrue(!!error) } const expected = pokedex(1) - t.deepEqual(pokedexModule.doc('1').data, expected as any) + assert.deepEqual(pokedexModule.doc('1').data, expected as any) }) -test('revert: replace', async (t) => { +test('revert: replace', async () => { const { pokedexModule } = createMagnetarInstance() const payload = { base: { HP: 9000 }, shouldFail: 'remote' } - t.deepEqual(pokedexModule.doc('1').data, pokedex(1)) + assert.deepEqual(pokedexModule.doc('1').data, pokedex(1)) try { await pokedexModule.doc('1').replace(payload, { onError: 'revert' }) } catch (error) { - t.truthy(error) + assert.isTrue(!!error) } const expected = pokedex(1) - t.deepEqual(pokedexModule.doc('1').data, expected as any) + assert.deepEqual(pokedexModule.doc('1').data, expected as any) }) diff --git a/packages/core/test/external/stream.test.ts b/packages/core/test/external/stream.test.ts index 08bb9217..993ac380 100644 --- a/packages/core/test/external/stream.test.ts +++ b/packages/core/test/external/stream.test.ts @@ -1,66 +1,66 @@ -import test from 'ava' -import { createMagnetarInstance } from '../helpers/createMagnetarInstance' import { pokedex, waitMs } from '@magnetarjs/test-utils' import { isPromise } from 'is-what' +import { assert, test } from 'vitest' +import { createMagnetarInstance } from '../helpers/createMagnetarInstance.js' -test('stream (collection)', async (t) => { +test('stream (collection)', async () => { const { pokedexModule } = createMagnetarInstance() - t.deepEqual(pokedexModule.data.get('1'), pokedex(1)) - t.deepEqual(pokedexModule.data.size, 1) - t.deepEqual(pokedexModule.streaming(), null) + assert.deepEqual(pokedexModule.data.get('1'), pokedex(1)) + assert.deepEqual(pokedexModule.data.size, 1) + assert.deepEqual(pokedexModule.streaming(), null) // do not await, because it only resolves when the stream is closed - pokedexModule.stream().catch((e: any) => t.fail(e.message)) // prettier-ignore + pokedexModule.stream().catch((e: any) => assert.fail(e.message)) // prettier-ignore // hold the stream open for 600ms await waitMs(600) // the stream promise is now also available here: - t.deepEqual(isPromise(pokedexModule.streaming()), true) + assert.deepEqual(isPromise(pokedexModule.streaming()), true) // close the stream: pokedexModule.closeStream() - t.deepEqual(pokedexModule.streaming(), null) + assert.deepEqual(pokedexModule.streaming(), null) - t.deepEqual(pokedexModule.data.get('1'), pokedex(1)) - t.deepEqual(pokedexModule.data.get('2'), pokedex(2)) - t.deepEqual(pokedexModule.data.get('3'), pokedex(3)) - t.deepEqual(pokedexModule.data.size, 3) + assert.deepEqual(pokedexModule.data.get('1'), pokedex(1)) + assert.deepEqual(pokedexModule.data.get('2'), pokedex(2)) + assert.deepEqual(pokedexModule.data.get('3'), pokedex(3)) + assert.deepEqual(pokedexModule.data.size, 3) await waitMs(1000) - t.deepEqual(pokedexModule.data.size, 3) + assert.deepEqual(pokedexModule.data.size, 3) // '4': charmander should come in next, but doesn't because we closed the stream }) -test('stream (doc)', async (t) => { +test('stream (doc)', async () => { const { trainerModule } = createMagnetarInstance() - t.deepEqual(trainerModule.data, { name: 'Luca', age: 10 }) - t.deepEqual(trainerModule.streaming(), null) + assert.deepEqual(trainerModule.data, { name: 'Luca', age: 10 }) + assert.deepEqual(trainerModule.streaming(), null) // do not await, because it only resolves when the stream is closed - trainerModule.stream().catch((e: any) => t.fail(e.message)) // prettier-ignore + trainerModule.stream().catch((e: any) => assert.fail(e.message)) // prettier-ignore // hold the stream open for 600ms await waitMs(600) // the stream promise is now also available here: - t.deepEqual(isPromise(trainerModule.streaming()), true) + assert.deepEqual(isPromise(trainerModule.streaming()), true) // close the stream: trainerModule.closeStream() - t.deepEqual(trainerModule.streaming(), null) + assert.deepEqual(trainerModule.streaming(), null) - t.deepEqual(trainerModule.data, { name: 'Luca', age: 10, dream: 'job' }) + assert.deepEqual(trainerModule.data, { name: 'Luca', age: 10, dream: 'job' }) await waitMs(1000) - t.deepEqual(trainerModule.data, { name: 'Luca', age: 10, dream: 'job' }) + assert.deepEqual(trainerModule.data, { name: 'Luca', age: 10, dream: 'job' }) // {colour: 'blue'} should come in 3rd, but doesn't because we closed the stream }) -test('stream (collection) where-filter', async (t) => { +test('stream (collection) where-filter', async () => { const { pokedexModule } = createMagnetarInstance() // the original state has 1 Pokemon already - t.deepEqual(pokedexModule.data.size, 1) + assert.deepEqual(pokedexModule.data.size, 1) // let's get some more const pokedexModuleWithQuery = pokedexModule .where('type', 'array-contains', 'Fire') @@ -68,41 +68,44 @@ test('stream (collection) where-filter', async (t) => { // → Charizard 6, Ninetales 38, Rapidash 78 // do not await, because it only resolves when the stream is closed - pokedexModuleWithQuery.stream().catch((e: any) => t.fail(e.message)) + pokedexModuleWithQuery.stream().catch((e: any) => assert.fail(e.message)) await waitMs(600) // be careful, the `streaming` promise and `closeStream` function // are only available on the module with the same query: - t.deepEqual(isPromise(pokedexModuleWithQuery.streaming()), true) - t.deepEqual(pokedexModule.streaming(), null) + assert.deepEqual(isPromise(pokedexModuleWithQuery.streaming()), true) + assert.deepEqual(pokedexModule.streaming(), null) pokedexModuleWithQuery.closeStream() // the queried instance only has these 3 Pokemon - t.deepEqual([...pokedexModuleWithQuery.data.values()], [pokedex(6), pokedex(38), pokedex(78)]) + assert.deepEqual( + [...pokedexModuleWithQuery.data.values()], + [pokedex(6), pokedex(38), pokedex(78)] + ) // the main instance has one Pokemon from the beginning - t.deepEqual(pokedexModule.data.size, 4) + assert.deepEqual(pokedexModule.data.size, 4) }) -test('stream (collection) - can open multiple streams at once', async (t) => { +test('stream (collection) - can open multiple streams at once', async () => { const { pokedexModule } = createMagnetarInstance() const pokedexModuleWithQuery = pokedexModule .where('type', 'array-contains', 'Fire') .where('base.Speed', '>=', 100) - pokedexModule.stream().catch((e: any) => t.fail(e.message)) - pokedexModuleWithQuery.stream().catch((e: any) => t.fail(e.message)) + pokedexModule.stream().catch((e: any) => assert.fail(e.message)) + pokedexModuleWithQuery.stream().catch((e: any) => assert.fail(e.message)) await waitMs(1) - t.deepEqual(isPromise(pokedexModule.streaming()), true) - t.deepEqual(isPromise(pokedexModuleWithQuery.streaming()), true) + assert.deepEqual(isPromise(pokedexModule.streaming()), true) + assert.deepEqual(isPromise(pokedexModuleWithQuery.streaming()), true) pokedexModule.closeAllStreams() - t.deepEqual(pokedexModule.streaming(), null) - t.deepEqual(pokedexModuleWithQuery.streaming(), null) + assert.deepEqual(pokedexModule.streaming(), null) + assert.deepEqual(pokedexModuleWithQuery.streaming(), null) }) diff --git a/packages/core/test/helpers/createMagnetarInstance.ts b/packages/core/test/helpers/createMagnetarInstance.ts index 083e6a1b..5b434e01 100644 --- a/packages/core/test/helpers/createMagnetarInstance.ts +++ b/packages/core/test/helpers/createMagnetarInstance.ts @@ -11,7 +11,7 @@ import type { GlobalConfig, MagnetarInstance, } from '@magnetarjs/types' -import { Magnetar } from '../../src' +import { Magnetar } from '../../src/index.js' const CreatePluginLocal = PluginMockLocal.CreatePlugin const CreatePluginRemote = PluginMockRemote.CreatePlugin diff --git a/packages/core/test/internal/actions.test.ts b/packages/core/test/internal/actions.test.ts index 7cc6cc71..2249b0ed 100644 --- a/packages/core/test/internal/actions.test.ts +++ b/packages/core/test/internal/actions.test.ts @@ -1,23 +1,23 @@ import { pokedex, PokedexEntry } from '@magnetarjs/test-utils' import type { DocInstance } from '@magnetarjs/types' -import test from 'ava' import { merge } from 'merge-anything' -import { createMagnetarInstance } from '../helpers/createMagnetarInstance' +import { assert, test } from 'vitest' +import { createMagnetarInstance } from '../helpers/createMagnetarInstance.js' -test('write: insert (document)', async (t) => { +test('write: insert (document)', async () => { const { pokedexModule, magnetar } = createMagnetarInstance() const payload = pokedex(7) - t.deepEqual(pokedexModule.data.get('7'), undefined) - await pokedexModule.doc('7').insert(payload).catch((e: any) => t.fail(e.message)) // prettier-ignore + assert.deepEqual(pokedexModule.data.get('7'), undefined) + await pokedexModule.doc('7').insert(payload).catch((e: any) => assert.fail(e.message)) // prettier-ignore // check data of references executed on - t.deepEqual(pokedexModule.data.get('7'), payload) + assert.deepEqual(pokedexModule.data.get('7'), payload) // check data of new references - t.deepEqual(pokedexModule.doc('7').data, payload) - t.deepEqual(magnetar.doc('pokedex/7').data, payload) - t.deepEqual(magnetar.collection('pokedex').doc('7').data, payload) + assert.deepEqual(pokedexModule.doc('7').data, payload) + assert.deepEqual(magnetar.doc('pokedex/7').data, payload) + assert.deepEqual(magnetar.collection('pokedex').doc('7').data, payload) }) -test('write: insert (collection) → random ID', async (t) => { +test('write: insert (collection) → random ID', async () => { const { pokedexModule, magnetar } = createMagnetarInstance() const payload = pokedex(7) @@ -25,24 +25,24 @@ test('write: insert (collection) → random ID', async (t) => { try { moduleFromResult = await pokedexModule.insert(payload) } catch (error) { - t.fail(JSON.stringify(error)) + assert.fail(JSON.stringify(error)) return } const newId = moduleFromResult.id // check data of reference returned - t.deepEqual(moduleFromResult.data, payload) + assert.deepEqual(moduleFromResult.data, payload) // check data of references executed on - t.deepEqual(pokedexModule.data.get(newId), payload) + assert.deepEqual(pokedexModule.data.get(newId), payload) // check data of new references - t.deepEqual(magnetar.doc(`pokedex/${newId}`).data, payload) - t.deepEqual(magnetar.collection('pokedex').doc(newId).data, payload) - t.deepEqual(pokedexModule.doc(newId).data, payload) + assert.deepEqual(magnetar.doc(`pokedex/${newId}`).data, payload) + assert.deepEqual(magnetar.collection('pokedex').doc(newId).data, payload) + assert.deepEqual(pokedexModule.doc(newId).data, payload) }) -test('deleteProp: (document)', async (t) => { +test('deleteProp: (document)', async () => { const { trainerModule, magnetar } = createMagnetarInstance() const prop = 'age' - t.deepEqual(trainerModule.data?.age, 10) + assert.deepEqual(trainerModule.data?.age, 10) // create references on beforehand const magnetarDoc = magnetar.doc('app-data/trainer') // prettier-ignore @@ -52,21 +52,21 @@ test('deleteProp: (document)', async (t) => { try { const result = await trainerModule.deleteProp(prop) // check data of reference returned - t.deepEqual(result, trainerModule.data as any) + assert.deepEqual(result, trainerModule.data as any) } catch (error) { - t.fail(JSON.stringify(error)) + assert.fail(JSON.stringify(error)) } // check data of references created on beforehand - t.deepEqual(magnetarDoc.data?.[prop], undefined) - t.deepEqual(magnetarCollectionDoc.data?.[prop], undefined) - t.deepEqual(magnetarCollectionData.get('trainer')?.[prop], undefined) + assert.deepEqual(magnetarDoc.data?.[prop], undefined) + assert.deepEqual(magnetarCollectionDoc.data?.[prop], undefined) + assert.deepEqual(magnetarCollectionData.get('trainer')?.[prop], undefined) // check data of references executed on - t.deepEqual(trainerModule.data?.[prop], undefined) + assert.deepEqual(trainerModule.data?.[prop], undefined) }) -test('delete: (document)', async (t) => { +test('delete: (document)', async () => { const { trainerModule, magnetar } = createMagnetarInstance() - t.deepEqual(trainerModule.data, { age: 10, name: 'Luca' }) + assert.deepEqual(trainerModule.data, { age: 10, name: 'Luca' }) // create references on beforehand const magnetarCollection = magnetar.collection('app-data') @@ -76,85 +76,85 @@ test('delete: (document)', async (t) => { try { const result = await trainerModule.delete() // check data of reference returned - t.deepEqual(result, undefined) + assert.deepEqual(result, undefined) } catch (error) { - t.fail(JSON.stringify(error)) + assert.fail(JSON.stringify(error)) } // check data of references created on beforehand - t.deepEqual(magnetarCollection.data.get('trainer'), undefined) - t.deepEqual(magnetarCollectionDoc.data, undefined) - t.deepEqual(magnetarDoc.data, undefined) + assert.deepEqual(magnetarCollection.data.get('trainer'), undefined) + assert.deepEqual(magnetarCollectionDoc.data, undefined) + assert.deepEqual(magnetarDoc.data, undefined) // check data of references executed on - t.deepEqual(trainerModule.data, undefined) + assert.deepEqual(trainerModule.data, undefined) // check data of new references - t.deepEqual(magnetar.collection('app-data').doc('trainer').data, undefined) - t.deepEqual(magnetar.doc('app-data/trainer').data, undefined) - t.deepEqual(magnetar.collection('app-data').data.get('trainer'), undefined) + assert.deepEqual(magnetar.collection('app-data').doc('trainer').data, undefined) + assert.deepEqual(magnetar.doc('app-data/trainer').data, undefined) + assert.deepEqual(magnetar.collection('app-data').data.get('trainer'), undefined) }) -test('write: merge (document)', async (t) => { +test('write: merge (document)', async () => { const { pokedexModule } = createMagnetarInstance() const payload = { base: { HP: 9000 } } const doc = pokedexModule.doc('1') - t.deepEqual(doc.data, pokedex(1)) - await doc.merge(payload).catch((e: any) => t.fail(e.message)) // prettier-ignore + assert.deepEqual(doc.data, pokedex(1)) + await doc.merge(payload).catch((e: any) => assert.fail(e.message)) // prettier-ignore const mergedResult = merge(pokedex(1), { base: { HP: 9000 } }) - t.deepEqual(pokedexModule.data.get('1'), mergedResult) - t.deepEqual(doc.data, mergedResult) + assert.deepEqual(pokedexModule.data.get('1'), mergedResult) + assert.deepEqual(doc.data, mergedResult) }) -test('read: fetch (collection)', async (t) => { +test('read: fetch (collection)', async () => { // 'fetch' resolves once all stores have given a response with data const { pokedexModule } = createMagnetarInstance() - t.deepEqual(pokedexModule.data.get('1'), pokedex(1)) - t.deepEqual(pokedexModule.data.size, 1) + assert.deepEqual(pokedexModule.data.get('1'), pokedex(1)) + assert.deepEqual(pokedexModule.data.size, 1) try { const result = await pokedexModule.fetch({ force: true }) - t.deepEqual(result.get('1'), pokedex(1)) - t.deepEqual(result.get('136'), pokedex(136)) + assert.deepEqual(result.get('1'), pokedex(1)) + assert.deepEqual(result.get('136'), pokedex(136)) } catch (error) { - t.fail(JSON.stringify(error)) + assert.fail(JSON.stringify(error)) } - t.deepEqual(pokedexModule.data.get('1'), pokedex(1)) - t.deepEqual(pokedexModule.data.get('136'), pokedex(136)) - t.deepEqual(pokedexModule.data.size, 151) + assert.deepEqual(pokedexModule.data.get('1'), pokedex(1)) + assert.deepEqual(pokedexModule.data.get('136'), pokedex(136)) + assert.deepEqual(pokedexModule.data.size, 151) }) -test('read: fetch (document)', async (t) => { +test('read: fetch (document)', async () => { // get resolves once all stores have given a response with data const { trainerModule } = createMagnetarInstance() - t.deepEqual(trainerModule.data, { name: 'Luca', age: 10 }) + assert.deepEqual(trainerModule.data, { name: 'Luca', age: 10 }) try { const result = await trainerModule.fetch({ force: true }) - t.deepEqual(result, { name: 'Luca', age: 10, dream: 'job' }) + assert.deepEqual(result, { name: 'Luca', age: 10, dream: 'job' }) } catch (error) { - t.fail(JSON.stringify(error)) + assert.fail(JSON.stringify(error)) } - t.deepEqual(trainerModule.data, { name: 'Luca', age: 10, dream: 'job' }) + assert.deepEqual(trainerModule.data, { name: 'Luca', age: 10, dream: 'job' }) }) -test('fetch (collection) where-filter: ==', async (t) => { +test('fetch (collection) where-filter: ==', async () => { const { pokedexModule, magnetar } = createMagnetarInstance() const pokedexModuleWithQuery = pokedexModule.where('name', '==', 'Flareon') try { const queryModuleRef = pokedexModuleWithQuery await queryModuleRef.fetch({ force: true }) - t.deepEqual([...queryModuleRef.data.values()], [pokedex(136)]) + assert.deepEqual([...queryModuleRef.data.values()], [pokedex(136)]) } catch (error) { - t.fail(JSON.stringify(error)) + assert.fail(JSON.stringify(error)) } // try take the query again and see if it's the same result const queryModuleRef = pokedexModule.where('name', '==', 'Flareon') - t.deepEqual([...queryModuleRef.data.values()], [pokedex(136)]) + assert.deepEqual([...queryModuleRef.data.values()], [pokedex(136)]) // try take the pokedexModuleWithQuery and see if it's the same result - t.deepEqual([...pokedexModuleWithQuery.data.values()], [pokedex(136)]) + assert.deepEqual([...pokedexModuleWithQuery.data.values()], [pokedex(136)]) // check the invididual doc refs from the pokedexModuleWithQuery - t.deepEqual(pokedexModuleWithQuery.doc('136').data, pokedex(136)) + assert.deepEqual(pokedexModuleWithQuery.doc('136').data, pokedex(136)) // check the invididual doc refs from pokedexModule - t.deepEqual(pokedexModule.doc('136').data, pokedex(136)) + assert.deepEqual(pokedexModule.doc('136').data, pokedex(136)) // check the invididual doc refs from base - t.deepEqual(magnetar.doc('pokedex/136').data, pokedex(136)) + assert.deepEqual(magnetar.doc('pokedex/136').data, pokedex(136)) // see if the main module has also received this data - t.deepEqual([...pokedexModule.data.values()], [pokedex(1), pokedex(136)]) + assert.deepEqual([...pokedexModule.data.values()], [pokedex(1), pokedex(136)]) }) diff --git a/packages/core/test/internal/errorHandling.test.ts b/packages/core/test/internal/errorHandling.test.ts index 44f229f2..7071f976 100644 --- a/packages/core/test/internal/errorHandling.test.ts +++ b/packages/core/test/internal/errorHandling.test.ts @@ -1,9 +1,9 @@ import { pokedex, pokedexEntryDefaults } from '@magnetarjs/test-utils' import type { FetchResponse } from '@magnetarjs/types' -import test from 'ava' -import { createMagnetarInstance } from '../helpers/createMagnetarInstance' +import { assert, test } from 'vitest' +import { createMagnetarInstance } from '../helpers/createMagnetarInstance.js' -test('write + onError: stop -- emits fail events & aborts execution by default', async (t) => { +test('write + onError: stop -- emits fail events & aborts execution by default', async () => { const { pokedexModule } = createMagnetarInstance() const insertPayload = { ...pokedexEntryDefaults({ name: 'this should fail' }), @@ -15,21 +15,21 @@ test('write + onError: stop -- emits fail events & aborts execution by default', on: { error: ({ payload, storeName }) => { if (storeName === 'local') { - t.deepEqual(payload, insertPayload) + assert.deepEqual(payload, insertPayload) } }, before: ({ storeName }) => { - if (storeName === 'remote') t.fail() + if (storeName === 'remote') assert.fail() }, }, }) } catch (error) { - t.deepEqual(error, { message: 'failed', payload: insertPayload }) + assert.deepEqual(error, { message: 'failed', payload: insertPayload }) } - t.deepEqual(pokedexModule.data.get('testid'), undefined) + assert.deepEqual(pokedexModule.data.get('testid'), undefined) }) -test('write + onError: stop -- fail in second store plugin does not prevent execution first store plugin', async (t) => { +test('write + onError: stop -- fail in second store plugin does not prevent execution first store plugin', async () => { const { pokedexModule } = createMagnetarInstance() const insertPayload = { ...pokedexEntryDefaults({ name: 'this should fail' }), @@ -40,20 +40,20 @@ test('write + onError: stop -- fail in second store plugin does not prevent exec onError: 'stop', on: { error: ({ payload, storeName }) => { - if (storeName === 'local') t.fail() + if (storeName === 'local') assert.fail() if (storeName === 'remote') { - t.deepEqual(payload, insertPayload) + assert.deepEqual(payload, insertPayload) } }, }, }) } catch (error) { - t.deepEqual(error, { message: 'failed', payload: insertPayload }) + assert.deepEqual(error, { message: 'failed', payload: insertPayload }) } - t.deepEqual(pokedexModule.data.get('testid'), insertPayload) + assert.deepEqual(pokedexModule.data.get('testid'), insertPayload) }) -test('write + onError: continue', async (t) => { +test('write + onError: continue', async () => { const { pokedexModule } = createMagnetarInstance() const insertPayload = { ...pokedexEntryDefaults({ name: 'this should fail' }), @@ -65,24 +65,24 @@ test('write + onError: continue', async (t) => { on: { error: ({ payload, storeName }) => { if (storeName === 'local') { - t.deepEqual(payload, insertPayload) + assert.deepEqual(payload, insertPayload) } - if (storeName === 'remote') t.fail() + if (storeName === 'remote') assert.fail() }, success: ({ payload, storeName }) => { if (storeName === 'remote') { - t.deepEqual(payload, insertPayload) + assert.deepEqual(payload, insertPayload) } }, }, }) } catch (error) { - t.fail(JSON.stringify(error)) + assert.fail(JSON.stringify(error)) } - t.deepEqual(pokedexModule.data.get('testid'), undefined) + assert.deepEqual(pokedexModule.data.get('testid'), undefined) }) -test('write + onError: revert', async (t) => { +test('write + onError: revert', async () => { const { pokedexModule } = createMagnetarInstance() const insertPayload = { ...pokedexEntryDefaults({ name: 'this should fail' }), @@ -94,27 +94,28 @@ test('write + onError: revert', async (t) => { on: { revert: ({ payload, result, actionName, storeName }) => { if (storeName === 'local') { - t.deepEqual(actionName, 'insert') + assert.deepEqual(actionName, 'insert') } }, before: ({ storeName }) => { - if (storeName === 'remote') t.deepEqual(pokedexModule.data.get('testid'), insertPayload) + if (storeName === 'remote') + assert.deepEqual(pokedexModule.data.get('testid'), insertPayload) }, error: ({ payload, storeName }) => { - if (storeName === 'local') t.fail() + if (storeName === 'local') assert.fail() if (storeName === 'remote') { - t.deepEqual(payload, insertPayload) + assert.deepEqual(payload, insertPayload) } }, }, }) } catch (error) { - t.truthy(error) + assert.isTrue(!!error) } - t.deepEqual(pokedexModule.data.get('testid'), undefined) + assert.deepEqual(pokedexModule.data.get('testid'), undefined) }) -test('write + onError: revert - will not go to next store', async (t) => { +test('write + onError: revert - will not go to next store', async () => { const { pokedexModule } = createMagnetarInstance() const insertPayload = { ...pokedexEntryDefaults({ name: 'this should fail' }), @@ -126,102 +127,102 @@ test('write + onError: revert - will not go to next store', async (t) => { on: { error: ({ payload, storeName }) => { if (storeName === 'local') { - t.deepEqual(payload, insertPayload) + assert.deepEqual(payload, insertPayload) } }, revert: ({ storeName }) => { - if (storeName === 'local') t.fail() + if (storeName === 'local') assert.fail() }, before: ({ payload, storeName }) => { if (storeName === 'remote') { - t.fail() + assert.fail() } }, }, }) } catch (error) { - t.truthy(error) + assert.isTrue(!!error) } - t.deepEqual(pokedexModule.data.get('testid'), undefined) + assert.deepEqual(pokedexModule.data.get('testid'), undefined) }) -test('fetch + onError: stop -- emits fail events & aborts execution by default', async (t) => { +test('fetch + onError: stop -- emits fail events & aborts execution by default', async () => { const { pokedexModule } = createMagnetarInstance() const fetchPayload = { shouldFail: 'local', force: true } - t.deepEqual(pokedexModule.data.get('1'), pokedex(1)) + assert.deepEqual(pokedexModule.data.get('1'), pokedex(1)) try { await pokedexModule.fetch(fetchPayload, { onError: 'stop', on: { error: ({ payload, storeName }) => { if (storeName === 'local') { - t.deepEqual(payload, fetchPayload) + assert.deepEqual(payload, fetchPayload) } }, before: ({ storeName }) => { - if (storeName === 'remote') t.fail() + if (storeName === 'remote') assert.fail() }, }, }) } catch (error) { - t.deepEqual(error, { message: 'failed', payload: fetchPayload }) + assert.deepEqual(error, { message: 'failed', payload: fetchPayload }) } - t.deepEqual(pokedexModule.data.get('1'), pokedex(1)) + assert.deepEqual(pokedexModule.data.get('1'), pokedex(1)) }) -test('fetch + onError: stop -- fail in second store plugin does not prevent execution first store plugin', async (t) => { +test('fetch + onError: stop -- fail in second store plugin does not prevent execution first store plugin', async () => { const { pokedexModule } = createMagnetarInstance() const fetchPayload = { shouldFail: 'remote', force: true } - t.deepEqual(pokedexModule.data.get('1'), pokedex(1)) + assert.deepEqual(pokedexModule.data.get('1'), pokedex(1)) let result: any try { result = await pokedexModule.fetch(fetchPayload, { onError: 'stop', on: { error: ({ payload, storeName }) => { - if (storeName === 'local') t.fail() + if (storeName === 'local') assert.fail() if (storeName === 'remote') { - t.deepEqual(payload, fetchPayload) + assert.deepEqual(payload, fetchPayload) } }, }, }) } catch (error) { - t.deepEqual(error, { message: 'failed', payload: fetchPayload }) + assert.deepEqual(error, { message: 'failed', payload: fetchPayload }) } - t.deepEqual(result, undefined) - t.deepEqual(pokedexModule.data.get('1'), pokedex(1)) + assert.deepEqual(result, undefined) + assert.deepEqual(pokedexModule.data.get('1'), pokedex(1)) }) -test('fetch + onError: continue', async (t) => { +test('fetch + onError: continue', async () => { const { pokedexModule } = createMagnetarInstance() const fetchPayload = { shouldFail: 'local', force: true } - t.deepEqual(pokedexModule.data.get('1'), pokedex(1)) + assert.deepEqual(pokedexModule.data.get('1'), pokedex(1)) try { const result = await pokedexModule.fetch(fetchPayload, { onError: 'continue', on: { error: ({ payload, storeName }) => { if (storeName === 'local') { - t.deepEqual(payload, fetchPayload) + assert.deepEqual(payload, fetchPayload) } - if (storeName === 'remote') t.fail() + if (storeName === 'remote') assert.fail() }, success: ({ payload, result, storeName }) => { if (storeName === 'remote') { - t.deepEqual(payload, fetchPayload) + assert.deepEqual(payload, fetchPayload) // even though the local store failed, we got the result of the remote store - t.deepEqual((result as FetchResponse).docs.length, 151) + assert.deepEqual((result as FetchResponse).docs.length, 151) } }, }, }) - t.deepEqual(result.get('1'), pokedex(1)) - t.deepEqual(result.get('136'), pokedex(136)) // the remote store result is returned no matter what + assert.deepEqual(result.get('1'), pokedex(1)) + assert.deepEqual(result.get('136'), pokedex(136)) // the remote store result is returned no matter what } catch (error) { - t.fail(JSON.stringify(error)) + assert.fail(JSON.stringify(error)) } // the local store didn't succeed in applying its 'inserted' event, so its local data will be empty: - t.deepEqual(pokedexModule.data.get('1'), pokedex(1)) - t.deepEqual(pokedexModule.data.get('136'), undefined) + assert.deepEqual(pokedexModule.data.get('1'), pokedex(1)) + assert.deepEqual(pokedexModule.data.get('136'), undefined) }) diff --git a/packages/core/test/internal/events.test.ts b/packages/core/test/internal/events.test.ts index fa715881..70846bf8 100644 --- a/packages/core/test/internal/events.test.ts +++ b/packages/core/test/internal/events.test.ts @@ -1,8 +1,8 @@ -import test from 'ava' -import { createMagnetarInstance } from '../helpers/createMagnetarInstance' import { pokedex } from '@magnetarjs/test-utils' +import { assert, test } from 'vitest' +import { createMagnetarInstance } from '../helpers/createMagnetarInstance.js' -test('delete: emits before & success events', async (t) => { +test('delete: emits before & success events', async () => { const { pokedexModule } = createMagnetarInstance() const insertPayload = pokedex(7) await pokedexModule.insert(insertPayload) @@ -17,10 +17,10 @@ test('delete: emits before & success events', async (t) => { }, }, }) - t.deepEqual(ranAllEvents.length, 4) + assert.deepEqual(ranAllEvents.length, 4) }) -test('insert: emits before & success events', async (t) => { +test('insert: emits before & success events', async () => { const { pokedexModule } = createMagnetarInstance() const insertPayload = pokedex(7) const ranAllEvents: any[] = [] @@ -28,30 +28,30 @@ test('insert: emits before & success events', async (t) => { on: { before: ({ payload, storeName }) => { if (storeName === 'local') { - t.deepEqual(payload, insertPayload) + assert.deepEqual(payload, insertPayload) ranAllEvents.push(1) } if (storeName === 'remote') { - t.deepEqual(payload, insertPayload) + assert.deepEqual(payload, insertPayload) ranAllEvents.push(1) } }, success: ({ payload, storeName }) => { if (storeName === 'local') { - t.deepEqual(payload, insertPayload) + assert.deepEqual(payload, insertPayload) ranAllEvents.push(1) } if (storeName === 'remote') { - t.deepEqual(payload, insertPayload) + assert.deepEqual(payload, insertPayload) ranAllEvents.push(1) } }, }, }) - t.deepEqual(ranAllEvents.length, 4) + assert.deepEqual(ranAllEvents.length, 4) }) -test('insert: can abort in before events', async (t) => { +test('insert: can abort in before events', async () => { const { pokedexModule } = createMagnetarInstance() const insertPayload = pokedex(7) try { @@ -61,23 +61,23 @@ test('insert: can abort in before events', async (t) => { if (storeName === 'local') { abort() } - if (storeName === 'remote') t.fail() + if (storeName === 'remote') assert.fail() }, success: ({ storeName, result }) => { - t.fail() + assert.fail() }, error: ({ storeName }) => { - if (storeName === 'local') t.fail() + if (storeName === 'local') assert.fail() }, }, }) - t.deepEqual(result.data, pokedexModule.data.get('7')) + assert.deepEqual(result.data, pokedexModule.data.get('7')) } catch (error) { - t.fail(JSON.stringify(error)) + assert.fail(JSON.stringify(error)) } }) -test('insert: can abort in success events', async (t) => { +test('insert: can abort in success events', async () => { const { pokedexModule } = createMagnetarInstance() const insertPayload = pokedex(7) const ranAllEvents: any[] = [] @@ -88,7 +88,7 @@ test('insert: can abort in success events', async (t) => { if (storeName === 'local') { ranAllEvents.push(1) } - if (storeName === 'remote') t.fail() + if (storeName === 'remote') assert.fail() }, success: ({ payload, abort, storeName }) => { if (storeName === 'local') { @@ -98,9 +98,9 @@ test('insert: can abort in success events', async (t) => { }, }, }) - t.deepEqual(result.data, insertPayload) + assert.deepEqual(result.data, insertPayload) } catch (error) { - t.fail(JSON.stringify(error)) + assert.fail(JSON.stringify(error)) } - t.deepEqual(ranAllEvents.length, 2) + assert.deepEqual(ranAllEvents.length, 2) }) diff --git a/packages/core/test/internal/fetch.test.ts b/packages/core/test/internal/fetch.test.ts index d21d22b2..8961d1d2 100644 --- a/packages/core/test/internal/fetch.test.ts +++ b/packages/core/test/internal/fetch.test.ts @@ -1,55 +1,55 @@ -import test from 'ava' -import { createMagnetarInstance } from '../helpers/createMagnetarInstance' import { pokedex } from '@magnetarjs/test-utils' +import { assert, test } from 'vitest' +import { createMagnetarInstance } from '../helpers/createMagnetarInstance.js' -test('read: fetch (collection)', async (t) => { +test('read: fetch (collection)', async () => { // 'fetch' resolves once all stores have given a response with data const { pokedexModule } = createMagnetarInstance() - t.deepEqual(pokedexModule.data.get('1'), pokedex(1)) - t.deepEqual(pokedexModule.data.size, 1) + assert.deepEqual(pokedexModule.data.get('1'), pokedex(1)) + assert.deepEqual(pokedexModule.data.size, 1) try { const result = await pokedexModule.fetch({ force: true }) - t.deepEqual(result.get('1'), pokedex(1)) - t.deepEqual(result.get('136'), pokedex(136)) + assert.deepEqual(result.get('1'), pokedex(1)) + assert.deepEqual(result.get('136'), pokedex(136)) } catch (error) { - t.fail(JSON.stringify(error)) + assert.fail(JSON.stringify(error)) } - t.deepEqual(pokedexModule.data.get('1'), pokedex(1)) - t.deepEqual(pokedexModule.data.get('136'), pokedex(136)) - t.deepEqual(pokedexModule.data.size, 151) + assert.deepEqual(pokedexModule.data.get('1'), pokedex(1)) + assert.deepEqual(pokedexModule.data.get('136'), pokedex(136)) + assert.deepEqual(pokedexModule.data.size, 151) }) -test('read: fetch (collection) — should throw error', async (t) => { +test('read: fetch (collection) — should throw error', async () => { const { pokedexModule } = createMagnetarInstance() try { await pokedexModule.doc('136').fetch({ shouldFail: 'remote' }) } catch (error) { - t.deepEqual(!!error, true) + assert.deepEqual(!!error, true) } }) -test('read: fetch (collection) — should fetch again after one error', async (t) => { +test('read: fetch (collection) — should fetch again after one error', async () => { const { pokedexModule } = createMagnetarInstance() - t.deepEqual(pokedexModule.data.get('136'), undefined) + assert.deepEqual(pokedexModule.data.get('136'), undefined) try { await pokedexModule.doc('136').fetch({ shouldFail: 'remote' }) } catch (error) { - t.deepEqual(!!error, true) + assert.deepEqual(!!error, true) } - t.deepEqual(pokedexModule.data.get('136'), undefined) + assert.deepEqual(pokedexModule.data.get('136'), undefined) try { await pokedexModule.doc('136').fetch() } catch (error) { - t.deepEqual(!!error, false) + assert.deepEqual(!!error, false) } - t.deepEqual(pokedexModule.data.get('136'), pokedex(136)) + assert.deepEqual(pokedexModule.data.get('136'), pokedex(136)) }) -test('read: fetch (collection) — should fetch other docs when one throws errors', async (t) => { +test('read: fetch (collection) — should fetch other docs when one throws errors', async () => { const { pokedexModule } = createMagnetarInstance() - t.deepEqual(pokedexModule.data.get('135'), undefined) - t.deepEqual(pokedexModule.data.get('136'), undefined) - t.deepEqual(pokedexModule.data.get('137'), undefined) + assert.deepEqual(pokedexModule.data.get('135'), undefined) + assert.deepEqual(pokedexModule.data.get('136'), undefined) + assert.deepEqual(pokedexModule.data.get('137'), undefined) try { await Promise.allSettled([ pokedexModule.doc('135').fetch(), @@ -57,14 +57,14 @@ test('read: fetch (collection) — should fetch other docs when one throws error pokedexModule.doc('137').fetch(), ]) } catch (error) { - t.deepEqual(!!error, true) + assert.deepEqual(!!error, true) } - t.deepEqual(pokedexModule.data.get('135'), pokedex(135)) - t.deepEqual(pokedexModule.data.get('136'), undefined) - t.deepEqual(pokedexModule.data.get('137'), pokedex(137)) + assert.deepEqual(pokedexModule.data.get('135'), pokedex(135)) + assert.deepEqual(pokedexModule.data.get('136'), undefined) + assert.deepEqual(pokedexModule.data.get('137'), pokedex(137)) }) -test('read: fetch (document) - prevent multiple fetch requests at the same time', async (t) => { +test('read: fetch (document) - prevent multiple fetch requests at the same time', async () => { // fetch resolves once all stores have given a response with data const storeNames: string[] = [] const { trainerModule } = createMagnetarInstance({ @@ -78,26 +78,26 @@ test('read: fetch (document) - prevent multiple fetch requests at the same time' // fetch twice at the same time await Promise.all([trainerModule.fetch({ force: true }), trainerModule.fetch({ force: true })]) } catch (error) { - t.fail(JSON.stringify(error)) + assert.fail(JSON.stringify(error)) } // make sure the remote store was only triggered once - t.deepEqual(storeNames.filter((n) => n === 'remote').length, 1) + assert.deepEqual(storeNames.filter((n) => n === 'remote').length, 1) try { // fetch twice again the same time await Promise.all([trainerModule.fetch({ force: true }), trainerModule.fetch({ force: true })]) } catch (error) { - t.fail(JSON.stringify(error)) + assert.fail(JSON.stringify(error)) } // make sure the remote store was only triggered once more - t.deepEqual(storeNames.filter((n) => n === 'remote').length, 2) + assert.deepEqual(storeNames.filter((n) => n === 'remote').length, 2) - t.deepEqual(trainerModule.data, { name: 'Luca', age: 10, dream: 'job' }) + assert.deepEqual(trainerModule.data, { name: 'Luca', age: 10, dream: 'job' }) }) -test('read: fetch (document) - optimistic fetch by default', async (t) => { +test('read: fetch (document) - optimistic fetch by default', async () => { // fetch resolves once all stores have given a response with data const storeNames: string[] = [] const startEmpty = true @@ -115,21 +115,21 @@ test('read: fetch (document) - optimistic fetch by default', async (t) => { // fetch twice at the same time await Promise.all([trainerModule.fetch({ force: true }), trainerModule.fetch({ force: true })]) } catch (error) { - t.fail(JSON.stringify(error)) + assert.fail(JSON.stringify(error)) } // make sure the remote store was only triggered once - t.deepEqual(storeNames.filter((n) => n === 'remote').length, 1) + assert.deepEqual(storeNames.filter((n) => n === 'remote').length, 1) try { // fetch twice again the same time await Promise.all([trainerModule.fetch(), trainerModule.fetch()]) } catch (error) { - t.fail(JSON.stringify(error)) + assert.fail(JSON.stringify(error)) } // make sure the remote store was not triggered again - t.deepEqual(storeNames.filter((n) => n === 'remote').length, 1) + assert.deepEqual(storeNames.filter((n) => n === 'remote').length, 1) - t.deepEqual(trainerModule.data, { name: 'Luca', age: 10, dream: 'job' }) + assert.deepEqual(trainerModule.data, { name: 'Luca', age: 10, dream: 'job' }) }) diff --git a/packages/core/test/internal/globalModuleAndActionConfig.test.ts b/packages/core/test/internal/globalModuleAndActionConfig.test.ts index 9bbe4085..10d1d8c7 100644 --- a/packages/core/test/internal/globalModuleAndActionConfig.test.ts +++ b/packages/core/test/internal/globalModuleAndActionConfig.test.ts @@ -1,11 +1,11 @@ -import test from 'ava' -import { Magnetar } from '../../src/index' import { PluginMockLocal, generateRandomId, pokedex } from '@magnetarjs/test-utils' -import { createMagnetarInstance } from '../helpers/createMagnetarInstance' +import { assert, test } from 'vitest' +import { Magnetar } from '../../src/index.js' +import { createMagnetarInstance } from '../helpers/createMagnetarInstance.js' const CreatePluginLocal = PluginMockLocal.CreatePlugin -test('emits global, module and action events', async (t) => { +test('emits global, module and action events', async () => { const local = CreatePluginLocal({ storeName: 'local', generateRandomId }) const ranAllEvents: any[] = [] const magnetar = Magnetar({ @@ -37,11 +37,11 @@ test('emits global, module and action events', async (t) => { }, }, }) - t.deepEqual(result.data, insertPayload) - t.deepEqual(ranAllEvents, [insertPayload, insertPayload, insertPayload]) + assert.deepEqual(result.data, insertPayload) + assert.deepEqual(ranAllEvents, [insertPayload, insertPayload, insertPayload]) }) -test('can modify payload in global, module and action settings', async (t) => { +test('can modify payload in global, module and action settings', async () => { const local = CreatePluginLocal({ storeName: 'local', generateRandomId }) const magnetar = Magnetar({ localStoreName: 'local', @@ -72,7 +72,7 @@ test('can modify payload in global, module and action settings', async (t) => { }, }, }) - t.deepEqual(result.data, { + assert.deepEqual(result.data, { ...insertPayload, addedInModule: true, addedInGlobal: true, @@ -80,7 +80,7 @@ test('can modify payload in global, module and action settings', async (t) => { }) }) -test('can overwrite execution order', async (t) => { +test('can overwrite execution order', async () => { const { pokedexModule } = createMagnetarInstance() const insertPayload = pokedex(7) await pokedexModule.insert(insertPayload) @@ -96,7 +96,7 @@ test('can overwrite execution order', async (t) => { }, }, }) - t.deepEqual(ranAllEvents, ['local', 'local', 'remote', 'remote']) + assert.deepEqual(ranAllEvents, ['local', 'local', 'remote', 'remote']) await pokedexModule.insert(insertPayload) ranAllEvents = [] await pokedexModule.doc('7').delete(undefined, { @@ -110,5 +110,5 @@ test('can overwrite execution order', async (t) => { }, }, }) - t.deepEqual(ranAllEvents, ['remote', 'remote', 'local', 'local']) + assert.deepEqual(ranAllEvents, ['remote', 'remote', 'local', 'local']) }) diff --git a/packages/core/test/internal/modifyPayloadAndReadResponse.test.ts b/packages/core/test/internal/modifyPayloadAndReadResponse.test.ts index 4df8d1f5..c80a7cd4 100644 --- a/packages/core/test/internal/modifyPayloadAndReadResponse.test.ts +++ b/packages/core/test/internal/modifyPayloadAndReadResponse.test.ts @@ -1,8 +1,8 @@ -import test from 'ava' -import { createMagnetarInstance } from '../helpers/createMagnetarInstance' import { pokedex, waitMs } from '@magnetarjs/test-utils' +import { assert, test } from 'vitest' +import { createMagnetarInstance } from '../helpers/createMagnetarInstance.js' -test('fetch: can mutate payload & read response (config in global magnetar instance)', async (t) => { +test('fetch: can mutate payload & read response (config in global magnetar instance)', async () => { function addSeen(payload: any) { return { ...payload, seen: true } } @@ -27,16 +27,16 @@ test('fetch: can mutate payload & read response (config in global magnetar insta } ) // the remote result SHOULD HAVE the applied defaults - t.deepEqual(payloadInSuccessEvent, { auth: 'Bearer 123123', force: true }) - t.deepEqual(result.get('136'), { ...pokedex(136), seen: true }) + assert.deepEqual(payloadInSuccessEvent, { auth: 'Bearer 123123', force: true }) + assert.deepEqual(result.get('136'), { ...pokedex(136), seen: true }) } catch (error) { - t.fail(JSON.stringify(error)) + assert.fail(JSON.stringify(error)) } // the local store SHOULD HAVE the applied defaults - t.deepEqual(magnetar.collection('pokedex').data.get('136'), { ...pokedex(136), seen: true }) + assert.deepEqual(magnetar.collection('pokedex').data.get('136'), { ...pokedex(136), seen: true }) }) -test('stream: can mutate payload & read response (config in global magnetar instance)', async (t) => { +test('stream: can mutate payload & read response (config in global magnetar instance)', async () => { function addSeen(payload: any) { return { ...payload, seen: true } } @@ -60,11 +60,11 @@ test('stream: can mutate payload & read response (config in global magnetar inst ) await waitMs(600) // the local store SHOULD HAVE the applied defaults - t.deepEqual(payloadInSuccessEvent, { auth: 'Bearer 123123' }) - t.deepEqual(magnetar.collection('pokedex').data.get('2'), { ...pokedex(2), seen: true }) + assert.deepEqual(payloadInSuccessEvent, { auth: 'Bearer 123123' }) + assert.deepEqual(magnetar.collection('pokedex').data.get('2'), { ...pokedex(2), seen: true }) }) -test('insert: can mutate payload (config in global magnetar instance)', async (t) => { +test('insert: can mutate payload (config in global magnetar instance)', async () => { function addSeen(payload: any) { if (!('seen' in payload)) return { ...payload, seen: true } } @@ -77,19 +77,19 @@ test('insert: can mutate payload (config in global magnetar instance)', async (t const resultB = await magnetar.collection('pokedex').doc('10').insert(pokedex(10)) const resultC = await magnetar.doc('pokedex/25').insert(pokedex(25)) // the remote result SHOULD HAVE the applied defaults - t.deepEqual(resultA.data, { ...pokedex(7), seen: true }) - t.deepEqual(resultB.data, { ...pokedex(10), seen: true }) - t.deepEqual(resultC.data, { ...pokedex(25), seen: true }) + assert.deepEqual(resultA.data, { ...pokedex(7), seen: true }) + assert.deepEqual(resultB.data, { ...pokedex(10), seen: true }) + assert.deepEqual(resultC.data, { ...pokedex(25), seen: true }) } catch (error) { - t.fail(JSON.stringify(error)) + assert.fail(JSON.stringify(error)) } // the local store SHOULD HAVE the applied defaults - t.deepEqual(magnetar.collection('pokedex').data.get('7'), { ...pokedex(7), seen: true }) - t.deepEqual(magnetar.collection('pokedex').data.get('10'), { ...pokedex(10), seen: true }) - t.deepEqual(magnetar.collection('pokedex').data.get('25'), { ...pokedex(25), seen: true }) + assert.deepEqual(magnetar.collection('pokedex').data.get('7'), { ...pokedex(7), seen: true }) + assert.deepEqual(magnetar.collection('pokedex').data.get('10'), { ...pokedex(10), seen: true }) + assert.deepEqual(magnetar.collection('pokedex').data.get('25'), { ...pokedex(25), seen: true }) }) -test('fetch: can mutate payload & read response (config in module)', async (t) => { +test('fetch: can mutate payload & read response (config in module)', async () => { function addSeen(payload: any) { return { ...payload, seen: true } } @@ -115,16 +115,16 @@ test('fetch: can mutate payload & read response (config in module)', async (t) = } ) // the remote result SHOULD HAVE the applied defaults - t.deepEqual(payloadInSuccessEvent, { auth: 'Bearer 123123', force: true }) - t.deepEqual(result.get('136'), { ...pokedex(136), seen: true }) + assert.deepEqual(payloadInSuccessEvent, { auth: 'Bearer 123123', force: true }) + assert.deepEqual(result.get('136'), { ...pokedex(136), seen: true }) } catch (error) { - t.fail(JSON.stringify(error)) + assert.fail(JSON.stringify(error)) } // the local store SHOULD HAVE the applied defaults - t.deepEqual(pokedexModule.data.get('136'), { ...pokedex(136), seen: true }) + assert.deepEqual(pokedexModule.data.get('136'), { ...pokedex(136), seen: true }) }) -test('stream: can mutate payload & read response (config in module)', async (t) => { +test('stream: can mutate payload & read response (config in module)', async () => { function addSeen(payload: any) { return { ...payload, seen: true } } @@ -149,11 +149,11 @@ test('stream: can mutate payload & read response (config in module)', async (t) ) await waitMs(600) // the local store SHOULD HAVE the applied defaults - t.deepEqual(payloadInSuccessEvent, { auth: 'Bearer 123123' }) - t.deepEqual(pokedexModule.data.get('2'), { ...pokedex(2), seen: true }) + assert.deepEqual(payloadInSuccessEvent, { auth: 'Bearer 123123' }) + assert.deepEqual(pokedexModule.data.get('2'), { ...pokedex(2), seen: true }) }) -test('insert: can mutate payload (config in module)', async (t) => { +test('insert: can mutate payload (config in module)', async () => { function addSeen(payload: any) { if (!('seen' in payload)) return { ...payload, seen: true } } @@ -166,15 +166,15 @@ test('insert: can mutate payload (config in module)', async (t) => { const payload = pokedex(7) const result = await pokedexModule.insert(payload) // the remote result SHOULD HAVE the applied defaults - t.deepEqual(result.data, { ...pokedex(7), seen: true }) + assert.deepEqual(result.data, { ...pokedex(7), seen: true }) } catch (error) { - t.fail(JSON.stringify(error)) + assert.fail(JSON.stringify(error)) } // the local store SHOULD HAVE the applied defaults - t.deepEqual(pokedexModule.data.get('7'), { ...pokedex(7), seen: true }) + assert.deepEqual(pokedexModule.data.get('7'), { ...pokedex(7), seen: true }) }) -test('fetch: can mutate payload & read response (config in action)', async (t) => { +test('fetch: can mutate payload & read response (config in action)', async () => { function addSeen(payload: any) { return { ...payload, seen: true } } @@ -183,7 +183,7 @@ test('fetch: can mutate payload & read response (config in action)', async (t) = } // get resolves once all stores have given a response with data const { pokedexModule } = createMagnetarInstance() - t.deepEqual(pokedexModule.data.get('1'), pokedex(1)) + assert.deepEqual(pokedexModule.data.get('1'), pokedex(1)) try { let payloadInSuccessEvent: any const result = await pokedexModule.fetch( @@ -199,18 +199,18 @@ test('fetch: can mutate payload & read response (config in action)', async (t) = } ) // the remote result SHOULD HAVE the applied defaults - t.deepEqual(result.get('1'), { ...pokedex(1), seen: true }) - t.deepEqual(result.get('136'), { ...pokedex(136), seen: true }) - t.deepEqual(payloadInSuccessEvent, { auth: 'Bearer 123123', force: true }) + assert.deepEqual(result.get('1'), { ...pokedex(1), seen: true }) + assert.deepEqual(result.get('136'), { ...pokedex(136), seen: true }) + assert.deepEqual(payloadInSuccessEvent, { auth: 'Bearer 123123', force: true }) } catch (error) { - t.fail(JSON.stringify(error)) + assert.fail(JSON.stringify(error)) } // the local store SHOULD HAVE the applied defaults - t.deepEqual(pokedexModule.data.get('1'), { ...pokedex(1), seen: true }) - t.deepEqual(pokedexModule.data.get('136'), { ...pokedex(136), seen: true }) + assert.deepEqual(pokedexModule.data.get('1'), { ...pokedex(1), seen: true }) + assert.deepEqual(pokedexModule.data.get('136'), { ...pokedex(136), seen: true }) }) -test('stream: can mutate payload & read response (config in action)', async (t) => { +test('stream: can mutate payload & read response (config in action)', async () => { function addSeen(payload: any) { return { ...payload, seen: true } } @@ -218,7 +218,7 @@ test('stream: can mutate payload & read response (config in action)', async (t) return { ...payload, auth: 'Bearer 123123' } } const { pokedexModule } = createMagnetarInstance() - t.deepEqual(pokedexModule.data.get('1'), pokedex(1)) + assert.deepEqual(pokedexModule.data.get('1'), pokedex(1)) let payloadInSuccessEvent: any pokedexModule.stream( {}, @@ -233,35 +233,35 @@ test('stream: can mutate payload & read response (config in action)', async (t) } ) await waitMs(600) - t.deepEqual(payloadInSuccessEvent, { auth: 'Bearer 123123' }) + assert.deepEqual(payloadInSuccessEvent, { auth: 'Bearer 123123' }) // the local store SHOULD HAVE the applied defaults - t.deepEqual(pokedexModule.data.get('1'), { ...pokedex(1), seen: true }) - t.deepEqual(pokedexModule.data.get('2'), { ...pokedex(2), seen: true }) + assert.deepEqual(pokedexModule.data.get('1'), { ...pokedex(1), seen: true }) + assert.deepEqual(pokedexModule.data.get('2'), { ...pokedex(2), seen: true }) }) -test('insert: can mutate payload (config in action)', async (t) => { +test('insert: can mutate payload (config in action)', async () => { function addSeen(payload: any) { if (!('seen' in payload)) return { ...payload, seen: true } } // get resolves once all stores have given a response with data const { pokedexModule } = createMagnetarInstance() - t.deepEqual(pokedexModule.data.get('1'), pokedex(1)) + assert.deepEqual(pokedexModule.data.get('1'), pokedex(1)) try { const payload = pokedex(7) const result = await pokedexModule.insert(payload, { modifyPayloadOn: { write: addSeen }, }) // the remote result SHOULD HAVE the applied defaults - t.deepEqual(result.data, { ...pokedex(7), seen: true }) + assert.deepEqual(result.data, { ...pokedex(7), seen: true }) } catch (error) { - t.fail(JSON.stringify(error)) + assert.fail(JSON.stringify(error)) } // the local store SHOULD HAVE the applied defaults - t.deepEqual(pokedexModule.data.get('1'), { ...pokedex(1) }) - t.deepEqual(pokedexModule.data.get('7'), { ...pokedex(7), seen: true }) + assert.deepEqual(pokedexModule.data.get('1'), { ...pokedex(1) }) + assert.deepEqual(pokedexModule.data.get('7'), { ...pokedex(7), seen: true }) }) -test('insert: can mutate payload (config in module - action from doc)', async (t) => { +test('insert: can mutate payload (config in module - action from doc)', async () => { function addSeen(payload: any) { if (!('seen' in payload)) return { ...payload, seen: true } } @@ -274,15 +274,15 @@ test('insert: can mutate payload (config in module - action from doc)', async (t const resultWithoutSeen = await magnetar.collection('pokedex').doc('10').insert(pokedex(10)) const resultWithSeen = await pokedexModule.doc('7').insert(pokedex(7)) // the remote result not from pokedexModule SHOULD NOT HAVE the applied defaults - t.deepEqual(resultWithoutSeen.data, { ...pokedex(10) }) - t.falsy('seen' in resultWithoutSeen) + assert.deepEqual(resultWithoutSeen.data, { ...pokedex(10) }) + assert.isFalse(!!('seen' in resultWithoutSeen)) // the remote result SHOULD HAVE the applied defaults - t.deepEqual(resultWithSeen.data, { ...pokedex(7), seen: true }) + assert.deepEqual(resultWithSeen.data, { ...pokedex(7), seen: true }) } catch (error) { - t.fail(JSON.stringify(error)) + assert.fail(JSON.stringify(error)) } // the local store result not from pokedexModule SHOULD NOT HAVE the applied defaults - t.deepEqual(pokedexModule.data.get('7'), { ...pokedex(7), seen: true }) + assert.deepEqual(pokedexModule.data.get('7'), { ...pokedex(7), seen: true }) // the local store SHOULD HAVE the applied defaults - t.deepEqual(pokedexModule.data.get('10'), { ...pokedex(10) }) + assert.deepEqual(pokedexModule.data.get('10'), { ...pokedex(10) }) }) diff --git a/packages/core/test/internal/stream.test.ts b/packages/core/test/internal/stream.test.ts index cde0489d..e714f874 100644 --- a/packages/core/test/internal/stream.test.ts +++ b/packages/core/test/internal/stream.test.ts @@ -1,94 +1,94 @@ -import test from 'ava' -import { createMagnetarInstance } from '../helpers/createMagnetarInstance' import { pokedex, waitMs } from '@magnetarjs/test-utils' import { isPromise } from 'is-what' +import { assert, test } from 'vitest' +import { createMagnetarInstance } from '../helpers/createMagnetarInstance.js' -test('stream (collection)', async (t) => { +test('stream (collection)', async () => { const { pokedexModule } = createMagnetarInstance() - t.deepEqual(pokedexModule.data.get('1'), pokedex(1)) - t.deepEqual(pokedexModule.data.size, 1) + assert.deepEqual(pokedexModule.data.get('1'), pokedex(1)) + assert.deepEqual(pokedexModule.data.size, 1) // do not await, because it only resolves when the stream is closed - pokedexModule.stream().catch((e: any) => t.fail(e.message)) // prettier-ignore + pokedexModule.stream().catch((e: any) => assert.fail(e.message)) // prettier-ignore await waitMs(600) // close the stream: pokedexModule.closeStream() - t.deepEqual(pokedexModule.data.get('1'), pokedex(1)) - t.deepEqual(pokedexModule.data.get('2'), pokedex(2)) - t.deepEqual(pokedexModule.data.get('3'), pokedex(3)) - t.deepEqual(pokedexModule.data.size, 3) + assert.deepEqual(pokedexModule.data.get('1'), pokedex(1)) + assert.deepEqual(pokedexModule.data.get('2'), pokedex(2)) + assert.deepEqual(pokedexModule.data.get('3'), pokedex(3)) + assert.deepEqual(pokedexModule.data.size, 3) await waitMs(1000) - t.deepEqual(pokedexModule.data.size, 3) + assert.deepEqual(pokedexModule.data.size, 3) // '4': charmander should come in next, but doesn't because we closed the stream }) -test('stream (doc)', async (t) => { +test('stream (doc)', async () => { const { trainerModule } = createMagnetarInstance() - t.deepEqual(trainerModule.data, { name: 'Luca', age: 10 }) + assert.deepEqual(trainerModule.data, { name: 'Luca', age: 10 }) // do not await, because it only resolves when the stream is closed - trainerModule.stream().catch((e: any) => t.fail(e.message)) // prettier-ignore + trainerModule.stream().catch((e: any) => assert.fail(e.message)) // prettier-ignore await waitMs(600) // close the stream: trainerModule.closeStream() - t.deepEqual(trainerModule.data, { name: 'Luca', age: 10, dream: 'job' }) + assert.deepEqual(trainerModule.data, { name: 'Luca', age: 10, dream: 'job' }) await waitMs(1000) - t.deepEqual(trainerModule.data, { name: 'Luca', age: 10, dream: 'job' }) + assert.deepEqual(trainerModule.data, { name: 'Luca', age: 10, dream: 'job' }) // {colour: 'blue'} should come in 3rd, but doesn't because we closed the stream }) type P = { promise?: Promise; resolve: (p?: any) => any } -test('stream (doc) but updating multiple times in between stream', async (t) => { +test('stream (doc) but updating multiple times in between stream', async () => { const { trainerModule } = createMagnetarInstance() - t.deepEqual(trainerModule.data, { name: 'Luca', age: 10 }) + assert.deepEqual(trainerModule.data, { name: 'Luca', age: 10 }) // do not await, because it only resolves when the stream is closed - const p1: P = { resolve: () => {} } + const p1: P = { resolve: () => undefined } p1.promise = new Promise((resolve) => { p1.resolve = resolve }) - const p2: P = { resolve: () => {} } + const p2: P = { resolve: () => undefined } p2.promise = new Promise((resolve) => { p2.resolve = resolve }) - const p3: P = { resolve: () => {} } + const p3: P = { resolve: () => undefined } p3.promise = new Promise((resolve) => { p3.resolve = resolve }) - const p4: P = { resolve: () => {} } + const p4: P = { resolve: () => undefined } p4.promise = new Promise((resolve) => { p4.resolve = resolve }) - trainerModule.stream([p1.promise, p2.promise, p3.promise, p4.promise]).catch((e: any) => t.fail(e.message)) // prettier-ignore + trainerModule.stream([p1.promise, p2.promise, p3.promise, p4.promise]).catch((e: any) => assert.fail(e.message)) // prettier-ignore await Promise.all([p1.resolve(), await p1.promise]) await Promise.all([p2.resolve(), await p2.promise]) - t.deepEqual(trainerModule.data, { name: 'Luca', age: 10 }) + assert.deepEqual(trainerModule.data, { name: 'Luca', age: 10 }) // we will update and "wait" until this reached the server: await trainerModule.merge({ dream: 'job' }) - t.deepEqual(trainerModule.data, { name: 'Luca', age: 10, dream: 'job' }) + assert.deepEqual(trainerModule.data, { name: 'Luca', age: 10, dream: 'job' }) // but shortly after make another call: await trainerModule.merge({ colour: 'blue' }) - t.deepEqual(trainerModule.data, { name: 'Luca', age: 10, dream: 'job', colour: 'blue' }) + assert.deepEqual(trainerModule.data, { name: 'Luca', age: 10, dream: 'job', colour: 'blue' }) // now the first change comes back from the server: await Promise.all([p3.resolve(), await p3.promise]) // WE MUST MAKE SURE THAT `colour: 'blue'` is not undone in our local state!!! - t.deepEqual(trainerModule.data, { name: 'Luca', age: 10, dream: 'job', colour: 'blue' }) + assert.deepEqual(trainerModule.data, { name: 'Luca', age: 10, dream: 'job', colour: 'blue' }) // now the second change comes back from the server: await Promise.all([p4.resolve(), await p4.promise]) - t.deepEqual(trainerModule.data, { name: 'Luca', age: 10, dream: 'job', colour: 'blue' }) + assert.deepEqual(trainerModule.data, { name: 'Luca', age: 10, dream: 'job', colour: 'blue' }) trainerModule.closeStream() }) -// test('stream (doc) edit right before opening', async (t) => { +// test('stream (doc) edit right before opening', async () => { // const { trainerModule } = createMagnetarInstance() -// t.deepEqual(trainerModule.data, { name: 'Luca', age: 10 }) +// assert.deepEqual(trainerModule.data, { name: 'Luca', age: 10 }) // // do not await, because it only resolves when the stream is closed // const p1: P = { resolve: () => {} } // p1.promise = new Promise((resolve) => { @@ -96,28 +96,28 @@ test('stream (doc) but updating multiple times in between stream', async (t) => // }) // trainerModule.merge({ name: 'L' }) -// trainerModule.stream([p1.promise]).catch((e: any) => t.fail(e.message)) // prettier-ignore +// trainerModule.stream([p1.promise]).catch((e: any) => assert.fail(e.message)) // prettier-ignore // await Promise.all([p1.resolve(), await p1.promise]) -// t.deepEqual(trainerModule.data, { name: 'LUCA', age: 10 }) +// assert.deepEqual(trainerModule.data, { name: 'LUCA', age: 10 }) // }) -// test('stream (collection) edit right before opening', async (t) => { +// test('stream (collection) edit right before opening', async () => { // const { pokedexModule } = createMagnetarInstance() -// t.deepEqual(pokedexModule.data.get('1'), pokedex(1)) -// t.deepEqual(pokedexModule.data.size, 1) +// assert.deepEqual(pokedexModule.data.get('1'), pokedex(1)) +// assert.deepEqual(pokedexModule.data.size, 1) // pokedexModule.doc('1').merge({ name: 'B' }) -// pokedexModule.stream().catch((e: any) => t.fail(e.message)) // prettier-ignore +// pokedexModule.stream().catch((e: any) => assert.fail(e.message)) // prettier-ignore // await waitMs(220) // // close the stream: // pokedexModule.closeStream() -// t.deepEqual(pokedexModule.data.get('1'), { ...pokedex(1), name: 'B' }) +// assert.deepEqual(pokedexModule.data.get('1'), { ...pokedex(1), name: 'B' }) // }) -test('stream (collection) where-filter stream doesnt affect base collection', async (t) => { +test('stream (collection) where-filter stream doesnt affect base collection', async () => { const { pokedexModule } = createMagnetarInstance() - t.deepEqual(pokedexModule.streaming(), null) + assert.deepEqual(pokedexModule.streaming(), null) const collection = pokedexModule .where('type', 'array-contains', 'Fire') @@ -127,41 +127,41 @@ test('stream (collection) where-filter stream doesnt affect base collection', as await waitMs(1) - t.deepEqual(isPromise(collection.streaming()), true) - t.deepEqual(pokedexModule.streaming(), null) + assert.deepEqual(isPromise(collection.streaming()), true) + assert.deepEqual(pokedexModule.streaming(), null) collection.closeStream() - t.deepEqual(collection.streaming(), null) + assert.deepEqual(collection.streaming(), null) }) -test('stream should throw', async (t) => { +test('stream should throw', async () => { const { pokedexModule } = createMagnetarInstance() - t.deepEqual(pokedexModule.data.get('1'), pokedex(1)) - t.deepEqual(pokedexModule.data.size, 1) + assert.deepEqual(pokedexModule.data.get('1'), pokedex(1)) + assert.deepEqual(pokedexModule.data.size, 1) try { // we expect this to fail, so we can await the throw await pokedexModule.stream({ shouldFail: 'remote' }) } catch (e: any) { - t.deepEqual(e.message, 'failed') + assert.deepEqual(e.message, 'failed') } }) -test('stream should not throw again after throwing once', async (t) => { +test('stream should not throw again after throwing once', async () => { const { pokedexModule } = createMagnetarInstance() - t.deepEqual(pokedexModule.data.size, 1) + assert.deepEqual(pokedexModule.data.size, 1) try { // we expect this to fail, so we can await the throw await pokedexModule.stream({ shouldFail: 'remote' }) } catch (e: any) { - t.deepEqual(e.message, 'failed') + assert.deepEqual(e.message, 'failed') } // the second time around the stream should NOT fail and open correctly - t.deepEqual(pokedexModule.data.size, 1) + assert.deepEqual(pokedexModule.data.size, 1) // we expect this NOT to fail!!! const streaming = pokedexModule.stream() - streaming.catch((e) => (t.fail(e.message))) + streaming.catch((e) => assert.fail(e.message)) await waitMs(600) // close the stream: pokedexModule.closeStream() - t.deepEqual(pokedexModule.data.size, 3) + assert.deepEqual(pokedexModule.data.size, 3) }) diff --git a/packages/core/tsconfig.json b/packages/core/tsconfig.json index cce1c663..007e0995 100644 --- a/packages/core/tsconfig.json +++ b/packages/core/tsconfig.json @@ -1,10 +1,8 @@ { "extends": "../../tsconfig.json", "compilerOptions": { - "declaration": true, - "declarationDir": "./dist/types/", - // This must be specified if "paths" is set - "baseUrl": "." + "baseUrl": ".", + "outDir": "dist" }, - "include": ["src/**/*", "test/**/*"] + "include": ["src"] } diff --git a/packages/dev-nuxt-firestore/.gitignore b/packages/dev-nuxt-firestore/.gitignore deleted file mode 100644 index 438cb086..00000000 --- a/packages/dev-nuxt-firestore/.gitignore +++ /dev/null @@ -1,8 +0,0 @@ -node_modules -*.log* -.nuxt -.nitro -.cache -.output -.env -dist diff --git a/packages/dev-nuxt-firestore/README.md b/packages/dev-nuxt-firestore/README.md deleted file mode 100644 index d4b81ef6..00000000 --- a/packages/dev-nuxt-firestore/README.md +++ /dev/null @@ -1,3 +0,0 @@ -# dev-vue3-firestore - -🚧 This is WIP diff --git a/packages/dev-nuxt-firestore/app.vue b/packages/dev-nuxt-firestore/app.vue deleted file mode 100644 index d01de097..00000000 --- a/packages/dev-nuxt-firestore/app.vue +++ /dev/null @@ -1,14 +0,0 @@ - - - diff --git a/packages/dev-nuxt-firestore/assets/style.css b/packages/dev-nuxt-firestore/assets/style.css deleted file mode 100644 index 0192f9aa..00000000 --- a/packages/dev-nuxt-firestore/assets/style.css +++ /dev/null @@ -1,81 +0,0 @@ -:root { - font-family: Inter, Avenir, Helvetica, Arial, sans-serif; - font-size: 16px; - line-height: 24px; - font-weight: 400; - - color-scheme: light dark; - color: rgba(255, 255, 255, 0.87); - background-color: #242424; - - font-synthesis: none; - text-rendering: optimizeLegibility; - -webkit-font-smoothing: antialiased; - -moz-osx-font-smoothing: grayscale; - -webkit-text-size-adjust: 100%; -} - -a { - font-weight: 500; - color: #646cff; - text-decoration: inherit; -} -a:hover { - color: #535bf2; -} - -body { - margin: 0; - display: flex; - place-items: center; - min-width: 320px; - min-height: 100vh; -} - -h1 { - font-size: 3.2em; - line-height: 1.1; -} - -button { - border-radius: 8px; - border: 1px solid transparent; - padding: 0.6em 1.2em; - font-size: 1em; - font-weight: 500; - font-family: inherit; - background-color: #1a1a1a; - cursor: pointer; - transition: border-color 0.25s; -} -button:hover { - border-color: #646cff; -} -button:focus, -button:focus-visible { - outline: 4px auto -webkit-focus-ring-color; -} - -.card { - padding: 2em; -} - -#app { - max-width: 1280px; - margin: 0 auto; - padding: 2rem; - text-align: center; -} - -@media (prefers-color-scheme: light) { - :root { - color: #213547; - background-color: #ffffff; - } - a:hover { - color: #747bff; - } - button { - background-color: #f9f9f9; - } -} diff --git a/packages/dev-nuxt-firestore/components/ButtonToggle.vue b/packages/dev-nuxt-firestore/components/ButtonToggle.vue deleted file mode 100644 index fda576ae..00000000 --- a/packages/dev-nuxt-firestore/components/ButtonToggle.vue +++ /dev/null @@ -1,57 +0,0 @@ - - - - - diff --git a/packages/dev-nuxt-firestore/components/TestFirestorePluginFetch.vue b/packages/dev-nuxt-firestore/components/TestFirestorePluginFetch.vue deleted file mode 100644 index 3b87dfa1..00000000 --- a/packages/dev-nuxt-firestore/components/TestFirestorePluginFetch.vue +++ /dev/null @@ -1,83 +0,0 @@ - - - diff --git a/packages/dev-nuxt-firestore/components/TestFirestorePluginStream.vue b/packages/dev-nuxt-firestore/components/TestFirestorePluginStream.vue deleted file mode 100644 index 4493b674..00000000 --- a/packages/dev-nuxt-firestore/components/TestFirestorePluginStream.vue +++ /dev/null @@ -1,79 +0,0 @@ - - - diff --git a/packages/dev-nuxt-firestore/components/TodoApp.vue b/packages/dev-nuxt-firestore/components/TodoApp.vue deleted file mode 100644 index 38b4abfd..00000000 --- a/packages/dev-nuxt-firestore/components/TodoApp.vue +++ /dev/null @@ -1,117 +0,0 @@ - - - - - diff --git a/packages/dev-nuxt-firestore/nuxt.config.ts b/packages/dev-nuxt-firestore/nuxt.config.ts deleted file mode 100644 index 7a34e34f..00000000 --- a/packages/dev-nuxt-firestore/nuxt.config.ts +++ /dev/null @@ -1,31 +0,0 @@ -/** - * NOTE: - * avoid typedef errors due to `tsc --noEmit`. - * `defineNuxtConfig` is defined by default in IDE like vscode. - */ -import { defineNuxtConfig } from 'nuxt/config' - -// https://nuxt.com/docs/api/configuration/nuxt-config -export default defineNuxtConfig({ - runtimeConfig: { - public: { - apiKey: 'AIzaSyDivMlXIuHqDFsTCCqBDTVL0h29xbltcL8', - authDomain: 'tests-firestore.firebaseapp.com', - databaseURL: 'https://tests-firestore.firebaseio.com', - projectId: 'tests-firestore', - }, - }, - css: ['~/assets/style.css'], - /** - * NOTE: - * 'fast-sort' is provided by CommonJS module as default. - * Nuxt 3 need to require ES Modules. - * https://nuxt.com/docs/guide/concepts/esm#troubleshooting-esm-issues - */ - build: { - transpile: ['fast-sort'], - }, - modules: [ - '@nuxt/devtools' - ] -}) diff --git a/packages/dev-nuxt-firestore/nuxt.d.ts b/packages/dev-nuxt-firestore/nuxt.d.ts deleted file mode 100644 index 36070a6e..00000000 --- a/packages/dev-nuxt-firestore/nuxt.d.ts +++ /dev/null @@ -1,10 +0,0 @@ -declare module '#app' { - interface NuxtApp { - payload: { - // add payload for magnetar SSR - magnetar: Record - } - } -} - -export {} diff --git a/packages/dev-nuxt-firestore/package.json b/packages/dev-nuxt-firestore/package.json deleted file mode 100644 index d497c787..00000000 --- a/packages/dev-nuxt-firestore/package.json +++ /dev/null @@ -1,24 +0,0 @@ -{ - "name": "dev-nuxt-firestore", - "private": true, - "scripts": { - "typecheck": "echo temporarily removed", - "build": "echo temporarily removed", - "dev": "nuxt dev", - "generate": "nuxt generate", - "preview": "nuxt preview", - "postinstall": "nuxt prepare" - }, - "dependencies": { - "@magnetarjs/core": "workspace:*", - "@magnetarjs/plugin-firestore": "workspace:*", - "@magnetarjs/plugin-vue3": "workspace:*", - "firebase": "^10.12.2" - }, - "devDependencies": { - "nuxt": "^3.11.2", - "@nuxt/devtools": "^0.8.5", - "vue": "^3.4.27" - }, - "version": "0.20.1" -} diff --git a/packages/dev-nuxt-firestore/pages/index.vue b/packages/dev-nuxt-firestore/pages/index.vue deleted file mode 100644 index c9cc284d..00000000 --- a/packages/dev-nuxt-firestore/pages/index.vue +++ /dev/null @@ -1,19 +0,0 @@ - - - diff --git a/packages/dev-nuxt-firestore/plugins/magetar.ts b/packages/dev-nuxt-firestore/plugins/magetar.ts deleted file mode 100644 index 4f4cd331..00000000 --- a/packages/dev-nuxt-firestore/plugins/magetar.ts +++ /dev/null @@ -1,46 +0,0 @@ -import { initializeApp } from 'firebase/app' -import { getFirestore, collection, doc } from 'firebase/firestore' -import { Magnetar } from '@magnetarjs/core' -import { CreatePlugin as PluginFirestore } from '@magnetarjs/plugin-firestore' -import { CreatePlugin as PluginVue3 } from '@magnetarjs/plugin-vue3' - -export default defineNuxtPlugin((nuxtApp) => { - const config = useRuntimeConfig() - const firebaseApp = initializeApp(config.public) - const db = getFirestore(firebaseApp) - - const generateRandomId = (): string => doc(collection(db, 'random')).id - - // create the local store plugin instance - const local = PluginVue3({ generateRandomId }) - // create the remote store plugin instance - const remote = PluginFirestore({ db }) - - // instantiate the Magnetar instance with the store plugins - const magnetar = Magnetar({ - stores: { local, remote }, - localStoreName: 'local', - executionOrder: { - read: ['local', 'remote'], - write: ['local', 'remote'], - delete: ['local', 'remote'], - }, - }) - - /** - * TODO: hydration for SSR - */ - if (process.server) { - // collect the initial state - nuxtApp.payload.magnetar = {} - } else if (nuxtApp.payload?.magnetar) { - // ... hydrate the state - } - - return { - provide: { - magnetar, - generateRandomId, - }, - } -}) diff --git a/packages/dev-nuxt-firestore/tsconfig.json b/packages/dev-nuxt-firestore/tsconfig.json deleted file mode 100644 index a746f2a7..00000000 --- a/packages/dev-nuxt-firestore/tsconfig.json +++ /dev/null @@ -1,4 +0,0 @@ -{ - // https://nuxt.com/docs/guide/concepts/typescript - "extends": "./.nuxt/tsconfig.json" -} diff --git a/packages/dev-vue3-firestore/package.json b/packages/dev-vue3-firestore/package.json index 6039279e..7420d6ff 100644 --- a/packages/dev-vue3-firestore/package.json +++ b/packages/dev-vue3-firestore/package.json @@ -1,23 +1,18 @@ { "name": "dev-vue3-firestore", - "version": "0.20.1", + "version": "1.0.1", + "type": "module", "private": true, "scripts": { - "typecheck": "echo na", + "typecheck": "vue-tsc --noEmit", "dev": "vite", "build": "vue-tsc && vite build", + "test": "echo none", "preview": "vite preview" }, "dependencies": { - "firebase": "^10.12.2", - "magnetar": "workspace:*", - "vue": "^3.4.27" - }, - "devDependencies": { - "@vitejs/plugin-vue": "^4.6.2", - "typescript": "^5.4.5", - "vite": "^4.5.3", - "sass": "^1.77.3", - "vue-tsc": "^1.8.27" + "@magnetarjs/core": "workspace:*", + "@magnetarjs/plugin-firestore": "workspace:*", + "@magnetarjs/plugin-vue3": "workspace:*" } } diff --git a/packages/dev-vue3-firestore/src/components/TestFirestorePluginFetch.vue b/packages/dev-vue3-firestore/src/components/TestFirestorePluginFetch.vue index f6d6dc25..2eaa0758 100644 --- a/packages/dev-vue3-firestore/src/components/TestFirestorePluginFetch.vue +++ b/packages/dev-vue3-firestore/src/components/TestFirestorePluginFetch.vue @@ -1,6 +1,6 @@