Files
ttrpg-initiative-tracker/src/storage/firebase.js
T
david raistrick 27b2272ced fix(storage): neutral queryConstraints honored by both adapters
Bug: server adapter accepted queryConstraints (orderBy/limit) but ignored them.
Combat log [orderBy('timestamp','desc'), limit(500)] returned ALL logs unordered
in server mode — unbounded growth. No test caught it: shared contract tested
subscribeCollection with 0 constraints; the firebase-only queryConstraint test
never touched the server adapter. Parity gap.

Fix (Plan A — neutral shape):
- index.js: orderBy()/limit() now NEUTRAL builders returning {__type}. Removed
  SDK orderBy/limit re-export.
- firebase.js: subscribeCollection translates neutral -> SDK query constraints.
- server.js: applyConstraints() helper sorts/limits client-side (backend returns
  all). Constraints stored per collection, applied on initial fetch + WS change.
- contract.js: added 3 queryConstraint tests (orderBy desc, limit, no-constraints)
  to SHARED contract — both adapters now run identical assertions.
- firebase.contract.test.js: removed now-redundant firebase-only constraint
  block (covered by shared contract).

Data impact: ZERO. Constraints are query-time only, never stored. Combat log
docs keep timestamp field. No Firebase data migration needed.

208 tests green.
2026-07-04 16:06:28 -04:00

161 lines
6.2 KiB
JavaScript

// firebase.js — storage adapter wrapping Firebase SDK. Default impl (upstream-unchanged).
// Matches interface of memory.js / ws.js so App.js calls stay identical.
//
// App.js imports SDK via this module (doc, setDoc, etc re-exported) for both
// the adapter (createFirebaseStorage) and direct SDK calls. ONE import path.
'use strict';
import { initializeApp } from 'firebase/app';
import { getAuth, signInAnonymously, onAuthStateChanged, signInWithCustomToken } from 'firebase/auth';
import {
getFirestore, doc, setDoc, getDoc as getDocReal, getDocs as getDocsReal, addDoc, collection,
onSnapshot, updateDoc, deleteDoc, query, orderBy, limit, writeBatch, serverTimestamp,
} from 'firebase/firestore';
// Adapter call recorder (instrumentation, no behavior change).
// Tests assert adapter.subscribeDoc called (catches raw-SDK bypass like DisplayView).
const ADAPTER_CALLS = [];
function recordAdapterCall(entry) { ADAPTER_CALLS.push({ ...entry, ts: Date.now() }); }
export function getAdapterCalls() { return [...ADAPTER_CALLS]; }
export function resetAdapterCalls() { ADAPTER_CALLS.length = 0; }
// Path helpers mirror App.js getPath object.
const APP_ID = process.env.REACT_APP_TRACKER_APP_ID || 'ttrpg-initiative-tracker-default';
const PUBLIC_DATA_PATH = `artifacts/${APP_ID}/public/data`;
export const getPath = {
campaigns: () => `${PUBLIC_DATA_PATH}/campaigns`,
campaign: (id) => `${PUBLIC_DATA_PATH}/campaigns/${id}`,
encounters: (campaignId) => `${PUBLIC_DATA_PATH}/campaigns/${campaignId}/encounters`,
encounter: (campaignId, encounterId) => `${PUBLIC_DATA_PATH}/campaigns/${campaignId}/encounters/${encounterId}`,
activeDisplay: () => `${PUBLIC_DATA_PATH}/activeDisplay/status`,
logs: () => `${PUBLIC_DATA_PATH}/logs`
};
let firebaseApp = null;
let dbInstance = null;
let authInstance = null;
export function initFirebase() {
const config = {
apiKey: process.env.REACT_APP_FIREBASE_API_KEY,
authDomain: process.env.REACT_APP_FIREBASE_AUTH_DOMAIN,
projectId: process.env.REACT_APP_FIREBASE_PROJECT_ID,
storageBucket: process.env.REACT_APP_FIREBASE_STORAGE_BUCKET,
messagingSenderId: process.env.REACT_APP_FIREBASE_MESSAGING_SENDER_ID,
appId: process.env.REACT_APP_FIREBASE_APP_ID
};
const requiredKeys = ['apiKey', 'authDomain', 'projectId', 'appId'];
const missing = requiredKeys.filter(k => !config[k]);
if (missing.length > 0) {
console.error(`CRITICAL: Missing Firebase config: ${missing.join(', ')}`);
return false;
}
try {
firebaseApp = initializeApp(config);
dbInstance = getFirestore(firebaseApp);
authInstance = getAuth(firebaseApp);
return true;
} catch (err) {
console.error('Firebase init failed:', err);
return false;
}
}
export function getDb() { return dbInstance; }
export function getAuthInstance() { return authInstance; }
// ============================================================================
// STORAGE ADAPTER
// ============================================================================
// Wraps SDK in the storage interface (getDoc/setDoc/etc).
// App.js can now import { storage } and call storage.setDoc(path, data).
// Hooks (useFirestoreDocument etc) still use SDK directly for now.
export function createFirebaseStorage() {
const db = dbInstance;
if (!db) throw new Error('Firestore not initialized. Call initFirebase() first.');
return {
async getDoc(path) {
const snap = await getDocReal(doc(db, path));
return snap.exists() ? { id: snap.id, ...snap.data() } : null;
},
async setDoc(path, data, opts = {}) {
recordAdapterCall({ fn: 'setDoc', path, data, opts });
await setDoc(doc(db, path), data, opts.merge ? { merge: true } : undefined);
},
async updateDoc(path, patch) {
recordAdapterCall({ fn: 'updateDoc', path, patch });
await updateDoc(doc(db, path), patch);
},
async deleteDoc(path) {
await deleteDoc(doc(db, path));
},
async addDoc(collectionPath, data) {
const ref = await addDoc(collection(db, collectionPath), data);
return { id: ref.id, path: `${collectionPath}/${ref.id}` };
},
async getCollection(collectionPath) {
const snapshot = await getDocsReal(collection(db, collectionPath));
return snapshot.docs.map(d => ({ id: d.id, ...d.data() }));
},
async batchWrite(ops) {
const batch = writeBatch(db);
for (const op of ops) {
if (op.type === 'set') batch.set(doc(db, op.path), op.data);
else if (op.type === 'delete') batch.delete(doc(db, op.path));
else if (op.type === 'update') batch.update(doc(db, op.path), op.data);
}
await batch.commit();
},
// Subscribe = onSnapshot. cb fires immediately + on change. Returns unsubscribe.
subscribeDoc(path, cb, errCb) {
recordAdapterCall({ fn: 'subscribeDoc', path });
return onSnapshot(doc(db, path), (snap) => {
cb(snap.exists() ? { id: snap.id, ...snap.data() } : null);
}, (err) => {
console.error(`subscribeDoc ${path}:`, err);
if (typeof errCb === 'function') errCb(err);
});
},
subscribeCollection(collectionPath, cb, queryConstraints = [], errCb) {
recordAdapterCall({ fn: 'subscribeCollection', path: collectionPath });
// queryConstraints = neutral {__type} builders (from index.js).
// Translate to SDK orderBy/limit.
const sdkConstraints = queryConstraints.map(c => {
if (c.__type === 'orderBy') return orderBy(c.field, c.dir);
if (c.__type === 'limit') return limit(c.n);
return c; // pass-through (forward compat)
});
const q = sdkConstraints.length > 0
? query(collection(db, collectionPath), ...sdkConstraints)
: collection(db, collectionPath);
return onSnapshot(q, (snap) => {
cb(snap.docs.map(d => ({ id: d.id, ...d.data() })));
}, (err) => {
console.error(`subscribeCollection ${collectionPath}:`, err);
if (typeof errCb === 'function') errCb(err);
});
},
dispose() { /* SDK managed; no-op */ },
};
}
// Re-export SDK pieces App.js uses directly (until full refactor).
// orderBy/limit NOT re-exported: App uses neutral builders from index.js.
export {
doc, setDoc, updateDoc, deleteDoc, addDoc, collection, onSnapshot,
query, writeBatch,
};