@black-cape/microstore 0.0.4 → 0.0.5

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 CHANGED
@@ -1,2 +1,2 @@
1
- 'use strict';var emberInflector=require('ember-inflector'),lodashEs=require('lodash-es'),tinybase=require('tinybase'),react=require('react'),uiReact=require('tinybase/ui-react'),jsxRuntime=require('react/jsx-runtime');var K=Object.defineProperty;var z=(o,e,r)=>e in o?K(o,e,{enumerable:true,configurable:true,writable:true,value:r}):o[e]=r;var m=(o,e,r)=>z(o,typeof e!="symbol"?e+"":e,r);function l(o,e){let r={data:[],meta:void 0},s;return o!==void 0&&Object.keys(o).forEach(t=>{let i=o[t];if(t!=="meta"){let n=[],c=lodashEs.camelCase(emberInflector.singularize(t));lodashEs.isArray(i)?i.forEach(a=>{n.push(a);}):n.push(i),r.data.push({data:n,type:c});}else s=o[t];}),r.meta=s,r}var p={serialize(o){return o?JSON.stringify(o):null},deserialize(o){return o?JSON.parse(o):null}};var N=["transform","primaryKey"],q={json:p},y=class{constructor(e){m(this,"schemas");m(this,"fieldTransforms");m(this,"recordTransforms");m(this,"store");m(this,"queries");m(this,"interpreter");m(this,"primaryKeys");this.primaryKeys={},this.schemas=e.schemas?e.schemas:{},this.fieldTransforms={...e.fieldTransforms?e.fieldTransforms:{},...q},this.recordTransforms=e.recordTransforms?e.recordTransforms:{},this.interpreter=e.interpreter?e.interpreter:l,this.store=tinybase.createStore(),this.store.setTablesSchema(this.transformSchemas()),this.queries=tinybase.createQueries(this.store);}transformSchemas(){let e={};return Object.keys(this.schemas).forEach(r=>{if(e[r]={},Object.keys(this.schemas[r]).forEach(s=>{if(e[r][s]=lodashEs.omit(this.schemas[r][s],N),this.schemas[r][s].primaryKey&&this.schemas[r][s].type==="string"){if(this.primaryKeys[r])throw Error(`More than one primary key defined for schema ${r}`);this.primaryKeys[r]=s;}}),!this.getPrimaryKey(r)&&this.schemas[r].id&&this.schemas[r].id.type==="string"&&(this.primaryKeys[r]="id"),!this.getPrimaryKey(r))throw Error(`No primary key defined for schema ${r}. This schema must have an 'id' field of "type": "string", or another field of "type": "string" with "primaryKey": true.`)}),e}getPrimaryKey(e){let r=this.primaryKeys[e];return r||void 0}getSchema(e){return e&&Object.hasOwn(this.schemas,e)?this.schemas[e]:null}getRecordTransform(e){if(e)return this.recordTransforms[e]?this.recordTransforms[e]:void 0}getFieldTransform(e){if(e)return this.fieldTransforms[e]?this.fieldTransforms[e]:void 0}serialize(e,r){let s={};return Object.keys(e).forEach(t=>{let i=r[t];if(i){let n=this.getFieldTransform(i.transform);s[t]=n?n.serialize(e[t]):e[t];}}),s}deserialize(e,r){let s={};return Object.keys(e).forEach(t=>{let i=r[t];if(i){let n=i.transform&&this.fieldTransforms[i.transform]?this.fieldTransforms[i.transform]:void 0;s[t]=n?n.deserialize(e[t]):e[t];}}),s}pushRecord(e,r,s,t={}){return this.pushRecords(e,[r],s,t)}pushRecords(e,r,s,t={}){let i=this.getRecordTransform(e),n=lodashEs.camelCase(emberInflector.pluralize(e));if(!i)return this.pushPayload(s,{[n]:r},t);let c=r.map(a=>i.serialize(a));return this.pushPayload(s,{[n]:c},t)}pushPayload(e,r,s={}){try{let t=this.interpreter(r,s);return t.data.forEach(i=>{let n=this.getSchema(i.type);if(n){let c=this.getPrimaryKey(i.type)||"id";e==="DELETE"?i.data.forEach(a=>{this.store.delRow(i.type,a[c]);}):e==="PATCH"?i.data.forEach(a=>{this.store.getRow(i.type,a[c])?this.store.setPartialRow(i.type,a[c],this.serialize(a,n)):this.store.setRow(i.type,a[c],this.serialize(a,n));}):i.data.forEach(a=>{this.store.setRow(i.type,a[c],this.serialize(a,n));});}}),t}catch(t){console.warn(t);}}peekRecord(e,r){let s=this.getSchema(e),t=this.getPrimaryKey(e),i=this.getRecordTransform(e),n=i?i.deserialize:c=>c;if(s&&t){let c=this.getStore().getRow(e,r);if(c)return n(this.deserialize(c,s))}}peekAll(e){let r=this.getSchema(e),s=this.getPrimaryKey(e),t=this.getRecordTransform(e),i=t?t.deserialize:n=>n;if(r&&s){let n=this.getStore().getTable(e);return Object.entries(n).map(([c,a])=>i(this.deserialize(a,r)))}return []}unloadRecord(e,r){let s=this.peekRecord(e,r);return s&&this.getStore().delRow(e,r),s}unloadAll(e){this.getSchema(e)&&this.getStore().delTable(e);}reset(){Object.entries(this.schemas).forEach(([e,r])=>{this.unloadAll(e);});}getStore(){return this.store}getQueries(){return this.queries}};var w=react.createContext(null);function g(){return react.useContext(w)}function J(o){let e=react.useMemo(()=>o.store,[o]);return jsxRuntime.jsx(w.Provider,{value:e,children:jsxRuntime.jsx(uiReact.Provider,{store:e.getStore(),queries:e.getQueries(),children:o.children})})}function U(o,e){return new Set(o?o.map(r=>typeof r=="string"?r:r[e]):[])}function G(o,e,r,s,t,i){t.setQueryDefinition(s,o,({select:n,where:c})=>{Object.keys(e).forEach(a=>{n(a);}),c(a=>i.has(a(r)));});}function X(o,e){let r=g(),s=r?.getSchema(o),t=r?.getPrimaryKey(o);if(!s||!t)throw new Error(`No MicroStore schema defined for type ${o}`);let[i,n]=react.useState(crypto.randomUUID()),c=uiReact.useQueries(),a=uiReact.useResultTable(i,c),[d,P]=react.useState(""),u=react.useRef("");react.useEffect(()=>{if(c){let f=U(e,t),h=JSON.stringify([...f]);d!==h&&u.current!==h&&(Object.entries(a).length>0&&(u.current=h),P(h),G(o,s,t,i,c,f));}},[e,t,s,o,c,i,d,a,u]);let S=r?.getRecordTransform(o),b=S?S.deserialize:f=>f,R=[];return e.forEach(f=>{let h=typeof f=="string"?f:f[t],T=a[h];if(T){let v=r?.deserialize(T,s);R.push(b(v));}}),R}exports.MicroStore=y;exports.MicroStoreProvider=J;exports.RESTInterpreter=l;exports.json=p;exports.useMicroStore=g;exports.useReactive=X;//# sourceMappingURL=index.js.map
1
+ 'use strict';var emberInflector=require('ember-inflector'),lodashEs=require('lodash-es'),tinybase=require('tinybase'),react=require('react'),uiReact=require('tinybase/ui-react'),jsxRuntime=require('react/jsx-runtime');var K=Object.defineProperty;var z=(o,e,r)=>e in o?K(o,e,{enumerable:true,configurable:true,writable:true,value:r}):o[e]=r;var m=(o,e,r)=>z(o,typeof e!="symbol"?e+"":e,r);function u(o,e){let r={data:[],meta:void 0},s;return o!==void 0&&Object.keys(o).forEach(t=>{let i=o[t];if(t!=="meta"){let n=[],c=lodashEs.camelCase(emberInflector.singularize(t));lodashEs.isArray(i)?i.forEach(a=>{n.push(a);}):n.push(i),r.data.push({data:n,type:c});}else s=o[t];}),r.meta=s,r}var p={serialize(o){return o?JSON.stringify(o):null},deserialize(o){return o?JSON.parse(o):null}};var N=["transform","primaryKey"],q={json:p},y=class{constructor(e){m(this,"schemas");m(this,"fieldTransforms");m(this,"recordTransforms");m(this,"store");m(this,"queries");m(this,"interpreter");m(this,"primaryKeys");this.primaryKeys={},this.schemas=e.schemas?e.schemas:{},this.fieldTransforms={...e.fieldTransforms?e.fieldTransforms:{},...q},this.recordTransforms=e.recordTransforms?e.recordTransforms:{},this.interpreter=e.interpreter?e.interpreter:u,this.store=tinybase.createStore(),this.store.setTablesSchema(this.transformSchemas()),this.queries=tinybase.createQueries(this.store);}transformSchemas(){let e={};return Object.keys(this.schemas).forEach(r=>{if(e[r]={},Object.keys(this.schemas[r]).forEach(s=>{if(e[r][s]=lodashEs.omit(this.schemas[r][s],N),this.schemas[r][s].primaryKey&&this.schemas[r][s].type==="string"){if(this.primaryKeys[r])throw Error(`More than one primary key defined for schema ${r}`);this.primaryKeys[r]=s;}}),!this.getPrimaryKey(r)&&this.schemas[r].id&&this.schemas[r].id.type==="string"&&(this.primaryKeys[r]="id"),!this.getPrimaryKey(r))throw Error(`No primary key defined for schema ${r}. This schema must have an 'id' field of "type": "string", or another field of "type": "string" with "primaryKey": true.`)}),e}getPrimaryKey(e){let r=this.primaryKeys[e];return r||void 0}getSchema(e){return e&&Object.hasOwn(this.schemas,e)?this.schemas[e]:null}getRecordTransform(e){if(e)return this.recordTransforms[e]?this.recordTransforms[e]:void 0}getFieldTransform(e){if(e)return this.fieldTransforms[e]?this.fieldTransforms[e]:void 0}serialize(e,r){let s={};return Object.keys(e).forEach(t=>{let i=r[t];if(i){let n=this.getFieldTransform(i.transform);s[t]=n?n.serialize(e[t]):e[t];}}),s}deserialize(e,r){let s={};return Object.keys(e).forEach(t=>{let i=r[t];if(i){let n=i.transform&&this.fieldTransforms[i.transform]?this.fieldTransforms[i.transform]:void 0;s[t]=n?n.deserialize(e[t]):e[t];}}),s}pushRecord(e,r,s,t={}){return this.pushRecords(e,[r],s,t)}pushRecords(e,r,s,t={}){let i=this.getRecordTransform(e),n=lodashEs.camelCase(emberInflector.pluralize(e));if(!i)return this.pushPayload(s,{[n]:r},t);let c=r.map(a=>i.serialize(a));return this.pushPayload(s,{[n]:c},t)}pushPayload(e,r,s={}){try{let t=this.interpreter(r,s);return t.data.forEach(i=>{let n=this.getSchema(i.type);if(n){let c=this.getPrimaryKey(i.type)||"id";e==="DELETE"?i.data.forEach(a=>{this.store.delRow(i.type,a[c]);}):e==="PATCH"?i.data.forEach(a=>{this.store.getRow(i.type,a[c])?this.store.setPartialRow(i.type,a[c],this.serialize(a,n)):this.store.setRow(i.type,a[c],this.serialize(a,n));}):i.data.forEach(a=>{this.store.setRow(i.type,a[c],this.serialize(a,n));});}}),t}catch(t){console.warn(t);}}peekRecord(e,r){let s=this.getSchema(e),t=this.getPrimaryKey(e),i=this.getRecordTransform(e),n=i?i.deserialize:c=>c;if(s&&t){let c=this.getStore().getRow(e,r);if(Object.keys(c).length)return n(this.deserialize(c,s))}}peekAll(e){let r=this.getSchema(e),s=this.getPrimaryKey(e),t=this.getRecordTransform(e),i=t?t.deserialize:n=>n;if(r&&s){let n=this.getStore().getTable(e);return Object.entries(n).map(([c,a])=>i(this.deserialize(a,r)))}return []}unloadRecord(e,r){let s=this.peekRecord(e,r);return s&&this.getStore().delRow(e,r),s}unloadAll(e){this.getSchema(e)&&this.getStore().delTable(e);}reset(){Object.entries(this.schemas).forEach(([e,r])=>{this.unloadAll(e);});}getStore(){return this.store}getQueries(){return this.queries}};var w=react.createContext(null);function g(){return react.useContext(w)}function J(o){let e=react.useMemo(()=>o.store,[o]);return jsxRuntime.jsx(w.Provider,{value:e,children:jsxRuntime.jsx(uiReact.Provider,{store:e.getStore(),queries:e.getQueries(),children:o.children})})}function U(o,e){return new Set(o?o.map(r=>typeof r=="string"?r:r[e]):[])}function G(o,e,r,s,t,i){t.setQueryDefinition(s,o,({select:n,where:c})=>{Object.keys(e).forEach(a=>{n(a);}),c(a=>i.has(a(r)));});}function X(o,e){let r=g(),s=r?.getSchema(o),t=r?.getPrimaryKey(o);if(!s||!t)throw new Error(`No MicroStore schema defined for type ${o}`);let[i,n]=react.useState(crypto.randomUUID()),c=uiReact.useQueries(),a=uiReact.useResultTable(i,c),[d,b]=react.useState(""),l=react.useRef("");react.useEffect(()=>{if(c){let f=U(e,t),h=JSON.stringify([...f]);d!==h&&l.current!==h&&(Object.entries(a).length>0&&(l.current=h),b(h),G(o,s,t,i,c,f));}},[e,t,s,o,c,i,d,a,l]);let S=r?.getRecordTransform(o),P=S?S.deserialize:f=>f,R=[];return e.forEach(f=>{let h=typeof f=="string"?f:f[t],T=a[h];if(T){let v=r?.deserialize(T,s);R.push(P(v));}}),R}exports.MicroStore=y;exports.MicroStoreProvider=J;exports.RESTInterpreter=u;exports.json=p;exports.useMicroStore=g;exports.useReactive=X;//# sourceMappingURL=index.js.map
2
2
  //# sourceMappingURL=index.js.map
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/interpreter.ts","../src/transforms.ts","../src/microstore.ts","../src/provider.tsx","../src/reactive.ts"],"names":["RESTInterpreter","data","_options","typedPayload","meta","k","content","typedData","typeName","camelCase","singularize","isArray","item","json","microStoreReservedKeys","defaultFieldTransforms","MicroStore","options","__publicField","createStore","createQueries","transformedSchemas","k2","omit","type","possiblePK","row","schema","serializedRow","field","transform","deserializedRow","method","typeKey","pluralize","rawData","batchedPayload","payload","pk","e","id","transformer","effectiveTransformer","x","table","_","record","schemaName","StoreContext","createContext","useMicroStore","useContext","MicroStoreProvider","props","store","useMemo","jsx","TinyBaseProvider","generateFilter","obj","resetQueryDefinition","queryName","queries","filter","select","where","getCell","useReactive","uniqueHookID","useState","useQueries","rows","useResultTable","lastFilter","setLastFilter","airBrake","useRef","useEffect","stringifiedFilter","returnData","identifier","possibleRow","thing"],"mappings":"0NAAA,IAAA,CAAA,CAAA,MAAA,CAAA,cAAA,CAAA,IAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,GAAA,CAAA,IAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,UAAA,CAAA,IAAA,CAAA,YAAA,CAAA,IAAA,CAAA,QAAA,CAAA,IAAA,CAAA,KAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,IAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,GAAA,CAAA,CAAA,CAAA,CAAA,OAAA,CAAA,EAAA,QAAA,CAAA,CAAA,CAAA,EAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAIO,SAASA,CAAAA,CAAgBC,CAAAA,CAA2BC,CAAAA,CAA+B,CACxF,IAAMC,CAAAA,CAAuC,CAC3C,IAAA,CAAM,EAAC,CACP,IAAA,CAAM,MACR,CAAA,CACIC,EAEJ,OAAIH,CAAAA,GAAS,MAAA,EACX,MAAA,CAAO,KAAKA,CAAI,CAAA,CAAE,OAAA,CAASI,CAAAA,EAAM,CAC/B,IAAMC,CAAAA,CAAUL,CAAAA,CAAKI,CAAC,CAAA,CACtB,GAAIA,CAAAA,GAAM,MAAA,CAAQ,CAChB,IAAME,CAAAA,CAAmC,EAAC,CACpCC,EAAWC,kBAAAA,CAAUC,0BAAAA,CAAYL,CAAC,CAAC,EACrCM,gBAAAA,CAAQL,CAAO,CAAA,CACjBA,CA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AA,CAAOA,EAAK0B,CAAE,CAAA,CACtD2C,CAAAA,CAAcV,CAAAA,CAAKS,CAAU,CAAA,CACnC,GAAIC,CAAAA,CAAa,CACf,IAAMC,CAAAA,CAAa5B,CAAAA,EAAO,WAAA,CAAY2B,CAAAA,CAAatD,CAAM,CAAA,CACzDoD,CAAAA,CAAW,IAAA,CAAKrC,CAAAA,CAAqBwC,CAAK,CAAM,EAClD,CACF,CAAC,EACMH,CACT","file":"index.js","sourcesContent":["import { singularize } from 'ember-inflector';\nimport { camelCase, isArray } from 'lodash-es';\nimport type { InterpreterReturnValue } from './types';\n\nexport function RESTInterpreter(data: Record<string, any>, _options: Record<string, any>) {\n const typedPayload: InterpreterReturnValue = {\n data: [],\n meta: undefined\n };\n let meta: Record<string, any> | undefined = undefined;\n\n if (data !== undefined) {\n Object.keys(data).forEach((k) => {\n const content = data[k];\n if (k !== 'meta') {\n const typedData: Record<string, any>[] = [];\n const typeName = camelCase(singularize(k));\n if (isArray(content)) {\n content.forEach((item: any) => {\n typedData.push(item);\n });\n } else {\n typedData.push(content);\n }\n typedPayload.data.push({\n data: typedData,\n type: typeName\n });\n } else {\n meta = data[k];\n }\n });\n }\n typedPayload.meta = meta;\n return typedPayload;\n}\n","import type { FieldTransform } from './types';\n\nexport const json: FieldTransform = {\n serialize(data) {\n return data ? JSON.stringify(data) : null;\n },\n deserialize(data) {\n return data ? JSON.parse(data) : null;\n }\n};\n","import { pluralize } from 'ember-inflector';\nimport { camelCase, omit } from 'lodash-es';\nimport { createQueries, createStore, type CellSchema, type Queries, type Row, type Store } from 'tinybase';\nimport { RESTInterpreter } from './interpreter';\nimport { json } from './transforms';\nimport type {\n ConventionalSchema,\n ConventionalSchemas,\n FieldTransforms,\n MethodType,\n MicrostoreInterpreter,\n MicroStoreOptions,\n MicroStoreSchema,\n MicroStoreSchemas,\n RawRecord,\n RawRow,\n RecordTransforms\n} from './types';\n\nconst microStoreReservedKeys = ['transform', 'primaryKey'];\nconst defaultFieldTransforms = {\n json\n};\n\nexport class MicroStore {\n schemas: MicroStoreSchemas;\n fieldTransforms: FieldTransforms;\n recordTransforms: RecordTransforms;\n store: Store;\n queries: Queries;\n interpreter: MicrostoreInterpreter;\n private primaryKeys: Record<string, string>;\n\n constructor(options: MicroStoreOptions) {\n this.primaryKeys = {};\n this.schemas = options.schemas ? options.schemas : {};\n // Thats right, we even support our own field and record level transforms!\n this.fieldTransforms = { ...(options.fieldTransforms ? options.fieldTransforms : {}), ...defaultFieldTransforms };\n this.recordTransforms = options.recordTransforms ? options.recordTransforms : {};\n this.interpreter = options.interpreter ? options.interpreter : RESTInterpreter;\n this.store = createStore();\n this.store.setTablesSchema(this.transformSchemas());\n this.queries = createQueries(this.store);\n }\n\n private transformSchemas() {\n // we have to remove custom properties or tinybase\n // will ignore our fields.\n const transformedSchemas: ConventionalSchemas = {};\n Object.keys(this.schemas).forEach((k) => {\n transformedSchemas[k] = <ConventionalSchema>{};\n Object.keys(this.schemas[k]).forEach((k2) => {\n transformedSchemas[k][k2] = omit(this.schemas[k][k2], microStoreReservedKeys) as CellSchema;\n const possiblePK: boolean | undefined = this.schemas[k][k2]['primaryKey'];\n if (possiblePK && this.schemas[k][k2]['type'] === 'string') {\n if (this.primaryKeys[k]) {\n throw Error(`More than one primary key defined for schema ${k}`);\n }\n this.primaryKeys[k] = k2;\n }\n });\n // Default PK to id\n if (!this.getPrimaryKey(k) && this.schemas[k]['id'] && this.schemas[k]['id']['type'] === 'string') {\n this.primaryKeys[k] = 'id';\n }\n if (!this.getPrimaryKey(k)) {\n throw Error(\n `No primary key defined for schema ${k}. This schema must have an 'id' field of \"type\": \"string\", or another field of \"type\": \"string\" with \"primaryKey\": true.`\n );\n }\n });\n return transformedSchemas;\n }\n\n getPrimaryKey(type: string) {\n const possiblePK = this.primaryKeys[type];\n return possiblePK ? possiblePK : undefined;\n }\n\n getSchema(type: string) {\n if (type) {\n if (Object.hasOwn(this.schemas, type)) {\n return this.schemas[type];\n }\n }\n return null;\n }\n\n getRecordTransform(type: string | undefined) {\n if (type) {\n return this.recordTransforms[type] ? this.recordTransforms[type] : undefined;\n }\n return undefined;\n }\n\n getFieldTransform(type: string | undefined) {\n if (type) {\n return this.fieldTransforms[type] ? this.fieldTransforms[type] : undefined;\n }\n return undefined;\n }\n\n serialize(row: RawRow, schema: MicroStoreSchema) {\n const serializedRow: RawRow = {};\n Object.keys(row).forEach((k) => {\n const field = schema[k];\n if (field) {\n const transform = this.getFieldTransform(field.transform);\n serializedRow[k] = transform ? transform.serialize(row[k]) : row[k];\n }\n });\n return serializedRow;\n }\n\n deserialize(row: Row, schema: MicroStoreSchema) {\n const deserializedRow: RawRow = {};\n Object.keys(row).forEach((k) => {\n const field = schema[k];\n if (field) {\n const transform =\n field.transform && this.fieldTransforms[field.transform] ? this.fieldTransforms[field.transform] : undefined;\n deserializedRow[k] = transform ? transform.deserialize(row[k]) : row[k];\n }\n });\n return deserializedRow;\n }\n\n // pushRecord is a sugar method to take a single record and push it into the store using whatever verb was used\n pushRecord(type: string, data: RawRecord, method: MethodType, options: Record<string, any> = {}) {\n return this.pushRecords(type, [data], method, options);\n }\n\n // pushRecords handles an incoming data (\"row\"s) that are in application level format (with dates, blobs, or other complex types that can't be POJO'd)\n pushRecords(type: string, data: RawRecord[], method: MethodType, options: Record<string, any> = {}) {\n const transform = this.getRecordTransform(type);\n const typeKey = camelCase(pluralize(type));\n if (!transform) {\n return this.pushPayload(method, { [typeKey]: data }, options);\n }\n const rawData = data.map((item) => {\n return transform.serialize(item);\n });\n return this.pushPayload(method, { [typeKey]: rawData }, options);\n }\n\n // pushPayload handles incoming data (many \"row\"s) that are in POJO format\n pushPayload(method: MethodType, data: any, options: Record<string, any> = {}) {\n try {\n const batchedPayload = this.interpreter(data, options);\n batchedPayload.data.forEach((payload) => {\n const schema = this.getSchema(payload.type);\n // Only process typed batches that match a defined data schema\n if (schema) {\n const pk = this.getPrimaryKey(payload.type) || 'id';\n if (method === 'DELETE') {\n payload.data.forEach((row) => {\n this.store.delRow(payload.type, row[pk]);\n });\n } else if (method === 'PATCH') {\n payload.data.forEach((row) => {\n // Only try a partial row update if a row already exists\n if (this.store.getRow(payload.type, row[pk])) {\n this.store.setPartialRow(payload.type, row[pk], this.serialize(row, schema));\n } else {\n this.store.setRow(payload.type, row[pk], this.serialize(row, schema));\n }\n });\n } else {\n payload.data.forEach((row) => {\n this.store.setRow(payload.type, row[pk], this.serialize(row, schema));\n });\n }\n }\n });\n return batchedPayload;\n } catch (e) {\n console.warn(e);\n }\n }\n\n peekRecord<T>(type: string, id: string): T | undefined {\n const schema = this.getSchema(type);\n const pk = this.getPrimaryKey(type);\n const transformer = this.getRecordTransform(type);\n const effectiveTransformer = transformer ? transformer.deserialize : (x: any) => x;\n if (schema && pk) {\n const row = this.getStore().getRow(type, id);\n if (row) {\n return effectiveTransformer(this.deserialize(row, schema));\n }\n }\n return undefined;\n }\n\n peekAll<T>(type: string): T[] {\n const schema = this.getSchema(type);\n const pk = this.getPrimaryKey(type);\n const transformer = this.getRecordTransform(type);\n const effectiveTransformer = transformer ? transformer.deserialize : (x: any) => x;\n if (schema && pk) {\n const table = this.getStore().getTable(type);\n return Object.entries(table).map(([_, row]) => {\n const thing = effectiveTransformer(this.deserialize(row, schema));\n return thing as T;\n });\n }\n return [];\n }\n\n unloadRecord<T>(type: string, id: string): T | undefined {\n const record = this.peekRecord<T>(type, id);\n if (record) {\n this.getStore().delRow(type, id);\n }\n return record;\n }\n\n unloadAll(type: string) {\n if (this.getSchema(type)) {\n this.getStore().delTable(type);\n }\n }\n\n reset() {\n Object.entries(this.schemas).forEach(([schemaName, _]) => {\n this.unloadAll(schemaName);\n });\n }\n\n // Need to get the raw tinybase store? use this method\n getStore() {\n return this.store;\n }\n\n // Need to get the raw tinybase query views? use this method\n getQueries() {\n return this.queries;\n }\n}\n","import { createContext, useContext, useMemo, type ReactNode } from 'react';\nimport { Provider as TinyBaseProvider } from 'tinybase/ui-react';\nimport type { MicroStore } from './microstore';\n\nconst StoreContext = createContext<MicroStore | null>(null);\n\nexport function useMicroStore(): MicroStore | null {\n const store = useContext(StoreContext);\n\n return store;\n}\n\ntype WithExistingStore = { store: MicroStore; children: ReactNode };\n\nexport function MicroStoreProvider(props: WithExistingStore) {\n const store = useMemo(() => props.store, [props]);\n\n // TODO: Add store.relationships, which can be passed to tinybase\n return (\n <StoreContext.Provider value={store}>\n <TinyBaseProvider store={store.getStore()} queries={store.getQueries()}>\n {props.children}\n </TinyBaseProvider>\n </StoreContext.Provider>\n );\n}\n","import { useEffect, useRef, useState } from 'react';\nimport { type Queries } from 'tinybase';\nimport { useQueries, useResultTable } from 'tinybase/ui-react';\nimport { useMicroStore } from './provider';\nimport type { MicroStoreSchema } from './types';\n\nfunction generateFilter(data: any[] | undefined, pk: string) {\n return new Set(\n data\n ? data.map((obj) => {\n if (typeof obj === 'string') {\n return obj;\n }\n return obj[pk];\n })\n : []\n );\n}\n\nfunction resetQueryDefinition(\n type: string,\n schema: MicroStoreSchema,\n pk: string,\n queryName: string,\n queries: Queries,\n filter: Set<string>\n) {\n // So what exactly does this do? It returns all the same tinybase rows that are\n // returned by the same React query being referenced by this reactive wrapper!!\n // That way, when the rows from useResultTable change due to some localized store\n // update through the MicroStore engine, we see those changes reflected without\n // additional server traffic!\n queries.setQueryDefinition(queryName, type, ({ select, where }) => {\n Object.keys(schema).forEach((k) => {\n select(k);\n });\n where((getCell) => filter.has(<string>getCell(pk)));\n });\n}\n\n// Wrap the objects in tinybase rows to make them react at a record level\n// to individual record changes\nexport function useReactive<T>(type: string, data: T[] | string[]): T[] {\n const store = useMicroStore();\n const schema = store?.getSchema(type);\n const pk = store?.getPrimaryKey(type);\n if (!schema || !pk) {\n throw new Error(`No MicroStore schema defined for type ${type}`);\n }\n const [uniqueHookID, _] = useState(crypto.randomUUID());\n const queries = useQueries();\n const rows = useResultTable(uniqueHookID, queries);\n const [lastFilter, setLastFilter] = useState('');\n // Air Brake prevents render loops if a user does something very silly like chasing\n // records in a circle\n const airBrake = useRef('');\n\n // Why is this effect important? Because you ONLY want to update the thing\n // that is bubbling out new rows (the query) if the supporting REST request\n // with its own internal IDs has changed. We\n useEffect(() => {\n if (queries) {\n const filter = generateFilter(data, pk);\n const stringifiedFilter = JSON.stringify([...filter]);\n if (lastFilter !== stringifiedFilter && airBrake.current !== stringifiedFilter) {\n if (Object.entries(rows).length > 0) {\n airBrake.current = stringifiedFilter;\n }\n setLastFilter(stringifiedFilter);\n resetQueryDefinition(type, schema, pk, uniqueHookID, queries, filter);\n }\n }\n }, [data, pk, schema, type, queries, uniqueHookID, lastFilter, rows, airBrake]);\n\n const transformer = store?.getRecordTransform(type);\n const effectiveTransformer = transformer ? transformer.deserialize : (x: any) => x;\n const returnData: T[] = [];\n data.forEach((item: any) => {\n const identifier = typeof item === 'string' ? item : item[pk];\n const possibleRow = rows[identifier];\n if (possibleRow) {\n const thing: any = store?.deserialize(possibleRow, schema);\n returnData.push(effectiveTransformer(thing) as T);\n }\n });\n return returnData;\n}\n"]}
1
+ {"version":3,"sources":["../src/interpreter.ts","../src/transforms.ts","../src/microstore.ts","../src/provider.tsx","../src/reactive.ts"],"names":["RESTInterpreter","data","_options","typedPayload","meta","k","content","typedData","typeName","camelCase","singularize","isArray","item","json","microStoreReservedKeys","defaultFieldTransforms","MicroStore","options","__publicField","createStore","createQueries","transformedSchemas","k2","omit","type","possiblePK","row","schema","serializedRow","field","transform","deserializedRow","method","typeKey","pluralize","rawData","batchedPayload","payload","pk","e","id","transformer","effectiveTransformer","x","table","_","record","schemaName","StoreContext","createContext","useMicroStore","useContext","MicroStoreProvider","props","store","useMemo","jsx","TinyBaseProvider","generateFilter","obj","resetQueryDefinition","queryName","queries","filter","select","where","getCell","useReactive","uniqueHookID","useState","useQueries","rows","useResultTable","lastFilter","setLastFilter","airBrake","useRef","useEffect","stringifiedFilter","returnData","identifier","possibleRow","thing"],"mappings":"0NAAA,IAAA,CAAA,CAAA,MAAA,CAAA,cAAA,CAAA,IAAA,CAAA,CAAA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AqBwC,CAAK,CAAM,EAClD,CACF,CAAC,EACMH,CACT","file":"index.js","sourcesContent":["import { singularize } from 'ember-inflector';\nimport { camelCase, isArray } from 'lodash-es';\nimport type { InterpreterReturnValue } from './types';\n\nexport function RESTInterpreter(data: Record<string, any>, _options: Record<string, any>) {\n const typedPayload: InterpreterReturnValue = {\n data: [],\n meta: undefined\n };\n let meta: Record<string, any> | undefined = undefined;\n\n if (data !== undefined) {\n Object.keys(data).forEach((k) => {\n const content = data[k];\n if (k !== 'meta') {\n const typedData: Record<string, any>[] = [];\n const typeName = camelCase(singularize(k));\n if (isArray(content)) {\n content.forEach((item: any) => {\n typedData.push(item);\n });\n } else {\n typedData.push(content);\n }\n typedPayload.data.push({\n data: typedData,\n type: typeName\n });\n } else {\n meta = data[k];\n }\n });\n }\n typedPayload.meta = meta;\n return typedPayload;\n}\n","import type { FieldTransform } from './types';\n\nexport const json: FieldTransform = {\n serialize(data) {\n return data ? JSON.stringify(data) : null;\n },\n deserialize(data) {\n return data ? JSON.parse(data) : null;\n }\n};\n","import { pluralize } from 'ember-inflector';\nimport { camelCase, omit } from 'lodash-es';\nimport { createQueries, createStore, type CellSchema, type Queries, type Row, type Store } from 'tinybase';\nimport { RESTInterpreter } from './interpreter';\nimport { json } from './transforms';\nimport type {\n ConventionalSchema,\n ConventionalSchemas,\n FieldTransforms,\n MethodType,\n MicrostoreInterpreter,\n MicroStoreOptions,\n MicroStoreSchema,\n MicroStoreSchemas,\n RawRecord,\n RawRow,\n RecordTransforms\n} from './types';\n\nconst microStoreReservedKeys = ['transform', 'primaryKey'];\nconst defaultFieldTransforms = {\n json\n};\n\nexport class MicroStore {\n schemas: MicroStoreSchemas;\n fieldTransforms: FieldTransforms;\n recordTransforms: RecordTransforms;\n store: Store;\n queries: Queries;\n interpreter: MicrostoreInterpreter;\n private primaryKeys: Record<string, string>;\n\n constructor(options: MicroStoreOptions) {\n this.primaryKeys = {};\n this.schemas = options.schemas ? options.schemas : {};\n // Thats right, we even support our own field and record level transforms!\n this.fieldTransforms = { ...(options.fieldTransforms ? options.fieldTransforms : {}), ...defaultFieldTransforms };\n this.recordTransforms = options.recordTransforms ? options.recordTransforms : {};\n this.interpreter = options.interpreter ? options.interpreter : RESTInterpreter;\n this.store = createStore();\n this.store.setTablesSchema(this.transformSchemas());\n this.queries = createQueries(this.store);\n }\n\n private transformSchemas() {\n // we have to remove custom properties or tinybase\n // will ignore our fields.\n const transformedSchemas: ConventionalSchemas = {};\n Object.keys(this.schemas).forEach((k) => {\n transformedSchemas[k] = <ConventionalSchema>{};\n Object.keys(this.schemas[k]).forEach((k2) => {\n transformedSchemas[k][k2] = omit(this.schemas[k][k2], microStoreReservedKeys) as CellSchema;\n const possiblePK: boolean | undefined = this.schemas[k][k2]['primaryKey'];\n if (possiblePK && this.schemas[k][k2]['type'] === 'string') {\n if (this.primaryKeys[k]) {\n throw Error(`More than one primary key defined for schema ${k}`);\n }\n this.primaryKeys[k] = k2;\n }\n });\n // Default PK to id\n if (!this.getPrimaryKey(k) && this.schemas[k]['id'] && this.schemas[k]['id']['type'] === 'string') {\n this.primaryKeys[k] = 'id';\n }\n if (!this.getPrimaryKey(k)) {\n throw Error(\n `No primary key defined for schema ${k}. This schema must have an 'id' field of \"type\": \"string\", or another field of \"type\": \"string\" with \"primaryKey\": true.`\n );\n }\n });\n return transformedSchemas;\n }\n\n getPrimaryKey(type: string) {\n const possiblePK = this.primaryKeys[type];\n return possiblePK ? possiblePK : undefined;\n }\n\n getSchema(type: string) {\n if (type) {\n if (Object.hasOwn(this.schemas, type)) {\n return this.schemas[type];\n }\n }\n return null;\n }\n\n getRecordTransform(type: string | undefined) {\n if (type) {\n return this.recordTransforms[type] ? this.recordTransforms[type] : undefined;\n }\n return undefined;\n }\n\n getFieldTransform(type: string | undefined) {\n if (type) {\n return this.fieldTransforms[type] ? this.fieldTransforms[type] : undefined;\n }\n return undefined;\n }\n\n serialize(row: RawRow, schema: MicroStoreSchema) {\n const serializedRow: RawRow = {};\n Object.keys(row).forEach((k) => {\n const field = schema[k];\n if (field) {\n const transform = this.getFieldTransform(field.transform);\n serializedRow[k] = transform ? transform.serialize(row[k]) : row[k];\n }\n });\n return serializedRow;\n }\n\n deserialize(row: Row, schema: MicroStoreSchema) {\n const deserializedRow: RawRow = {};\n Object.keys(row).forEach((k) => {\n const field = schema[k];\n if (field) {\n const transform =\n field.transform && this.fieldTransforms[field.transform] ? this.fieldTransforms[field.transform] : undefined;\n deserializedRow[k] = transform ? transform.deserialize(row[k]) : row[k];\n }\n });\n return deserializedRow;\n }\n\n // pushRecord is a sugar method to take a single record and push it into the store using whatever verb was used\n pushRecord(type: string, data: RawRecord, method: MethodType, options: Record<string, any> = {}) {\n return this.pushRecords(type, [data], method, options);\n }\n\n // pushRecords handles an incoming data (\"row\"s) that are in application level format (with dates, blobs, or other complex types that can't be POJO'd)\n pushRecords(type: string, data: RawRecord[], method: MethodType, options: Record<string, any> = {}) {\n const transform = this.getRecordTransform(type);\n const typeKey = camelCase(pluralize(type));\n if (!transform) {\n return this.pushPayload(method, { [typeKey]: data }, options);\n }\n const rawData = data.map((item) => {\n return transform.serialize(item);\n });\n return this.pushPayload(method, { [typeKey]: rawData }, options);\n }\n\n // pushPayload handles incoming data (many \"row\"s) that are in POJO format\n pushPayload(method: MethodType, data: any, options: Record<string, any> = {}) {\n try {\n const batchedPayload = this.interpreter(data, options);\n batchedPayload.data.forEach((payload) => {\n const schema = this.getSchema(payload.type);\n // Only process typed batches that match a defined data schema\n if (schema) {\n const pk = this.getPrimaryKey(payload.type) || 'id';\n if (method === 'DELETE') {\n payload.data.forEach((row) => {\n this.store.delRow(payload.type, row[pk]);\n });\n } else if (method === 'PATCH') {\n payload.data.forEach((row) => {\n // Only try a partial row update if a row already exists\n if (this.store.getRow(payload.type, row[pk])) {\n this.store.setPartialRow(payload.type, row[pk], this.serialize(row, schema));\n } else {\n this.store.setRow(payload.type, row[pk], this.serialize(row, schema));\n }\n });\n } else {\n payload.data.forEach((row) => {\n this.store.setRow(payload.type, row[pk], this.serialize(row, schema));\n });\n }\n }\n });\n return batchedPayload;\n } catch (e) {\n console.warn(e);\n }\n }\n\n peekRecord<T>(type: string, id: string) {\n const schema = this.getSchema(type);\n const pk = this.getPrimaryKey(type);\n const transformer = this.getRecordTransform(type);\n const effectiveTransformer = transformer ? transformer.deserialize : (x: any) => x;\n if (schema && pk) {\n const row = this.getStore().getRow(type, id);\n if (Object.keys(row).length) {\n return effectiveTransformer(this.deserialize(row, schema)) as T;\n }\n }\n return undefined;\n }\n\n peekAll<T>(type: string) {\n const schema = this.getSchema(type);\n const pk = this.getPrimaryKey(type);\n const transformer = this.getRecordTransform(type);\n const effectiveTransformer = transformer ? transformer.deserialize : (x: any) => x;\n if (schema && pk) {\n const table = this.getStore().getTable(type);\n return Object.entries(table).map(([_, row]) => {\n const thing = effectiveTransformer(this.deserialize(row, schema));\n return thing as T;\n });\n }\n return [] as T[];\n }\n\n unloadRecord<T>(type: string, id: string) {\n const record = this.peekRecord<T>(type, id);\n if (record) {\n this.getStore().delRow(type, id);\n }\n return record;\n }\n\n unloadAll(type: string) {\n if (this.getSchema(type)) {\n this.getStore().delTable(type);\n }\n }\n\n reset() {\n Object.entries(this.schemas).forEach(([schemaName, _]) => {\n this.unloadAll(schemaName);\n });\n }\n\n // Need to get the raw tinybase store? use this method\n getStore() {\n return this.store;\n }\n\n // Need to get the raw tinybase query views? use this method\n getQueries() {\n return this.queries;\n }\n}\n","import { createContext, useContext, useMemo, type ReactNode } from 'react';\nimport { Provider as TinyBaseProvider } from 'tinybase/ui-react';\nimport type { MicroStore } from './microstore';\n\nconst StoreContext = createContext<MicroStore | null>(null);\n\nexport function useMicroStore(): MicroStore | null {\n const store = useContext(StoreContext);\n\n return store;\n}\n\ntype WithExistingStore = { store: MicroStore; children: ReactNode };\n\nexport function MicroStoreProvider(props: WithExistingStore) {\n const store = useMemo(() => props.store, [props]);\n\n // TODO: Add store.relationships, which can be passed to tinybase\n return (\n <StoreContext.Provider value={store}>\n <TinyBaseProvider store={store.getStore()} queries={store.getQueries()}>\n {props.children}\n </TinyBaseProvider>\n </StoreContext.Provider>\n );\n}\n","import { useEffect, useRef, useState } from 'react';\nimport { type Queries } from 'tinybase';\nimport { useQueries, useResultTable } from 'tinybase/ui-react';\nimport { useMicroStore } from './provider';\nimport type { MicroStoreSchema } from './types';\n\nfunction generateFilter(data: any[] | undefined, pk: string) {\n return new Set(\n data\n ? data.map((obj) => {\n if (typeof obj === 'string') {\n return obj;\n }\n return obj[pk];\n })\n : []\n );\n}\n\nfunction resetQueryDefinition(\n type: string,\n schema: MicroStoreSchema,\n pk: string,\n queryName: string,\n queries: Queries,\n filter: Set<string>\n) {\n // So what exactly does this do? It returns all the same tinybase rows that are\n // returned by the same React query being referenced by this reactive wrapper!!\n // That way, when the rows from useResultTable change due to some localized store\n // update through the MicroStore engine, we see those changes reflected without\n // additional server traffic!\n queries.setQueryDefinition(queryName, type, ({ select, where }) => {\n Object.keys(schema).forEach((k) => {\n select(k);\n });\n where((getCell) => filter.has(<string>getCell(pk)));\n });\n}\n\n// Wrap the objects in tinybase rows to make them react at a record level\n// to individual record changes\nexport function useReactive<T>(type: string, data: T[] | string[]): T[] {\n const store = useMicroStore();\n const schema = store?.getSchema(type);\n const pk = store?.getPrimaryKey(type);\n if (!schema || !pk) {\n throw new Error(`No MicroStore schema defined for type ${type}`);\n }\n const [uniqueHookID, _] = useState(crypto.randomUUID());\n const queries = useQueries();\n const rows = useResultTable(uniqueHookID, queries);\n const [lastFilter, setLastFilter] = useState('');\n // Air Brake prevents render loops if a user does something very silly like chasing\n // records in a circle\n const airBrake = useRef('');\n\n // Why is this effect important? Because you ONLY want to update the thing\n // that is bubbling out new rows (the query) if the supporting REST request\n // with its own internal IDs has changed.\n useEffect(() => {\n if (queries) {\n const filter = generateFilter(data, pk);\n const stringifiedFilter = JSON.stringify([...filter]);\n if (lastFilter !== stringifiedFilter && airBrake.current !== stringifiedFilter) {\n if (Object.entries(rows).length > 0) {\n airBrake.current = stringifiedFilter;\n }\n setLastFilter(stringifiedFilter);\n resetQueryDefinition(type, schema, pk, uniqueHookID, queries, filter);\n }\n }\n }, [data, pk, schema, type, queries, uniqueHookID, lastFilter, rows, airBrake]);\n\n const transformer = store?.getRecordTransform(type);\n const effectiveTransformer = transformer ? transformer.deserialize : (x: any) => x;\n const returnData: T[] = [];\n data.forEach((item: any) => {\n const identifier = typeof item === 'string' ? item : item[pk];\n const possibleRow = rows[identifier];\n if (possibleRow) {\n const thing: any = store?.deserialize(possibleRow, schema);\n returnData.push(effectiveTransformer(thing) as T);\n }\n });\n return returnData;\n}\n"]}
package/dist/index.mjs CHANGED
@@ -1,2 +1,2 @@
1
- import {singularize,pluralize}from'ember-inflector';import {camelCase,isArray,omit}from'lodash-es';import {createStore,createQueries}from'tinybase';import {createContext,useContext,useMemo,useState,useRef,useEffect}from'react';import {Provider,useQueries,useResultTable}from'tinybase/ui-react';import {jsx}from'react/jsx-runtime';var K=Object.defineProperty;var z=(o,e,r)=>e in o?K(o,e,{enumerable:true,configurable:true,writable:true,value:r}):o[e]=r;var m=(o,e,r)=>z(o,typeof e!="symbol"?e+"":e,r);function l(o,e){let r={data:[],meta:void 0},s;return o!==void 0&&Object.keys(o).forEach(t=>{let i=o[t];if(t!=="meta"){let n=[],c=camelCase(singularize(t));isArray(i)?i.forEach(a=>{n.push(a);}):n.push(i),r.data.push({data:n,type:c});}else s=o[t];}),r.meta=s,r}var p={serialize(o){return o?JSON.stringify(o):null},deserialize(o){return o?JSON.parse(o):null}};var N=["transform","primaryKey"],q={json:p},y=class{constructor(e){m(this,"schemas");m(this,"fieldTransforms");m(this,"recordTransforms");m(this,"store");m(this,"queries");m(this,"interpreter");m(this,"primaryKeys");this.primaryKeys={},this.schemas=e.schemas?e.schemas:{},this.fieldTransforms={...e.fieldTransforms?e.fieldTransforms:{},...q},this.recordTransforms=e.recordTransforms?e.recordTransforms:{},this.interpreter=e.interpreter?e.interpreter:l,this.store=createStore(),this.store.setTablesSchema(this.transformSchemas()),this.queries=createQueries(this.store);}transformSchemas(){let e={};return Object.keys(this.schemas).forEach(r=>{if(e[r]={},Object.keys(this.schemas[r]).forEach(s=>{if(e[r][s]=omit(this.schemas[r][s],N),this.schemas[r][s].primaryKey&&this.schemas[r][s].type==="string"){if(this.primaryKeys[r])throw Error(`More than one primary key defined for schema ${r}`);this.primaryKeys[r]=s;}}),!this.getPrimaryKey(r)&&this.schemas[r].id&&this.schemas[r].id.type==="string"&&(this.primaryKeys[r]="id"),!this.getPrimaryKey(r))throw Error(`No primary key defined for schema ${r}. This schema must have an 'id' field of "type": "string", or another field of "type": "string" with "primaryKey": true.`)}),e}getPrimaryKey(e){let r=this.primaryKeys[e];return r||void 0}getSchema(e){return e&&Object.hasOwn(this.schemas,e)?this.schemas[e]:null}getRecordTransform(e){if(e)return this.recordTransforms[e]?this.recordTransforms[e]:void 0}getFieldTransform(e){if(e)return this.fieldTransforms[e]?this.fieldTransforms[e]:void 0}serialize(e,r){let s={};return Object.keys(e).forEach(t=>{let i=r[t];if(i){let n=this.getFieldTransform(i.transform);s[t]=n?n.serialize(e[t]):e[t];}}),s}deserialize(e,r){let s={};return Object.keys(e).forEach(t=>{let i=r[t];if(i){let n=i.transform&&this.fieldTransforms[i.transform]?this.fieldTransforms[i.transform]:void 0;s[t]=n?n.deserialize(e[t]):e[t];}}),s}pushRecord(e,r,s,t={}){return this.pushRecords(e,[r],s,t)}pushRecords(e,r,s,t={}){let i=this.getRecordTransform(e),n=camelCase(pluralize(e));if(!i)return this.pushPayload(s,{[n]:r},t);let c=r.map(a=>i.serialize(a));return this.pushPayload(s,{[n]:c},t)}pushPayload(e,r,s={}){try{let t=this.interpreter(r,s);return t.data.forEach(i=>{let n=this.getSchema(i.type);if(n){let c=this.getPrimaryKey(i.type)||"id";e==="DELETE"?i.data.forEach(a=>{this.store.delRow(i.type,a[c]);}):e==="PATCH"?i.data.forEach(a=>{this.store.getRow(i.type,a[c])?this.store.setPartialRow(i.type,a[c],this.serialize(a,n)):this.store.setRow(i.type,a[c],this.serialize(a,n));}):i.data.forEach(a=>{this.store.setRow(i.type,a[c],this.serialize(a,n));});}}),t}catch(t){console.warn(t);}}peekRecord(e,r){let s=this.getSchema(e),t=this.getPrimaryKey(e),i=this.getRecordTransform(e),n=i?i.deserialize:c=>c;if(s&&t){let c=this.getStore().getRow(e,r);if(c)return n(this.deserialize(c,s))}}peekAll(e){let r=this.getSchema(e),s=this.getPrimaryKey(e),t=this.getRecordTransform(e),i=t?t.deserialize:n=>n;if(r&&s){let n=this.getStore().getTable(e);return Object.entries(n).map(([c,a])=>i(this.deserialize(a,r)))}return []}unloadRecord(e,r){let s=this.peekRecord(e,r);return s&&this.getStore().delRow(e,r),s}unloadAll(e){this.getSchema(e)&&this.getStore().delTable(e);}reset(){Object.entries(this.schemas).forEach(([e,r])=>{this.unloadAll(e);});}getStore(){return this.store}getQueries(){return this.queries}};var w=createContext(null);function g(){return useContext(w)}function J(o){let e=useMemo(()=>o.store,[o]);return jsx(w.Provider,{value:e,children:jsx(Provider,{store:e.getStore(),queries:e.getQueries(),children:o.children})})}function U(o,e){return new Set(o?o.map(r=>typeof r=="string"?r:r[e]):[])}function G(o,e,r,s,t,i){t.setQueryDefinition(s,o,({select:n,where:c})=>{Object.keys(e).forEach(a=>{n(a);}),c(a=>i.has(a(r)));});}function X(o,e){let r=g(),s=r?.getSchema(o),t=r?.getPrimaryKey(o);if(!s||!t)throw new Error(`No MicroStore schema defined for type ${o}`);let[i,n]=useState(crypto.randomUUID()),c=useQueries(),a=useResultTable(i,c),[d,P]=useState(""),u=useRef("");useEffect(()=>{if(c){let f=U(e,t),h=JSON.stringify([...f]);d!==h&&u.current!==h&&(Object.entries(a).length>0&&(u.current=h),P(h),G(o,s,t,i,c,f));}},[e,t,s,o,c,i,d,a,u]);let S=r?.getRecordTransform(o),b=S?S.deserialize:f=>f,R=[];return e.forEach(f=>{let h=typeof f=="string"?f:f[t],T=a[h];if(T){let v=r?.deserialize(T,s);R.push(b(v));}}),R}export{y as MicroStore,J as MicroStoreProvider,l as RESTInterpreter,p as json,g as useMicroStore,X as useReactive};//# sourceMappingURL=index.mjs.map
1
+ import {singularize,pluralize}from'ember-inflector';import {camelCase,isArray,omit}from'lodash-es';import {createStore,createQueries}from'tinybase';import {createContext,useContext,useMemo,useState,useRef,useEffect}from'react';import {Provider,useQueries,useResultTable}from'tinybase/ui-react';import {jsx}from'react/jsx-runtime';var K=Object.defineProperty;var z=(o,e,r)=>e in o?K(o,e,{enumerable:true,configurable:true,writable:true,value:r}):o[e]=r;var m=(o,e,r)=>z(o,typeof e!="symbol"?e+"":e,r);function u(o,e){let r={data:[],meta:void 0},s;return o!==void 0&&Object.keys(o).forEach(t=>{let i=o[t];if(t!=="meta"){let n=[],c=camelCase(singularize(t));isArray(i)?i.forEach(a=>{n.push(a);}):n.push(i),r.data.push({data:n,type:c});}else s=o[t];}),r.meta=s,r}var p={serialize(o){return o?JSON.stringify(o):null},deserialize(o){return o?JSON.parse(o):null}};var N=["transform","primaryKey"],q={json:p},y=class{constructor(e){m(this,"schemas");m(this,"fieldTransforms");m(this,"recordTransforms");m(this,"store");m(this,"queries");m(this,"interpreter");m(this,"primaryKeys");this.primaryKeys={},this.schemas=e.schemas?e.schemas:{},this.fieldTransforms={...e.fieldTransforms?e.fieldTransforms:{},...q},this.recordTransforms=e.recordTransforms?e.recordTransforms:{},this.interpreter=e.interpreter?e.interpreter:u,this.store=createStore(),this.store.setTablesSchema(this.transformSchemas()),this.queries=createQueries(this.store);}transformSchemas(){let e={};return Object.keys(this.schemas).forEach(r=>{if(e[r]={},Object.keys(this.schemas[r]).forEach(s=>{if(e[r][s]=omit(this.schemas[r][s],N),this.schemas[r][s].primaryKey&&this.schemas[r][s].type==="string"){if(this.primaryKeys[r])throw Error(`More than one primary key defined for schema ${r}`);this.primaryKeys[r]=s;}}),!this.getPrimaryKey(r)&&this.schemas[r].id&&this.schemas[r].id.type==="string"&&(this.primaryKeys[r]="id"),!this.getPrimaryKey(r))throw Error(`No primary key defined for schema ${r}. This schema must have an 'id' field of "type": "string", or another field of "type": "string" with "primaryKey": true.`)}),e}getPrimaryKey(e){let r=this.primaryKeys[e];return r||void 0}getSchema(e){return e&&Object.hasOwn(this.schemas,e)?this.schemas[e]:null}getRecordTransform(e){if(e)return this.recordTransforms[e]?this.recordTransforms[e]:void 0}getFieldTransform(e){if(e)return this.fieldTransforms[e]?this.fieldTransforms[e]:void 0}serialize(e,r){let s={};return Object.keys(e).forEach(t=>{let i=r[t];if(i){let n=this.getFieldTransform(i.transform);s[t]=n?n.serialize(e[t]):e[t];}}),s}deserialize(e,r){let s={};return Object.keys(e).forEach(t=>{let i=r[t];if(i){let n=i.transform&&this.fieldTransforms[i.transform]?this.fieldTransforms[i.transform]:void 0;s[t]=n?n.deserialize(e[t]):e[t];}}),s}pushRecord(e,r,s,t={}){return this.pushRecords(e,[r],s,t)}pushRecords(e,r,s,t={}){let i=this.getRecordTransform(e),n=camelCase(pluralize(e));if(!i)return this.pushPayload(s,{[n]:r},t);let c=r.map(a=>i.serialize(a));return this.pushPayload(s,{[n]:c},t)}pushPayload(e,r,s={}){try{let t=this.interpreter(r,s);return t.data.forEach(i=>{let n=this.getSchema(i.type);if(n){let c=this.getPrimaryKey(i.type)||"id";e==="DELETE"?i.data.forEach(a=>{this.store.delRow(i.type,a[c]);}):e==="PATCH"?i.data.forEach(a=>{this.store.getRow(i.type,a[c])?this.store.setPartialRow(i.type,a[c],this.serialize(a,n)):this.store.setRow(i.type,a[c],this.serialize(a,n));}):i.data.forEach(a=>{this.store.setRow(i.type,a[c],this.serialize(a,n));});}}),t}catch(t){console.warn(t);}}peekRecord(e,r){let s=this.getSchema(e),t=this.getPrimaryKey(e),i=this.getRecordTransform(e),n=i?i.deserialize:c=>c;if(s&&t){let c=this.getStore().getRow(e,r);if(Object.keys(c).length)return n(this.deserialize(c,s))}}peekAll(e){let r=this.getSchema(e),s=this.getPrimaryKey(e),t=this.getRecordTransform(e),i=t?t.deserialize:n=>n;if(r&&s){let n=this.getStore().getTable(e);return Object.entries(n).map(([c,a])=>i(this.deserialize(a,r)))}return []}unloadRecord(e,r){let s=this.peekRecord(e,r);return s&&this.getStore().delRow(e,r),s}unloadAll(e){this.getSchema(e)&&this.getStore().delTable(e);}reset(){Object.entries(this.schemas).forEach(([e,r])=>{this.unloadAll(e);});}getStore(){return this.store}getQueries(){return this.queries}};var w=createContext(null);function g(){return useContext(w)}function J(o){let e=useMemo(()=>o.store,[o]);return jsx(w.Provider,{value:e,children:jsx(Provider,{store:e.getStore(),queries:e.getQueries(),children:o.children})})}function U(o,e){return new Set(o?o.map(r=>typeof r=="string"?r:r[e]):[])}function G(o,e,r,s,t,i){t.setQueryDefinition(s,o,({select:n,where:c})=>{Object.keys(e).forEach(a=>{n(a);}),c(a=>i.has(a(r)));});}function X(o,e){let r=g(),s=r?.getSchema(o),t=r?.getPrimaryKey(o);if(!s||!t)throw new Error(`No MicroStore schema defined for type ${o}`);let[i,n]=useState(crypto.randomUUID()),c=useQueries(),a=useResultTable(i,c),[d,b]=useState(""),l=useRef("");useEffect(()=>{if(c){let f=U(e,t),h=JSON.stringify([...f]);d!==h&&l.current!==h&&(Object.entries(a).length>0&&(l.current=h),b(h),G(o,s,t,i,c,f));}},[e,t,s,o,c,i,d,a,l]);let S=r?.getRecordTransform(o),P=S?S.deserialize:f=>f,R=[];return e.forEach(f=>{let h=typeof f=="string"?f:f[t],T=a[h];if(T){let v=r?.deserialize(T,s);R.push(P(v));}}),R}export{y as MicroStore,J as MicroStoreProvider,u as RESTInterpreter,p as json,g as useMicroStore,X as useReactive};//# sourceMappingURL=index.mjs.map
2
2
  //# sourceMappingURL=index.mjs.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/interpreter.ts","../src/transforms.ts","../src/microstore.ts","../src/provider.tsx","../src/reactive.ts"],"names":["RESTInterpreter","data","_options","typedPayload","meta","k","content","typedData","typeName","camelCase","singularize","isArray","item","json","microStoreReservedKeys","defaultFieldTransforms","MicroStore","options","__publicField","createStore","createQueries","transformedSchemas","k2","omit","type","possiblePK","row","schema","serializedRow","field","transform","deserializedRow","method","typeKey","pluralize","rawData","batchedPayload","payload","pk","e","id","transformer","effectiveTransformer","x","table","_","record","schemaName","StoreContext","createContext","useMicroStore","useContext","MicroStoreProvider","props","store","useMemo","jsx","TinyBaseProvider","generateFilter","obj","resetQueryDefinition","queryName","queries","filter","select","where","getCell","useReactive","uniqueHookID","useState","useQueries","rows","useResultTable","lastFilter","setLastFilter","airBrake","useRef","useEffect","stringifiedFilter","returnData","identifier","possibleRow","thing"],"mappings":"0UAAA,IAAA,CAAA,CAAA,MAAA,CAAA,cAAA,CAAA,IAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,GAAA,CAAA,IAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,UAAA,CAAA,IAAA,CAAA,YAAA,CAAA,IAAA,CAAA,QAAA,CAAA,IAAA,CAAA,KAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,IAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,GAAA,CAAA,CAAA,CAAA,CAAA,OAAA,CAAA,EAAA,QAAA,CAAA,CAAA,CAAA,EAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAIO,SAASA,CAAAA,CAAgBC,CAAAA,CAA2BC,CAAAA,CAA+B,CACxF,IAAMC,CAAAA,CAAuC,CAC3C,IAAA,CAAM,EAAC,CACP,IAAA,CAAM,MACR,CAAA,CACIC,EAEJ,OAAIH,CAAAA,GAAS,MAAA,EACX,MAAA,CAAO,KAAKA,CAAI,CAAA,CAAE,OAAA,CAASI,CAAAA,EAAM,CAC/B,IAAMC,CAAAA,CAAUL,CAAAA,CAAKI,CAAC,CAAA,CACtB,GAAIA,CAAAA,GAAM,MAAA,CAAQ,CAChB,IAAME,CAAAA,CAA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AAAA,CAAK,OAAA,CAASW,CAAAA,EAAc,CAC1B,IAAMoE,EAAa,OAAOpE,CAAAA,EAAS,QAAA,CAAWA,CAAAA,CAAOA,EAAK0B,CAAE,CAAA,CACtD2C,CAAAA,CAAcV,CAAAA,CAAKS,CAAU,CAAA,CACnC,GAAIC,CAAAA,CAAa,CACf,IAAMC,CAAAA,CAAa5B,CAAAA,EAAO,WAAA,CAAY2B,CAAAA,CAAatD,CAAM,CAAA,CACzDoD,CAAAA,CAAW,IAAA,CAAKrC,CAAAA,CAAqBwC,CAAK,CAAM,EAClD,CACF,CAAC,EACMH,CACT","file":"index.mjs","sourcesContent":["import { singularize } from 'ember-inflector';\nimport { camelCase, isArray } from 'lodash-es';\nimport type { InterpreterReturnValue } from './types';\n\nexport function RESTInterpreter(data: Record<string, any>, _options: Record<string, any>) {\n const typedPayload: InterpreterReturnValue = {\n data: [],\n meta: undefined\n };\n let meta: Record<string, any> | undefined = undefined;\n\n if (data !== undefined) {\n Object.keys(data).forEach((k) => {\n const content = data[k];\n if (k !== 'meta') {\n const typedData: Record<string, any>[] = [];\n const typeName = camelCase(singularize(k));\n if (isArray(content)) {\n content.forEach((item: any) => {\n typedData.push(item);\n });\n } else {\n typedData.push(content);\n }\n typedPayload.data.push({\n data: typedData,\n type: typeName\n });\n } else {\n meta = data[k];\n }\n });\n }\n typedPayload.meta = meta;\n return typedPayload;\n}\n","import type { FieldTransform } from './types';\n\nexport const json: FieldTransform = {\n serialize(data) {\n return data ? JSON.stringify(data) : null;\n },\n deserialize(data) {\n return data ? JSON.parse(data) : null;\n }\n};\n","import { pluralize } from 'ember-inflector';\nimport { camelCase, omit } from 'lodash-es';\nimport { createQueries, createStore, type CellSchema, type Queries, type Row, type Store } from 'tinybase';\nimport { RESTInterpreter } from './interpreter';\nimport { json } from './transforms';\nimport type {\n ConventionalSchema,\n ConventionalSchemas,\n FieldTransforms,\n MethodType,\n MicrostoreInterpreter,\n MicroStoreOptions,\n MicroStoreSchema,\n MicroStoreSchemas,\n RawRecord,\n RawRow,\n RecordTransforms\n} from './types';\n\nconst microStoreReservedKeys = ['transform', 'primaryKey'];\nconst defaultFieldTransforms = {\n json\n};\n\nexport class MicroStore {\n schemas: MicroStoreSchemas;\n fieldTransforms: FieldTransforms;\n recordTransforms: RecordTransforms;\n store: Store;\n queries: Queries;\n interpreter: MicrostoreInterpreter;\n private primaryKeys: Record<string, string>;\n\n constructor(options: MicroStoreOptions) {\n this.primaryKeys = {};\n this.schemas = options.schemas ? options.schemas : {};\n // Thats right, we even support our own field and record level transforms!\n this.fieldTransforms = { ...(options.fieldTransforms ? options.fieldTransforms : {}), ...defaultFieldTransforms };\n this.recordTransforms = options.recordTransforms ? options.recordTransforms : {};\n this.interpreter = options.interpreter ? options.interpreter : RESTInterpreter;\n this.store = createStore();\n this.store.setTablesSchema(this.transformSchemas());\n this.queries = createQueries(this.store);\n }\n\n private transformSchemas() {\n // we have to remove custom properties or tinybase\n // will ignore our fields.\n const transformedSchemas: ConventionalSchemas = {};\n Object.keys(this.schemas).forEach((k) => {\n transformedSchemas[k] = <ConventionalSchema>{};\n Object.keys(this.schemas[k]).forEach((k2) => {\n transformedSchemas[k][k2] = omit(this.schemas[k][k2], microStoreReservedKeys) as CellSchema;\n const possiblePK: boolean | undefined = this.schemas[k][k2]['primaryKey'];\n if (possiblePK && this.schemas[k][k2]['type'] === 'string') {\n if (this.primaryKeys[k]) {\n throw Error(`More than one primary key defined for schema ${k}`);\n }\n this.primaryKeys[k] = k2;\n }\n });\n // Default PK to id\n if (!this.getPrimaryKey(k) && this.schemas[k]['id'] && this.schemas[k]['id']['type'] === 'string') {\n this.primaryKeys[k] = 'id';\n }\n if (!this.getPrimaryKey(k)) {\n throw Error(\n `No primary key defined for schema ${k}. This schema must have an 'id' field of \"type\": \"string\", or another field of \"type\": \"string\" with \"primaryKey\": true.`\n );\n }\n });\n return transformedSchemas;\n }\n\n getPrimaryKey(type: string) {\n const possiblePK = this.primaryKeys[type];\n return possiblePK ? possiblePK : undefined;\n }\n\n getSchema(type: string) {\n if (type) {\n if (Object.hasOwn(this.schemas, type)) {\n return this.schemas[type];\n }\n }\n return null;\n }\n\n getRecordTransform(type: string | undefined) {\n if (type) {\n return this.recordTransforms[type] ? this.recordTransforms[type] : undefined;\n }\n return undefined;\n }\n\n getFieldTransform(type: string | undefined) {\n if (type) {\n return this.fieldTransforms[type] ? this.fieldTransforms[type] : undefined;\n }\n return undefined;\n }\n\n serialize(row: RawRow, schema: MicroStoreSchema) {\n const serializedRow: RawRow = {};\n Object.keys(row).forEach((k) => {\n const field = schema[k];\n if (field) {\n const transform = this.getFieldTransform(field.transform);\n serializedRow[k] = transform ? transform.serialize(row[k]) : row[k];\n }\n });\n return serializedRow;\n }\n\n deserialize(row: Row, schema: MicroStoreSchema) {\n const deserializedRow: RawRow = {};\n Object.keys(row).forEach((k) => {\n const field = schema[k];\n if (field) {\n const transform =\n field.transform && this.fieldTransforms[field.transform] ? this.fieldTransforms[field.transform] : undefined;\n deserializedRow[k] = transform ? transform.deserialize(row[k]) : row[k];\n }\n });\n return deserializedRow;\n }\n\n // pushRecord is a sugar method to take a single record and push it into the store using whatever verb was used\n pushRecord(type: string, data: RawRecord, method: MethodType, options: Record<string, any> = {}) {\n return this.pushRecords(type, [data], method, options);\n }\n\n // pushRecords handles an incoming data (\"row\"s) that are in application level format (with dates, blobs, or other complex types that can't be POJO'd)\n pushRecords(type: string, data: RawRecord[], method: MethodType, options: Record<string, any> = {}) {\n const transform = this.getRecordTransform(type);\n const typeKey = camelCase(pluralize(type));\n if (!transform) {\n return this.pushPayload(method, { [typeKey]: data }, options);\n }\n const rawData = data.map((item) => {\n return transform.serialize(item);\n });\n return this.pushPayload(method, { [typeKey]: rawData }, options);\n }\n\n // pushPayload handles incoming data (many \"row\"s) that are in POJO format\n pushPayload(method: MethodType, data: any, options: Record<string, any> = {}) {\n try {\n const batchedPayload = this.interpreter(data, options);\n batchedPayload.data.forEach((payload) => {\n const schema = this.getSchema(payload.type);\n // Only process typed batches that match a defined data schema\n if (schema) {\n const pk = this.getPrimaryKey(payload.type) || 'id';\n if (method === 'DELETE') {\n payload.data.forEach((row) => {\n this.store.delRow(payload.type, row[pk]);\n });\n } else if (method === 'PATCH') {\n payload.data.forEach((row) => {\n // Only try a partial row update if a row already exists\n if (this.store.getRow(payload.type, row[pk])) {\n this.store.setPartialRow(payload.type, row[pk], this.serialize(row, schema));\n } else {\n this.store.setRow(payload.type, row[pk], this.serialize(row, schema));\n }\n });\n } else {\n payload.data.forEach((row) => {\n this.store.setRow(payload.type, row[pk], this.serialize(row, schema));\n });\n }\n }\n });\n return batchedPayload;\n } catch (e) {\n console.warn(e);\n }\n }\n\n peekRecord<T>(type: string, id: string): T | undefined {\n const schema = this.getSchema(type);\n const pk = this.getPrimaryKey(type);\n const transformer = this.getRecordTransform(type);\n const effectiveTransformer = transformer ? transformer.deserialize : (x: any) => x;\n if (schema && pk) {\n const row = this.getStore().getRow(type, id);\n if (row) {\n return effectiveTransformer(this.deserialize(row, schema));\n }\n }\n return undefined;\n }\n\n peekAll<T>(type: string): T[] {\n const schema = this.getSchema(type);\n const pk = this.getPrimaryKey(type);\n const transformer = this.getRecordTransform(type);\n const effectiveTransformer = transformer ? transformer.deserialize : (x: any) => x;\n if (schema && pk) {\n const table = this.getStore().getTable(type);\n return Object.entries(table).map(([_, row]) => {\n const thing = effectiveTransformer(this.deserialize(row, schema));\n return thing as T;\n });\n }\n return [];\n }\n\n unloadRecord<T>(type: string, id: string): T | undefined {\n const record = this.peekRecord<T>(type, id);\n if (record) {\n this.getStore().delRow(type, id);\n }\n return record;\n }\n\n unloadAll(type: string) {\n if (this.getSchema(type)) {\n this.getStore().delTable(type);\n }\n }\n\n reset() {\n Object.entries(this.schemas).forEach(([schemaName, _]) => {\n this.unloadAll(schemaName);\n });\n }\n\n // Need to get the raw tinybase store? use this method\n getStore() {\n return this.store;\n }\n\n // Need to get the raw tinybase query views? use this method\n getQueries() {\n return this.queries;\n }\n}\n","import { createContext, useContext, useMemo, type ReactNode } from 'react';\nimport { Provider as TinyBaseProvider } from 'tinybase/ui-react';\nimport type { MicroStore } from './microstore';\n\nconst StoreContext = createContext<MicroStore | null>(null);\n\nexport function useMicroStore(): MicroStore | null {\n const store = useContext(StoreContext);\n\n return store;\n}\n\ntype WithExistingStore = { store: MicroStore; children: ReactNode };\n\nexport function MicroStoreProvider(props: WithExistingStore) {\n const store = useMemo(() => props.store, [props]);\n\n // TODO: Add store.relationships, which can be passed to tinybase\n return (\n <StoreContext.Provider value={store}>\n <TinyBaseProvider store={store.getStore()} queries={store.getQueries()}>\n {props.children}\n </TinyBaseProvider>\n </StoreContext.Provider>\n );\n}\n","import { useEffect, useRef, useState } from 'react';\nimport { type Queries } from 'tinybase';\nimport { useQueries, useResultTable } from 'tinybase/ui-react';\nimport { useMicroStore } from './provider';\nimport type { MicroStoreSchema } from './types';\n\nfunction generateFilter(data: any[] | undefined, pk: string) {\n return new Set(\n data\n ? data.map((obj) => {\n if (typeof obj === 'string') {\n return obj;\n }\n return obj[pk];\n })\n : []\n );\n}\n\nfunction resetQueryDefinition(\n type: string,\n schema: MicroStoreSchema,\n pk: string,\n queryName: string,\n queries: Queries,\n filter: Set<string>\n) {\n // So what exactly does this do? It returns all the same tinybase rows that are\n // returned by the same React query being referenced by this reactive wrapper!!\n // That way, when the rows from useResultTable change due to some localized store\n // update through the MicroStore engine, we see those changes reflected without\n // additional server traffic!\n queries.setQueryDefinition(queryName, type, ({ select, where }) => {\n Object.keys(schema).forEach((k) => {\n select(k);\n });\n where((getCell) => filter.has(<string>getCell(pk)));\n });\n}\n\n// Wrap the objects in tinybase rows to make them react at a record level\n// to individual record changes\nexport function useReactive<T>(type: string, data: T[] | string[]): T[] {\n const store = useMicroStore();\n const schema = store?.getSchema(type);\n const pk = store?.getPrimaryKey(type);\n if (!schema || !pk) {\n throw new Error(`No MicroStore schema defined for type ${type}`);\n }\n const [uniqueHookID, _] = useState(crypto.randomUUID());\n const queries = useQueries();\n const rows = useResultTable(uniqueHookID, queries);\n const [lastFilter, setLastFilter] = useState('');\n // Air Brake prevents render loops if a user does something very silly like chasing\n // records in a circle\n const airBrake = useRef('');\n\n // Why is this effect important? Because you ONLY want to update the thing\n // that is bubbling out new rows (the query) if the supporting REST request\n // with its own internal IDs has changed. We\n useEffect(() => {\n if (queries) {\n const filter = generateFilter(data, pk);\n const stringifiedFilter = JSON.stringify([...filter]);\n if (lastFilter !== stringifiedFilter && airBrake.current !== stringifiedFilter) {\n if (Object.entries(rows).length > 0) {\n airBrake.current = stringifiedFilter;\n }\n setLastFilter(stringifiedFilter);\n resetQueryDefinition(type, schema, pk, uniqueHookID, queries, filter);\n }\n }\n }, [data, pk, schema, type, queries, uniqueHookID, lastFilter, rows, airBrake]);\n\n const transformer = store?.getRecordTransform(type);\n const effectiveTransformer = transformer ? transformer.deserialize : (x: any) => x;\n const returnData: T[] = [];\n data.forEach((item: any) => {\n const identifier = typeof item === 'string' ? item : item[pk];\n const possibleRow = rows[identifier];\n if (possibleRow) {\n const thing: any = store?.deserialize(possibleRow, schema);\n returnData.push(effectiveTransformer(thing) as T);\n }\n });\n return returnData;\n}\n"]}
1
+ {"version":3,"sources":["../src/interpreter.ts","../src/transforms.ts","../src/microstore.ts","../src/provider.tsx","../src/reactive.ts"],"names":["RESTInterpreter","data","_options","typedPayload","meta","k","content","typedData","typeName","camelCase","singularize","isArray","item","json","microStoreReservedKeys","defaultFieldTransforms","MicroStore","options","__publicField","createStore","createQueries","transformedSchemas","k2","omit","type","possiblePK","row","schema","serializedRow","field","transform","deserializedRow","method","typeKey","pluralize","rawData","batchedPayload","payload","pk","e","id","transformer","effectiveTransformer","x","table","_","record","schemaName","StoreContext","createContext","useMicroStore","useContext","MicroStoreProvider","props","store","useMemo","jsx","TinyBaseProvider","generateFilter","obj","resetQueryDefinition","queryName","queries","filter","select","where","getCell","useReactive","uniqueHookID","useState","useQueries","rows","useResultTable","lastFilter","setLastFilter","airBrake","useRef","useEffect","stringified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AAA,CAAY2B,CAAAA,CAAatD,CAAM,CAAA,CACzDoD,CAAAA,CAAW,IAAA,CAAKrC,CAAAA,CAAqBwC,CAAK,CAAM,EAClD,CACF,CAAC,EACMH,CACT","file":"index.mjs","sourcesContent":["import { singularize } from 'ember-inflector';\nimport { camelCase, isArray } from 'lodash-es';\nimport type { InterpreterReturnValue } from './types';\n\nexport function RESTInterpreter(data: Record<string, any>, _options: Record<string, any>) {\n const typedPayload: InterpreterReturnValue = {\n data: [],\n meta: undefined\n };\n let meta: Record<string, any> | undefined = undefined;\n\n if (data !== undefined) {\n Object.keys(data).forEach((k) => {\n const content = data[k];\n if (k !== 'meta') {\n const typedData: Record<string, any>[] = [];\n const typeName = camelCase(singularize(k));\n if (isArray(content)) {\n content.forEach((item: any) => {\n typedData.push(item);\n });\n } else {\n typedData.push(content);\n }\n typedPayload.data.push({\n data: typedData,\n type: typeName\n });\n } else {\n meta = data[k];\n }\n });\n }\n typedPayload.meta = meta;\n return typedPayload;\n}\n","import type { FieldTransform } from './types';\n\nexport const json: FieldTransform = {\n serialize(data) {\n return data ? JSON.stringify(data) : null;\n },\n deserialize(data) {\n return data ? JSON.parse(data) : null;\n }\n};\n","import { pluralize } from 'ember-inflector';\nimport { camelCase, omit } from 'lodash-es';\nimport { createQueries, createStore, type CellSchema, type Queries, type Row, type Store } from 'tinybase';\nimport { RESTInterpreter } from './interpreter';\nimport { json } from './transforms';\nimport type {\n ConventionalSchema,\n ConventionalSchemas,\n FieldTransforms,\n MethodType,\n MicrostoreInterpreter,\n MicroStoreOptions,\n MicroStoreSchema,\n MicroStoreSchemas,\n RawRecord,\n RawRow,\n RecordTransforms\n} from './types';\n\nconst microStoreReservedKeys = ['transform', 'primaryKey'];\nconst defaultFieldTransforms = {\n json\n};\n\nexport class MicroStore {\n schemas: MicroStoreSchemas;\n fieldTransforms: FieldTransforms;\n recordTransforms: RecordTransforms;\n store: Store;\n queries: Queries;\n interpreter: MicrostoreInterpreter;\n private primaryKeys: Record<string, string>;\n\n constructor(options: MicroStoreOptions) {\n this.primaryKeys = {};\n this.schemas = options.schemas ? options.schemas : {};\n // Thats right, we even support our own field and record level transforms!\n this.fieldTransforms = { ...(options.fieldTransforms ? options.fieldTransforms : {}), ...defaultFieldTransforms };\n this.recordTransforms = options.recordTransforms ? options.recordTransforms : {};\n this.interpreter = options.interpreter ? options.interpreter : RESTInterpreter;\n this.store = createStore();\n this.store.setTablesSchema(this.transformSchemas());\n this.queries = createQueries(this.store);\n }\n\n private transformSchemas() {\n // we have to remove custom properties or tinybase\n // will ignore our fields.\n const transformedSchemas: ConventionalSchemas = {};\n Object.keys(this.schemas).forEach((k) => {\n transformedSchemas[k] = <ConventionalSchema>{};\n Object.keys(this.schemas[k]).forEach((k2) => {\n transformedSchemas[k][k2] = omit(this.schemas[k][k2], microStoreReservedKeys) as CellSchema;\n const possiblePK: boolean | undefined = this.schemas[k][k2]['primaryKey'];\n if (possiblePK && this.schemas[k][k2]['type'] === 'string') {\n if (this.primaryKeys[k]) {\n throw Error(`More than one primary key defined for schema ${k}`);\n }\n this.primaryKeys[k] = k2;\n }\n });\n // Default PK to id\n if (!this.getPrimaryKey(k) && this.schemas[k]['id'] && this.schemas[k]['id']['type'] === 'string') {\n this.primaryKeys[k] = 'id';\n }\n if (!this.getPrimaryKey(k)) {\n throw Error(\n `No primary key defined for schema ${k}. This schema must have an 'id' field of \"type\": \"string\", or another field of \"type\": \"string\" with \"primaryKey\": true.`\n );\n }\n });\n return transformedSchemas;\n }\n\n getPrimaryKey(type: string) {\n const possiblePK = this.primaryKeys[type];\n return possiblePK ? possiblePK : undefined;\n }\n\n getSchema(type: string) {\n if (type) {\n if (Object.hasOwn(this.schemas, type)) {\n return this.schemas[type];\n }\n }\n return null;\n }\n\n getRecordTransform(type: string | undefined) {\n if (type) {\n return this.recordTransforms[type] ? this.recordTransforms[type] : undefined;\n }\n return undefined;\n }\n\n getFieldTransform(type: string | undefined) {\n if (type) {\n return this.fieldTransforms[type] ? this.fieldTransforms[type] : undefined;\n }\n return undefined;\n }\n\n serialize(row: RawRow, schema: MicroStoreSchema) {\n const serializedRow: RawRow = {};\n Object.keys(row).forEach((k) => {\n const field = schema[k];\n if (field) {\n const transform = this.getFieldTransform(field.transform);\n serializedRow[k] = transform ? transform.serialize(row[k]) : row[k];\n }\n });\n return serializedRow;\n }\n\n deserialize(row: Row, schema: MicroStoreSchema) {\n const deserializedRow: RawRow = {};\n Object.keys(row).forEach((k) => {\n const field = schema[k];\n if (field) {\n const transform =\n field.transform && this.fieldTransforms[field.transform] ? this.fieldTransforms[field.transform] : undefined;\n deserializedRow[k] = transform ? transform.deserialize(row[k]) : row[k];\n }\n });\n return deserializedRow;\n }\n\n // pushRecord is a sugar method to take a single record and push it into the store using whatever verb was used\n pushRecord(type: string, data: RawRecord, method: MethodType, options: Record<string, any> = {}) {\n return this.pushRecords(type, [data], method, options);\n }\n\n // pushRecords handles an incoming data (\"row\"s) that are in application level format (with dates, blobs, or other complex types that can't be POJO'd)\n pushRecords(type: string, data: RawRecord[], method: MethodType, options: Record<string, any> = {}) {\n const transform = this.getRecordTransform(type);\n const typeKey = camelCase(pluralize(type));\n if (!transform) {\n return this.pushPayload(method, { [typeKey]: data }, options);\n }\n const rawData = data.map((item) => {\n return transform.serialize(item);\n });\n return this.pushPayload(method, { [typeKey]: rawData }, options);\n }\n\n // pushPayload handles incoming data (many \"row\"s) that are in POJO format\n pushPayload(method: MethodType, data: any, options: Record<string, any> = {}) {\n try {\n const batchedPayload = this.interpreter(data, options);\n batchedPayload.data.forEach((payload) => {\n const schema = this.getSchema(payload.type);\n // Only process typed batches that match a defined data schema\n if (schema) {\n const pk = this.getPrimaryKey(payload.type) || 'id';\n if (method === 'DELETE') {\n payload.data.forEach((row) => {\n this.store.delRow(payload.type, row[pk]);\n });\n } else if (method === 'PATCH') {\n payload.data.forEach((row) => {\n // Only try a partial row update if a row already exists\n if (this.store.getRow(payload.type, row[pk])) {\n this.store.setPartialRow(payload.type, row[pk], this.serialize(row, schema));\n } else {\n this.store.setRow(payload.type, row[pk], this.serialize(row, schema));\n }\n });\n } else {\n payload.data.forEach((row) => {\n this.store.setRow(payload.type, row[pk], this.serialize(row, schema));\n });\n }\n }\n });\n return batchedPayload;\n } catch (e) {\n console.warn(e);\n }\n }\n\n peekRecord<T>(type: string, id: string) {\n const schema = this.getSchema(type);\n const pk = this.getPrimaryKey(type);\n const transformer = this.getRecordTransform(type);\n const effectiveTransformer = transformer ? transformer.deserialize : (x: any) => x;\n if (schema && pk) {\n const row = this.getStore().getRow(type, id);\n if (Object.keys(row).length) {\n return effectiveTransformer(this.deserialize(row, schema)) as T;\n }\n }\n return undefined;\n }\n\n peekAll<T>(type: string) {\n const schema = this.getSchema(type);\n const pk = this.getPrimaryKey(type);\n const transformer = this.getRecordTransform(type);\n const effectiveTransformer = transformer ? transformer.deserialize : (x: any) => x;\n if (schema && pk) {\n const table = this.getStore().getTable(type);\n return Object.entries(table).map(([_, row]) => {\n const thing = effectiveTransformer(this.deserialize(row, schema));\n return thing as T;\n });\n }\n return [] as T[];\n }\n\n unloadRecord<T>(type: string, id: string) {\n const record = this.peekRecord<T>(type, id);\n if (record) {\n this.getStore().delRow(type, id);\n }\n return record;\n }\n\n unloadAll(type: string) {\n if (this.getSchema(type)) {\n this.getStore().delTable(type);\n }\n }\n\n reset() {\n Object.entries(this.schemas).forEach(([schemaName, _]) => {\n this.unloadAll(schemaName);\n });\n }\n\n // Need to get the raw tinybase store? use this method\n getStore() {\n return this.store;\n }\n\n // Need to get the raw tinybase query views? use this method\n getQueries() {\n return this.queries;\n }\n}\n","import { createContext, useContext, useMemo, type ReactNode } from 'react';\nimport { Provider as TinyBaseProvider } from 'tinybase/ui-react';\nimport type { MicroStore } from './microstore';\n\nconst StoreContext = createContext<MicroStore | null>(null);\n\nexport function useMicroStore(): MicroStore | null {\n const store = useContext(StoreContext);\n\n return store;\n}\n\ntype WithExistingStore = { store: MicroStore; children: ReactNode };\n\nexport function MicroStoreProvider(props: WithExistingStore) {\n const store = useMemo(() => props.store, [props]);\n\n // TODO: Add store.relationships, which can be passed to tinybase\n return (\n <StoreContext.Provider value={store}>\n <TinyBaseProvider store={store.getStore()} queries={store.getQueries()}>\n {props.children}\n </TinyBaseProvider>\n </StoreContext.Provider>\n );\n}\n","import { useEffect, useRef, useState } from 'react';\nimport { type Queries } from 'tinybase';\nimport { useQueries, useResultTable } from 'tinybase/ui-react';\nimport { useMicroStore } from './provider';\nimport type { MicroStoreSchema } from './types';\n\nfunction generateFilter(data: any[] | undefined, pk: string) {\n return new Set(\n data\n ? data.map((obj) => {\n if (typeof obj === 'string') {\n return obj;\n }\n return obj[pk];\n })\n : []\n );\n}\n\nfunction resetQueryDefinition(\n type: string,\n schema: MicroStoreSchema,\n pk: string,\n queryName: string,\n queries: Queries,\n filter: Set<string>\n) {\n // So what exactly does this do? It returns all the same tinybase rows that are\n // returned by the same React query being referenced by this reactive wrapper!!\n // That way, when the rows from useResultTable change due to some localized store\n // update through the MicroStore engine, we see those changes reflected without\n // additional server traffic!\n queries.setQueryDefinition(queryName, type, ({ select, where }) => {\n Object.keys(schema).forEach((k) => {\n select(k);\n });\n where((getCell) => filter.has(<string>getCell(pk)));\n });\n}\n\n// Wrap the objects in tinybase rows to make them react at a record level\n// to individual record changes\nexport function useReactive<T>(type: string, data: T[] | string[]): T[] {\n const store = useMicroStore();\n const schema = store?.getSchema(type);\n const pk = store?.getPrimaryKey(type);\n if (!schema || !pk) {\n throw new Error(`No MicroStore schema defined for type ${type}`);\n }\n const [uniqueHookID, _] = useState(crypto.randomUUID());\n const queries = useQueries();\n const rows = useResultTable(uniqueHookID, queries);\n const [lastFilter, setLastFilter] = useState('');\n // Air Brake prevents render loops if a user does something very silly like chasing\n // records in a circle\n const airBrake = useRef('');\n\n // Why is this effect important? Because you ONLY want to update the thing\n // that is bubbling out new rows (the query) if the supporting REST request\n // with its own internal IDs has changed.\n useEffect(() => {\n if (queries) {\n const filter = generateFilter(data, pk);\n const stringifiedFilter = JSON.stringify([...filter]);\n if (lastFilter !== stringifiedFilter && airBrake.current !== stringifiedFilter) {\n if (Object.entries(rows).length > 0) {\n airBrake.current = stringifiedFilter;\n }\n setLastFilter(stringifiedFilter);\n resetQueryDefinition(type, schema, pk, uniqueHookID, queries, filter);\n }\n }\n }, [data, pk, schema, type, queries, uniqueHookID, lastFilter, rows, airBrake]);\n\n const transformer = store?.getRecordTransform(type);\n const effectiveTransformer = transformer ? transformer.deserialize : (x: any) => x;\n const returnData: T[] = [];\n data.forEach((item: any) => {\n const identifier = typeof item === 'string' ? item : item[pk];\n const possibleRow = rows[identifier];\n if (possibleRow) {\n const thing: any = store?.deserialize(possibleRow, schema);\n returnData.push(effectiveTransformer(thing) as T);\n }\n });\n return returnData;\n}\n"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@black-cape/microstore",
3
- "version": "0.0.4",
3
+ "version": "0.0.5",
4
4
  "main": "dist/index.js",
5
5
  "module": "dist/index.mjs",
6
6
  "types": "dist/index.d.ts",