{"_id":"@dbs-portal/core-store","name":"@dbs-portal/core-store","dist-tags":{"latest":"1.0.0"},"versions":{"1.0.0":{"name":"@dbs-portal/core-store","version":"1.0.0","description":"Global state management with Zustand for DBS Portal","type":"module","main":"dist/index.js","types":"dist/index.d.ts","exports":{".":{"import":"./dist/index.js","types":"./dist/index.d.ts"},"./store":{"import":"./dist/store.js","types":"./dist/store.d.ts"},"./slices":{"import":"./dist/slices.js","types":"./dist/slices.d.ts"},"./hooks":{"import":"./dist/hooks.js","types":"./dist/hooks.d.ts"}},"scripts":{"build":"tsc && vite build","dev":"tsc --watch","test":"vitest run","test:watch":"vitest","test:coverage":"vitest run --coverage","lint":"biome lint src","format":"biome format src --write","type-check":"tsc --noEmit","clean":"rm -rf dist","validate-boundaries":"node ../../../scripts/validate-package-boundaries.js","migrate-build-config":"node ../../tools/build/scripts/migrate-package.mjs","verify-build-config":"node ../../tools/build/scripts/verify-build-config.mjs"},"dependencies":{"@dbs-portal/core-shared":"1.0.0","convict":"^6.2.4","deepmerge":"^4.3.1","zustand":"^5.0.6"},"devDependencies":{"@biomejs/biome":"1.9.4","@dbs-portal/tool-build":"1.0.0","@dbs-portal/tool-testing":"1.0.0","@dbs-portal/tool-tsconfig":"1.0.0","@types/convict":"^6.1.6","@types/deepmerge":"^2.2.3","@types/node":"^22.10.2","typescript":"^5.7.2","vite":"^6.1.0","vitest":"^3.0.5"},"keywords":["state-management","zustand","store","global-state","dbs-portal"],"author":{"name":"DBS Portal Team"},"license":"MIT","repository":{"type":"git","url":"git+https://github.com/your-org/dbs-portal.git","directory":"packages/core/store"},"bugs":{"url":"https://github.com/your-org/dbs-portal/issues"},"homepage":"https://github.com/your-org/dbs-portal#readme","publishConfig":{"access":"public","registry":"https://registry.npmjs.org/"},"_id":"@dbs-portal/core-store@1.0.0","gitHead":"61a23904a481b624f3e8ed7abb6c944ecfeaca7b","_nodeVersion":"20.19.0","_npmVersion":"10.8.2","dist":{"integrity":"sha512-bPa1t0vn4ICxp5tQKH3VIGE63j4alDs8eYJ0ALTizk4cOuJuCBLRjUiLRRKncJTcKqDM3tb+R7CoIVlGhV8wjw==","shasum":"423ee6585bd1ef53127da7377d890b8060d38c84","tarball":"https://registry.npmjs.org/@dbs-portal/core-store/-/core-store-1.0.0.tgz","fileCount":62,"unpackedSize":1678908,"signatures":[{"keyid":"SHA256:DhQ8wR5APBvFHLF/+Tc+AYvPOdTpcIDqOhxsBHRwC7U","sig":"MEUCIQDuYngzJmNhyIBGB2XZR4fW0J5XP5PaSFaCi5qxIR8Q1wIgVwivGok/e+y9OgUo0lU9L4APjCVZexXTKvBnC802DTc="}]},"_npmUser":{"name":"longvq","email":"vqlong1604@gmail.com"},"directories":{},"maintainers":[{"name":"longvq","email":"vqlong1604@gmail.com"}],"_npmOperationalInternal":{"host":"s3://npm-registry-packages-npm-production","tmp":"tmp/core-store_1.0.0_1754218656302_0.5333060016697504"},"_hasShrinkwrap":false}},"time":{"created":"2025-08-03T10:57:36.195Z","1.0.0":"2025-08-03T10:57:36.584Z","modified":"2025-08-03T10:57:36.891Z"},"maintainers":[{"name":"longvq","email":"vqlong1604@gmail.com"}],"description":"Global state management with Zustand for DBS Portal","homepage":"https://github.com/your-org/dbs-portal#readme","keywords":["state-management","zustand","store","global-state","dbs-portal"],"repository":{"type":"git","url":"git+https://github.com/your-org/dbs-portal.git","directory":"packages/core/store"},"author":{"name":"DBS Portal Team"},"bugs":{"url":"https://github.com/your-org/dbs-portal/issues"},"license":"MIT","readme":"# @dbs-portal/core-store\n\nEnhanced global state management with Zustand for DBS Portal, featuring immutable updates with Immer, runtime validation with Zod, and comprehensive middleware support.\n\n## Features\n\n### 🔧 **Core Capabilities**\n- **Zustand-based** state management with TypeScript support\n- **Immer integration** for immutable state updates\n- **Zod validation** for runtime type checking and data integrity\n- **Persistence middleware** with customizable storage options\n- **DevTools integration** for development debugging\n- **Backward compatibility** with existing store implementations\n\n### 🎯 **Enhanced Features**\n- **State validation** with custom error handling\n- **Async action utilities** with automatic loading states\n- **Computed values** (derived state) with memoization\n- **Selector utilities** for optimized component subscriptions\n- **Middleware composition** for extensible functionality\n\n## Installation\n\nThis package is part of the DBS Portal monorepo and includes all necessary dependencies:\n\n```bash\n# Dependencies are automatically managed\nyarn install\n```\n\n## Quick Start\n\n### Basic Enhanced Store\n\n```typescript\nimport { createEnhancedStore } from '@dbs-portal/core-store'\nimport { z } from 'zod'\n\n// Define validation schema\nconst CounterSchema = z.object({\n  count: z.number(),\n  step: z.number().positive()\n})\n\ntype CounterState = z.infer<typeof CounterSchema> & {\n  increment: () => void\n  decrement: () => void\n  setStep: (step: number) => void\n  reset: () => void\n}\n\n// Create enhanced store\nexport const useCounterStore = createEnhancedStore<CounterState>(\n  (set) => ({\n    count: 0,\n    step: 1,\n    \n    // Immer allows direct mutations\n    increment: () => set((state) => {\n      state.count += state.step\n    }),\n    \n    decrement: () => set((state) => {\n      state.count -= state.step\n    }),\n    \n    setStep: (step: number) => set((state) => {\n      state.step = step\n    }),\n    \n    reset: () => set((state) => {\n      state.count = 0\n      state.step = 1\n    })\n  }),\n  {\n    name: 'Counter Store',\n    immer: true,\n    validation: {\n      schema: CounterSchema,\n      enabled: process.env.NODE_ENV === 'development'\n    },\n    persist: {\n      key: 'counter-store',\n      options: {\n        partialize: (state) => ({ count: state.count })\n      }\n    }\n  }\n)\n```\n\n### Using the Enhanced Root Store\n\n```typescript\nimport { useEnhancedStore } from '@dbs-portal/core-store'\n\nfunction MyComponent() {\n  const { \n    theme, \n    setTheme, \n    notifications, \n    success,\n    isLoading \n  } = useEnhancedStore()\n\n  const handleThemeChange = () => {\n    setTheme(theme === 'light' ? 'dark' : 'light')\n  }\n\n  const showNotification = () => {\n    success('Success!', 'Operation completed successfully')\n  }\n\n  return (\n    <div>\n      <button onClick={handleThemeChange}>\n        Current theme: {theme}\n      </button>\n      <button onClick={showNotification}>\n        Show Notification\n      </button>\n      {isLoading && <div>Loading...</div>}\n    </div>\n  )\n}\n```\n\n## Advanced Usage\n\n### State Validation\n\n```typescript\nimport { createEnhancedStore } from '@dbs-portal/core-store'\nimport { z } from 'zod'\n\nconst UserSchema = z.object({\n  id: z.string(),\n  name: z.string().min(1),\n  email: z.string().email(),\n  role: z.enum(['admin', 'user', 'guest'])\n})\n\nconst store = createEnhancedStore(\n  (set) => ({\n    users: [],\n    addUser: (user) => set((state) => {\n      state.users.push(user)\n    })\n  }),\n  {\n    validation: {\n      schema: z.object({\n        users: z.array(UserSchema)\n      }),\n      enabled: true,\n      onError: (error) => {\n        console.error('Validation failed:', error)\n        // Handle validation errors\n      }\n    }\n  }\n)\n```\n\n### Async Actions with Loading States\n\n```typescript\nimport { createAsyncAction } from '@dbs-portal/core-store'\n\nconst useAsyncActions = {\n  fetchData: createAsyncAction(useMyStore, 'fetchData')\n}\n\n// Usage\nconst handleFetch = async () => {\n  await useAsyncActions.fetchData(async () => {\n    const response = await fetch('/api/data')\n    const data = await response.json()\n    \n    useMyStore.getState().setData(data)\n  })\n}\n```\n\n### Computed Values\n\n```typescript\nimport { createComputed } from '@dbs-portal/core-store'\n\nconst useDoubledCount = createComputed(\n  useCounterStore,\n  (state) => state.count * 2\n)\n\nconst useFilteredUsers = createComputed(\n  useUserStore,\n  (state) => state.users.filter(user => user.isActive),\n  (a, b) => a.length === b.length // Custom equality function\n)\n```\n\n### Custom Middleware\n\n```typescript\nimport { createStoreWithMiddleware } from '@dbs-portal/core-store'\n\nconst store = createStoreWithMiddleware(\n  (set, get) => ({\n    // Your state and actions\n  }),\n  {\n    immer: true,\n    persist: {\n      key: 'my-store',\n      options: {\n        version: 1,\n        migrate: (persistedState, version) => {\n          // Handle migrations\n          return persistedState\n        }\n      }\n    },\n    devtools: {\n      name: 'My Store',\n      enabled: process.env.NODE_ENV === 'development'\n    },\n    validation: {\n      schema: MySchema,\n      enabled: true\n    }\n  }\n)\n```\n\n## API Reference\n\n### Core Functions\n\n#### `createEnhancedStore<T>(initializer, options)`\nCreates an enhanced store with middleware support.\n\n**Parameters:**\n- `initializer`: Store state and actions initializer function\n- `options`: Configuration options for middleware\n\n**Options:**\n- `name`: Store name for debugging\n- `immer`: Enable immer middleware (default: true)\n- `persist`: Persistence configuration\n- `devtools`: DevTools configuration\n- `validation`: State validation configuration\n- `middleware`: Custom middleware array\n\n#### `createStoreWithMiddleware<T>(initializer, middlewareConfig)`\nAlternative API for creating stores with middleware configuration.\n\n#### `createEnhancedRootStore(config)`\nCreates the enhanced root store with all application state.\n\n### Utility Functions\n\n#### `createSelectors(useStore)`\nCreates typed selectors for store properties.\n\n#### `createActions(useStore)`\nExtracts action functions from store.\n\n#### `createComputed(useStore, selector, equalityFn?)`\nCreates computed/derived values with memoization.\n\n#### `createAsyncAction(useStore, key)`\nCreates async action wrapper with loading state management.\n\n## Migration Guide\n\n### From Legacy Store\n\nThe enhanced store is fully backward compatible. You can gradually migrate:\n\n```typescript\n// Legacy usage (still works)\nimport { useStore } from '@dbs-portal/core-store'\n\n// Enhanced usage (new features)\nimport { useEnhancedStore } from '@dbs-portal/core-store'\n```\n\n### Adding Validation\n\n```typescript\n// Before\nconst store = createStore(initializer)\n\n// After\nconst store = createEnhancedStore(initializer, {\n  validation: {\n    schema: MySchema,\n    enabled: process.env.NODE_ENV === 'development'\n  }\n})\n```\n\n## Best Practices\n\n1. **Use Immer for Complex Updates**: Leverage immer's draft mutations for cleaner code\n2. **Validate in Development**: Enable validation during development for better DX\n3. **Partition Persistence**: Only persist necessary state to reduce storage usage\n4. **Use Computed Values**: Create derived state with `createComputed` for performance\n5. **Handle Async Actions**: Use `createAsyncAction` for consistent loading states\n\n## TypeScript Support\n\nFull TypeScript support with:\n- Type-safe state and actions\n- Inferred types from Zod schemas\n- Generic store creation\n- Typed selectors and computed values\n\n## Performance\n\n- **Tree-shaking**: Only bundle used middleware\n- **Selective subscriptions**: Use selectors to prevent unnecessary re-renders\n- **Memoized computations**: Computed values are automatically memoized\n- **Optimized persistence**: Configurable state partitioning\n\n## License\n\nMIT - Part of the DBS Portal monorepo.\n","readmeFilename":"README.md","_rev":"1-7020bd80d10bc0d6320a09e70c72659c"}