@noy-db/pinia 0.3.0 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -61,7 +61,9 @@ function defineNoydbStore(id, options) {
61
61
  if (cachedCollection) return cachedCollection;
62
62
  const noydb = resolveNoydb(options.noydb ?? null);
63
63
  cachedCompartment = await noydb.openCompartment(options.compartment);
64
- cachedCollection = cachedCompartment.collection(collectionName);
64
+ const collOpts = {};
65
+ if (options.schema !== void 0) collOpts.schema = options.schema;
66
+ cachedCollection = cachedCompartment.collection(collectionName, collOpts);
65
67
  return cachedCollection;
66
68
  }
67
69
  async function refresh() {
@@ -76,9 +78,8 @@ function defineNoydbStore(id, options) {
76
78
  return void 0;
77
79
  }
78
80
  async function add(id2, record) {
79
- const validated = options.schema ? options.schema.parse(record) : record;
80
81
  const c = await getCollection();
81
- await c.put(id2, validated);
82
+ await c.put(id2, record);
82
83
  items.value = await c.list();
83
84
  }
84
85
  async function update(id2, record) {
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/index.ts","../src/defineNoydbStore.ts","../src/context.ts","../src/plugin.ts"],"sourcesContent":["/**\n * @noy-db/pinia — Pinia integration for noy-db.\n *\n * Two adoption paths:\n *\n * 1. **Greenfield** — `defineNoydbStore<T>(id, options)` creates a new\n * Pinia store fully wired to a NOYDB collection.\n *\n * 2. **Augmentation** — `createNoydbPiniaPlugin(options)` lets existing\n * `defineStore()` stores opt into NOYDB persistence by adding one\n * `noydb:` option, with no component code changes.\n *\n * Plus a global instance binding for both paths:\n * - `setActiveNoydb(instance)` / `getActiveNoydb()` / `resolveNoydb()`\n */\n\nexport { defineNoydbStore } from './defineNoydbStore.js'\nexport type { NoydbStoreOptions, NoydbStore } from './defineNoydbStore.js'\nexport { setActiveNoydb, getActiveNoydb, resolveNoydb } from './context.js'\nexport { createNoydbPiniaPlugin } from './plugin.js'\nexport type { StoreNoydbOptions, NoydbPiniaPluginOptions } from './plugin.js'\n","/**\n * `defineNoydbStore` — drop-in `defineStore` that wires a Pinia store to a\n * NOYDB compartment + collection.\n *\n * Returned store exposes:\n * - `items` — reactive array of all records\n * - `byId(id)` — O(1) lookup\n * - `count` — reactive count getter\n * - `add(id, rec)` — encrypt + persist + update reactive state\n * - `update(id, rec)` — same as add (Collection.put is upsert)\n * - `remove(id)` — delete + update reactive state\n * - `refresh()` — re-hydrate from the adapter\n * - `query()` — chainable query DSL bound to the store\n * - `$ready` — Promise<void> resolved on first hydration\n *\n * Compatible with `storeToRefs`, Vue Devtools, SSR, and pinia plugins.\n */\n\nimport { defineStore } from 'pinia'\nimport { computed, shallowRef, type Ref, type ComputedRef } from 'vue'\nimport type { Noydb, Compartment, Collection, Query } from '@noy-db/core'\nimport { resolveNoydb } from './context.js'\n\n/**\n * Options accepted by `defineNoydbStore`.\n *\n * Generic `T` is the record shape — defaults to `unknown` if the caller\n * doesn't supply a type. Use `defineNoydbStore<Invoice>('invoices', {...})`\n * for full type safety.\n */\nexport interface NoydbStoreOptions<T> {\n /** Compartment (tenant) name. */\n compartment: string\n /** Collection name within the compartment. Defaults to the store id. */\n collection?: string\n /**\n * Optional explicit Noydb instance. If omitted, the store resolves the\n * globally bound instance via `getActiveNoydb()`.\n */\n noydb?: Noydb | null\n /**\n * If true (default), hydration kicks off immediately when the store is\n * first instantiated. If false, hydration is deferred until the first\n * call to `refresh()` or any read accessor.\n */\n prefetch?: boolean\n /**\n * Optional schema validator. Any object exposing a `parse(input): T`\n * method (Zod, Valibot, ArkType, etc.) is accepted.\n */\n schema?: { parse: (input: unknown) => T }\n}\n\n/**\n * The runtime shape of the store returned by `defineNoydbStore`.\n * Exposed as a public type so consumers can write `useStore: ReturnType<typeof useInvoices>`.\n */\nexport interface NoydbStore<T> {\n items: Ref<T[]>\n count: ComputedRef<number>\n $ready: Promise<void>\n byId(id: string): T | undefined\n add(id: string, record: T): Promise<void>\n update(id: string, record: T): Promise<void>\n remove(id: string): Promise<void>\n refresh(): Promise<void>\n query(): Query<T>\n}\n\n/**\n * Define a Pinia store that's wired to a NOYDB collection.\n *\n * Generic T defaults to `unknown` — pass `<MyType>` for full type inference.\n *\n * @example\n * ```ts\n * import { defineNoydbStore } from '@noy-db/pinia';\n *\n * export const useInvoices = defineNoydbStore<Invoice>('invoices', {\n * compartment: 'C101',\n * schema: InvoiceSchema, // optional\n * });\n * ```\n */\nexport function defineNoydbStore<T>(\n id: string,\n options: NoydbStoreOptions<T>,\n) {\n const collectionName = options.collection ?? id\n const prefetch = options.prefetch ?? true\n\n return defineStore(id, () => {\n // Reactive state. shallowRef on items because the array reference is what\n // changes — replacing it triggers reactivity without per-record proxying.\n const items: Ref<T[]> = shallowRef<T[]>([])\n const count = computed(() => items.value.length)\n\n // Lazy collection handle — created on first hydrate.\n let cachedCompartment: Compartment | null = null\n let cachedCollection: Collection<T> | null = null\n\n async function getCollection(): Promise<Collection<T>> {\n if (cachedCollection) return cachedCollection\n const noydb = resolveNoydb(options.noydb ?? null)\n cachedCompartment = await noydb.openCompartment(options.compartment)\n cachedCollection = cachedCompartment.collection<T>(collectionName)\n return cachedCollection\n }\n\n async function refresh(): Promise<void> {\n const c = await getCollection()\n const list = await c.list()\n items.value = list\n }\n\n function byId(id: string): T | undefined {\n // Linear scan against the reactive cache. Index-aware lookups land in #13.\n // Optimization opportunity: maintain a Map<string, T> alongside items.\n for (const item of items.value) {\n if ((item as { id?: string }).id === id) return item\n }\n return undefined\n }\n\n async function add(id: string, record: T): Promise<void> {\n const validated = options.schema ? options.schema.parse(record) : record\n const c = await getCollection()\n await c.put(id, validated)\n // Re-list to pick up the new record. Cheaper alternative would be to\n // splice into items.value directly, but list() ensures consistency\n // with the underlying cache.\n items.value = await c.list()\n }\n\n async function update(id: string, record: T): Promise<void> {\n // Collection.put is upsert; this is just a more readable alias.\n await add(id, record)\n }\n\n async function remove(id: string): Promise<void> {\n const c = await getCollection()\n await c.delete(id)\n items.value = await c.list()\n }\n\n function query(): Query<T> {\n // Synchronous query() requires the collection to be hydrated.\n // The lazy refresh() in $ready handles that — but if the user calls\n // query() before $ready resolves, the collection still works because\n // Collection.query() reads from its own internal cache (which Noydb\n // hydrates lazily as well).\n if (!cachedCollection) {\n throw new Error(\n '@noy-db/pinia: query() called before the store was ready. ' +\n 'Await store.$ready first, or set prefetch: true (default).',\n )\n }\n return cachedCollection.query()\n }\n\n // Kick off hydration. The promise is exposed as $ready so components\n // can `await store.$ready` before rendering data-dependent UI.\n const $ready: Promise<void> = prefetch\n ? refresh()\n : Promise.resolve()\n\n return {\n items,\n count,\n $ready,\n byId,\n add,\n update,\n remove,\n refresh,\n query,\n }\n })\n}\n","/**\n * Active NOYDB instance binding.\n *\n * `defineNoydbStore` resolves the `Noydb` instance from one of three places,\n * in priority order:\n *\n * 1. The store options' explicit `noydb:` field (highest precedence — useful\n * for tests and multi-database apps).\n * 2. A globally bound instance set via `setActiveNoydb()` — this is what the\n * Nuxt module's runtime plugin and playground apps use.\n * 3. Throws a clear error if neither is set.\n *\n * Keeping the binding pluggable means tests can pass an instance directly\n * without polluting global state.\n */\n\nimport type { Noydb } from '@noy-db/core'\n\nlet activeInstance: Noydb | null = null\n\n/** Bind a Noydb instance globally. Called by the Nuxt module / app plugin. */\nexport function setActiveNoydb(instance: Noydb | null): void {\n activeInstance = instance\n}\n\n/** Returns the globally bound Noydb instance, or null if none. */\nexport function getActiveNoydb(): Noydb | null {\n return activeInstance\n}\n\n/**\n * Resolve the Noydb instance to use for a store. Throws if no instance is\n * bound — the error message points the developer at the three options.\n */\nexport function resolveNoydb(explicit?: Noydb | null): Noydb {\n if (explicit) return explicit\n if (activeInstance) return activeInstance\n throw new Error(\n '@noy-db/pinia: no Noydb instance bound.\\n' +\n ' Option A — pass `noydb:` directly to defineNoydbStore({...})\\n' +\n ' Option B — call setActiveNoydb(instance) once at app startup\\n' +\n ' Option C — install the @noy-db/nuxt module (Nuxt 4+)',\n )\n}\n","/**\n * `createNoydbPiniaPlugin` — augmentation path for existing Pinia stores.\n *\n * Lets a developer take any existing `defineStore()` call and opt into NOYDB\n * persistence by adding a single `noydb:` option, without touching component\n * code. The plugin watches the chosen state key(s), encrypts on change, syncs\n * to a NOYDB collection, and rehydrates on store init.\n *\n * @example\n * ```ts\n * import { createPinia } from 'pinia';\n * import { createNoydbPiniaPlugin } from '@noy-db/pinia';\n * import { jsonFile } from '@noy-db/file';\n *\n * const pinia = createPinia();\n * pinia.use(createNoydbPiniaPlugin({\n * adapter: jsonFile({ dir: './data' }),\n * user: 'owner-01',\n * secret: () => promptPassphrase(),\n * }));\n *\n * // existing store — add one option, no component changes:\n * export const useClients = defineStore('clients', {\n * state: () => ({ list: [] as Client[] }),\n * noydb: { compartment: 'C101', collection: 'clients', persist: 'list' },\n * });\n * ```\n *\n * Design notes\n * ------------\n * - Each augmented store persists a SINGLE document at id `__state__`\n * containing the picked keys. We don't try to map state arrays onto\n * per-element records — that's `defineNoydbStore`'s territory.\n * - The Noydb instance is constructed lazily on first store-with-noydb\n * instantiation, then memoized for the lifetime of the Pinia app.\n * This means apps that don't actually use any noydb-augmented stores\n * pay zero crypto cost.\n * - `secret` is a function so the passphrase can come from a prompt,\n * biometric unlock, or session token — never stored in config.\n * - The plugin sets `store.$noydbReady` (a `Promise<void>`) and\n * `store.$noydbError` (an `Error | null`) on every augmented store\n * so components can await hydration and surface failures.\n */\n\nimport type { PiniaPluginContext, PiniaPlugin, StateTree } from 'pinia'\nimport { createNoydb, type Noydb, type NoydbOptions, type NoydbAdapter, type Compartment, type Collection } from '@noy-db/core'\n\n/**\n * Per-store NOYDB configuration. Attached to a Pinia store via the `noydb`\n * option inside `defineStore({ ..., noydb: {...} })`.\n *\n * `persist` selects which top-level state keys to mirror into NOYDB.\n * Pass a single key, an array of keys, or `'*'` to mirror the entire state.\n */\nexport interface StoreNoydbOptions<S extends StateTree = StateTree> {\n /** Compartment (tenant) name. */\n compartment: string\n /** Collection name within the compartment. */\n collection: string\n /**\n * Which state keys to persist. Defaults to `'*'` (the entire state object).\n * Pass a string or string[] to scope to specific keys.\n */\n persist?: keyof S | (keyof S)[] | '*'\n /**\n * Optional schema validator applied at the document level (the persisted\n * subset of state, not individual records). Throws if validation fails on\n * hydration — the store stays at its initial state and `$noydbError` is set.\n */\n schema?: { parse: (input: unknown) => unknown }\n}\n\n/**\n * Configuration for `createNoydbPiniaPlugin`. Mirrors `NoydbOptions` but\n * makes `secret` a function so the passphrase can come from a prompt\n * rather than being stored in config.\n */\nexport interface NoydbPiniaPluginOptions {\n /** The NOYDB adapter to use for persistence. */\n adapter: NoydbAdapter\n /** User identifier (matches the keyring file). */\n user: string\n /**\n * Passphrase provider. Called once on first noydb-augmented store\n * instantiation. Return a string or a Promise that resolves to one.\n */\n secret: () => string | Promise<string>\n /** Optional Noydb open-options forwarded to `createNoydb`. */\n noydbOptions?: Partial<Omit<NoydbOptions, 'adapter' | 'user' | 'secret'>>\n}\n\n// The fixed document id under which a store's persisted state lives. Using a\n// reserved prefix so it can't collide with any user-chosen record id.\nconst STATE_DOC_ID = '__state__'\n\n/**\n * Create a Pinia plugin that wires NOYDB persistence into any store\n * declaring a `noydb:` option.\n *\n * Returns a `PiniaPlugin` directly usable with `pinia.use(...)`.\n */\nexport function createNoydbPiniaPlugin(opts: NoydbPiniaPluginOptions): PiniaPlugin {\n // Single Noydb instance shared across all augmented stores in this Pinia\n // app. Created lazily on first use so apps that never instantiate a\n // noydb-augmented store pay zero crypto cost.\n let dbPromise: Promise<Noydb> | null = null\n function getDb(): Promise<Noydb> {\n if (!dbPromise) {\n dbPromise = (async (): Promise<Noydb> => {\n const secret = await opts.secret()\n return createNoydb({\n adapter: opts.adapter,\n user: opts.user,\n secret,\n ...opts.noydbOptions,\n })\n })()\n }\n return dbPromise\n }\n\n // Compartment cache so opening a compartment is a one-time cost per app.\n const compartmentCache = new Map<string, Promise<Compartment>>()\n function getCompartment(name: string): Promise<Compartment> {\n let p = compartmentCache.get(name)\n if (!p) {\n p = getDb().then((db) => db.openCompartment(name))\n compartmentCache.set(name, p)\n }\n return p\n }\n\n return (context: PiniaPluginContext) => {\n // Pinia stores can declare arbitrary options on `defineStore`, but the\n // plugin context only exposes them via `context.options`. Pull our\n // `noydb` option out and bail early if it's not present — that's\n // the \"store is untouched\" path for non-augmented stores.\n const noydbOption = (context.options as { noydb?: StoreNoydbOptions }).noydb\n if (!noydbOption) {\n // Mark the store as opted-out so devtools / consumers can detect it.\n context.store.$noydbAugmented = false\n return\n }\n\n context.store.$noydbAugmented = true\n context.store.$noydbError = null as Error | null\n\n // Track in-flight persistence promises so tests (and consumers) can\n // await deterministic flushes via `$noydbFlush()`. Plain Set-of-Promises\n // — entries auto-remove on settle.\n const pending = new Set<Promise<void>>()\n\n // Hydrate-then-subscribe. Both happen inside an async closure so the\n // store can be awaited via `$noydbReady`.\n const ready = (async (): Promise<void> => {\n try {\n const compartment = await getCompartment(noydbOption.compartment)\n const collection: Collection<StateTree> = compartment.collection<StateTree>(\n noydbOption.collection,\n )\n\n // 1. Hydration: read the persisted document (if any) and apply\n // the picked keys onto the store's current state. We use\n // `$patch` so reactivity fires correctly.\n const persisted = await collection.get(STATE_DOC_ID)\n if (persisted) {\n const validated = noydbOption.schema\n ? (noydbOption.schema.parse(persisted) as StateTree)\n : persisted\n const picked = pickKeys(validated, noydbOption.persist)\n context.store.$patch(picked)\n }\n\n // 2. Subscribe: every state mutation triggers an encrypted write\n // of the picked subset back to NOYDB. The subscription captures\n // `collection` so it doesn't re-resolve on every event.\n context.store.$subscribe(\n (_mutation, state) => {\n const subset = pickKeys(state, noydbOption.persist)\n const p = collection.put(STATE_DOC_ID, subset)\n .catch((err: unknown) => {\n context.store.$noydbError = err instanceof Error ? err : new Error(String(err))\n })\n .finally(() => {\n pending.delete(p)\n })\n pending.add(p)\n },\n { detached: true }, // outlive the component that triggered the mutation\n )\n } catch (err) {\n context.store.$noydbError = err instanceof Error ? err : new Error(String(err))\n }\n })()\n\n context.store.$noydbReady = ready\n /**\n * Wait for all in-flight persistence puts to settle. Use this in tests\n * to deterministically observe the encrypted state on the adapter, and\n * in app code before unmounting components that mutated the store.\n */\n context.store.$noydbFlush = async (): Promise<void> => {\n await ready\n // Snapshot the current pending set; new puts added during await\n // are picked up by the next $noydbFlush() call.\n while (pending.size > 0) {\n await Promise.all([...pending])\n }\n }\n }\n}\n\n/**\n * Pick the configured subset of keys from a state object.\n *\n * Behaviors:\n * - `undefined` or `'*'` → returns the entire state shallow-copied\n * - single key string → returns `{ [key]: state[key] }`\n * - key array → returns `{ [k1]: state[k1], [k2]: state[k2], ... }`\n *\n * The result is always a fresh object so callers can mutate it without\n * touching the store's reactive state.\n */\nfunction pickKeys(state: StateTree, persist: StoreNoydbOptions['persist']): StateTree {\n if (persist === undefined || persist === '*') {\n return { ...state }\n }\n if (typeof persist === 'string') {\n return { [persist]: state[persist] } as StateTree\n }\n if (Array.isArray(persist)) {\n const out: StateTree = {}\n for (const key of persist) {\n out[key as string] = state[key as string]\n }\n return out\n }\n // Should be unreachable thanks to the type, but defensive default.\n return { ...state }\n}\n\n// ─── Pinia module augmentation ─────────────────────────────────────\n//\n// Pinia exposes `DefineStoreOptionsBase` as the place where third-party\n// plugins are expected to attach their custom option types. Augmenting it\n// here means `defineStore('x', { ..., noydb: {...} })` autocompletes inside\n// the IDE and type-checks correctly without forcing users to import\n// anything from `@noy-db/pinia`.\n//\n// We also augment `PiniaCustomProperties` so the runtime fields we add to\n// every store (`$noydbReady`, `$noydbError`, `$noydbAugmented`) are typed.\n\ndeclare module 'pinia' {\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n export interface DefineStoreOptionsBase<S extends StateTree, Store> {\n /**\n * Opt this store into NOYDB persistence via the\n * `createNoydbPiniaPlugin` augmentation plugin.\n *\n * The chosen state keys are encrypted and persisted to the configured\n * compartment + collection on every mutation, and rehydrated on first\n * store access.\n */\n noydb?: StoreNoydbOptions<S>\n }\n\n export interface PiniaCustomProperties {\n /**\n * Resolves once this store has finished its initial hydration from\n * NOYDB. `undefined` for stores that don't declare a `noydb:` option.\n */\n $noydbReady?: Promise<void>\n /**\n * Set when hydration or persistence fails. `null` while healthy.\n * Plugins (and devtools) can poll this to surface storage errors.\n */\n $noydbError?: Error | null\n /**\n * `true` if this store opted into NOYDB persistence via the `noydb:`\n * option, `false` otherwise. Useful for debugging and devtools.\n */\n $noydbAugmented?: boolean\n /**\n * Wait for all in-flight encrypted persistence puts to complete.\n * Useful in tests for deterministic flushing, and in app code before\n * unmounting components that just mutated the store.\n */\n $noydbFlush?: () => Promise<void>\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACkBA,mBAA4B;AAC5B,iBAAiE;;;ACDjE,IAAI,iBAA+B;AAG5B,SAAS,eAAe,UAA8B;AAC3D,mBAAiB;AACnB;AAGO,SAAS,iBAA+B;AAC7C,SAAO;AACT;AAMO,SAAS,aAAa,UAAgC;AAC3D,MAAI,SAAU,QAAO;AACrB,MAAI,eAAgB,QAAO;AAC3B,QAAM,IAAI;AAAA,IACR;AAAA,EAIF;AACF;;;ADyCO,SAAS,iBACd,IACA,SACA;AACA,QAAM,iBAAiB,QAAQ,cAAc;AAC7C,QAAM,WAAW,QAAQ,YAAY;AAErC,aAAO,0BAAY,IAAI,MAAM;AAG3B,UAAM,YAAkB,uBAAgB,CAAC,CAAC;AAC1C,UAAM,YAAQ,qBAAS,MAAM,MAAM,MAAM,MAAM;AAG/C,QAAI,oBAAwC;AAC5C,QAAI,mBAAyC;AAE7C,mBAAe,gBAAwC;AACrD,UAAI,iBAAkB,QAAO;AAC7B,YAAM,QAAQ,aAAa,QAAQ,SAAS,IAAI;AAChD,0BAAoB,MAAM,MAAM,gBAAgB,QAAQ,WAAW;AACnE,yBAAmB,kBAAkB,WAAc,cAAc;AACjE,aAAO;AAAA,IACT;AAEA,mBAAe,UAAyB;AACtC,YAAM,IAAI,MAAM,cAAc;AAC9B,YAAM,OAAO,MAAM,EAAE,K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;AAAA,UACA,EAAE,UAAU,KAAK;AAAA;AAAA,QACnB;AAAA,MACF,SAAS,KAAK;AACZ,gBAAQ,MAAM,cAAc,eAAe,QAAQ,MAAM,IAAI,MAAM,OAAO,GAAG,CAAC;AAAA,MAChF;AAAA,IACF,GAAG;AAEH,YAAQ,MAAM,cAAc;AAM5B,YAAQ,MAAM,cAAc,YAA2B;AACrD,YAAM;AAGN,aAAO,QAAQ,OAAO,GAAG;AACvB,cAAM,QAAQ,IAAI,CAAC,GAAG,OAAO,CAAC;AAAA,MAChC;AAAA,IACF;AAAA,EACF;AACF;AAaA,SAAS,SAAS,OAAkB,SAAkD;AACpF,MAAI,YAAY,UAAa,YAAY,KAAK;AAC5C,WAAO,EAAE,GAAG,MAAM;AAAA,EACpB;AACA,MAAI,OAAO,YAAY,UAAU;AAC/B,WAAO,EAAE,CAAC,OAAO,GAAG,MAAM,OAAO,EAAE;AAAA,EACrC;AACA,MAAI,MAAM,QAAQ,OAAO,GAAG;AAC1B,UAAM,MAAiB,CAAC;AACxB,eAAW,OAAO,SAAS;AACzB,UAAI,GAAa,IAAI,MAAM,GAAa;AAAA,IAC1C;AACA,WAAO;AAAA,EACT;AAEA,SAAO,EAAE,GAAG,MAAM;AACpB;","names":["id"]}
1
+ {"version":3,"sources":["../src/index.ts","../src/defineNoydbStore.ts","../src/context.ts","../src/plugin.ts"],"sourcesContent":["/**\n * @noy-db/pinia — Pinia integration for noy-db.\n *\n * Two adoption paths:\n *\n * 1. **Greenfield** — `defineNoydbStore<T>(id, options)` creates a new\n * Pinia store fully wired to a NOYDB collection.\n *\n * 2. **Augmentation** — `createNoydbPiniaPlugin(options)` lets existing\n * `defineStore()` stores opt into NOYDB persistence by adding one\n * `noydb:` option, with no component code changes.\n *\n * Plus a global instance binding for both paths:\n * - `setActiveNoydb(instance)` / `getActiveNoydb()` / `resolveNoydb()`\n */\n\nexport { defineNoydbStore } from './defineNoydbStore.js'\nexport type { NoydbStoreOptions, NoydbStore } from './defineNoydbStore.js'\nexport { setActiveNoydb, getActiveNoydb, resolveNoydb } from './context.js'\nexport { createNoydbPiniaPlugin } from './plugin.js'\nexport type { StoreNoydbOptions, NoydbPiniaPluginOptions } from './plugin.js'\n","/**\n * `defineNoydbStore` — drop-in `defineStore` that wires a Pinia store to a\n * NOYDB compartment + collection.\n *\n * Returned store exposes:\n * - `items` — reactive array of all records\n * - `byId(id)` — O(1) lookup\n * - `count` — reactive count getter\n * - `add(id, rec)` — encrypt + persist + update reactive state\n * - `update(id, rec)` — same as add (Collection.put is upsert)\n * - `remove(id)` — delete + update reactive state\n * - `refresh()` — re-hydrate from the adapter\n * - `query()` — chainable query DSL bound to the store\n * - `$ready` — Promise<void> resolved on first hydration\n *\n * Compatible with `storeToRefs`, Vue Devtools, SSR, and pinia plugins.\n */\n\nimport { defineStore } from 'pinia'\nimport { computed, shallowRef, type Ref, type ComputedRef } from 'vue'\nimport type {\n Noydb,\n Compartment,\n Collection,\n Query,\n StandardSchemaV1,\n} from '@noy-db/core'\nimport { resolveNoydb } from './context.js'\n\n/**\n * Options accepted by `defineNoydbStore`.\n *\n * Generic `T` is the record shape — defaults to `unknown` if the caller\n * doesn't supply a type. Use `defineNoydbStore<Invoice>('invoices', {...})`\n * for full type safety.\n */\nexport interface NoydbStoreOptions<T> {\n /** Compartment (tenant) name. */\n compartment: string\n /** Collection name within the compartment. Defaults to the store id. */\n collection?: string\n /**\n * Optional explicit Noydb instance. If omitted, the store resolves the\n * globally bound instance via `getActiveNoydb()`.\n */\n noydb?: Noydb | null\n /**\n * If true (default), hydration kicks off immediately when the store is\n * first instantiated. If false, hydration is deferred until the first\n * call to `refresh()` or any read accessor.\n */\n prefetch?: boolean\n /**\n * Optional schema validator.\n *\n * Accepts any [Standard Schema v1](https://standardschema.dev) validator\n * — Zod, Valibot, ArkType, Effect Schema, etc. The same validator is\n * installed on the underlying `Collection`, so every `put()` is\n * validated **before encryption** and every read is validated **after\n * decryption**. The store's `add`/`update` methods inherit this\n * validation automatically; no duplicate `.parse()` call is needed.\n *\n * Schema-less stores behave exactly as before (no validation, no\n * perf cost, backwards compatible with v0.3 usage).\n */\n schema?: StandardSchemaV1<unknown, T>\n}\n\n/**\n * The runtime shape of the store returned by `defineNoydbStore`.\n * Exposed as a public type so consumers can write `useStore: ReturnType<typeof useInvoices>`.\n */\nexport interface NoydbStore<T> {\n items: Ref<T[]>\n count: ComputedRef<number>\n $ready: Promise<void>\n byId(id: string): T | undefined\n add(id: string, record: T): Promise<void>\n update(id: string, record: T): Promise<void>\n remove(id: string): Promise<void>\n refresh(): Promise<void>\n query(): Query<T>\n}\n\n/**\n * Define a Pinia store that's wired to a NOYDB collection.\n *\n * Generic T defaults to `unknown` — pass `<MyType>` for full type inference.\n *\n * @example\n * ```ts\n * import { defineNoydbStore } from '@noy-db/pinia';\n *\n * export const useInvoices = defineNoydbStore<Invoice>('invoices', {\n * compartment: 'C101',\n * schema: InvoiceSchema, // optional\n * });\n * ```\n */\nexport function defineNoydbStore<T>(\n id: string,\n options: NoydbStoreOptions<T>,\n) {\n const collectionName = options.collection ?? id\n const prefetch = options.prefetch ?? true\n\n return defineStore(id, () => {\n // Reactive state. shallowRef on items because the array reference is what\n // changes — replacing it triggers reactivity without per-record proxying.\n const items: Ref<T[]> = shallowRef<T[]>([])\n const count = computed(() => items.value.length)\n\n // Lazy collection handle — created on first hydrate.\n let cachedCompartment: Compartment | null = null\n let cachedCollection: Collection<T> | null = null\n\n async function getCollection(): Promise<Collection<T>> {\n if (cachedCollection) return cachedCollection\n const noydb = resolveNoydb(options.noydb ?? null)\n cachedCompartment = await noydb.openCompartment(options.compartment)\n // Pass the schema down to the Collection so validation runs at\n // the encrypt/decrypt boundary instead of only at the store\n // layer. This catches drifted stored data on read (which the\n // old `options.schema.parse(record)` call in add() could not do).\n const collOpts: Parameters<typeof cachedCompartment.collection<T>>[1] = {}\n if (options.schema !== undefined) collOpts.schema = options.schema\n cachedCollection = cachedCompartment.collection<T>(collectionName, collOpts)\n return cachedCollection\n }\n\n async function refresh(): Promise<void> {\n const c = await getCollection()\n const list = await c.list()\n items.value = list\n }\n\n function byId(id: string): T | undefined {\n // Linear scan against the reactive cache. Index-aware lookups land in #13.\n // Optimization opportunity: maintain a Map<string, T> alongside items.\n for (const item of items.value) {\n if ((item as { id?: string }).id === id) return item\n }\n return undefined\n }\n\n async function add(id: string, record: T): Promise<void> {\n // No explicit validation here — the Collection's own schema hook\n // runs before encryption, which means we get validation AND\n // transforms applied consistently across every code path that\n // writes to the collection (add/update/remove, future batch\n // operations, raw Collection.put calls). Users who want to\n // pre-validate in the UI layer can still do so with their own\n // schema handle.\n const c = await getCollection()\n await c.put(id, record)\n // Re-list to pick up the new record. Cheaper alternative would be to\n // splice into items.value directly, but list() ensures consistency\n // with the underlying cache.\n items.value = await c.list()\n }\n\n async function update(id: string, record: T): Promise<void> {\n // Collection.put is upsert; this is just a more readable alias.\n await add(id, record)\n }\n\n async function remove(id: string): Promise<void> {\n const c = await getCollection()\n await c.delete(id)\n items.value = await c.list()\n }\n\n function query(): Query<T> {\n // Synchronous query() requires the collection to be hydrated.\n // The lazy refresh() in $ready handles that — but if the user calls\n // query() before $ready resolves, the collection still works because\n // Collection.query() reads from its own internal cache (which Noydb\n // hydrates lazily as well).\n if (!cachedCollection) {\n throw new Error(\n '@noy-db/pinia: query() called before the store was ready. ' +\n 'Await store.$ready first, or set prefetch: true (default).',\n )\n }\n return cachedCollection.query()\n }\n\n // Kick off hydration. The promise is exposed as $ready so components\n // can `await store.$ready` before rendering data-dependent UI.\n const $ready: Promise<void> = prefetch\n ? refresh()\n : Promise.resolve()\n\n return {\n items,\n count,\n $ready,\n byId,\n add,\n update,\n remove,\n refresh,\n query,\n }\n })\n}\n","/**\n * Active NOYDB instance binding.\n *\n * `defineNoydbStore` resolves the `Noydb` instance from one of three places,\n * in priority order:\n *\n * 1. The store options' explicit `noydb:` field (highest precedence — useful\n * for tests and multi-database apps).\n * 2. A globally bound instance set via `setActiveNoydb()` — this is what the\n * Nuxt module's runtime plugin and playground apps use.\n * 3. Throws a clear error if neither is set.\n *\n * Keeping the binding pluggable means tests can pass an instance directly\n * without polluting global state.\n */\n\nimport type { Noydb } from '@noy-db/core'\n\nlet activeInstance: Noydb | null = null\n\n/** Bind a Noydb instance globally. Called by the Nuxt module / app plugin. */\nexport function setActiveNoydb(instance: Noydb | null): void {\n activeInstance = instance\n}\n\n/** Returns the globally bound Noydb instance, or null if none. */\nexport function getActiveNoydb(): Noydb | null {\n return activeInstance\n}\n\n/**\n * Resolve the Noydb instance to use for a store. Throws if no instance is\n * bound — the error message points the developer at the three options.\n */\nexport function resolveNoydb(explicit?: Noydb | null): Noydb {\n if (explicit) return explicit\n if (activeInstance) return activeInstance\n throw new Error(\n '@noy-db/pinia: no Noydb instance bound.\\n' +\n ' Option A — pass `noydb:` directly to defineNoydbStore({...})\\n' +\n ' Option B — call setActiveNoydb(instance) once at app startup\\n' +\n ' Option C — install the @noy-db/nuxt module (Nuxt 4+)',\n )\n}\n","/**\n * `createNoydbPiniaPlugin` — augmentation path for existing Pinia stores.\n *\n * Lets a developer take any existing `defineStore()` call and opt into NOYDB\n * persistence by adding a single `noydb:` option, without touching component\n * code. The plugin watches the chosen state key(s), encrypts on change, syncs\n * to a NOYDB collection, and rehydrates on store init.\n *\n * @example\n * ```ts\n * import { createPinia } from 'pinia';\n * import { createNoydbPiniaPlugin } from '@noy-db/pinia';\n * import { jsonFile } from '@noy-db/file';\n *\n * const pinia = createPinia();\n * pinia.use(createNoydbPiniaPlugin({\n * adapter: jsonFile({ dir: './data' }),\n * user: 'owner-01',\n * secret: () => promptPassphrase(),\n * }));\n *\n * // existing store — add one option, no component changes:\n * export const useClients = defineStore('clients', {\n * state: () => ({ list: [] as Client[] }),\n * noydb: { compartment: 'C101', collection: 'clients', persist: 'list' },\n * });\n * ```\n *\n * Design notes\n * ------------\n * - Each augmented store persists a SINGLE document at id `__state__`\n * containing the picked keys. We don't try to map state arrays onto\n * per-element records — that's `defineNoydbStore`'s territory.\n * - The Noydb instance is constructed lazily on first store-with-noydb\n * instantiation, then memoized for the lifetime of the Pinia app.\n * This means apps that don't actually use any noydb-augmented stores\n * pay zero crypto cost.\n * - `secret` is a function so the passphrase can come from a prompt,\n * biometric unlock, or session token — never stored in config.\n * - The plugin sets `store.$noydbReady` (a `Promise<void>`) and\n * `store.$noydbError` (an `Error | null`) on every augmented store\n * so components can await hydration and surface failures.\n */\n\nimport type { PiniaPluginContext, PiniaPlugin, StateTree } from 'pinia'\nimport { createNoydb, type Noydb, type NoydbOptions, type NoydbAdapter, type Compartment, type Collection } from '@noy-db/core'\n\n/**\n * Per-store NOYDB configuration. Attached to a Pinia store via the `noydb`\n * option inside `defineStore({ ..., noydb: {...} })`.\n *\n * `persist` selects which top-level state keys to mirror into NOYDB.\n * Pass a single key, an array of keys, or `'*'` to mirror the entire state.\n */\nexport interface StoreNoydbOptions<S extends StateTree = StateTree> {\n /** Compartment (tenant) name. */\n compartment: string\n /** Collection name within the compartment. */\n collection: string\n /**\n * Which state keys to persist. Defaults to `'*'` (the entire state object).\n * Pass a string or string[] to scope to specific keys.\n */\n persist?: keyof S | (keyof S)[] | '*'\n /**\n * Optional schema validator applied at the document level (the persisted\n * subset of state, not individual records). Throws if validation fails on\n * hydration — the store stays at its initial state and `$noydbError` is set.\n */\n schema?: { parse: (input: unknown) => unknown }\n}\n\n/**\n * Configuration for `createNoydbPiniaPlugin`. Mirrors `NoydbOptions` but\n * makes `secret` a function so the passphrase can come from a prompt\n * rather than being stored in config.\n */\nexport interface NoydbPiniaPluginOptions {\n /** The NOYDB adapter to use for persistence. */\n adapter: NoydbAdapter\n /** User identifier (matches the keyring file). */\n user: string\n /**\n * Passphrase provider. Called once on first noydb-augmented store\n * instantiation. Return a string or a Promise that resolves to one.\n */\n secret: () => string | Promise<string>\n /** Optional Noydb open-options forwarded to `createNoydb`. */\n noydbOptions?: Partial<Omit<NoydbOptions, 'adapter' | 'user' | 'secret'>>\n}\n\n// The fixed document id under which a store's persisted state lives. Using a\n// reserved prefix so it can't collide with any user-chosen record id.\nconst STATE_DOC_ID = '__state__'\n\n/**\n * Create a Pinia plugin that wires NOYDB persistence into any store\n * declaring a `noydb:` option.\n *\n * Returns a `PiniaPlugin` directly usable with `pinia.use(...)`.\n */\nexport function createNoydbPiniaPlugin(opts: NoydbPiniaPluginOptions): PiniaPlugin {\n // Single Noydb instance shared across all augmented stores in this Pinia\n // app. Created lazily on first use so apps that never instantiate a\n // noydb-augmented store pay zero crypto cost.\n let dbPromise: Promise<Noydb> | null = null\n function getDb(): Promise<Noydb> {\n if (!dbPromise) {\n dbPromise = (async (): Promise<Noydb> => {\n const secret = await opts.secret()\n return createNoydb({\n adapter: opts.adapter,\n user: opts.user,\n secret,\n ...opts.noydbOptions,\n })\n })()\n }\n return dbPromise\n }\n\n // Compartment cache so opening a compartment is a one-time cost per app.\n const compartmentCache = new Map<string, Promise<Compartment>>()\n function getCompartment(name: string): Promise<Compartment> {\n let p = compartmentCache.get(name)\n if (!p) {\n p = getDb().then((db) => db.openCompartment(name))\n compartmentCache.set(name, p)\n }\n return p\n }\n\n return (context: PiniaPluginContext) => {\n // Pinia stores can declare arbitrary options on `defineStore`, but the\n // plugin context only exposes them via `context.options`. Pull our\n // `noydb` option out and bail early if it's not present — that's\n // the \"store is untouched\" path for non-augmented stores.\n const noydbOption = (context.options as { noydb?: StoreNoydbOptions }).noydb\n if (!noydbOption) {\n // Mark the store as opted-out so devtools / consumers can detect it.\n context.store.$noydbAugmented = false\n return\n }\n\n context.store.$noydbAugmented = true\n context.store.$noydbError = null as Error | null\n\n // Track in-flight persistence promises so tests (and consumers) can\n // await deterministic flushes via `$noydbFlush()`. Plain Set-of-Promises\n // — entries auto-remove on settle.\n const pending = new Set<Promise<void>>()\n\n // Hydrate-then-subscribe. Both happen inside an async closure so the\n // store can be awaited via `$noydbReady`.\n const ready = (async (): Promise<void> => {\n try {\n const compartment = await getCompartment(noydbOption.compartment)\n const collection: Collection<StateTree> = compartment.collection<StateTree>(\n noydbOption.collection,\n )\n\n // 1. Hydration: read the persisted document (if any) and apply\n // the picked keys onto the store's current state. We use\n // `$patch` so reactivity fires correctly.\n const persisted = await collection.get(STATE_DOC_ID)\n if (persisted) {\n const validated = noydbOption.schema\n ? (noydbOption.schema.parse(persisted) as StateTree)\n : persisted\n const picked = pickKeys(validated, noydbOption.persist)\n context.store.$patch(picked)\n }\n\n // 2. Subscribe: every state mutation triggers an encrypted write\n // of the picked subset back to NOYDB. The subscription captures\n // `collection` so it doesn't re-resolve on every event.\n context.store.$subscribe(\n (_mutation, state) => {\n const subset = pickKeys(state, noydbOption.persist)\n const p = collection.put(STATE_DOC_ID, subset)\n .catch((err: unknown) => {\n context.store.$noydbError = err instanceof Error ? err : new Error(String(err))\n })\n .finally(() => {\n pending.delete(p)\n })\n pending.add(p)\n },\n { detached: true }, // outlive the component that triggered the mutation\n )\n } catch (err) {\n context.store.$noydbError = err instanceof Error ? err : new Error(String(err))\n }\n })()\n\n context.store.$noydbReady = ready\n /**\n * Wait for all in-flight persistence puts to settle. Use this in tests\n * to deterministically observe the encrypted state on the adapter, and\n * in app code before unmounting components that mutated the store.\n */\n context.store.$noydbFlush = async (): Promise<void> => {\n await ready\n // Snapshot the current pending set; new puts added during await\n // are picked up by the next $noydbFlush() call.\n while (pending.size > 0) {\n await Promise.all([...pending])\n }\n }\n }\n}\n\n/**\n * Pick the configured subset of keys from a state object.\n *\n * Behaviors:\n * - `undefined` or `'*'` → returns the entire state shallow-copied\n * - single key string → returns `{ [key]: state[key] }`\n * - key array → returns `{ [k1]: state[k1], [k2]: state[k2], ... }`\n *\n * The result is always a fresh object so callers can mutate it without\n * touching the store's reactive state.\n */\nfunction pickKeys(state: StateTree, persist: StoreNoydbOptions['persist']): StateTree {\n if (persist === undefined || persist === '*') {\n return { ...state }\n }\n if (typeof persist === 'string') {\n return { [persist]: state[persist] } as StateTree\n }\n if (Array.isArray(persist)) {\n const out: StateTree = {}\n for (const key of persist) {\n out[key as string] = state[key as string]\n }\n return out\n }\n // Should be unreachable thanks to the type, but defensive default.\n return { ...state }\n}\n\n// ─── Pinia module augmentation ─────────────────────────────────────\n//\n// Pinia exposes `DefineStoreOptionsBase` as the place where third-party\n// plugins are expected to attach their custom option types. Augmenting it\n// here means `defineStore('x', { ..., noydb: {...} })` autocompletes inside\n// the IDE and type-checks correctly without forcing users to import\n// anything from `@noy-db/pinia`.\n//\n// We also augment `PiniaCustomProperties` so the runtime fields we add to\n// every store (`$noydbReady`, `$noydbError`, `$noydbAugmented`) are typed.\n\ndeclare module 'pinia' {\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n export interface DefineStoreOptionsBase<S extends StateTree, Store> {\n /**\n * Opt this store into NOYDB persistence via the\n * `createNoydbPiniaPlugin` augmentation plugin.\n *\n * The chosen state keys are encrypted and persisted to the configured\n * compartment + collection on every mutation, and rehydrated on first\n * store access.\n */\n noydb?: StoreNoydbOptions<S>\n }\n\n export interface PiniaCustomProperties {\n /**\n * Resolves once this store has finished its initial hydration from\n * NOYDB. `undefined` for stores that don't declare a `noydb:` option.\n */\n $noydbReady?: Promise<void>\n /**\n * Set when hydration or persistence fails. `null` while healthy.\n * Plugins (and devtools) can poll this to surface storage errors.\n */\n $noydbError?: Error | null\n /**\n * `true` if this store opted into NOYDB persistence via the `noydb:`\n * option, `false` otherwise. Useful for debugging and devtools.\n */\n $noydbAugmented?: boolean\n /**\n * Wait for all in-flight encrypted persistence puts to complete.\n * Useful in tests for deterministic flushing, and in app code before\n * unmounting components that just mutated the store.\n */\n $noydbFlush?: () => Promise<void>\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACkBA,mBAA4B;AAC5B,iBAAiE;;;ACDjE,IAAI,iBAA+B;AAG5B,SAAS,eAAe,UAA8B;AAC3D,mBAAiB;AACnB;AAGO,SAAS,iBAA+B;AAC7C,SAAO;AACT;AAMO,SAAS,aAAa,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AO,EAAE;AAAA,EACrC;AACA,MAAI,MAAM,QAAQ,OAAO,GAAG;AAC1B,UAAM,MAAiB,CAAC;AACxB,eAAW,OAAO,SAAS;AACzB,UAAI,GAAa,IAAI,MAAM,GAAa;AAAA,IAC1C;AACA,WAAO;AAAA,EACT;AAEA,SAAO,EAAE,GAAG,MAAM;AACpB;","names":["id"]}
package/dist/index.d.cts CHANGED
@@ -1,7 +1,7 @@
1
1
  import * as pinia from 'pinia';
2
2
  import { StateTree, PiniaPlugin } from 'pinia';
3
3
  import { Ref, ComputedRef } from 'vue';
4
- import { Query, Noydb, NoydbAdapter, NoydbOptions } from '@noy-db/core';
4
+ import { Query, Noydb, StandardSchemaV1, NoydbAdapter, NoydbOptions } from '@noy-db/core';
5
5
 
6
6
  /**
7
7
  * Options accepted by `defineNoydbStore`.
@@ -27,12 +27,19 @@ interface NoydbStoreOptions<T> {
27
27
  */
28
28
  prefetch?: boolean;
29
29
  /**
30
- * Optional schema validator. Any object exposing a `parse(input): T`
31
- * method (Zod, Valibot, ArkType, etc.) is accepted.
30
+ * Optional schema validator.
31
+ *
32
+ * Accepts any [Standard Schema v1](https://standardschema.dev) validator
33
+ * — Zod, Valibot, ArkType, Effect Schema, etc. The same validator is
34
+ * installed on the underlying `Collection`, so every `put()` is
35
+ * validated **before encryption** and every read is validated **after
36
+ * decryption**. The store's `add`/`update` methods inherit this
37
+ * validation automatically; no duplicate `.parse()` call is needed.
38
+ *
39
+ * Schema-less stores behave exactly as before (no validation, no
40
+ * perf cost, backwards compatible with v0.3 usage).
32
41
  */
33
- schema?: {
34
- parse: (input: unknown) => T;
35
- };
42
+ schema?: StandardSchemaV1<unknown, T>;
36
43
  }
37
44
  /**
38
45
  * The runtime shape of the store returned by `defineNoydbStore`.
package/dist/index.d.ts CHANGED
@@ -1,7 +1,7 @@
1
1
  import * as pinia from 'pinia';
2
2
  import { StateTree, PiniaPlugin } from 'pinia';
3
3
  import { Ref, ComputedRef } from 'vue';
4
- import { Query, Noydb, NoydbAdapter, NoydbOptions } from '@noy-db/core';
4
+ import { Query, Noydb, StandardSchemaV1, NoydbAdapter, NoydbOptions } from '@noy-db/core';
5
5
 
6
6
  /**
7
7
  * Options accepted by `defineNoydbStore`.
@@ -27,12 +27,19 @@ interface NoydbStoreOptions<T> {
27
27
  */
28
28
  prefetch?: boolean;
29
29
  /**
30
- * Optional schema validator. Any object exposing a `parse(input): T`
31
- * method (Zod, Valibot, ArkType, etc.) is accepted.
30
+ * Optional schema validator.
31
+ *
32
+ * Accepts any [Standard Schema v1](https://standardschema.dev) validator
33
+ * — Zod, Valibot, ArkType, Effect Schema, etc. The same validator is
34
+ * installed on the underlying `Collection`, so every `put()` is
35
+ * validated **before encryption** and every read is validated **after
36
+ * decryption**. The store's `add`/`update` methods inherit this
37
+ * validation automatically; no duplicate `.parse()` call is needed.
38
+ *
39
+ * Schema-less stores behave exactly as before (no validation, no
40
+ * perf cost, backwards compatible with v0.3 usage).
32
41
  */
33
- schema?: {
34
- parse: (input: unknown) => T;
35
- };
42
+ schema?: StandardSchemaV1<unknown, T>;
36
43
  }
37
44
  /**
38
45
  * The runtime shape of the store returned by `defineNoydbStore`.
package/dist/index.js CHANGED
@@ -31,7 +31,9 @@ function defineNoydbStore(id, options) {
31
31
  if (cachedCollection) return cachedCollection;
32
32
  const noydb = resolveNoydb(options.noydb ?? null);
33
33
  cachedCompartment = await noydb.openCompartment(options.compartment);
34
- cachedCollection = cachedCompartment.collection(collectionName);
34
+ const collOpts = {};
35
+ if (options.schema !== void 0) collOpts.schema = options.schema;
36
+ cachedCollection = cachedCompartment.collection(collectionName, collOpts);
35
37
  return cachedCollection;
36
38
  }
37
39
  async function refresh() {
@@ -46,9 +48,8 @@ function defineNoydbStore(id, options) {
46
48
  return void 0;
47
49
  }
48
50
  async function add(id2, record) {
49
- const validated = options.schema ? options.schema.parse(record) : record;
50
51
  const c = await getCollection();
51
- await c.put(id2, validated);
52
+ await c.put(id2, record);
52
53
  items.value = await c.list();
53
54
  }
54
55
  async function update(id2, record) {
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/defineNoydbStore.ts","../src/context.ts","../src/plugin.ts"],"sourcesContent":["/**\n * `defineNoydbStore` — drop-in `defineStore` that wires a Pinia store to a\n * NOYDB compartment + collection.\n *\n * Returned store exposes:\n * - `items` — reactive array of all records\n * - `byId(id)` — O(1) lookup\n * - `count` — reactive count getter\n * - `add(id, rec)` — encrypt + persist + update reactive state\n * - `update(id, rec)` — same as add (Collection.put is upsert)\n * - `remove(id)` — delete + update reactive state\n * - `refresh()` — re-hydrate from the adapter\n * - `query()` — chainable query DSL bound to the store\n * - `$ready` — Promise<void> resolved on first hydration\n *\n * Compatible with `storeToRefs`, Vue Devtools, SSR, and pinia plugins.\n */\n\nimport { defineStore } from 'pinia'\nimport { computed, shallowRef, type Ref, type ComputedRef } from 'vue'\nimport type { Noydb, Compartment, Collection, Query } from '@noy-db/core'\nimport { resolveNoydb } from './context.js'\n\n/**\n * Options accepted by `defineNoydbStore`.\n *\n * Generic `T` is the record shape — defaults to `unknown` if the caller\n * doesn't supply a type. Use `defineNoydbStore<Invoice>('invoices', {...})`\n * for full type safety.\n */\nexport interface NoydbStoreOptions<T> {\n /** Compartment (tenant) name. */\n compartment: string\n /** Collection name within the compartment. Defaults to the store id. */\n collection?: string\n /**\n * Optional explicit Noydb instance. If omitted, the store resolves the\n * globally bound instance via `getActiveNoydb()`.\n */\n noydb?: Noydb | null\n /**\n * If true (default), hydration kicks off immediately when the store is\n * first instantiated. If false, hydration is deferred until the first\n * call to `refresh()` or any read accessor.\n */\n prefetch?: boolean\n /**\n * Optional schema validator. Any object exposing a `parse(input): T`\n * method (Zod, Valibot, ArkType, etc.) is accepted.\n */\n schema?: { parse: (input: unknown) => T }\n}\n\n/**\n * The runtime shape of the store returned by `defineNoydbStore`.\n * Exposed as a public type so consumers can write `useStore: ReturnType<typeof useInvoices>`.\n */\nexport interface NoydbStore<T> {\n items: Ref<T[]>\n count: ComputedRef<number>\n $ready: Promise<void>\n byId(id: string): T | undefined\n add(id: string, record: T): Promise<void>\n update(id: string, record: T): Promise<void>\n remove(id: string): Promise<void>\n refresh(): Promise<void>\n query(): Query<T>\n}\n\n/**\n * Define a Pinia store that's wired to a NOYDB collection.\n *\n * Generic T defaults to `unknown` — pass `<MyType>` for full type inference.\n *\n * @example\n * ```ts\n * import { defineNoydbStore } from '@noy-db/pinia';\n *\n * export const useInvoices = defineNoydbStore<Invoice>('invoices', {\n * compartment: 'C101',\n * schema: InvoiceSchema, // optional\n * });\n * ```\n */\nexport function defineNoydbStore<T>(\n id: string,\n options: NoydbStoreOptions<T>,\n) {\n const collectionName = options.collection ?? id\n const prefetch = options.prefetch ?? true\n\n return defineStore(id, () => {\n // Reactive state. shallowRef on items because the array reference is what\n // changes — replacing it triggers reactivity without per-record proxying.\n const items: Ref<T[]> = shallowRef<T[]>([])\n const count = computed(() => items.value.length)\n\n // Lazy collection handle — created on first hydrate.\n let cachedCompartment: Compartment | null = null\n let cachedCollection: Collection<T> | null = null\n\n async function getCollection(): Promise<Collection<T>> {\n if (cachedCollection) return cachedCollection\n const noydb = resolveNoydb(options.noydb ?? null)\n cachedCompartment = await noydb.openCompartment(options.compartment)\n cachedCollection = cachedCompartment.collection<T>(collectionName)\n return cachedCollection\n }\n\n async function refresh(): Promise<void> {\n const c = await getCollection()\n const list = await c.list()\n items.value = list\n }\n\n function byId(id: string): T | undefined {\n // Linear scan against the reactive cache. Index-aware lookups land in #13.\n // Optimization opportunity: maintain a Map<string, T> alongside items.\n for (const item of items.value) {\n if ((item as { id?: string }).id === id) return item\n }\n return undefined\n }\n\n async function add(id: string, record: T): Promise<void> {\n const validated = options.schema ? options.schema.parse(record) : record\n const c = await getCollection()\n await c.put(id, validated)\n // Re-list to pick up the new record. Cheaper alternative would be to\n // splice into items.value directly, but list() ensures consistency\n // with the underlying cache.\n items.value = await c.list()\n }\n\n async function update(id: string, record: T): Promise<void> {\n // Collection.put is upsert; this is just a more readable alias.\n await add(id, record)\n }\n\n async function remove(id: string): Promise<void> {\n const c = await getCollection()\n await c.delete(id)\n items.value = await c.list()\n }\n\n function query(): Query<T> {\n // Synchronous query() requires the collection to be hydrated.\n // The lazy refresh() in $ready handles that — but if the user calls\n // query() before $ready resolves, the collection still works because\n // Collection.query() reads from its own internal cache (which Noydb\n // hydrates lazily as well).\n if (!cachedCollection) {\n throw new Error(\n '@noy-db/pinia: query() called before the store was ready. ' +\n 'Await store.$ready first, or set prefetch: true (default).',\n )\n }\n return cachedCollection.query()\n }\n\n // Kick off hydration. The promise is exposed as $ready so components\n // can `await store.$ready` before rendering data-dependent UI.\n const $ready: Promise<void> = prefetch\n ? refresh()\n : Promise.resolve()\n\n return {\n items,\n count,\n $ready,\n byId,\n add,\n update,\n remove,\n refresh,\n query,\n }\n })\n}\n","/**\n * Active NOYDB instance binding.\n *\n * `defineNoydbStore` resolves the `Noydb` instance from one of three places,\n * in priority order:\n *\n * 1. The store options' explicit `noydb:` field (highest precedence — useful\n * for tests and multi-database apps).\n * 2. A globally bound instance set via `setActiveNoydb()` — this is what the\n * Nuxt module's runtime plugin and playground apps use.\n * 3. Throws a clear error if neither is set.\n *\n * Keeping the binding pluggable means tests can pass an instance directly\n * without polluting global state.\n */\n\nimport type { Noydb } from '@noy-db/core'\n\nlet activeInstance: Noydb | null = null\n\n/** Bind a Noydb instance globally. Called by the Nuxt module / app plugin. */\nexport function setActiveNoydb(instance: Noydb | null): void {\n activeInstance = instance\n}\n\n/** Returns the globally bound Noydb instance, or null if none. */\nexport function getActiveNoydb(): Noydb | null {\n return activeInstance\n}\n\n/**\n * Resolve the Noydb instance to use for a store. Throws if no instance is\n * bound — the error message points the developer at the three options.\n */\nexport function resolveNoydb(explicit?: Noydb | null): Noydb {\n if (explicit) return explicit\n if (activeInstance) return activeInstance\n throw new Error(\n '@noy-db/pinia: no Noydb instance bound.\\n' +\n ' Option A — pass `noydb:` directly to defineNoydbStore({...})\\n' +\n ' Option B — call setActiveNoydb(instance) once at app startup\\n' +\n ' Option C — install the @noy-db/nuxt module (Nuxt 4+)',\n )\n}\n","/**\n * `createNoydbPiniaPlugin` — augmentation path for existing Pinia stores.\n *\n * Lets a developer take any existing `defineStore()` call and opt into NOYDB\n * persistence by adding a single `noydb:` option, without touching component\n * code. The plugin watches the chosen state key(s), encrypts on change, syncs\n * to a NOYDB collection, and rehydrates on store init.\n *\n * @example\n * ```ts\n * import { createPinia } from 'pinia';\n * import { createNoydbPiniaPlugin } from '@noy-db/pinia';\n * import { jsonFile } from '@noy-db/file';\n *\n * const pinia = createPinia();\n * pinia.use(createNoydbPiniaPlugin({\n * adapter: jsonFile({ dir: './data' }),\n * user: 'owner-01',\n * secret: () => promptPassphrase(),\n * }));\n *\n * // existing store — add one option, no component changes:\n * export const useClients = defineStore('clients', {\n * state: () => ({ list: [] as Client[] }),\n * noydb: { compartment: 'C101', collection: 'clients', persist: 'list' },\n * });\n * ```\n *\n * Design notes\n * ------------\n * - Each augmented store persists a SINGLE document at id `__state__`\n * containing the picked keys. We don't try to map state arrays onto\n * per-element records — that's `defineNoydbStore`'s territory.\n * - The Noydb instance is constructed lazily on first store-with-noydb\n * instantiation, then memoized for the lifetime of the Pinia app.\n * This means apps that don't actually use any noydb-augmented stores\n * pay zero crypto cost.\n * - `secret` is a function so the passphrase can come from a prompt,\n * biometric unlock, or session token — never stored in config.\n * - The plugin sets `store.$noydbReady` (a `Promise<void>`) and\n * `store.$noydbError` (an `Error | null`) on every augmented store\n * so components can await hydration and surface failures.\n */\n\nimport type { PiniaPluginContext, PiniaPlugin, StateTree } from 'pinia'\nimport { createNoydb, type Noydb, type NoydbOptions, type NoydbAdapter, type Compartment, type Collection } from '@noy-db/core'\n\n/**\n * Per-store NOYDB configuration. Attached to a Pinia store via the `noydb`\n * option inside `defineStore({ ..., noydb: {...} })`.\n *\n * `persist` selects which top-level state keys to mirror into NOYDB.\n * Pass a single key, an array of keys, or `'*'` to mirror the entire state.\n */\nexport interface StoreNoydbOptions<S extends StateTree = StateTree> {\n /** Compartment (tenant) name. */\n compartment: string\n /** Collection name within the compartment. */\n collection: string\n /**\n * Which state keys to persist. Defaults to `'*'` (the entire state object).\n * Pass a string or string[] to scope to specific keys.\n */\n persist?: keyof S | (keyof S)[] | '*'\n /**\n * Optional schema validator applied at the document level (the persisted\n * subset of state, not individual records). Throws if validation fails on\n * hydration — the store stays at its initial state and `$noydbError` is set.\n */\n schema?: { parse: (input: unknown) => unknown }\n}\n\n/**\n * Configuration for `createNoydbPiniaPlugin`. Mirrors `NoydbOptions` but\n * makes `secret` a function so the passphrase can come from a prompt\n * rather than being stored in config.\n */\nexport interface NoydbPiniaPluginOptions {\n /** The NOYDB adapter to use for persistence. */\n adapter: NoydbAdapter\n /** User identifier (matches the keyring file). */\n user: string\n /**\n * Passphrase provider. Called once on first noydb-augmented store\n * instantiation. Return a string or a Promise that resolves to one.\n */\n secret: () => string | Promise<string>\n /** Optional Noydb open-options forwarded to `createNoydb`. */\n noydbOptions?: Partial<Omit<NoydbOptions, 'adapter' | 'user' | 'secret'>>\n}\n\n// The fixed document id under which a store's persisted state lives. Using a\n// reserved prefix so it can't collide with any user-chosen record id.\nconst STATE_DOC_ID = '__state__'\n\n/**\n * Create a Pinia plugin that wires NOYDB persistence into any store\n * declaring a `noydb:` option.\n *\n * Returns a `PiniaPlugin` directly usable with `pinia.use(...)`.\n */\nexport function createNoydbPiniaPlugin(opts: NoydbPiniaPluginOptions): PiniaPlugin {\n // Single Noydb instance shared across all augmented stores in this Pinia\n // app. Created lazily on first use so apps that never instantiate a\n // noydb-augmented store pay zero crypto cost.\n let dbPromise: Promise<Noydb> | null = null\n function getDb(): Promise<Noydb> {\n if (!dbPromise) {\n dbPromise = (async (): Promise<Noydb> => {\n const secret = await opts.secret()\n return createNoydb({\n adapter: opts.adapter,\n user: opts.user,\n secret,\n ...opts.noydbOptions,\n })\n })()\n }\n return dbPromise\n }\n\n // Compartment cache so opening a compartment is a one-time cost per app.\n const compartmentCache = new Map<string, Promise<Compartment>>()\n function getCompartment(name: string): Promise<Compartment> {\n let p = compartmentCache.get(name)\n if (!p) {\n p = getDb().then((db) => db.openCompartment(name))\n compartmentCache.set(name, p)\n }\n return p\n }\n\n return (context: PiniaPluginContext) => {\n // Pinia stores can declare arbitrary options on `defineStore`, but the\n // plugin context only exposes them via `context.options`. Pull our\n // `noydb` option out and bail early if it's not present — that's\n // the \"store is untouched\" path for non-augmented stores.\n const noydbOption = (context.options as { noydb?: StoreNoydbOptions }).noydb\n if (!noydbOption) {\n // Mark the store as opted-out so devtools / consumers can detect it.\n context.store.$noydbAugmented = false\n return\n }\n\n context.store.$noydbAugmented = true\n context.store.$noydbError = null as Error | null\n\n // Track in-flight persistence promises so tests (and consumers) can\n // await deterministic flushes via `$noydbFlush()`. Plain Set-of-Promises\n // — entries auto-remove on settle.\n const pending = new Set<Promise<void>>()\n\n // Hydrate-then-subscribe. Both happen inside an async closure so the\n // store can be awaited via `$noydbReady`.\n const ready = (async (): Promise<void> => {\n try {\n const compartment = await getCompartment(noydbOption.compartment)\n const collection: Collection<StateTree> = compartment.collection<StateTree>(\n noydbOption.collection,\n )\n\n // 1. Hydration: read the persisted document (if any) and apply\n // the picked keys onto the store's current state. We use\n // `$patch` so reactivity fires correctly.\n const persisted = await collection.get(STATE_DOC_ID)\n if (persisted) {\n const validated = noydbOption.schema\n ? (noydbOption.schema.parse(persisted) as StateTree)\n : persisted\n const picked = pickKeys(validated, noydbOption.persist)\n context.store.$patch(picked)\n }\n\n // 2. Subscribe: every state mutation triggers an encrypted write\n // of the picked subset back to NOYDB. The subscription captures\n // `collection` so it doesn't re-resolve on every event.\n context.store.$subscribe(\n (_mutation, state) => {\n const subset = pickKeys(state, noydbOption.persist)\n const p = collection.put(STATE_DOC_ID, subset)\n .catch((err: unknown) => {\n context.store.$noydbError = err instanceof Error ? err : new Error(String(err))\n })\n .finally(() => {\n pending.delete(p)\n })\n pending.add(p)\n },\n { detached: true }, // outlive the component that triggered the mutation\n )\n } catch (err) {\n context.store.$noydbError = err instanceof Error ? err : new Error(String(err))\n }\n })()\n\n context.store.$noydbReady = ready\n /**\n * Wait for all in-flight persistence puts to settle. Use this in tests\n * to deterministically observe the encrypted state on the adapter, and\n * in app code before unmounting components that mutated the store.\n */\n context.store.$noydbFlush = async (): Promise<void> => {\n await ready\n // Snapshot the current pending set; new puts added during await\n // are picked up by the next $noydbFlush() call.\n while (pending.size > 0) {\n await Promise.all([...pending])\n }\n }\n }\n}\n\n/**\n * Pick the configured subset of keys from a state object.\n *\n * Behaviors:\n * - `undefined` or `'*'` → returns the entire state shallow-copied\n * - single key string → returns `{ [key]: state[key] }`\n * - key array → returns `{ [k1]: state[k1], [k2]: state[k2], ... }`\n *\n * The result is always a fresh object so callers can mutate it without\n * touching the store's reactive state.\n */\nfunction pickKeys(state: StateTree, persist: StoreNoydbOptions['persist']): StateTree {\n if (persist === undefined || persist === '*') {\n return { ...state }\n }\n if (typeof persist === 'string') {\n return { [persist]: state[persist] } as StateTree\n }\n if (Array.isArray(persist)) {\n const out: StateTree = {}\n for (const key of persist) {\n out[key as string] = state[key as string]\n }\n return out\n }\n // Should be unreachable thanks to the type, but defensive default.\n return { ...state }\n}\n\n// ─── Pinia module augmentation ─────────────────────────────────────\n//\n// Pinia exposes `DefineStoreOptionsBase` as the place where third-party\n// plugins are expected to attach their custom option types. Augmenting it\n// here means `defineStore('x', { ..., noydb: {...} })` autocompletes inside\n// the IDE and type-checks correctly without forcing users to import\n// anything from `@noy-db/pinia`.\n//\n// We also augment `PiniaCustomProperties` so the runtime fields we add to\n// every store (`$noydbReady`, `$noydbError`, `$noydbAugmented`) are typed.\n\ndeclare module 'pinia' {\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n export interface DefineStoreOptionsBase<S extends StateTree, Store> {\n /**\n * Opt this store into NOYDB persistence via the\n * `createNoydbPiniaPlugin` augmentation plugin.\n *\n * The chosen state keys are encrypted and persisted to the configured\n * compartment + collection on every mutation, and rehydrated on first\n * store access.\n */\n noydb?: StoreNoydbOptions<S>\n }\n\n export interface PiniaCustomProperties {\n /**\n * Resolves once this store has finished its initial hydration from\n * NOYDB. `undefined` for stores that don't declare a `noydb:` option.\n */\n $noydbReady?: Promise<void>\n /**\n * Set when hydration or persistence fails. `null` while healthy.\n * Plugins (and devtools) can poll this to surface storage errors.\n */\n $noydbError?: Error | null\n /**\n * `true` if this store opted into NOYDB persistence via the `noydb:`\n * option, `false` otherwise. Useful for debugging and devtools.\n */\n $noydbAugmented?: boolean\n /**\n * Wait for all in-flight encrypted persistence puts to complete.\n * Useful in tests for deterministic flushing, and in app code before\n * unmounting components that just mutated the store.\n */\n $noydbFlush?: () => Promise<void>\n }\n}\n"],"mappings":";AAkBA,SAAS,mBAAmB;AAC5B,SAAS,UAAU,kBAA8C;;;ACDjE,IAAI,iBAA+B;AAG5B,SAAS,eAAe,UAA8B;AAC3D,mBAAiB;AACnB;AAGO,SAAS,iBAA+B;AAC7C,SAAO;AACT;AAMO,SAAS,aAAa,UAAgC;AAC3D,MAAI,SAAU,QAAO;AACrB,MAAI,eAAgB,QAAO;AAC3B,QAAM,IAAI;AAAA,IACR;AAAA,EAIF;AACF;;;ADyCO,SAAS,iBACd,IACA,SACA;AACA,QAAM,iBAAiB,QAAQ,cAAc;AAC7C,QAAM,WAAW,QAAQ,YAAY;AAErC,SAAO,YAAY,IAAI,MAAM;AAG3B,UAAM,QAAkB,WAAgB,CAAC,CAAC;AAC1C,UAAM,QAAQ,SAAS,MAAM,MAAM,MAAM,MAAM;AAG/C,QAAI,oBAAwC;AAC5C,QAAI,mBAAyC;AAE7C,mBAAe,gBAAwC;AACrD,UAAI,iBAAkB,QAAO;AAC7B,YAAM,QAAQ,aAAa,QAAQ,SAAS,IAAI;AAChD,0BAAoB,MAAM,MAAM,gBAAgB,QAAQ,WAAW;AACnE,yBAAmB,kBAAkB,WAAc,cAAc;AACjE,aAAO;AAAA,IACT;AAEA,mBAAe,UAAyB;AACtC,YAAM,IAAI,M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YAClB,CAAC;AACH,oBAAQ,IAAI,CAAC;AAAA,UACf;AAAA,UACA,EAAE,UAAU,KAAK;AAAA;AAAA,QACnB;AAAA,MACF,SAAS,KAAK;AACZ,gBAAQ,MAAM,cAAc,eAAe,QAAQ,MAAM,IAAI,MAAM,OAAO,GAAG,CAAC;AAAA,MAChF;AAAA,IACF,GAAG;AAEH,YAAQ,MAAM,cAAc;AAM5B,YAAQ,MAAM,cAAc,YAA2B;AACrD,YAAM;AAGN,aAAO,QAAQ,OAAO,GAAG;AACvB,cAAM,QAAQ,IAAI,CAAC,GAAG,OAAO,CAAC;AAAA,MAChC;AAAA,IACF;AAAA,EACF;AACF;AAaA,SAAS,SAAS,OAAkB,SAAkD;AACpF,MAAI,YAAY,UAAa,YAAY,KAAK;AAC5C,WAAO,EAAE,GAAG,MAAM;AAAA,EACpB;AACA,MAAI,OAAO,YAAY,UAAU;AAC/B,WAAO,EAAE,CAAC,OAAO,GAAG,MAAM,OAAO,EAAE;AAAA,EACrC;AACA,MAAI,MAAM,QAAQ,OAAO,GAAG;AAC1B,UAAM,MAAiB,CAAC;AACxB,eAAW,OAAO,SAAS;AACzB,UAAI,GAAa,IAAI,MAAM,GAAa;AAAA,IAC1C;AACA,WAAO;AAAA,EACT;AAEA,SAAO,EAAE,GAAG,MAAM;AACpB;","names":["id"]}
1
+ {"version":3,"sources":["../src/defineNoydbStore.ts","../src/context.ts","../src/plugin.ts"],"sourcesContent":["/**\n * `defineNoydbStore` — drop-in `defineStore` that wires a Pinia store to a\n * NOYDB compartment + collection.\n *\n * Returned store exposes:\n * - `items` — reactive array of all records\n * - `byId(id)` — O(1) lookup\n * - `count` — reactive count getter\n * - `add(id, rec)` — encrypt + persist + update reactive state\n * - `update(id, rec)` — same as add (Collection.put is upsert)\n * - `remove(id)` — delete + update reactive state\n * - `refresh()` — re-hydrate from the adapter\n * - `query()` — chainable query DSL bound to the store\n * - `$ready` — Promise<void> resolved on first hydration\n *\n * Compatible with `storeToRefs`, Vue Devtools, SSR, and pinia plugins.\n */\n\nimport { defineStore } from 'pinia'\nimport { computed, shallowRef, type Ref, type ComputedRef } from 'vue'\nimport type {\n Noydb,\n Compartment,\n Collection,\n Query,\n StandardSchemaV1,\n} from '@noy-db/core'\nimport { resolveNoydb } from './context.js'\n\n/**\n * Options accepted by `defineNoydbStore`.\n *\n * Generic `T` is the record shape — defaults to `unknown` if the caller\n * doesn't supply a type. Use `defineNoydbStore<Invoice>('invoices', {...})`\n * for full type safety.\n */\nexport interface NoydbStoreOptions<T> {\n /** Compartment (tenant) name. */\n compartment: string\n /** Collection name within the compartment. Defaults to the store id. */\n collection?: string\n /**\n * Optional explicit Noydb instance. If omitted, the store resolves the\n * globally bound instance via `getActiveNoydb()`.\n */\n noydb?: Noydb | null\n /**\n * If true (default), hydration kicks off immediately when the store is\n * first instantiated. If false, hydration is deferred until the first\n * call to `refresh()` or any read accessor.\n */\n prefetch?: boolean\n /**\n * Optional schema validator.\n *\n * Accepts any [Standard Schema v1](https://standardschema.dev) validator\n * — Zod, Valibot, ArkType, Effect Schema, etc. The same validator is\n * installed on the underlying `Collection`, so every `put()` is\n * validated **before encryption** and every read is validated **after\n * decryption**. The store's `add`/`update` methods inherit this\n * validation automatically; no duplicate `.parse()` call is needed.\n *\n * Schema-less stores behave exactly as before (no validation, no\n * perf cost, backwards compatible with v0.3 usage).\n */\n schema?: StandardSchemaV1<unknown, T>\n}\n\n/**\n * The runtime shape of the store returned by `defineNoydbStore`.\n * Exposed as a public type so consumers can write `useStore: ReturnType<typeof useInvoices>`.\n */\nexport interface NoydbStore<T> {\n items: Ref<T[]>\n count: ComputedRef<number>\n $ready: Promise<void>\n byId(id: string): T | undefined\n add(id: string, record: T): Promise<void>\n update(id: string, record: T): Promise<void>\n remove(id: string): Promise<void>\n refresh(): Promise<void>\n query(): Query<T>\n}\n\n/**\n * Define a Pinia store that's wired to a NOYDB collection.\n *\n * Generic T defaults to `unknown` — pass `<MyType>` for full type inference.\n *\n * @example\n * ```ts\n * import { defineNoydbStore } from '@noy-db/pinia';\n *\n * export const useInvoices = defineNoydbStore<Invoice>('invoices', {\n * compartment: 'C101',\n * schema: InvoiceSchema, // optional\n * });\n * ```\n */\nexport function defineNoydbStore<T>(\n id: string,\n options: NoydbStoreOptions<T>,\n) {\n const collectionName = options.collection ?? id\n const prefetch = options.prefetch ?? true\n\n return defineStore(id, () => {\n // Reactive state. shallowRef on items because the array reference is what\n // changes — replacing it triggers reactivity without per-record proxying.\n const items: Ref<T[]> = shallowRef<T[]>([])\n const count = computed(() => items.value.length)\n\n // Lazy collection handle — created on first hydrate.\n let cachedCompartment: Compartment | null = null\n let cachedCollection: Collection<T> | null = null\n\n async function getCollection(): Promise<Collection<T>> {\n if (cachedCollection) return cachedCollection\n const noydb = resolveNoydb(options.noydb ?? null)\n cachedCompartment = await noydb.openCompartment(options.compartment)\n // Pass the schema down to the Collection so validation runs at\n // the encrypt/decrypt boundary instead of only at the store\n // layer. This catches drifted stored data on read (which the\n // old `options.schema.parse(record)` call in add() could not do).\n const collOpts: Parameters<typeof cachedCompartment.collection<T>>[1] = {}\n if (options.schema !== undefined) collOpts.schema = options.schema\n cachedCollection = cachedCompartment.collection<T>(collectionName, collOpts)\n return cachedCollection\n }\n\n async function refresh(): Promise<void> {\n const c = await getCollection()\n const list = await c.list()\n items.value = list\n }\n\n function byId(id: string): T | undefined {\n // Linear scan against the reactive cache. Index-aware lookups land in #13.\n // Optimization opportunity: maintain a Map<string, T> alongside items.\n for (const item of items.value) {\n if ((item as { id?: string }).id === id) return item\n }\n return undefined\n }\n\n async function add(id: string, record: T): Promise<void> {\n // No explicit validation here — the Collection's own schema hook\n // runs before encryption, which means we get validation AND\n // transforms applied consistently across every code path that\n // writes to the collection (add/update/remove, future batch\n // operations, raw Collection.put calls). Users who want to\n // pre-validate in the UI layer can still do so with their own\n // schema handle.\n const c = await getCollection()\n await c.put(id, record)\n // Re-list to pick up the new record. Cheaper alternative would be to\n // splice into items.value directly, but list() ensures consistency\n // with the underlying cache.\n items.value = await c.list()\n }\n\n async function update(id: string, record: T): Promise<void> {\n // Collection.put is upsert; this is just a more readable alias.\n await add(id, record)\n }\n\n async function remove(id: string): Promise<void> {\n const c = await getCollection()\n await c.delete(id)\n items.value = await c.list()\n }\n\n function query(): Query<T> {\n // Synchronous query() requires the collection to be hydrated.\n // The lazy refresh() in $ready handles that — but if the user calls\n // query() before $ready resolves, the collection still works because\n // Collection.query() reads from its own internal cache (which Noydb\n // hydrates lazily as well).\n if (!cachedCollection) {\n throw new Error(\n '@noy-db/pinia: query() called before the store was ready. ' +\n 'Await store.$ready first, or set prefetch: true (default).',\n )\n }\n return cachedCollection.query()\n }\n\n // Kick off hydration. The promise is exposed as $ready so components\n // can `await store.$ready` before rendering data-dependent UI.\n const $ready: Promise<void> = prefetch\n ? refresh()\n : Promise.resolve()\n\n return {\n items,\n count,\n $ready,\n byId,\n add,\n update,\n remove,\n refresh,\n query,\n }\n })\n}\n","/**\n * Active NOYDB instance binding.\n *\n * `defineNoydbStore` resolves the `Noydb` instance from one of three places,\n * in priority order:\n *\n * 1. The store options' explicit `noydb:` field (highest precedence — useful\n * for tests and multi-database apps).\n * 2. A globally bound instance set via `setActiveNoydb()` — this is what the\n * Nuxt module's runtime plugin and playground apps use.\n * 3. Throws a clear error if neither is set.\n *\n * Keeping the binding pluggable means tests can pass an instance directly\n * without polluting global state.\n */\n\nimport type { Noydb } from '@noy-db/core'\n\nlet activeInstance: Noydb | null = null\n\n/** Bind a Noydb instance globally. Called by the Nuxt module / app plugin. */\nexport function setActiveNoydb(instance: Noydb | null): void {\n activeInstance = instance\n}\n\n/** Returns the globally bound Noydb instance, or null if none. */\nexport function getActiveNoydb(): Noydb | null {\n return activeInstance\n}\n\n/**\n * Resolve the Noydb instance to use for a store. Throws if no instance is\n * bound — the error message points the developer at the three options.\n */\nexport function resolveNoydb(explicit?: Noydb | null): Noydb {\n if (explicit) return explicit\n if (activeInstance) return activeInstance\n throw new Error(\n '@noy-db/pinia: no Noydb instance bound.\\n' +\n ' Option A — pass `noydb:` directly to defineNoydbStore({...})\\n' +\n ' Option B — call setActiveNoydb(instance) once at app startup\\n' +\n ' Option C — install the @noy-db/nuxt module (Nuxt 4+)',\n )\n}\n","/**\n * `createNoydbPiniaPlugin` — augmentation path for existing Pinia stores.\n *\n * Lets a developer take any existing `defineStore()` call and opt into NOYDB\n * persistence by adding a single `noydb:` option, without touching component\n * code. The plugin watches the chosen state key(s), encrypts on change, syncs\n * to a NOYDB collection, and rehydrates on store init.\n *\n * @example\n * ```ts\n * import { createPinia } from 'pinia';\n * import { createNoydbPiniaPlugin } from '@noy-db/pinia';\n * import { jsonFile } from '@noy-db/file';\n *\n * const pinia = createPinia();\n * pinia.use(createNoydbPiniaPlugin({\n * adapter: jsonFile({ dir: './data' }),\n * user: 'owner-01',\n * secret: () => promptPassphrase(),\n * }));\n *\n * // existing store — add one option, no component changes:\n * export const useClients = defineStore('clients', {\n * state: () => ({ list: [] as Client[] }),\n * noydb: { compartment: 'C101', collection: 'clients', persist: 'list' },\n * });\n * ```\n *\n * Design notes\n * ------------\n * - Each augmented store persists a SINGLE document at id `__state__`\n * containing the picked keys. We don't try to map state arrays onto\n * per-element records — that's `defineNoydbStore`'s territory.\n * - The Noydb instance is constructed lazily on first store-with-noydb\n * instantiation, then memoized for the lifetime of the Pinia app.\n * This means apps that don't actually use any noydb-augmented stores\n * pay zero crypto cost.\n * - `secret` is a function so the passphrase can come from a prompt,\n * biometric unlock, or session token — never stored in config.\n * - The plugin sets `store.$noydbReady` (a `Promise<void>`) and\n * `store.$noydbError` (an `Error | null`) on every augmented store\n * so components can await hydration and surface failures.\n */\n\nimport type { PiniaPluginContext, PiniaPlugin, StateTree } from 'pinia'\nimport { createNoydb, type Noydb, type NoydbOptions, type NoydbAdapter, type Compartment, type Collection } from '@noy-db/core'\n\n/**\n * Per-store NOYDB configuration. Attached to a Pinia store via the `noydb`\n * option inside `defineStore({ ..., noydb: {...} })`.\n *\n * `persist` selects which top-level state keys to mirror into NOYDB.\n * Pass a single key, an array of keys, or `'*'` to mirror the entire state.\n */\nexport interface StoreNoydbOptions<S extends StateTree = StateTree> {\n /** Compartment (tenant) name. */\n compartment: string\n /** Collection name within the compartment. */\n collection: string\n /**\n * Which state keys to persist. Defaults to `'*'` (the entire state object).\n * Pass a string or string[] to scope to specific keys.\n */\n persist?: keyof S | (keyof S)[] | '*'\n /**\n * Optional schema validator applied at the document level (the persisted\n * subset of state, not individual records). Throws if validation fails on\n * hydration — the store stays at its initial state and `$noydbError` is set.\n */\n schema?: { parse: (input: unknown) => unknown }\n}\n\n/**\n * Configuration for `createNoydbPiniaPlugin`. Mirrors `NoydbOptions` but\n * makes `secret` a function so the passphrase can come from a prompt\n * rather than being stored in config.\n */\nexport interface NoydbPiniaPluginOptions {\n /** The NOYDB adapter to use for persistence. */\n adapter: NoydbAdapter\n /** User identifier (matches the keyring file). */\n user: string\n /**\n * Passphrase provider. Called once on first noydb-augmented store\n * instantiation. Return a string or a Promise that resolves to one.\n */\n secret: () => string | Promise<string>\n /** Optional Noydb open-options forwarded to `createNoydb`. */\n noydbOptions?: Partial<Omit<NoydbOptions, 'adapter' | 'user' | 'secret'>>\n}\n\n// The fixed document id under which a store's persisted state lives. Using a\n// reserved prefix so it can't collide with any user-chosen record id.\nconst STATE_DOC_ID = '__state__'\n\n/**\n * Create a Pinia plugin that wires NOYDB persistence into any store\n * declaring a `noydb:` option.\n *\n * Returns a `PiniaPlugin` directly usable with `pinia.use(...)`.\n */\nexport function createNoydbPiniaPlugin(opts: NoydbPiniaPluginOptions): PiniaPlugin {\n // Single Noydb instance shared across all augmented stores in this Pinia\n // app. Created lazily on first use so apps that never instantiate a\n // noydb-augmented store pay zero crypto cost.\n let dbPromise: Promise<Noydb> | null = null\n function getDb(): Promise<Noydb> {\n if (!dbPromise) {\n dbPromise = (async (): Promise<Noydb> => {\n const secret = await opts.secret()\n return createNoydb({\n adapter: opts.adapter,\n user: opts.user,\n secret,\n ...opts.noydbOptions,\n })\n })()\n }\n return dbPromise\n }\n\n // Compartment cache so opening a compartment is a one-time cost per app.\n const compartmentCache = new Map<string, Promise<Compartment>>()\n function getCompartment(name: string): Promise<Compartment> {\n let p = compartmentCache.get(name)\n if (!p) {\n p = getDb().then((db) => db.openCompartment(name))\n compartmentCache.set(name, p)\n }\n return p\n }\n\n return (context: PiniaPluginContext) => {\n // Pinia stores can declare arbitrary options on `defineStore`, but the\n // plugin context only exposes them via `context.options`. Pull our\n // `noydb` option out and bail early if it's not present — that's\n // the \"store is untouched\" path for non-augmented stores.\n const noydbOption = (context.options as { noydb?: StoreNoydbOptions }).noydb\n if (!noydbOption) {\n // Mark the store as opted-out so devtools / consumers can detect it.\n context.store.$noydbAugmented = false\n return\n }\n\n context.store.$noydbAugmented = true\n context.store.$noydbError = null as Error | null\n\n // Track in-flight persistence promises so tests (and consumers) can\n // await deterministic flushes via `$noydbFlush()`. Plain Set-of-Promises\n // — entries auto-remove on settle.\n const pending = new Set<Promise<void>>()\n\n // Hydrate-then-subscribe. Both happen inside an async closure so the\n // store can be awaited via `$noydbReady`.\n const ready = (async (): Promise<void> => {\n try {\n const compartment = await getCompartment(noydbOption.compartment)\n const collection: Collection<StateTree> = compartment.collection<StateTree>(\n noydbOption.collection,\n )\n\n // 1. Hydration: read the persisted document (if any) and apply\n // the picked keys onto the store's current state. We use\n // `$patch` so reactivity fires correctly.\n const persisted = await collection.get(STATE_DOC_ID)\n if (persisted) {\n const validated = noydbOption.schema\n ? (noydbOption.schema.parse(persisted) as StateTree)\n : persisted\n const picked = pickKeys(validated, noydbOption.persist)\n context.store.$patch(picked)\n }\n\n // 2. Subscribe: every state mutation triggers an encrypted write\n // of the picked subset back to NOYDB. The subscription captures\n // `collection` so it doesn't re-resolve on every event.\n context.store.$subscribe(\n (_mutation, state) => {\n const subset = pickKeys(state, noydbOption.persist)\n const p = collection.put(STATE_DOC_ID, subset)\n .catch((err: unknown) => {\n context.store.$noydbError = err instanceof Error ? err : new Error(String(err))\n })\n .finally(() => {\n pending.delete(p)\n })\n pending.add(p)\n },\n { detached: true }, // outlive the component that triggered the mutation\n )\n } catch (err) {\n context.store.$noydbError = err instanceof Error ? err : new Error(String(err))\n }\n })()\n\n context.store.$noydbReady = ready\n /**\n * Wait for all in-flight persistence puts to settle. Use this in tests\n * to deterministically observe the encrypted state on the adapter, and\n * in app code before unmounting components that mutated the store.\n */\n context.store.$noydbFlush = async (): Promise<void> => {\n await ready\n // Snapshot the current pending set; new puts added during await\n // are picked up by the next $noydbFlush() call.\n while (pending.size > 0) {\n await Promise.all([...pending])\n }\n }\n }\n}\n\n/**\n * Pick the configured subset of keys from a state object.\n *\n * Behaviors:\n * - `undefined` or `'*'` → returns the entire state shallow-copied\n * - single key string → returns `{ [key]: state[key] }`\n * - key array → returns `{ [k1]: state[k1], [k2]: state[k2], ... }`\n *\n * The result is always a fresh object so callers can mutate it without\n * touching the store's reactive state.\n */\nfunction pickKeys(state: StateTree, persist: StoreNoydbOptions['persist']): StateTree {\n if (persist === undefined || persist === '*') {\n return { ...state }\n }\n if (typeof persist === 'string') {\n return { [persist]: state[persist] } as StateTree\n }\n if (Array.isArray(persist)) {\n const out: StateTree = {}\n for (const key of persist) {\n out[key as string] = state[key as string]\n }\n return out\n }\n // Should be unreachable thanks to the type, but defensive default.\n return { ...state }\n}\n\n// ─── Pinia module augmentation ─────────────────────────────────────\n//\n// Pinia exposes `DefineStoreOptionsBase` as the place where third-party\n// plugins are expected to attach their custom option types. Augmenting it\n// here means `defineStore('x', { ..., noydb: {...} })` autocompletes inside\n// the IDE and type-checks correctly without forcing users to import\n// anything from `@noy-db/pinia`.\n//\n// We also augment `PiniaCustomProperties` so the runtime fields we add to\n// every store (`$noydbReady`, `$noydbError`, `$noydbAugmented`) are typed.\n\ndeclare module 'pinia' {\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n export interface DefineStoreOptionsBase<S extends StateTree, Store> {\n /**\n * Opt this store into NOYDB persistence via the\n * `createNoydbPiniaPlugin` augmentation plugin.\n *\n * The chosen state keys are encrypted and persisted to the configured\n * compartment + collection on every mutation, and rehydrated on first\n * store access.\n */\n noydb?: StoreNoydbOptions<S>\n }\n\n export interface PiniaCustomProperties {\n /**\n * Resolves once this store has finished its initial hydration from\n * NOYDB. `undefined` for stores that don't declare a `noydb:` option.\n */\n $noydbReady?: Promise<void>\n /**\n * Set when hydration or persistence fails. `null` while healthy.\n * Plugins (and devtools) can poll this to surface storage errors.\n */\n $noydbError?: Error | null\n /**\n * `true` if this store opted into NOYDB persistence via the `noydb:`\n * option, `false` otherwise. Useful for debugging and devtools.\n */\n $noydbAugmented?: boolean\n /**\n * Wait for all in-flight encrypted persistence puts to complete.\n * Useful in tests for deterministic flushing, and in app code before\n * unmounting components that just mutated the store.\n */\n $noydbFlush?: () => Promise<void>\n }\n}\n"],"mappings":";AAkBA,SAAS,mBAAmB;AAC5B,SAAS,UAAU,kBAA8C;;;ACDjE,IAAI,iBAA+B;AAG5B,SAAS,eAAe,UAA8B;AAC3D,mBAAiB;AACnB;AAGO,SAAS,iBAA+B;AAC7C,SAAO;AACT;AAMO,SAAS,aAAa,UAAgC;AAC3D,MAAI,SAAU,QAAO;AACrB,MAAI,eAAgB,QAAO;AAC3B,QAAM,IAAI;AAAA,IACR;AAAA,EAIF;AACF;;;ADwDO,SAAS,iBACd,IACA,SACA;AACA,QAAM,iBAAiB,QAAQ,cAAc;AAC7C,QAAM,WAAW,QAAQ,YAAY;AAErC,SAAO,YAAY,IAAI,MAAM;AAG3B,UAAM,QAAkB,WAAgB,CAAC,CAAC;AAC1C,UAAM,QAAQ,SAAS,MAAM,MAAM,MAAM,MAAM;AAG/C,QAAI,oBAAwC;AAC5C,QAAI,mBAAyC;AAE7C,mBAAe,gBAAwC;AACrD,UAAI,iBAAkB,QAAO;AAC7B,YAAM,QAAQ,aAAa,QAAQ,SAAS,IAAI;AAChD,0BAAoB,MAAM,MAAM,gBAAgB,QAAQ,WAAW;AAKnE,YAAM,WAAkE,CAAC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M,IAAI,MAAM,OAAO,GAAG,CAAC;AAAA,YAChF,CAAC,EACA,QAAQ,MAAM;AACb,sBAAQ,OAAO,CAAC;AAAA,YAClB,CAAC;AACH,oBAAQ,IAAI,CAAC;AAAA,UACf;AAAA,UACA,EAAE,UAAU,KAAK;AAAA;AAAA,QACnB;AAAA,MACF,SAAS,KAAK;AACZ,gBAAQ,MAAM,cAAc,eAAe,QAAQ,MAAM,IAAI,MAAM,OAAO,GAAG,CAAC;AAAA,MAChF;AAAA,IACF,GAAG;AAEH,YAAQ,MAAM,cAAc;AAM5B,YAAQ,MAAM,cAAc,YAA2B;AACrD,YAAM;AAGN,aAAO,QAAQ,OAAO,GAAG;AACvB,cAAM,QAAQ,IAAI,CAAC,GAAG,OAAO,CAAC;AAAA,MAChC;AAAA,IACF;AAAA,EACF;AACF;AAaA,SAAS,SAAS,OAAkB,SAAkD;AACpF,MAAI,YAAY,UAAa,YAAY,KAAK;AAC5C,WAAO,EAAE,GAAG,MAAM;AAAA,EACpB;AACA,MAAI,OAAO,YAAY,UAAU;AAC/B,WAAO,EAAE,CAAC,OAAO,GAAG,MAAM,OAAO,EAAE;AAAA,EACrC;AACA,MAAI,MAAM,QAAQ,OAAO,GAAG;AAC1B,UAAM,MAAiB,CAAC;AACxB,eAAW,OAAO,SAAS;AACzB,UAAI,GAAa,IAAI,MAAM,GAAa;AAAA,IAC1C;AACA,WAAO;AAAA,EACT;AAEA,SAAO,EAAE,GAAG,MAAM;AACpB;","names":["id"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@noy-db/pinia",
3
- "version": "0.3.0",
3
+ "version": "0.4.0",
4
4
  "description": "Pinia integration for noy-db — defineNoydbStore() and the augmentation plugin for existing stores",
5
5
  "license": "MIT",
6
6
  "author": "vLannaAi <vicio@lanna.ai>",
@@ -41,14 +41,14 @@
41
41
  "peerDependencies": {
42
42
  "pinia": "^2.1.0 || ^3.0.0",
43
43
  "vue": "^3.4.0",
44
- "@noy-db/core": "0.3.0"
44
+ "@noy-db/core": "0.4.0"
45
45
  },
46
46
  "devDependencies": {
47
47
  "@vue/test-utils": "^2.4.6",
48
48
  "happy-dom": "^15.11.7",
49
49
  "pinia": "^3.0.1",
50
50
  "vue": "^3.5.32",
51
- "@noy-db/core": "0.3.0"
51
+ "@noy-db/core": "0.4.0"
52
52
  },
53
53
  "keywords": [
54
54
  "noy-db",