@noy-db/in-pinia 0.1.0-pre.3

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.js ADDED
@@ -0,0 +1,423 @@
1
+ // src/defineNoydbStore.ts
2
+ import { defineStore } from "pinia";
3
+ import {
4
+ computed,
5
+ getCurrentScope,
6
+ onScopeDispose,
7
+ ref,
8
+ shallowRef
9
+ } from "vue";
10
+
11
+ // src/context.ts
12
+ var activeInstance = null;
13
+ function setActiveNoydb(instance) {
14
+ activeInstance = instance;
15
+ }
16
+ function getActiveNoydb() {
17
+ return activeInstance;
18
+ }
19
+ function resolveNoydb(explicit) {
20
+ if (explicit) return explicit;
21
+ if (activeInstance) return activeInstance;
22
+ throw new Error(
23
+ "@noy-db/pinia: no Noydb instance bound.\n Option A \u2014 pass `noydb:` directly to defineNoydbStore({...})\n Option B \u2014 call setActiveNoydb(instance) once at app startup\n Option C \u2014 install the @noy-db/nuxt module (Nuxt 4+)"
24
+ );
25
+ }
26
+
27
+ // src/defineNoydbStore.ts
28
+ function defineNoydbStore(id, options) {
29
+ const collectionName = options.collection ?? id;
30
+ const prefetch = options.prefetch ?? true;
31
+ return defineStore(id, () => {
32
+ const items = shallowRef([]);
33
+ const count = computed(() => items.value.length);
34
+ let cachedCompartment = null;
35
+ let cachedCollection = null;
36
+ async function getCollection() {
37
+ if (cachedCollection) return cachedCollection;
38
+ const noydb = resolveNoydb(options.noydb ?? null);
39
+ cachedCompartment = await noydb.openVault(options.vault);
40
+ const collOpts = {};
41
+ if (options.schema !== void 0) collOpts.schema = options.schema;
42
+ cachedCollection = cachedCompartment.collection(collectionName, collOpts);
43
+ return cachedCollection;
44
+ }
45
+ async function refresh() {
46
+ const c = await getCollection();
47
+ const list = await c.list();
48
+ items.value = list;
49
+ }
50
+ function byId(id2) {
51
+ for (const item of items.value) {
52
+ if (item.id === id2) return item;
53
+ }
54
+ return void 0;
55
+ }
56
+ async function add(id2, record) {
57
+ const c = await getCollection();
58
+ await c.put(id2, record);
59
+ items.value = await c.list();
60
+ }
61
+ async function update(id2, record) {
62
+ await add(id2, record);
63
+ }
64
+ async function remove(id2) {
65
+ const c = await getCollection();
66
+ await c.delete(id2);
67
+ items.value = await c.list();
68
+ }
69
+ function query() {
70
+ if (!cachedCollection) {
71
+ throw new Error(
72
+ "@noy-db/pinia: query() called before the store was ready. Await store.$ready first, or set prefetch: true (default)."
73
+ );
74
+ }
75
+ return cachedCollection.query();
76
+ }
77
+ function liveQuery(build) {
78
+ if (!cachedCollection) {
79
+ throw new Error(
80
+ "@noy-db/pinia: liveQuery() called before the store was ready. Await store.$ready first, or set prefetch: true (default)."
81
+ );
82
+ }
83
+ const built = build(cachedCollection.query());
84
+ const live = built.live();
85
+ const items2 = shallowRef(live.value);
86
+ const error = ref(live.error);
87
+ const unsubscribe = live.subscribe(() => {
88
+ items2.value = live.value;
89
+ error.value = live.error;
90
+ });
91
+ let stopped = false;
92
+ const stop = () => {
93
+ if (stopped) return;
94
+ stopped = true;
95
+ unsubscribe();
96
+ live.stop();
97
+ };
98
+ if (getCurrentScope()) onScopeDispose(stop);
99
+ return { items: items2, error, stop };
100
+ }
101
+ const $ready = prefetch ? refresh() : Promise.resolve();
102
+ return {
103
+ items,
104
+ count,
105
+ $ready,
106
+ byId,
107
+ add,
108
+ update,
109
+ remove,
110
+ refresh,
111
+ query,
112
+ liveQuery
113
+ };
114
+ });
115
+ }
116
+
117
+ // src/plugin.ts
118
+ import { createNoydb } from "@noy-db/hub";
119
+ var STATE_DOC_ID = "__state__";
120
+ function createNoydbPiniaPlugin(opts) {
121
+ let dbPromise = null;
122
+ function getDb() {
123
+ if (!dbPromise) {
124
+ dbPromise = (async () => {
125
+ const secret = await opts.secret();
126
+ return createNoydb({
127
+ store: opts.adapter,
128
+ user: opts.user,
129
+ secret,
130
+ ...opts.noydbOptions
131
+ });
132
+ })();
133
+ }
134
+ return dbPromise;
135
+ }
136
+ const vaultCache = /* @__PURE__ */ new Map();
137
+ function getCompartment(name) {
138
+ let p = vaultCache.get(name);
139
+ if (!p) {
140
+ p = getDb().then((db) => db.openVault(name));
141
+ vaultCache.set(name, p);
142
+ }
143
+ return p;
144
+ }
145
+ return (context) => {
146
+ const noydbOption = context.options.noydb;
147
+ if (!noydbOption) {
148
+ context.store.$noydbAugmented = false;
149
+ return;
150
+ }
151
+ context.store.$noydbAugmented = true;
152
+ context.store.$noydbError = null;
153
+ const pending = /* @__PURE__ */ new Set();
154
+ const ready = (async () => {
155
+ try {
156
+ const vault = await getCompartment(noydbOption.vault);
157
+ const collection = vault.collection(
158
+ noydbOption.collection
159
+ );
160
+ const persisted = await collection.get(STATE_DOC_ID);
161
+ if (persisted) {
162
+ const validated = noydbOption.schema ? noydbOption.schema.parse(persisted) : persisted;
163
+ const picked = pickKeys(validated, noydbOption.persist);
164
+ context.store.$patch(picked);
165
+ }
166
+ context.store.$subscribe(
167
+ (_mutation, state) => {
168
+ const subset = pickKeys(state, noydbOption.persist);
169
+ const p = collection.put(STATE_DOC_ID, subset).catch((err) => {
170
+ context.store.$noydbError = err instanceof Error ? err : new Error(String(err));
171
+ }).finally(() => {
172
+ pending.delete(p);
173
+ });
174
+ pending.add(p);
175
+ },
176
+ { detached: true }
177
+ // outlive the component that triggered the mutation
178
+ );
179
+ } catch (err) {
180
+ context.store.$noydbError = err instanceof Error ? err : new Error(String(err));
181
+ }
182
+ })();
183
+ context.store.$noydbReady = ready;
184
+ context.store.$noydbFlush = async () => {
185
+ await ready;
186
+ while (pending.size > 0) {
187
+ await Promise.all([...pending]);
188
+ }
189
+ };
190
+ };
191
+ }
192
+ function pickKeys(state, persist) {
193
+ if (persist === void 0 || persist === "*") {
194
+ return { ...state };
195
+ }
196
+ if (typeof persist === "string") {
197
+ return { [persist]: state[persist] };
198
+ }
199
+ if (Array.isArray(persist)) {
200
+ const out = {};
201
+ for (const key of persist) {
202
+ out[key] = state[key];
203
+ }
204
+ return out;
205
+ }
206
+ return { ...state };
207
+ }
208
+
209
+ // src/useCapabilityGrant.ts
210
+ import {
211
+ computed as computed2,
212
+ getCurrentScope as getCurrentScope2,
213
+ onScopeDispose as onScopeDispose2,
214
+ ref as ref2,
215
+ shallowRef as shallowRef2,
216
+ watch
217
+ } from "vue";
218
+ var CAPABILITY_REQUESTS_COLLECTION = "_capability_requests";
219
+ function useCapabilityGrant(capability, options) {
220
+ const state = ref2("idle");
221
+ const error = ref2(null);
222
+ const recordRef = shallowRef2(null);
223
+ const inBrowser = typeof window !== "undefined";
224
+ let expiryTimer = null;
225
+ let unsubscribeChangeStream = null;
226
+ let resolvedVault = null;
227
+ let stopped = false;
228
+ async function resolveVault() {
229
+ if (resolvedVault) return resolvedVault;
230
+ if (typeof options.vault === "string") {
231
+ const noydb = resolveNoydb(null);
232
+ resolvedVault = await noydb.openVault(options.vault);
233
+ } else {
234
+ resolvedVault = options.vault;
235
+ }
236
+ resolvedVault.collection(
237
+ CAPABILITY_REQUESTS_COLLECTION
238
+ );
239
+ return resolvedVault;
240
+ }
241
+ function clearExpiryTimer() {
242
+ if (expiryTimer) {
243
+ clearTimeout(expiryTimer);
244
+ expiryTimer = null;
245
+ }
246
+ }
247
+ function scheduleExpiry(record) {
248
+ if (!record.expiresAt) return;
249
+ const remaining = new Date(record.expiresAt).getTime() - Date.now();
250
+ if (remaining <= 0) {
251
+ void handleExpiry(record);
252
+ return;
253
+ }
254
+ clearExpiryTimer();
255
+ expiryTimer = setTimeout(() => {
256
+ void handleExpiry(record);
257
+ }, remaining);
258
+ }
259
+ async function handleExpiry(record) {
260
+ if (stopped) return;
261
+ if (state.value !== "granted") return;
262
+ state.value = "expired";
263
+ try {
264
+ await options.onRelease?.({
265
+ record,
266
+ vault: resolvedVault,
267
+ cause: "expired"
268
+ });
269
+ } catch (err) {
270
+ error.value = err instanceof Error ? err : new Error(String(err));
271
+ }
272
+ state.value = "idle";
273
+ recordRef.value = null;
274
+ }
275
+ const now = ref2(Date.now());
276
+ const tickTimer = inBrowser ? setInterval(() => {
277
+ now.value = Date.now();
278
+ }, 1e3) : null;
279
+ const timeRemaining = computed2(() => {
280
+ if (state.value !== "granted" || !recordRef.value?.expiresAt) return 0;
281
+ void now.value;
282
+ const ms = new Date(recordRef.value.expiresAt).getTime() - Date.now();
283
+ return ms > 0 ? ms : 0;
284
+ });
285
+ watch(
286
+ () => recordRef.value?.id,
287
+ async (id) => {
288
+ if (!inBrowser || !id || unsubscribeChangeStream) return;
289
+ const vault = await resolveVault();
290
+ const coll = vault.collection(
291
+ CAPABILITY_REQUESTS_COLLECTION
292
+ );
293
+ unsubscribeChangeStream = coll.subscribe(
294
+ (evt) => {
295
+ if (evt.type !== "put" || evt.id !== id) return;
296
+ const updated = evt.record;
297
+ if (!updated || stopped) return;
298
+ recordRef.value = updated;
299
+ if (updated.status === "granted") {
300
+ state.value = "granted";
301
+ scheduleExpiry(updated);
302
+ } else if (updated.status === "released" || updated.status === "expired") {
303
+ state.value = "idle";
304
+ clearExpiryTimer();
305
+ }
306
+ }
307
+ );
308
+ },
309
+ { immediate: false }
310
+ );
311
+ async function request() {
312
+ if (state.value !== "idle") {
313
+ error.value = new Error(
314
+ `useCapabilityGrant: cannot request from state "${state.value}"`
315
+ );
316
+ throw error.value;
317
+ }
318
+ error.value = null;
319
+ if (!inBrowser) return;
320
+ try {
321
+ const vault = await resolveVault();
322
+ const coll = vault.collection(
323
+ CAPABILITY_REQUESTS_COLLECTION
324
+ );
325
+ const id = `cap-${Date.now().toString(36)}-${Math.random().toString(16).slice(2, 10)}`;
326
+ const record = {
327
+ id,
328
+ capability,
329
+ requestedBy: vault.userId,
330
+ approverRole: options.approver,
331
+ reason: options.reason,
332
+ ttlMs: options.ttlMs,
333
+ status: "requested",
334
+ requestedAt: (/* @__PURE__ */ new Date()).toISOString()
335
+ };
336
+ await coll.put(id, record);
337
+ recordRef.value = record;
338
+ state.value = "requested";
339
+ } catch (err) {
340
+ error.value = err instanceof Error ? err : new Error(String(err));
341
+ throw error.value;
342
+ }
343
+ }
344
+ async function approve() {
345
+ const record = recordRef.value;
346
+ if (state.value !== "requested" || !record) {
347
+ error.value = new Error(
348
+ `useCapabilityGrant: cannot approve from state "${state.value}"`
349
+ );
350
+ throw error.value;
351
+ }
352
+ error.value = null;
353
+ try {
354
+ const vault = await resolveVault();
355
+ if (vault.role !== options.approver && vault.role !== "owner") {
356
+ throw new Error(
357
+ `useCapabilityGrant: caller role "${vault.role}" cannot approve a "${options.approver}"-tier grant`
358
+ );
359
+ }
360
+ const approvedAt = /* @__PURE__ */ new Date();
361
+ const expiresAt = new Date(approvedAt.getTime() + options.ttlMs);
362
+ const granted = {
363
+ ...record,
364
+ status: "granted",
365
+ approvedBy: vault.userId,
366
+ approvedAt: approvedAt.toISOString(),
367
+ expiresAt: expiresAt.toISOString()
368
+ };
369
+ const coll = vault.collection(
370
+ CAPABILITY_REQUESTS_COLLECTION
371
+ );
372
+ await coll.put(record.id, granted);
373
+ recordRef.value = granted;
374
+ state.value = "granted";
375
+ scheduleExpiry(granted);
376
+ await options.onGrant?.({ record: granted, vault });
377
+ } catch (err) {
378
+ error.value = err instanceof Error ? err : new Error(String(err));
379
+ throw error.value;
380
+ }
381
+ }
382
+ async function release() {
383
+ const record = recordRef.value;
384
+ if (state.value !== "granted" || !record) {
385
+ return;
386
+ }
387
+ error.value = null;
388
+ try {
389
+ clearExpiryTimer();
390
+ const vault = await resolveVault();
391
+ const released = { ...record, status: "released" };
392
+ const coll = vault.collection(
393
+ CAPABILITY_REQUESTS_COLLECTION
394
+ );
395
+ await coll.put(record.id, released);
396
+ recordRef.value = null;
397
+ state.value = "idle";
398
+ await options.onRelease?.({ record, vault, cause: "released" });
399
+ } catch (err) {
400
+ error.value = err instanceof Error ? err : new Error(String(err));
401
+ throw error.value;
402
+ }
403
+ }
404
+ if (getCurrentScope2()) {
405
+ onScopeDispose2(() => {
406
+ stopped = true;
407
+ clearExpiryTimer();
408
+ if (tickTimer) clearInterval(tickTimer);
409
+ unsubscribeChangeStream?.();
410
+ });
411
+ }
412
+ return { state, timeRemaining, error, request, approve, release };
413
+ }
414
+ export {
415
+ CAPABILITY_REQUESTS_COLLECTION,
416
+ createNoydbPiniaPlugin,
417
+ defineNoydbStore,
418
+ getActiveNoydb,
419
+ resolveNoydb,
420
+ setActiveNoydb,
421
+ useCapabilityGrant
422
+ };
423
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/defineNoydbStore.ts","../src/context.ts","../src/plugin.ts","../src/useCapabilityGrant.ts"],"sourcesContent":["/**\n * `defineNoydbStore` — drop-in `defineStore` that wires a Pinia store to a\n * NOYDB vault + 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 {\n computed,\n getCurrentScope,\n onScopeDispose,\n ref,\n shallowRef,\n type Ref,\n type ShallowRef,\n type ComputedRef,\n} from 'vue'\nimport type {\n Noydb,\n Vault,\n Collection,\n Query,\n StandardSchemaV1,\n} from '@noy-db/hub'\nimport { resolveNoydb } from './context.js'\n\n/**\n * Reactive handle returned by `store.liveQuery(fn)`. Mirrors a hub\n * `LiveQuery<R>` into Vue refs; `items` updates on every left- or\n * joined-right-side mutation, `error` carries re-run errors as state\n * (a `DanglingReferenceError` in strict join mode is the common case),\n * `stop()` tears down upstream subscriptions. Auto-disposed on scope\n * teardown when called inside a Vue setup / Pinia store body.\n */\nexport interface NoydbLiveQuery<R> {\n items: ShallowRef<readonly R[]>\n error: Ref<Error | null>\n stop(): void\n}\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 /** Vault (tenant) name. */\n vault: string\n /** Collection name within the vault. 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 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 liveQuery<R = T>(build: (q: Query<T>) => Query<R>): NoydbLiveQuery<R>\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/in-pinia';\n *\n * export const useInvoices = defineNoydbStore<Invoice>('invoices', {\n * vault: '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: Vault | 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.openVault(options.vault)\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 planned.\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 function liveQuery<R = T>(\n build: (q: Query<T>) => Query<R>,\n ): NoydbLiveQuery<R> {\n if (!cachedCollection) {\n throw new Error(\n '@noy-db/pinia: liveQuery() called before the store was ready. ' +\n 'Await store.$ready first, or set prefetch: true (default).',\n )\n }\n const built = build(cachedCollection.query())\n const live = built.live()\n\n const items = shallowRef<readonly R[]>(live.value)\n const error = ref<Error | null>(live.error)\n\n const unsubscribe = live.subscribe(() => {\n items.value = live.value\n error.value = live.error\n })\n\n let stopped = false\n const stop = (): void => {\n if (stopped) return\n stopped = true\n unsubscribe()\n live.stop()\n }\n\n // Auto-teardown when the calling scope (a Vue component's setup,\n // a Pinia store body, or any user-created effectScope) disposes.\n // Outside an active scope (raw test harness, SSR top-level), skip\n // registration silently — caller is responsible for stop().\n if (getCurrentScope()) onScopeDispose(stop)\n\n return { items, error, stop }\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 liveQuery,\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/hub'\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/in-pinia';\n * import { jsonFile } from '@noy-db/to-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: { vault: '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 NoydbStore, type Vault, type Collection } from '@noy-db/hub'\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 /** Vault (tenant) name. */\n vault: string\n /** Collection name within the vault. */\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 store to use for persistence. */\n adapter: NoydbStore\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, 'store' | '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 store: opts.adapter,\n user: opts.user,\n secret,\n ...opts.noydbOptions,\n })\n })()\n }\n return dbPromise\n }\n\n // Vault cache so opening a vault is a one-time cost per app.\n const vaultCache = new Map<string, Promise<Vault>>()\n function getCompartment(name: string): Promise<Vault> {\n let p = vaultCache.get(name)\n if (!p) {\n p = getDb().then((db) => db.openVault(name))\n vaultCache.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 vault = await getCompartment(noydbOption.vault)\n const collection: Collection<StateTree> = vault.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 * vault + 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","/**\n * `useCapabilityGrant` — Vue/Pinia composable for time-boxed\n * capability approval flows.\n *\n * The composable orchestrates a request → approve → expire / release\n * lifecycle for a session-scoped capability. It manages UI state,\n * persists the request to a reserved `_capability_requests` collection\n * so a separate approver session can see it, and tracks TTL with\n * auto-revert.\n *\n * **It does NOT itself flip capability bits.** Capability mechanisms\n * vary across adopters: tier-based deployments wire `onGrant` to\n * `vault.elevate(tier, opts)`; keyring-based deployments wire it to\n * `db.grant(...)`; custom deployments do their own thing. Keeping the\n * actual flip behind a callback avoids introducing a parallel\n * \"capability elevation\" primitive in hub when the existing\n * `vault.elevate()` already covers the time-boxed-grant pattern.\n *\n * ## State machine\n *\n * idle ─── .request() ───────► requested\n * requested ─── .approve() ──► granted\n * granted ─── TTL expires ─► idle\n * granted ─── .release() ──► idle\n *\n * @module\n */\n\nimport {\n computed,\n getCurrentScope,\n onScopeDispose,\n ref,\n shallowRef,\n watch,\n type ComputedRef,\n type Ref,\n} from 'vue'\nimport type { Vault, Role, CollectionChangeEvent } from '@noy-db/hub'\nimport { resolveNoydb } from './context.js'\n\n/** Reserved internal collection that holds capability-grant lifecycle records. */\nexport const CAPABILITY_REQUESTS_COLLECTION = '_capability_requests'\n\nexport type CapabilityGrantState = 'idle' | 'requested' | 'granted' | 'expired'\n\n/**\n * On-disk shape of a capability-grant lifecycle record. Persisted in\n * the reserved {@link CAPABILITY_REQUESTS_COLLECTION}. Encrypted with\n * that collection's DEK at the storage layer; the in-memory shape\n * here is plaintext.\n *\n * The audit trail invariant: this record carries metadata only —\n * capability name, roles, ttl, reason. Never plaintext payload.\n */\nexport interface CapabilityGrantRecord {\n readonly id: string\n readonly capability: string\n readonly requestedBy: string\n readonly approverRole: Role\n readonly reason: string\n readonly ttlMs: number\n readonly status: 'requested' | 'granted' | 'released' | 'expired'\n readonly requestedAt: string\n readonly approvedBy?: string\n readonly approvedAt?: string\n readonly expiresAt?: string\n}\n\nexport interface UseCapabilityGrantOptions {\n /** TTL in milliseconds for the granted window. */\n readonly ttlMs: number\n /** Role required to call `.approve()`. Mismatch throws on `.approve()`. */\n readonly approver: Role\n /** Audit-ledger string. Stamped on the request record; no plaintext payload. */\n readonly reason: string\n /**\n * Optional explicit vault. Either a `Vault` instance or its name.\n * When omitted, resolves the active Noydb instance via\n * `setActiveNoydb()` and opens the first vault the caller has\n * already loaded.\n */\n readonly vault: Vault | string\n /**\n * Called on the approver's session when `.approve()` succeeds. Wire\n * this to whatever capability flip your codebase uses —\n * `vault.elevate(tier, opts)` for tier-based deployments,\n * `db.grant(...)` for keyring-based, custom for custom.\n *\n * The composable does NOT enforce that the capability was actually\n * granted — it just tracks the lifecycle. The post-expiry \"gated\n * call throws\" contract comes from the underlying mechanism the\n * callback wires up (e.g., `ElevationExpiredError` from\n * `vault.elevate`'s lazy TTL check).\n */\n readonly onGrant?: (ctx: {\n record: CapabilityGrantRecord\n vault: Vault\n }) => void | Promise<void>\n /**\n * Called when the grant ends (TTL expiry OR voluntary release).\n * Mirror of `onGrant`. Idempotent — may be called twice if release\n * and expiry race; callers should no-op on the second invocation.\n */\n readonly onRelease?: (ctx: {\n record: CapabilityGrantRecord\n vault: Vault\n cause: 'released' | 'expired'\n }) => void | Promise<void>\n}\n\nexport interface UseCapabilityGrantReturn {\n readonly state: Ref<CapabilityGrantState>\n /** Milliseconds remaining on the granted window; 0 outside `granted`. */\n readonly timeRemaining: ComputedRef<number>\n /** Most recent error from request/approve/release (resets on next op). */\n readonly error: Ref<Error | null>\n /** Issue a request. State must be `idle`. */\n request(): Promise<void>\n /** Approve a pending request. State must be `requested`. */\n approve(): Promise<void>\n /** Voluntarily revoke an active grant. State must be `granted`. */\n release(): Promise<void>\n}\n\n/**\n * Build a reactive capability-grant lifecycle handle.\n *\n * @example Tier-based capability flip\n * ```ts\n * let elevated: ElevatedHandle | null = null\n * const grant = useCapabilityGrant('canExportPlaintext', {\n * vault: 'V1',\n * ttlMs: 15 * 60_000,\n * approver: 'admin',\n * reason: 'bulk export',\n * onGrant: async ({ vault, record }) => {\n * elevated = await vault.elevate(2, {\n * ttlMs: record.ttlMs,\n * reason: record.reason,\n * })\n * },\n * onRelease: async () => { await elevated?.release(); elevated = null },\n * })\n * ```\n */\nexport function useCapabilityGrant(\n capability: string,\n options: UseCapabilityGrantOptions,\n): UseCapabilityGrantReturn {\n const state = ref<CapabilityGrantState>('idle')\n const error = ref<Error | null>(null)\n const recordRef = shallowRef<CapabilityGrantRecord | null>(null)\n\n // SSR / non-browser host: composable is a no-op. Methods reject; the\n // refs stay at their initial values so server-rendered output shows\n // the idle state.\n const inBrowser = typeof window !== 'undefined'\n\n let expiryTimer: ReturnType<typeof setTimeout> | null = null\n let unsubscribeChangeStream: (() => void) | null = null\n let resolvedVault: Vault | null = null\n let stopped = false\n\n async function resolveVault(): Promise<Vault> {\n if (resolvedVault) return resolvedVault\n if (typeof options.vault === 'string') {\n const noydb = resolveNoydb(null)\n resolvedVault = await noydb.openVault(options.vault)\n } else {\n resolvedVault = options.vault\n }\n // Open the requests collection eagerly so the change stream\n // subscription below has a target. We don't typed-cast here —\n // the collection holds CapabilityGrantRecord shapes only.\n resolvedVault.collection<CapabilityGrantRecord>(\n CAPABILITY_REQUESTS_COLLECTION,\n )\n return resolvedVault\n }\n\n function clearExpiryTimer(): void {\n if (expiryTimer) {\n clearTimeout(expiryTimer)\n expiryTimer = null\n }\n }\n\n function scheduleExpiry(record: CapabilityGrantRecord): void {\n if (!record.expiresAt) return\n const remaining = new Date(record.expiresAt).getTime() - Date.now()\n if (remaining <= 0) {\n void handleExpiry(record)\n return\n }\n clearExpiryTimer()\n expiryTimer = setTimeout(() => { void handleExpiry(record) }, remaining)\n }\n\n async function handleExpiry(record: CapabilityGrantRecord): Promise<void> {\n if (stopped) return\n if (state.value !== 'granted') return\n state.value = 'expired'\n try {\n await options.onRelease?.({\n record,\n vault: resolvedVault!,\n cause: 'expired',\n })\n } catch (err) {\n error.value = err instanceof Error ? err : new Error(String(err))\n }\n // Auto-return to idle after the expiry handler — matches the spec's\n // \"state auto-returns to idle\" contract.\n state.value = 'idle'\n recordRef.value = null\n }\n\n // `now` ticks every second so timeRemaining stays reactive without\n // wiring a per-frame loop.\n const now = ref(Date.now())\n const tickTimer = inBrowser\n ? setInterval(() => { now.value = Date.now() }, 1000)\n : null\n\n const timeRemaining = computed(() => {\n if (state.value !== 'granted' || !recordRef.value?.expiresAt) return 0\n // Subscribe to `now` for reactivity, but read the live clock for\n // accuracy — `now` ticks every second so the computed stays\n // honest between ticks too.\n void now.value\n const ms = new Date(recordRef.value.expiresAt).getTime() - Date.now()\n return ms > 0 ? ms : 0\n })\n\n // Subscribe to the requests collection so an approver session sees\n // pending records appear in real time within the same Noydb session.\n // Cross-session visibility additionally requires the sync engine.\n watch(\n () => recordRef.value?.id,\n async (id) => {\n if (!inBrowser || !id || unsubscribeChangeStream) return\n const vault = await resolveVault()\n const coll = vault.collection<CapabilityGrantRecord>(\n CAPABILITY_REQUESTS_COLLECTION,\n )\n unsubscribeChangeStream = coll.subscribe(\n (evt: CollectionChangeEvent<CapabilityGrantRecord>) => {\n if (evt.type !== 'put' || evt.id !== id) return\n const updated = evt.record\n if (!updated || stopped) return\n recordRef.value = updated\n if (updated.status === 'granted') {\n state.value = 'granted'\n scheduleExpiry(updated)\n } else if (updated.status === 'released' || updated.status === 'expired') {\n state.value = 'idle'\n clearExpiryTimer()\n }\n },\n )\n },\n { immediate: false },\n )\n\n async function request(): Promise<void> {\n if (state.value !== 'idle') {\n error.value = new Error(\n `useCapabilityGrant: cannot request from state \"${state.value}\"`,\n )\n throw error.value\n }\n error.value = null\n if (!inBrowser) return\n try {\n const vault = await resolveVault()\n const coll = vault.collection<CapabilityGrantRecord>(\n CAPABILITY_REQUESTS_COLLECTION,\n )\n const id = `cap-${Date.now().toString(36)}-${Math.random().toString(16).slice(2, 10)}`\n const record: CapabilityGrantRecord = {\n id,\n capability,\n requestedBy: vault.userId,\n approverRole: options.approver,\n reason: options.reason,\n ttlMs: options.ttlMs,\n status: 'requested',\n requestedAt: new Date().toISOString(),\n }\n await coll.put(id, record)\n recordRef.value = record\n state.value = 'requested'\n } catch (err) {\n error.value = err instanceof Error ? err : new Error(String(err))\n throw error.value\n }\n }\n\n async function approve(): Promise<void> {\n const record = recordRef.value\n if (state.value !== 'requested' || !record) {\n error.value = new Error(\n `useCapabilityGrant: cannot approve from state \"${state.value}\"`,\n )\n throw error.value\n }\n error.value = null\n try {\n const vault = await resolveVault()\n if (vault.role !== options.approver && vault.role !== 'owner') {\n throw new Error(\n `useCapabilityGrant: caller role \"${vault.role}\" cannot approve a \"${options.approver}\"-tier grant`,\n )\n }\n const approvedAt = new Date()\n const expiresAt = new Date(approvedAt.getTime() + options.ttlMs)\n const granted: CapabilityGrantRecord = {\n ...record,\n status: 'granted',\n approvedBy: vault.userId,\n approvedAt: approvedAt.toISOString(),\n expiresAt: expiresAt.toISOString(),\n }\n const coll = vault.collection<CapabilityGrantRecord>(\n CAPABILITY_REQUESTS_COLLECTION,\n )\n await coll.put(record.id, granted)\n recordRef.value = granted\n state.value = 'granted'\n scheduleExpiry(granted)\n await options.onGrant?.({ record: granted, vault })\n } catch (err) {\n error.value = err instanceof Error ? err : new Error(String(err))\n throw error.value\n }\n }\n\n async function release(): Promise<void> {\n const record = recordRef.value\n if (state.value !== 'granted' || !record) {\n // Releasing from non-granted state is a no-op.\n return\n }\n error.value = null\n try {\n clearExpiryTimer()\n const vault = await resolveVault()\n const released: CapabilityGrantRecord = { ...record, status: 'released' }\n const coll = vault.collection<CapabilityGrantRecord>(\n CAPABILITY_REQUESTS_COLLECTION,\n )\n await coll.put(record.id, released)\n recordRef.value = null\n state.value = 'idle'\n await options.onRelease?.({ record, vault, cause: 'released' })\n } catch (err) {\n error.value = err instanceof Error ? err : new Error(String(err))\n throw error.value\n }\n }\n\n if (getCurrentScope()) {\n onScopeDispose(() => {\n stopped = true\n clearExpiryTimer()\n if (tickTimer) clearInterval(tickTimer)\n unsubscribeChangeStream?.()\n })\n }\n\n return { state, timeRemaining, error, request, approve, release }\n}\n"],"mappings":";AAkBA,SAAS,mBAAmB;AAC5B;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OAIK;;;ACVP,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;;;ADgFO,SAAS,iBACd,IACA,SACA;A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A,IACF;AACA,UAAM,QAAQ;AACd,QAAI;AACF,uBAAiB;AACjB,YAAM,QAAQ,MAAM,aAAa;AACjC,YAAM,WAAkC,EAAE,GAAG,QAAQ,QAAQ,WAAW;AACxE,YAAM,OAAO,MAAM;AAAA,QACjB;AAAA,MACF;AACA,YAAM,KAAK,IAAI,OAAO,IAAI,QAAQ;AAClC,gBAAU,QAAQ;AAClB,YAAM,QAAQ;AACd,YAAM,QAAQ,YAAY,EAAE,QAAQ,OAAO,OAAO,WAAW,CAAC;AAAA,IAChE,SAAS,KAAK;AACZ,YAAM,QAAQ,eAAe,QAAQ,MAAM,IAAI,MAAM,OAAO,GAAG,CAAC;AAChE,YAAM,MAAM;AAAA,IACd;AAAA,EACF;AAEA,MAAIC,iBAAgB,GAAG;AACrB,IAAAC,gBAAe,MAAM;AACnB,gBAAU;AACV,uBAAiB;AACjB,UAAI,UAAW,eAAc,SAAS;AACtC,gCAA0B;AAAA,IAC5B,CAAC;AAAA,EACH;AAEA,SAAO,EAAE,OAAO,eAAe,OAAO,SAAS,SAAS,QAAQ;AAClE;","names":["id","items","computed","getCurrentScope","onScopeDispose","ref","shallowRef","ref","shallowRef","computed","getCurrentScope","onScopeDispose"]}
package/package.json ADDED
@@ -0,0 +1,74 @@
1
+ {
2
+ "name": "@noy-db/in-pinia",
3
+ "version": "0.1.0-pre.3",
4
+ "description": "Pinia integration for noy-db — defineNoydbStore() and the augmentation plugin for existing stores",
5
+ "license": "MIT",
6
+ "author": "vLannaAi <vicio@lanna.ai>",
7
+ "homepage": "https://github.com/vLannaAi/noy-db/tree/main/packages/in-pinia#readme",
8
+ "repository": {
9
+ "type": "git",
10
+ "url": "git+https://github.com/vLannaAi/noy-db.git",
11
+ "directory": "packages/in-pinia"
12
+ },
13
+ "bugs": {
14
+ "url": "https://github.com/vLannaAi/noy-db/issues"
15
+ },
16
+ "type": "module",
17
+ "sideEffects": false,
18
+ "exports": {
19
+ ".": {
20
+ "import": {
21
+ "types": "./dist/index.d.ts",
22
+ "default": "./dist/index.js"
23
+ },
24
+ "require": {
25
+ "types": "./dist/index.d.cts",
26
+ "default": "./dist/index.cjs"
27
+ }
28
+ }
29
+ },
30
+ "main": "./dist/index.cjs",
31
+ "module": "./dist/index.js",
32
+ "types": "./dist/index.d.ts",
33
+ "files": [
34
+ "dist",
35
+ "README.md",
36
+ "LICENSE"
37
+ ],
38
+ "engines": {
39
+ "node": ">=20.0.0"
40
+ },
41
+ "peerDependencies": {
42
+ "pinia": "^2.1.0 || ^3.0.0",
43
+ "vue": "^3.4.0",
44
+ "@noy-db/hub": "0.1.0-pre.3"
45
+ },
46
+ "devDependencies": {
47
+ "@vue/test-utils": "^2.4.6",
48
+ "happy-dom": "^15.11.7",
49
+ "pinia": "^3.0.1",
50
+ "vue": "^3.5.32",
51
+ "@noy-db/hub": "0.1.0-pre.3"
52
+ },
53
+ "keywords": [
54
+ "noy-db",
55
+ "pinia",
56
+ "vue",
57
+ "vue3",
58
+ "nuxt",
59
+ "store",
60
+ "encryption",
61
+ "zero-knowledge",
62
+ "offline-first"
63
+ ],
64
+ "publishConfig": {
65
+ "access": "public",
66
+ "tag": "latest"
67
+ },
68
+ "scripts": {
69
+ "build": "tsup",
70
+ "test": "vitest run",
71
+ "lint": "eslint src/",
72
+ "typecheck": "tsc --noEmit"
73
+ }
74
+ }