@knapsack/utils 4.108.0 → 4.110.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/immer.d.ts CHANGED
@@ -9,14 +9,65 @@ export declare function compressPatches<Data extends Objectish>({ baseData, patc
9
9
  baseData: Data;
10
10
  patches: Patch[][] | Patch[];
11
11
  }): readonly [Data, Patch[], Patch[]];
12
+ /** A patch that could not be applied, with the error Immer threw for it */
13
+ export interface PoisonPatch {
14
+ readonly patch: Patch;
15
+ readonly error: unknown;
16
+ }
17
+ /** A change whose patches did not all apply */
18
+ export interface FailedChange<Change> {
19
+ readonly change: Change;
20
+ /** The error from the first poison patch */
21
+ readonly error: unknown;
22
+ /** The change's patches that did apply, in order. Empty when none did. */
23
+ readonly appliedPatches: Patch[];
24
+ /** The change's patches that threw and were dropped */
25
+ readonly poisonPatches: PoisonPatch[];
26
+ /**
27
+ * Applied after `appliedPatches`: they put back values a poison patch was
28
+ * moving, where they were before the change (see `applyPatchesSafely`)
29
+ */
30
+ readonly restoredPatches: Patch[];
31
+ }
12
32
  /**
13
- * Loop over changes to applyPatches in small batches (safer) instead of all at once.
14
- * If a change's patches fail to apply, it's skipped (not the whole batch) and
15
- * returned in `failedChanges` instead of being silently dropped - callers decide
16
- * whether/how to surface that a change didn't make it in.
33
+ * Apply `changes` one at a time instead of all at once.
34
+ *
35
+ * When a change fails to apply as a unit, its patches are retried one at a
36
+ * time: each patch that applies is kept and only the ones that throw (the
37
+ * "poison" patches) are dropped. One stale patch, e.g. a `replace` under a
38
+ * block another branch deleted, does not take the change's unrelated edits
39
+ * down with it. Immer only throws when a patch's parent path is missing, and
40
+ * a dropped patch changed nothing, so patches that edit under the same
41
+ * missing parent are dropped too.
42
+ *
43
+ * A dependent patch on another path is not caught that way. Moving a value
44
+ * records an `add` at the target and a `remove` at the source; with the
45
+ * target gone, applying only the `remove` would delete the value outright.
46
+ * So a value a poison patch was moving that the change took out and did not
47
+ * land anywhere else is put back where it was just before the patch that
48
+ * took it out (`restoreMovedValues`), after the change's other patches, which
49
+ * keep their effect.
50
+ *
51
+ * A poison patch also means the change was recorded against a different base
52
+ * than `data`. Its surviving index-based array patches (`add`/`remove` at
53
+ * `list/3`) are applied at those indexes, which may now hold different items.
54
+ * A value put back shifts an array the same way for the changes after it,
55
+ * which were recorded without it. That is the same risk every change
56
+ * recorded against a stale base already carries; dropping the whole change
57
+ * instead loses the user's work outright.
58
+ *
59
+ * Every change that lost patches is returned in `failedChanges` with what
60
+ * applied, what threw, and what was put back, so callers can tell exactly
61
+ * what landed.
62
+ *
63
+ * `data` must not be an Immer draft: `applyPatches` mutates a draft in place,
64
+ * so a change that throws partway would leave its earlier patches applied and
65
+ * the one-at-a-time retry would apply them again. Reduce plain data and wrap
66
+ * the result in `produce` afterwards.
17
67
  */
18
68
  export declare function applyPatchesSafely<Data extends Objectish, Change extends {
19
69
  patches: Patch[];
70
+ id?: unknown;
20
71
  } = {
21
72
  patches: Patch[];
22
73
  }>({ data, changes, logError, logAppClientData, }: {
@@ -26,9 +77,6 @@ export declare function applyPatchesSafely<Data extends Objectish, Change extend
26
77
  logAppClientData?: boolean;
27
78
  }): {
28
79
  data: Data;
29
- failedChanges: Array<{
30
- change: Change;
31
- error: unknown;
32
- }>;
80
+ failedChanges: Array<FailedChange<Change>>;
33
81
  };
34
82
  //# sourceMappingURL=immer.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"immer.d.ts","sourceRoot":"","sources":["../src/immer.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,KAAK,KAAK,EACV,YAAY,EAEZ,kBAAkB,EAClB,OAAO,EACP,OAAO,EACP,KAAK,KAAK,EACV,KAAK,SAAS,EACf,MAAM,OAAO,CAAC;AAEf,OAAO,EAAE,OAAO,EAAE,kBAAkB,EAAE,YAAY,EAAE,OAAO,EAAE,CAAC;AAC9D,YAAY,EAAE,KAAK,EAAE,KAAK,EAAE,CAAC;AAI7B;;;GAGG;AACH,wBA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E,CA0D7D"}
package/dist/immer.js CHANGED
@@ -1,2 +1,2 @@
1
- 'use strict';var immer=require('immer');var d=Object.defineProperty;var n=(e,a)=>d(e,"name",{value:a,configurable:true});immer.enablePatches();function b({baseData:e,patches:a}){return immer.produceWithPatches(e,r=>{immer.applyPatches(r,a.flat());})}n(b,"compressPatches");function m({data:e,changes:a,logError:r=console.error,logAppClientData:p=false}){let o=[];return {data:a.reduce((c,t,l)=>{try{return immer.applyPatches(c,t.patches)}catch(s){let{LOG_IMMER_APP_CLIENT_DATA:i}=process.env,u=p||i?{data:e,change:t}:t;return r(`applyPatchesSafely had issues (and so will skip) with patches in change ${l}: ${s instanceof Error?s.message:""}`,u),o.push({change:t,error:s}),c}},e),failedChanges:o}}n(m,"applyPatchesSafely");Object.defineProperty(exports,"applyPatches",{enumerable:true,get:function(){return immer.applyPatches}});Object.defineProperty(exports,"isDraft",{enumerable:true,get:function(){return immer.isDraft}});Object.defineProperty(exports,"produce",{enumerable:true,get:function(){return immer.produce}});Object.defineProperty(exports,"produceWithPatches",{enumerable:true,get:function(){return immer.produceWithPatches}});exports.applyPatchesSafely=m;exports.compressPatches=b;//# sourceMappingURL=immer.js.map
1
+ 'use strict';var immer=require('immer');var Q=Object.defineProperty;var u=(t,e)=>Q(t,"name",{value:e,configurable:true});function K(t){if(typeof t!="object"||!t)return t;if(Array.isArray(t)){let r=[];return t.forEach((s,d)=>{r[d]=K(s);}),r}let e=Object.keys(t).sort(),n={};return e.forEach(r=>{n[r]=K(t[r]);}),n}u(K,"sortKeysRecursive");immer.enablePatches();function kt({baseData:t,patches:e}){return immer.produceWithPatches(t,n=>{immer.applyPatches(n,e.flat());})}u(kt,"compressPatches");function v({data:t,patches:e}){let n=[],r=[];return {data:e.reduce((d,c)=>{try{let i=immer.applyPatches(d,[c]);return n.push({patch:c,before:d,after:i}),i}catch(i){return r.push({patch:c,error:i}),d}},t),steps:n,poisonPatches:r}}u(v,"applyEachPatch");var tt=u(t=>JSON.stringify(t.map(String)),"pathKey"),et=u((t,e)=>t.length<e.length&&t.every((n,r)=>String(n)===String(e[r])),"isAncestor"),O=u(t=>`${typeof t}:${JSON.stringify(K(t))}`,"valueKey");function w(t,e){let n=t;for(let r of e){if(!n||typeof n!="object")return;n=n[r];}return n}u(w,"getAt");function I(t,e,n=[]){if(e(t,n),Array.isArray(t))t.forEach((r,s)=>I(r,e,[...n,s]));else if(t&&typeof t=="object")for(let[r,s]of Object.entries(t))I(s,e,[...n,r]);}u(I,"forEachValue");function L(t,e,n){let r=new Map;return I(w(t,e),s=>{let d=O(s);n.has(d)&&r.set(d,(r.get(d)??0)+1);}),r}u(L,"countValues");var M=u((t,e)=>Array.isArray(t)?t.filter(n=>O(n)===e).length:0,"countIn"),nt=u((t,e)=>typeof t=="string"?e:!!t&&typeof t=="object"&&Object.keys(t).length>0,"isMovable"),rt=new Set(["__proto__","constructor","prototype"]),_=class{constructor(e,n){this.key=e;this.content=n;}static{u(this,"PutDown");}},Y=u(t=>t instanceof _?t.content:t,"contentOf");function z(t,e=new Map){t instanceof _&&e.set(t.key,(e.get(t.key)??0)+1);let n=Y(t);return n&&typeof n=="object"&&Object.values(n).forEach(r=>z(r,e)),e}u(z,"tallyPutDown");function C(t,e,n){let r=Array.isArray(t)?t.map(d=>C(d,true,n)):t&&typeof t=="object"?Object.fromEntries(Object.entries(t).map(([d,c])=>[d,C(c,false,n)])):t;if(!nt(t,e))return r;let s=O(t);return n(s)?new _(s,r):r}u(C,"markPutDown");function ot(t,e){if(![...e].some(({op:s})=>s!=="remove"))return new Map;let n={},r=u(()=>true,"all");for(let s of t){let d=e.has(s),{op:c,path:i,value:b}=s;if(i.some(o=>rt.has(String(o))))continue;let p=n;for(let[o,f]of i.slice(0,-1).entries()){let l=p,a=Y(l[f]);if(!a||typeof a!="object"){if(!d){p=void 0;break}a=typeof i[o+1]=="number"?[]:{},l[f]=a;}p=a;}if(!p)continue;let x=p,h=i[i.length-1],j=Array.isArray(p),k;if(d&&c!=="remove")if(c==="add"||j)k=C(b,j,r);else if(Array.isArray(b))k=b.map(o=>C(o,true,r));else {let o=z(x[h]);k=C(b,false,f=>{let l=o.get(f)??0;return o.set(f,l-1),l>0});}if(Array.isArray(p)){let o=Number(h);c==="add"?(p.length<o&&(p.length=o),p.splice(o,0,k)):c==="replace"?p[o]=k:p.splice(o,1);}else c==="remove"?delete x[h]:x[h]=k;}return z(n)}u(ot,"countPutDown");function G(t,e,n){if(!Array.isArray(t))return -1;let r=0;return t.findIndex(s=>O(s)!==e?false:(r+=1,r===n))}u(G,"nthIndexOf");function at(t,e,n){let r=e.slice(0,n).map(O),s=new Map,d=r.map(c=>{let i=(s.get(c)??0)+1;return s.set(c,i),i});for(let c=n-1;c>=0;c--){let i=G(t,r[c],d[c]);if(i!==-1)return i+1}return 0}u(at,"insertionIndex");function st(t,e){if(!t||!e||t.array!==e.array)return false;if(e.op==="replace")return t.op==="replace"&&e.index>t.index;if(t.op==="replace")return e.index>t.index;let n=e.op==="add"?1:-1;return e.op===t.op&&e.index===t.index+n}u(st,"continuesArrayEdit");function ct({salvaged:t,patches:e,steps:n,poisonPatches:r}){let s=ot(e,new Set(r.map(({patch:o})=>o)));if(s.size===0)return {data:t,restoredPatches:[]};let d=new Set(s.keys()),c=new Map,i=[],b=[],p=0,x;n.forEach(({patch:o,before:f,after:l},a)=>{let y=o.path.slice(0,-1),S=Array.isArray(w(f,y)),g=S?y:o.path,m=S?{array:tt(y),op:o.op,index:Number(o.path[o.path.length-1])}:void 0;st(x,m)||(p=a),x=m,b.push({step:a,path:g});let T=L(f,g,d),A=L(l,g,d),E=new Set;for(let R of d){let D=(A.get(R)??0)-(T.get(R)??0),P=c.get(R)??0;D<0?(c.set(R,P-D),E.add(R)):D>0&&c.set(R,Math.max(0,P-D));}if(E.size===0)return;let B=n[p].before;I(w(f,g),(R,D)=>{let P=O(R);if(!E.has(P))return;let N=[...g,...D],V=N.slice(0,-1);if(!(Array.isArray(w(l,V))?M(w(l,V),P)<M(w(f,V),P):O(w(l,N))!==P))return;let J=w(f,g);if(D.length===1&&Array.isArray(J)){let U=Number(D[0]),q=M(J.slice(0,U+1),P),$=G(w(B,g),P,q);if($!==-1){let H=[...g,$];i.push({key:P,value:R,path:H,from:B,step:a,run:p,order:$});return}}i.push({key:P,value:R,path:N,from:f,step:a,run:p,order:-a});});});let h=new Map;for(let[o,f]of s){let l=Math.min(f,c.get(o)??0);l>0&&h.set(o,l);}if(h.size===0)return {data:t,restoredPatches:[]};let[j,k]=immer.produceWithPatches(t,o=>{let f=u(({key:a,value:y,path:S,from:g})=>{let m=S.slice(0,-1),T=S[S.length-1],A=w(o,m);if(Array.isArray(A)){let E=w(g,m);return M(A,a)>=M(E,a)?false:(A.splice(at(A,E,Number(T)),0,y),true)}return typeof y=="object"&&A&&typeof A=="object"&&!(String(T)in A)?(A[T]=y,true):false},"putBack"),l=[...i].sort((a,y)=>y.run-a.run||a.order-y.order);for(let a of l){if(!h.get(a.key))continue;let y=a.path.slice(0,-1);b.some(({step:g,path:m})=>g>=a.step&&et(m,y)&&y.slice(m.length).some(T=>typeof T=="number"))||!f(a)||I(a.value,g=>{let m=h.get(O(g));m&&h.set(O(g),m-1);});}});return {data:j,restoredPatches:k}}u(ct,"restoreMovedValues");function At({data:t,changes:e,logError:n=console.error,logAppClientData:r=false}){if(immer.isDraft(t))throw new Error("applyPatchesSafely: `data` must not be an Immer draft; a change that fails partway would leave its earlier patches applied");let s=[];return {data:e.reduce((c,i,b)=>{try{return immer.applyPatches(c,i.patches)}catch{let p=v({data:c,patches:i.patches}),{steps:x,poisonPatches:h}=p;if(h.length===0)return p.data;let j=x.map(({patch:a})=>a),{data:k,restoredPatches:o}=ct({salvaged:p.data,patches:i.patches,steps:x,poisonPatches:h}),{LOG_IMMER_APP_CLIENT_DATA:f}=process.env,l=u(a=>({op:a.op,path:a.path.join("/")}),"describe");return n(`applyPatchesSafely had issues with change ${b}: dropped ${h.length} of ${i.patches.length} patches and applied the rest`,{metadata:{changeIndex:b,changeId:i.id,appliedPatchCount:j.length,poisonPatches:h.map(({patch:a,error:y})=>({...l(a),error:y instanceof Error?y.message:String(y)})),restoredPatches:o.map(l),...r||f?{data:c}:{}}}),s.push({change:i,error:h[0]?.error,appliedPatches:j,poisonPatches:h,restoredPatches:o}),k}},t),failedChanges:s}}u(At,"applyPatchesSafely");Object.defineProperty(exports,"applyPatches",{enumerable:true,get:function(){return immer.applyPatches}});Object.defineProperty(exports,"isDraft",{enumerable:true,get:function(){return immer.isDraft}});Object.defineProperty(exports,"produce",{enumerable:true,get:function(){return immer.produce}});Object.defineProperty(exports,"produceWithPatches",{enumerable:true,get:function(){return immer.produceWithPatches}});exports.applyPatchesSafely=At;exports.compressPatches=kt;//# sourceMappingURL=immer.js.map
2
2
  //# sourceMappingURL=immer.js.map
package/dist/immer.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/immer.ts"],"names":["enablePatches","compressPatches","baseData","allPatches","produceWithPatches","draft","applyPatches","__name","applyPatchesSafely","data","changes","logError","logAppClientData","failedChanges","acc","change","i","error","LOG_IMMER_APP_CLIENT_DATA","metadata"],"mappings":"wCAAA,IAAA,CAAA,CAAA,MAAA,CAAA,cAAA,CAAA,IAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,GAAA,CAAA,CAAA,CAAA,CAAA,MAAA,CAAA,CAAA,KAAA,CAAA,CAAA,CAAA,YAAA,CAAA,IAAA,CAAA,CAAA,CAcAA,mBAAAA,EAAc,CAMP,SAASC,CAAAA,CAAwC,CACtD,QAAA,CAAAC,CAAAA,CACA,OAAA,CAASC,CACX,CAAA,CAGG,CACD,OAAOC,wBAAAA,CAAmBF,CAAAA,CAAWG,CAAAA,EAAU,CAC7CC,kBAAAA,CAAaD,EAAOF,CAAAA,CAAW,IAAA,EAAM,EACvC,CAAC,CACH,CAVgBI,CAAAA,CAAAN,CAAAA,CAAA,iBAAA,CAAA,CAkBT,SAASO,CAAAA,CAGd,CACA,IAAA,CAAAC,CAAAA,CACA,OAAA,CAAAC,CAAAA,CACA,QAAA,CAAAC,CAAAA,CAAW,OAAA,CAAQ,KAAA,CACnB,gBAAA,CAAAC,CAAAA,CAAmB,KACrB,CAAA,CAK6E,CAC3E,IAAMC,CAAAA,CAA2D,EAAC,CAoBlE,OAAO,CAAE,KAnBMH,CAAAA,CAAQ,MAAA,CAAO,CAACI,CAAAA,CAAKC,CAAAA,CAAQC,CAAAA,GAAM,CAChD,GAAI,CACF,OAAOV,kBAAAA,CAAaQ,CAAAA,CAAKC,CAAAA,CAAO,OAAO,CACzC,CAAA,MAASE,CAAAA,CAAO,CACd,GAAM,CAAE,yBAAA,CAAAC,CAA0B,CAAA,CAAI,OAAA,CAAQ,GAAA,CACxCC,CAAAA,CACJP,CAAAA,EAAoBM,CAAAA,CAChB,CAAE,IAAA,CAAAT,CAAAA,CAAM,MAAA,CAAAM,CAAO,CAAA,CACfA,CAAAA,CACN,OAAAJ,CAAAA,CACE,CAAA,wEAAA,EAA2EK,CAAC,CAAA,EAAA,EAC1EC,CAAAA,YAAiB,KAAA,CAAQA,CAAAA,CAAM,OAAA,CAAU,EAC3C,CAAA,CAAA,CACAE,CACF,CAAA,CACAN,CAAAA,CAAc,KAAK,CAAE,MAAA,CAAAE,CAAAA,CAAQ,KAAA,CAAAE,CAAM,CAAC,CAAA,CAC7BH,CACT,CACF,CAAA,CAAGL,CAAI,CAAA,CACgB,aAAA,CAAAI,CAAc,CACvC,CAnCgBN,EAAAC,CAAAA,CAAA,oBAAA,CAAA","file":"immer.js","sourcesContent":["import {\n type Patch,\n applyPatches,\n enablePatches,\n produceWithPatches,\n produce,\n isDraft,\n type Draft,\n type Objectish,\n} from 'immer';\n\nexport { produce, produceWithPatches, applyPatches, isDraft };\nexport type { Patch, Draft };\n\nenablePatches();\n\n/**\n * Take an array of Immer patches and compress them down to the smallest amount of patches\n * @link https://medium.com/@dedels/using-immer-to-compress-immer-patches-f382835b6c69\n */\nexport function compressPatches<Data extends Objectish>({\n baseData,\n patches: allPatches,\n}: {\n baseData: Data;\n patches: Patch[][] | Patch[];\n}) {\n return produceWithPatches(baseData, (draft) => {\n applyPatches(draft, allPatches.flat());\n });\n}\n\n/**\n * Loop over changes to applyPatches in small batches (safer) instead of all at once.\n * If a change's patches fail to apply, it's skipped (not the whole batch) and\n * returned in `failedChanges` instead of being silently dropped - callers decide\n * whether/how to surface that a change didn't make it in.\n */\nexport function applyPatchesSafely<\n Data extends Objectish,\n Change extends { patches: Patch[] } = { patches: Patch[] },\n>({\n data,\n changes,\n logError = console.error,\n logAppClientData = false,\n}: {\n data: Data;\n changes: Change[];\n logError?: (msg: unknown, ...optionalMsgs: unknown[]) => void;\n logAppClientData?: boolean;\n}): { data: Data; failedChanges: Array<{ change: Change; error: unknown }> } {\n const failedChanges: Array<{ change: Change; error: unknown }> = [];\n const result = changes.reduce((acc, change, i) => {\n try {\n return applyPatches(acc, change.patches);\n } catch (error) {\n const { LOG_IMMER_APP_CLIENT_DATA } = process.env;\n const metadata =\n logAppClientData || LOG_IMMER_APP_CLIENT_DATA\n ? { data, change }\n : change;\n logError(\n `applyPatchesSafely had issues (and so will skip) with patches in change ${i}: ${\n error instanceof Error ? error.message : ''\n }`,\n metadata,\n );\n failedChanges.push({ change, error });\n return acc;\n }\n }, data);\n return { data: result, failedChanges };\n}\n"]}
1
+ {"version":3,"sources":["../src/objects.ts","../src/immer.ts"],"names":["sortKeysRecursive","object","newArray","item","index","sortedKeys","sortedObject","key","__name","enablePatches","compressPatches","baseData","allPatches","produceWithPatches","draft","applyPatches","applyEachPatch","data","patches","steps","poisonPatches","acc","patch","next","error","pathKey","path","isAncestor","prefix","segment","i","valueKey","value","getAt","forEachValue","visit","countValues","root","wanted","counts","countIn","items","isMovable","inArray","PROTOTYPE_KEYS","PutDown","content","contentOf","node","tallyPutDown","markPutDown","take","countPutDown","poison","op","stand","all","failed","parent","holder","child","last","intoArray","placed","already","left","at","nthIndexOf","nth","seen","insertionIndex","from","keys","nths","j","continuesArrayEdit","prev","step","restoreMovedValues","salvaged","putDown","unlanded","removals","rewritten","run","previous","before","after","was","now","removed","delta","open","start","relative","parentPath","atStart","lost","count","missing","restoredPatches","putBack","ordered","b","removal","v","applyPatchesSafely","changes","logError","logAppClientData","isDraft","failedChanges","change","salvage","appliedPatches","restored","LOG_IMMER_APP_CLIENT_DATA","describe"],"mappings":"yHAkDO,SAASA,CAAAA,CAAkBC,CAAAA,CAAQ,CACxC,GAAI,OAAOA,CAAAA,EAAW,QAAA,EAAY,CAACA,CAAAA,CAAQ,OAAOA,EAClD,GAAI,KAAA,CAAM,OAAA,CAAQA,CAAM,CAAA,CAAG,CACzB,IAAMC,CAAAA,CAAkB,EAAC,CACzB,OAAAD,CAAAA,CAAO,OAAA,CAAQ,CAACE,CAAAA,CAAMC,CAAAA,GAAU,CAC9BF,CAAAA,CAASE,CAAK,CAAA,CAAIJ,CAAAA,CAAkBG,CAAI,EAC1C,CAAC,CAAA,CACMD,CACT,CACA,IAAMG,EAAa,MAAA,CAAO,IAAA,CAAKJ,CAAM,CAAA,CAAE,IAAA,EAAK,CACtCK,EAAe,EAAC,CACtB,OAAAD,CAAAA,CAAW,OAAA,CAASE,CAAAA,EAAQ,CAC1BD,CAAAA,CAAaC,CAAG,CAAA,CAAIP,CAAAA,CAAkBC,CAAAA,CAAOM,CAAG,CAAC,EACnD,CAAC,CAAA,CACMD,CACT,CAfgBE,CAAAA,CAAAR,CAAAA,CAAA,qBCnChBS,mBAAAA,EAAc,CAMP,SAASC,EAAAA,CAAwC,CACtD,QAAA,CAAAC,EACA,OAAA,CAASC,CACX,CAAA,CAGG,CACD,OAAOC,wBAAAA,CAAmBF,CAAAA,CAAWG,CAAAA,EAAU,CAC7CC,kBAAAA,CAAaD,CAAAA,CAAOF,CAAAA,CAAW,IAAA,EAAM,EACvC,CAAC,CACH,CAVgBJ,CAAAA,CAAAE,EAAAA,CAAA,iBAAA,CAAA,CA0ChB,SAASM,CAAAA,CAAuC,CAC9C,IAAA,CAAAC,CAAAA,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CAAI,CAAA,CACgB,aAAA,CAAA8F,CAAc,CACvC,CAvEgBvG,CAAAA,CAAAkG,EAAAA,CAAA,oBAAA,CAAA","file":"immer.js","sourcesContent":["import cleanDeep from 'clean-deep';\nimport { isObject } from './is-types';\n\nexport { default as groupBy } from 'lodash/groupBy.js';\n// @todo: look into lodash/merge vs deepMerge behavior differences and use cases (ie. immutable vs not)\n// export { default as deepMerge } from 'lodash/merge.js';\nexport { default as deepMerge } from 'deepmerge';\n\n/**\n * Sort object by alphabetizing keys.\n */\nexport function sortObject<T extends Record<string, unknown>>(theObject: T): T {\n return Object.keys(theObject)\n .sort()\n .reduce(\n (obj, key: keyof T) => {\n obj[key] = theObject[key];\n return obj;\n },\n <T>{},\n );\n}\n\n/**\n * Remove empty objects in nested object.\n * Leverage stringify to convert empty objects to undefined, which is removed\n * during stringification.\n */\nexport const removeEmptyObjects = <T extends Record<string, unknown>>(\n src: T,\n): Partial<T> => cleanDeep(src);\n\n/**\n * Removes keys like `{ x: undefined }` from the object\n */\nexport function removeUndefinedProps<T extends Record<PropertyKey, unknown>>(\n obj: T,\n): T {\n return cleanDeep(obj, {\n undefinedValues: true,\n nullValues: true,\n emptyArrays: false,\n emptyObjects: false,\n emptyStrings: true,\n }) as T;\n}\n\n/**\n * Sort object and arrays recursively by alphabetizing keys.\n */\nexport function sortKeysRecursive(object) {\n if (typeof object !== 'object' || !object) return object;\n if (Array.isArray(object)) {\n const newArray: any[] = [];\n object.forEach((item, index) => {\n newArray[index] = sortKeysRecursive(item);\n });\n return newArray;\n }\n const sortedKeys = Object.keys(object).sort();\n const sortedObject = {};\n sortedKeys.forEach((key) => {\n sortedObject[key] = sortKeysRecursive(object[key]);\n });\n return sortedObject;\n}\n\n/**\n * Turn a nested object into a single-level object with dot notation keys and\n * values equal to the deepest **object** in the nested object.\n */\nexport function flatten(\n obj: Record<string, unknown>,\n): Record<string, Record<string, unknown>> {\n if (!isObject(obj)) {\n throw new Error('Expected an object to flatten');\n }\n const flattenedObj: Record<string, Record<string, unknown>> = {};\n\n function dive(thisObj: Record<string, unknown>, path: string[]) {\n Object.entries(thisObj).forEach(([key, value]) => {\n const thisPath = [...path, key];\n if (isObject(value)) {\n flattenedObj[thisPath.join('.')] = value;\n dive(value, thisPath);\n }\n });\n }\n\n dive(obj, []);\n\n return flattenedObj;\n}\n\n/**\n * This function takes a dictionary of objects and returns an array of objects with the `id` merged into the object.\n * Helpful when you have a dictionary of objects and you want to add the `id` to the object (from dictionary key) then want to use array methods.\n * Example:\n * ```ts\n * const dictionary = {\n * '123': { name: 'foo' },\n * '456': { name: 'bar' },\n * }\n *\n * dictionaryToArray(dictionary).forEach(({ id, name }) => {\n * // stuff\n * })\n * ```\n * @see {@link updateDictionaryWithId}\n * @see {@link arrayToDictionary}\n */\nexport function dictionaryToArray<T extends Record<string, any>>(\n dictionary: Record<string, T>,\n): (T & { id: string })[] {\n return Object.entries(dictionary).map(([id, value]) => ({\n id,\n ...value,\n }));\n}\n\n/**\n * This function takes a dictionary of objects and returns a dictionary of objects with the `id` merged into the object.\n * Helpful when you have a dictionary of objects and you want to add the `id` to the object (from dictionary key)\n * @see {@link dictionaryToArray}\n * @example\n * ```ts\n * const dictionary = {\n * '123': { name: 'foo' },\n * '456': { name: 'bar' },\n * }\n *\n * const dictionaryWithId = updateDictionaryWithId(dictionary)\n * // Which is now:\n * {\n * '123': { id: '123', name: 'foo' },\n * '456': { id: '456', name: 'bar' },\n * }\n * ```\n */\nexport function updateDictionaryWithId<T extends Record<string, any>>(\n dict: Record<string, T>,\n): Record<string, T & { id: string }> {\n return Object.entries(dict).reduce(\n (acc, [id, value]) => {\n acc[id] = {\n id,\n ...value,\n };\n return acc;\n },\n {} as Record<string, T & { id: string }>,\n );\n}\n","import {\n type Patch,\n applyPatches,\n enablePatches,\n produceWithPatches,\n produce,\n isDraft,\n type Draft,\n type Objectish,\n} from 'immer';\nimport { sortKeysRecursive } from './objects';\n\nexport { produce, produceWithPatches, applyPatches, isDraft };\nexport type { Patch, Draft };\n\nenablePatches();\n\n/**\n * Take an array of Immer patches and compress them down to the smallest amount of patches\n * @link https://medium.com/@dedels/using-immer-to-compress-immer-patches-f382835b6c69\n */\nexport function compressPatches<Data extends Objectish>({\n baseData,\n patches: allPatches,\n}: {\n baseData: Data;\n patches: Patch[][] | Patch[];\n}) {\n return produceWithPatches(baseData, (draft) => {\n applyPatches(draft, allPatches.flat());\n });\n}\n\n/** A patch that could not be applied, with the error Immer threw for it */\nexport interface PoisonPatch {\n readonly patch: Patch;\n readonly error: unknown;\n}\n\n/** A change whose patches did not all apply */\nexport interface FailedChange<Change> {\n readonly change: Change;\n /** The error from the first poison patch */\n readonly error: unknown;\n /** The change's patches that did apply, in order. Empty when none did. */\n readonly appliedPatches: Patch[];\n /** The change's patches that threw and were dropped */\n readonly poisonPatches: PoisonPatch[];\n /**\n * Applied after `appliedPatches`: they put back values a poison patch was\n * moving, where they were before the change (see `applyPatchesSafely`)\n */\n readonly restoredPatches: Patch[];\n}\n\n/** An applied patch, with the document just before and just after it */\ninterface AppliedStep<Data> {\n readonly patch: Patch;\n readonly before: Data;\n readonly after: Data;\n}\n\n/** Apply `patches` one at a time, skipping the ones that throw */\nfunction applyEachPatch<Data extends Objectish>({\n data,\n patches,\n}: {\n data: Data;\n patches: Patch[];\n}): {\n data: Data;\n steps: Array<AppliedStep<Data>>;\n poisonPatches: PoisonPatch[];\n} {\n const steps: Array<AppliedStep<Data>> = [];\n const poisonPatches: PoisonPatch[] = [];\n const result = patches.reduce((acc, patch) => {\n try {\n const next = applyPatches(acc, [patch]);\n steps.push({ patch, before: acc, after: next });\n return next;\n } catch (error) {\n poisonPatches.push({ patch, error });\n return acc;\n }\n }, data);\n return { data: result, steps, poisonPatches };\n}\n\ntype Path = ReadonlyArray<string | number>;\n\nconst pathKey = (path: Path): string => JSON.stringify(path.map(String));\n\n/** `prefix` is a proper ancestor of `path` */\nconst isAncestor = (prefix: Path, path: Path): boolean =>\n prefix.length < path.length &&\n prefix.every((segment, i) => String(segment) === String(path[i]));\n\n/**\n * The same for deep-equal JSON values, whatever their key order: saved\n * patches come back from a `jsonb` column, which does not keep it\n */\nconst valueKey = (value: unknown): string =>\n `${typeof value}:${JSON.stringify(sortKeysRecursive(value))}`;\n\nfunction getAt(data: unknown, path: Path): unknown {\n let value = data;\n for (const key of path) {\n if (!value || typeof value !== 'object') return undefined;\n value = (value as Record<string | number, unknown>)[key];\n }\n return value;\n}\n\n/** Call `visit` for `value` and every value nested in it, with its path */\nfunction forEachValue(\n value: unknown,\n visit: (v: unknown, path: Path) => void,\n path: Path = [],\n): void {\n visit(value, path);\n if (Array.isArray(value)) {\n value.forEach((item, i) => forEachValue(item, visit, [...path, i]));\n } else if (value && typeof value === 'object') {\n for (const [key, item] of Object.entries(value)) {\n forEachValue(item, visit, [...path, key]);\n }\n }\n}\n\nfunction countValues(\n data: unknown,\n root: Path,\n wanted: ReadonlySet<string>,\n): Map<string, number> {\n const counts = new Map<string, number>();\n forEachValue(getAt(data, root), (value) => {\n const key = valueKey(value);\n if (wanted.has(key)) counts.set(key, (counts.get(key) ?? 0) + 1);\n });\n return counts;\n}\n\nconst countIn = (items: unknown, key: string): number =>\n Array.isArray(items)\n ? items.filter((item) => valueKey(item) === key).length\n : 0;\n\n/**\n * What a move carries: an id (a string in an array) or an entity (an object\n * or array with something in it). A number, boolean, null, empty container\n * or string under an object key is far more often a setting that happens to\n * equal another than a moved value.\n */\nconst isMovable = (value: unknown, inArray: boolean): boolean =>\n typeof value === 'string'\n ? inArray\n : !!value && typeof value === 'object' && Object.keys(value).length > 0;\n\n/** Path segments that reach a prototype instead of a property */\nconst PROTOTYPE_KEYS: ReadonlySet<string> = new Set([\n '__proto__',\n 'constructor',\n 'prototype',\n]);\n\n/** A movable value a poison patch put down, on the stand-in document */\nclass PutDown {\n constructor(\n readonly key: string,\n readonly content: unknown,\n ) {}\n}\n\nconst contentOf = (node: unknown): unknown =>\n node instanceof PutDown ? node.content : node;\n\n/** How many of each movable value `node` holds that a poison patch put down */\nfunction tallyPutDown(\n node: unknown,\n counts = new Map<string, number>(),\n): Map<string, number> {\n if (node instanceof PutDown) {\n counts.set(node.key, (counts.get(node.key) ?? 0) + 1);\n }\n const content = contentOf(node);\n if (content && typeof content === 'object') {\n Object.values(content).forEach((item) => tallyPutDown(item, counts));\n }\n return counts;\n}\n\n/** `value` for the stand-in, with each movable value `take` accepts marked */\nfunction markPutDown(\n value: unknown,\n inArray: boolean,\n take: (key: string) => boolean,\n): unknown {\n const content = Array.isArray(value)\n ? value.map((item) => markPutDown(item, true, take))\n : value && typeof value === 'object'\n ? Object.fromEntries(\n Object.entries(value).map(([key, item]) => [\n key,\n markPutDown(item, false, take),\n ]),\n )\n : value;\n if (!isMovable(value, inArray)) return content;\n const key = valueKey(value);\n return take(key) ? new PutDown(key, content) : content;\n}\n\n/**\n * How many of each movable value the poison patches put down are still where\n * they put them at the end of the change, as its author saw it. The change's\n * patches are replayed on a stand-in for the part of the document the poison\n * patches needed and did not find. It holds only what they wrote, with an\n * unknown item wherever an index says the author's array had one, so a later\n * patch that removes, overwrites or shifts a value there does so exactly; an\n * applied patch writes an unknown value.\n *\n * The target side of a move is an `add`, or inside an array a `replace`; what\n * it carries counts with everything movable inside it (a new group holding\n * the moved ids). A `replace` of an object key is an edit: it counts for the\n * items of an array it carries (a list rebuilt with the moved id in it), and\n * otherwise only for values that were already put down there.\n *\n * A patch whose path goes through `__proto__`, `constructor` or `prototype`\n * is skipped: Immer refuses it, and following it here would write onto a\n * shared prototype.\n */\nfunction countPutDown(\n patches: ReadonlyArray<Patch>,\n poison: ReadonlySet<Patch>,\n): Map<string, number> {\n if (![...poison].some(({ op }) => op !== 'remove')) return new Map();\n const stand: Record<string, unknown> = {};\n const all = (): boolean => true;\n for (const patch of patches) {\n const failed = poison.has(patch);\n const { op, path, value } = patch;\n if (path.some((segment) => PROTOTYPE_KEYS.has(String(segment)))) continue;\n let parent: unknown = stand;\n for (const [i, segment] of path.slice(0, -1).entries()) {\n const holder = parent as Record<string | number, unknown>;\n let child = contentOf(holder[segment]);\n if (!child || typeof child !== 'object') {\n // Only a poison patch says the author had something here\n if (!failed) {\n parent = undefined;\n break;\n }\n child = typeof path[i + 1] === 'number' ? [] : {};\n holder[segment] = child;\n }\n parent = child;\n }\n if (!parent) continue;\n\n const holder = parent as Record<string | number, unknown>;\n const last = path[path.length - 1];\n const intoArray = Array.isArray(parent);\n let placed: unknown;\n if (failed && op !== 'remove') {\n if (op === 'add' || intoArray) {\n placed = markPutDown(value, intoArray, all);\n } else if (Array.isArray(value)) {\n placed = value.map((item) => markPutDown(item, true, all));\n } else {\n const already = tallyPutDown(holder[last]);\n placed = markPutDown(value, false, (key) => {\n const left = already.get(key) ?? 0;\n already.set(key, left - 1);\n return left > 0;\n });\n }\n }\n if (Array.isArray(parent)) {\n const at = Number(last);\n if (op === 'add') {\n if (parent.length < at) parent.length = at;\n parent.splice(at, 0, placed);\n } else if (op === 'replace') {\n parent[at] = placed;\n } else {\n parent.splice(at, 1);\n }\n } else if (op === 'remove') {\n delete holder[last];\n } else {\n holder[last] = placed;\n }\n }\n return tallyPutDown(stand);\n}\n\n/** Index of the `nth` (from 1) item of `items` equal to `key`, or -1 */\nfunction nthIndexOf(items: unknown, key: string, nth: number): number {\n if (!Array.isArray(items)) return -1;\n let seen = 0;\n return items.findIndex((item) => {\n if (valueKey(item) !== key) return false;\n seen += 1;\n return seen === nth;\n });\n}\n\n/**\n * Where an item that was at `index` in `from` goes back into `items`: just\n * after the nearest item before it in `from` that `items` still holds, else\n * first\n */\nfunction insertionIndex(\n items: ReadonlyArray<unknown>,\n from: ReadonlyArray<unknown>,\n index: number,\n): number {\n const keys = from.slice(0, index).map(valueKey);\n const seen = new Map<string, number>();\n const nths = keys.map((key) => {\n const nth = (seen.get(key) ?? 0) + 1;\n seen.set(key, nth);\n return nth;\n });\n for (let j = index - 1; j >= 0; j--) {\n const at = nthIndexOf(items, keys[j], nths[j]);\n if (at !== -1) return at + 1;\n }\n return 0;\n}\n\n/** An applied patch on one item of an array */\ninterface ItemOp {\n readonly array: string;\n readonly op: Patch['op'];\n readonly index: number;\n}\n\n/**\n * Whether `next` continues the patches Immer saves for one edit of one\n * array: `replace`s in rising index order, then `add`s in rising order or\n * `remove`s in falling order\n */\nfunction continuesArrayEdit(prev?: ItemOp, next?: ItemOp): boolean {\n if (!prev || !next || prev.array !== next.array) return false;\n if (next.op === 'replace') {\n return prev.op === 'replace' && next.index > prev.index;\n }\n if (prev.op === 'replace') return next.index > prev.index;\n const step = next.op === 'add' ? 1 : -1;\n return next.op === prev.op && next.index === prev.index + step;\n}\n\n/** A spot an applied patch took a moving value out of */\ninterface Removal {\n readonly key: string;\n readonly value: unknown;\n /** Where it was in `from` */\n readonly path: Path;\n readonly from: unknown;\n readonly step: number;\n /** The first step of the array edit its step belongs to */\n readonly run: number;\n /** Its order within the run */\n readonly order: number;\n}\n\n/**\n * Put back the values `poisonPatches` put down that an applied patch took\n * out and no later applied patch landed again, as many times as the poison\n * patches left them where they put them (`countPutDown`). A value goes back\n * where it was before the patch that took it out, even when an earlier action\n * in the same saved change put it there (`updateBranchContent` saves several\n * actions as one change): into an array that now holds it fewer times, or,\n * for an entity, at its key on an object that no longer has that key.\n *\n * An array item goes back just after the nearest item that was before it and\n * is still there. Its place is read before the edit that took it out: one\n * edit saved as several patches (a `splice`) passes through orders nobody\n * saw, so those patches are read as one (`continuesArrayEdit`). The most\n * recent edit goes first; within one, items go in their order. An id is only put back into an array,\n * since under an object key a string is a setting as often as a reference.\n * Only the subtree each applied patch changed is counted; the rest of the\n * document is unchanged.\n *\n * Not put back: a value the same change also edited, which no longer matches\n * what was removed; a value whose old container the change deleted; and a\n * value inside an array item when anything above that item was rewritten\n * from then on (the array's items added, removed or replaced, or the array\n * or an object holding it reassigned), since its old index may hold another\n * item.\n */\nfunction restoreMovedValues<Data extends Objectish>({\n salvaged,\n patches,\n steps,\n poisonPatches,\n}: {\n salvaged: Data;\n patches: ReadonlyArray<Patch>;\n steps: ReadonlyArray<AppliedStep<Data>>;\n poisonPatches: ReadonlyArray<PoisonPatch>;\n}): { data: Data; restoredPatches: Patch[] } {\n const putDown = countPutDown(\n patches,\n new Set(poisonPatches.map(({ patch }) => patch)),\n );\n if (putDown.size === 0) return { data: salvaged, restoredPatches: [] };\n const wanted = new Set(putDown.keys());\n\n // Each value's removals that no later applied patch landed again\n const unlanded = new Map<string, number>();\n const removals: Removal[] = [];\n // What each step rewrote: the array for an item op, else the patch's path\n const rewritten: Array<{ step: number; path: Path }> = [];\n let run = 0;\n let previous: ItemOp | undefined;\n steps.forEach(({ patch, before, after }, step) => {\n const parent = patch.path.slice(0, -1);\n const intoArray = Array.isArray(getAt(before, parent));\n const root = intoArray ? parent : patch.path;\n const item = intoArray\n ? {\n array: pathKey(parent),\n op: patch.op,\n index: Number(patch.path[patch.path.length - 1]),\n }\n : undefined;\n if (!continuesArrayEdit(previous, item)) run = step;\n previous = item;\n rewritten.push({ step, path: root });\n const was = countValues(before, root, wanted);\n const now = countValues(after, root, wanted);\n const removed = new Set<string>();\n for (const key of wanted) {\n const delta = (now.get(key) ?? 0) - (was.get(key) ?? 0);\n const open = unlanded.get(key) ?? 0;\n if (delta < 0) {\n unlanded.set(key, open - delta);\n removed.add(key);\n } else if (delta > 0) {\n unlanded.set(key, Math.max(0, open - delta));\n }\n }\n if (removed.size === 0) return;\n const start = steps[run].before;\n forEachValue(getAt(before, root), (value, relative) => {\n const key = valueKey(value);\n if (!removed.has(key)) return;\n const path = [...root, ...relative];\n const parentPath = path.slice(0, -1);\n const gone = Array.isArray(getAt(after, parentPath))\n ? countIn(getAt(after, parentPath), key) <\n countIn(getAt(before, parentPath), key)\n : valueKey(getAt(after, path)) !== key;\n if (!gone) return;\n const items = getAt(before, root);\n if (relative.length === 1 && Array.isArray(items)) {\n const index = Number(relative[0]);\n const nth = countIn(items.slice(0, index + 1), key);\n const atStart = nthIndexOf(getAt(start, root), key, nth);\n if (atStart !== -1) {\n const at = [...root, atStart];\n removals.push({\n key,\n value,\n path: at,\n from: start,\n step,\n run,\n order: atStart,\n });\n return;\n }\n }\n removals.push({\n key,\n value,\n path,\n from: before,\n step,\n run,\n order: -step,\n });\n });\n });\n\n const lost = new Map<string, number>();\n for (const [key, count] of putDown) {\n const missing = Math.min(count, unlanded.get(key) ?? 0);\n if (missing > 0) lost.set(key, missing);\n }\n if (lost.size === 0) return { data: salvaged, restoredPatches: [] };\n\n const [data, restoredPatches] = produceWithPatches(salvaged, (draft) => {\n const putBack = ({ key, value, path, from }: Removal): boolean => {\n const parentPath = path.slice(0, -1);\n const last = path[path.length - 1];\n const parent = getAt(draft, parentPath);\n if (Array.isArray(parent)) {\n const was = getAt(from, parentPath) as unknown[];\n if (countIn(parent, key) >= countIn(was, key)) return false;\n parent.splice(insertionIndex(parent, was, Number(last)), 0, value);\n return true;\n }\n if (\n typeof value === 'object' &&\n parent &&\n typeof parent === 'object' &&\n !(String(last) in parent)\n ) {\n (parent as Record<string | number, unknown>)[last] = value;\n return true;\n }\n return false;\n };\n const ordered = [...removals].sort(\n (a, b) => b.run - a.run || a.order - b.order,\n );\n for (const removal of ordered) {\n if (!lost.get(removal.key)) continue;\n // An array item on the way to its old spot may be another item now if\n // anything above it was rewritten from then on\n const parentPath = removal.path.slice(0, -1);\n const shifted = rewritten.some(\n ({ step, path }) =>\n step >= removal.step &&\n isAncestor(path, parentPath) &&\n parentPath.slice(path.length).some((key) => typeof key === 'number'),\n );\n if (shifted || !putBack(removal)) continue;\n // It came back with everything in it\n forEachValue(removal.value, (v) => {\n const left = lost.get(valueKey(v));\n if (left) lost.set(valueKey(v), left - 1);\n });\n }\n });\n return { data, restoredPatches };\n}\n\n/**\n * Apply `changes` one at a time instead of all at once.\n *\n * When a change fails to apply as a unit, its patches are retried one at a\n * time: each patch that applies is kept and only the ones that throw (the\n * \"poison\" patches) are dropped. One stale patch, e.g. a `replace` under a\n * block another branch deleted, does not take the change's unrelated edits\n * down with it. Immer only throws when a patch's parent path is missing, and\n * a dropped patch changed nothing, so patches that edit under the same\n * missing parent are dropped too.\n *\n * A dependent patch on another path is not caught that way. Moving a value\n * records an `add` at the target and a `remove` at the source; with the\n * target gone, applying only the `remove` would delete the value outright.\n * So a value a poison patch was moving that the change took out and did not\n * land anywhere else is put back where it was just before the patch that\n * took it out (`restoreMovedValues`), after the change's other patches, which\n * keep their effect.\n *\n * A poison patch also means the change was recorded against a different base\n * than `data`. Its surviving index-based array patches (`add`/`remove` at\n * `list/3`) are applied at those indexes, which may now hold different items.\n * A value put back shifts an array the same way for the changes after it,\n * which were recorded without it. That is the same risk every change\n * recorded against a stale base already carries; dropping the whole change\n * instead loses the user's work outright.\n *\n * Every change that lost patches is returned in `failedChanges` with what\n * applied, what threw, and what was put back, so callers can tell exactly\n * what landed.\n *\n * `data` must not be an Immer draft: `applyPatches` mutates a draft in place,\n * so a change that throws partway would leave its earlier patches applied and\n * the one-at-a-time retry would apply them again. Reduce plain data and wrap\n * the result in `produce` afterwards.\n */\nexport function applyPatchesSafely<\n Data extends Objectish,\n Change extends { patches: Patch[]; id?: unknown } = { patches: Patch[] },\n>({\n data,\n changes,\n logError = console.error,\n logAppClientData = false,\n}: {\n data: Data;\n changes: Change[];\n logError?: (msg: unknown, ...optionalMsgs: unknown[]) => void;\n logAppClientData?: boolean;\n}): { data: Data; failedChanges: Array<FailedChange<Change>> } {\n if (isDraft(data)) {\n throw new Error(\n 'applyPatchesSafely: `data` must not be an Immer draft; a change that fails partway would leave its earlier patches applied',\n );\n }\n const failedChanges: Array<FailedChange<Change>> = [];\n const result = changes.reduce((acc, change, i) => {\n try {\n return applyPatches(acc, change.patches);\n } catch {\n const salvage = applyEachPatch({ data: acc, patches: change.patches });\n const { steps, poisonPatches } = salvage;\n if (poisonPatches.length === 0) return salvage.data;\n const appliedPatches = steps.map(({ patch }) => patch);\n\n const { data: restored, restoredPatches } = restoreMovedValues({\n salvaged: salvage.data,\n patches: change.patches,\n steps,\n poisonPatches,\n });\n\n const { LOG_IMMER_APP_CLIENT_DATA } = process.env;\n const describe = (patch: Patch): { op: string; path: string } => ({\n op: patch.op,\n path: patch.path.join('/'),\n });\n logError(\n `applyPatchesSafely had issues with change ${i}: dropped ${poisonPatches.length} of ${change.patches.length} patches and applied the rest`,\n {\n metadata: {\n changeIndex: i,\n changeId: change.id,\n appliedPatchCount: appliedPatches.length,\n poisonPatches: poisonPatches.map(({ patch, error }) => ({\n ...describe(patch),\n error: error instanceof Error ? error.message : String(error),\n })),\n restoredPatches: restoredPatches.map(describe),\n // The document this change was applied to\n ...(logAppClientData || LOG_IMMER_APP_CLIENT_DATA\n ? { data: acc }\n : {}),\n },\n },\n );\n failedChanges.push({\n change,\n error: poisonPatches[0]?.error,\n appliedPatches,\n poisonPatches,\n restoredPatches,\n });\n return restored;\n }\n }, data);\n return { data: result, failedChanges };\n}\n"]}
package/dist/immer.mjs CHANGED
@@ -1,2 +1,2 @@
1
- import {enablePatches,produceWithPatches,applyPatches}from'immer';export{applyPatches,isDraft,produce,produceWithPatches}from'immer';var d=Object.defineProperty;var n=(e,a)=>d(e,"name",{value:a,configurable:true});enablePatches();function b({baseData:e,patches:a}){return produceWithPatches(e,r=>{applyPatches(r,a.flat());})}n(b,"compressPatches");function m({data:e,changes:a,logError:r=console.error,logAppClientData:p=false}){let o=[];return {data:a.reduce((c,t,l)=>{try{return applyPatches(c,t.patches)}catch(s){let{LOG_IMMER_APP_CLIENT_DATA:i}=process.env,u=p||i?{data:e,change:t}:t;return r(`applyPatchesSafely had issues (and so will skip) with patches in change ${l}: ${s instanceof Error?s.message:""}`,u),o.push({change:t,error:s}),c}},e),failedChanges:o}}n(m,"applyPatchesSafely");export{m as applyPatchesSafely,b as compressPatches};//# sourceMappingURL=immer.mjs.map
1
+ import {enablePatches,produceWithPatches,applyPatches,isDraft}from'immer';export{applyPatches,isDraft,produce,produceWithPatches}from'immer';var Q=Object.defineProperty;var u=(t,e)=>Q(t,"name",{value:e,configurable:true});function K(t){if(typeof t!="object"||!t)return t;if(Array.isArray(t)){let r=[];return t.forEach((s,d)=>{r[d]=K(s);}),r}let e=Object.keys(t).sort(),n={};return e.forEach(r=>{n[r]=K(t[r]);}),n}u(K,"sortKeysRecursive");enablePatches();function kt({baseData:t,patches:e}){return produceWithPatches(t,n=>{applyPatches(n,e.flat());})}u(kt,"compressPatches");function v({data:t,patches:e}){let n=[],r=[];return {data:e.reduce((d,c)=>{try{let i=applyPatches(d,[c]);return n.push({patch:c,before:d,after:i}),i}catch(i){return r.push({patch:c,error:i}),d}},t),steps:n,poisonPatches:r}}u(v,"applyEachPatch");var tt=u(t=>JSON.stringify(t.map(String)),"pathKey"),et=u((t,e)=>t.length<e.length&&t.every((n,r)=>String(n)===String(e[r])),"isAncestor"),O=u(t=>`${typeof t}:${JSON.stringify(K(t))}`,"valueKey");function w(t,e){let n=t;for(let r of e){if(!n||typeof n!="object")return;n=n[r];}return n}u(w,"getAt");function I(t,e,n=[]){if(e(t,n),Array.isArray(t))t.forEach((r,s)=>I(r,e,[...n,s]));else if(t&&typeof t=="object")for(let[r,s]of Object.entries(t))I(s,e,[...n,r]);}u(I,"forEachValue");function L(t,e,n){let r=new Map;return I(w(t,e),s=>{let d=O(s);n.has(d)&&r.set(d,(r.get(d)??0)+1);}),r}u(L,"countValues");var M=u((t,e)=>Array.isArray(t)?t.filter(n=>O(n)===e).length:0,"countIn"),nt=u((t,e)=>typeof t=="string"?e:!!t&&typeof t=="object"&&Object.keys(t).length>0,"isMovable"),rt=new Set(["__proto__","constructor","prototype"]),_=class{constructor(e,n){this.key=e;this.content=n;}static{u(this,"PutDown");}},Y=u(t=>t instanceof _?t.content:t,"contentOf");function z(t,e=new Map){t instanceof _&&e.set(t.key,(e.get(t.key)??0)+1);let n=Y(t);return n&&typeof n=="object"&&Object.values(n).forEach(r=>z(r,e)),e}u(z,"tallyPutDown");function C(t,e,n){let r=Array.isArray(t)?t.map(d=>C(d,true,n)):t&&typeof t=="object"?Object.fromEntries(Object.entries(t).map(([d,c])=>[d,C(c,false,n)])):t;if(!nt(t,e))return r;let s=O(t);return n(s)?new _(s,r):r}u(C,"markPutDown");function ot(t,e){if(![...e].some(({op:s})=>s!=="remove"))return new Map;let n={},r=u(()=>true,"all");for(let s of t){let d=e.has(s),{op:c,path:i,value:b}=s;if(i.some(o=>rt.has(String(o))))continue;let p=n;for(let[o,f]of i.slice(0,-1).entries()){let l=p,a=Y(l[f]);if(!a||typeof a!="object"){if(!d){p=void 0;break}a=typeof i[o+1]=="number"?[]:{},l[f]=a;}p=a;}if(!p)continue;let x=p,h=i[i.length-1],j=Array.isArray(p),k;if(d&&c!=="remove")if(c==="add"||j)k=C(b,j,r);else if(Array.isArray(b))k=b.map(o=>C(o,true,r));else {let o=z(x[h]);k=C(b,false,f=>{let l=o.get(f)??0;return o.set(f,l-1),l>0});}if(Array.isArray(p)){let o=Number(h);c==="add"?(p.length<o&&(p.length=o),p.splice(o,0,k)):c==="replace"?p[o]=k:p.splice(o,1);}else c==="remove"?delete x[h]:x[h]=k;}return z(n)}u(ot,"countPutDown");function G(t,e,n){if(!Array.isArray(t))return -1;let r=0;return t.findIndex(s=>O(s)!==e?false:(r+=1,r===n))}u(G,"nthIndexOf");function at(t,e,n){let r=e.slice(0,n).map(O),s=new Map,d=r.map(c=>{let i=(s.get(c)??0)+1;return s.set(c,i),i});for(let c=n-1;c>=0;c--){let i=G(t,r[c],d[c]);if(i!==-1)return i+1}return 0}u(at,"insertionIndex");function st(t,e){if(!t||!e||t.array!==e.array)return false;if(e.op==="replace")return t.op==="replace"&&e.index>t.index;if(t.op==="replace")return e.index>t.index;let n=e.op==="add"?1:-1;return e.op===t.op&&e.index===t.index+n}u(st,"continuesArrayEdit");function ct({salvaged:t,patches:e,steps:n,poisonPatches:r}){let s=ot(e,new Set(r.map(({patch:o})=>o)));if(s.size===0)return {data:t,restoredPatches:[]};let d=new Set(s.keys()),c=new Map,i=[],b=[],p=0,x;n.forEach(({patch:o,before:f,after:l},a)=>{let y=o.path.slice(0,-1),S=Array.isArray(w(f,y)),g=S?y:o.path,m=S?{array:tt(y),op:o.op,index:Number(o.path[o.path.length-1])}:void 0;st(x,m)||(p=a),x=m,b.push({step:a,path:g});let T=L(f,g,d),A=L(l,g,d),E=new Set;for(let R of d){let D=(A.get(R)??0)-(T.get(R)??0),P=c.get(R)??0;D<0?(c.set(R,P-D),E.add(R)):D>0&&c.set(R,Math.max(0,P-D));}if(E.size===0)return;let B=n[p].before;I(w(f,g),(R,D)=>{let P=O(R);if(!E.has(P))return;let N=[...g,...D],V=N.slice(0,-1);if(!(Array.isArray(w(l,V))?M(w(l,V),P)<M(w(f,V),P):O(w(l,N))!==P))return;let J=w(f,g);if(D.length===1&&Array.isArray(J)){let U=Number(D[0]),q=M(J.slice(0,U+1),P),$=G(w(B,g),P,q);if($!==-1){let H=[...g,$];i.push({key:P,value:R,path:H,from:B,step:a,run:p,order:$});return}}i.push({key:P,value:R,path:N,from:f,step:a,run:p,order:-a});});});let h=new Map;for(let[o,f]of s){let l=Math.min(f,c.get(o)??0);l>0&&h.set(o,l);}if(h.size===0)return {data:t,restoredPatches:[]};let[j,k]=produceWithPatches(t,o=>{let f=u(({key:a,value:y,path:S,from:g})=>{let m=S.slice(0,-1),T=S[S.length-1],A=w(o,m);if(Array.isArray(A)){let E=w(g,m);return M(A,a)>=M(E,a)?false:(A.splice(at(A,E,Number(T)),0,y),true)}return typeof y=="object"&&A&&typeof A=="object"&&!(String(T)in A)?(A[T]=y,true):false},"putBack"),l=[...i].sort((a,y)=>y.run-a.run||a.order-y.order);for(let a of l){if(!h.get(a.key))continue;let y=a.path.slice(0,-1);b.some(({step:g,path:m})=>g>=a.step&&et(m,y)&&y.slice(m.length).some(T=>typeof T=="number"))||!f(a)||I(a.value,g=>{let m=h.get(O(g));m&&h.set(O(g),m-1);});}});return {data:j,restoredPatches:k}}u(ct,"restoreMovedValues");function At({data:t,changes:e,logError:n=console.error,logAppClientData:r=false}){if(isDraft(t))throw new Error("applyPatchesSafely: `data` must not be an Immer draft; a change that fails partway would leave its earlier patches applied");let s=[];return {data:e.reduce((c,i,b)=>{try{return applyPatches(c,i.patches)}catch{let p=v({data:c,patches:i.patches}),{steps:x,poisonPatches:h}=p;if(h.length===0)return p.data;let j=x.map(({patch:a})=>a),{data:k,restoredPatches:o}=ct({salvaged:p.data,patches:i.patches,steps:x,poisonPatches:h}),{LOG_IMMER_APP_CLIENT_DATA:f}=process.env,l=u(a=>({op:a.op,path:a.path.join("/")}),"describe");return n(`applyPatchesSafely had issues with change ${b}: dropped ${h.length} of ${i.patches.length} patches and applied the rest`,{metadata:{changeIndex:b,changeId:i.id,appliedPatchCount:j.length,poisonPatches:h.map(({patch:a,error:y})=>({...l(a),error:y instanceof Error?y.message:String(y)})),restoredPatches:o.map(l),...r||f?{data:c}:{}}}),s.push({change:i,error:h[0]?.error,appliedPatches:j,poisonPatches:h,restoredPatches:o}),k}},t),failedChanges:s}}u(At,"applyPatchesSafely");export{At as applyPatchesSafely,kt as compressPatches};//# sourceMappingURL=immer.mjs.map
2
2
  //# sourceMappingURL=immer.mjs.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/immer.ts"],"names":["enablePatches","compressPatches","baseData","allPatches","produceWithPatches","draft","applyPatches","__name","applyPatchesSafely","data","changes","logError","logAppClientData","failedChanges","acc","change","i","error","LOG_IMMER_APP_CLIENT_DATA","metadata"],"mappings":"qIAAA,IAAA,CAAA,CAAA,MAAA,CAAA,cAAA,CAAA,IAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,GAAA,CAAA,CAAA,CAAA,CAAA,MAAA,CAAA,CAAA,KAAA,CAAA,CAAA,CAAA,YAAA,CAAA,IAAA,CAAA,CAAA,CAcAA,aAAAA,EAAc,CAMP,SAASC,CAAAA,CAAwC,CACtD,QAAA,CAAAC,CAAAA,CACA,OAAA,CAASC,CACX,CAAA,CAGG,CACD,OAAOC,kBAAAA,CAAmBF,CAAAA,CAAWG,CAAAA,EAAU,CAC7CC,YAAAA,CAAaD,EAAOF,CAAAA,CAAW,IAAA,EAAM,EACvC,CAAC,CACH,CAVgBI,CAAAA,CAAAN,CAAAA,CAAA,iBAAA,CAAA,CAkBT,SAASO,CAAAA,CAGd,CACA,IAAA,CAAAC,CAAAA,CACA,OAAA,CAAAC,CAAAA,CACA,QAAA,CAAAC,CAAAA,CAAW,OAAA,CAAQ,KAAA,CACnB,gBAAA,CAAAC,CAAAA,CAAmB,KACrB,CAAA,CAK6E,CAC3E,IAAMC,CAAAA,CAA2D,EAAC,CAoBlE,OAAO,CAAE,KAnBMH,CAAAA,CAAQ,MAAA,CAAO,CAACI,CAAAA,CAAKC,CAAAA,CAAQC,CAAAA,GAAM,CAChD,GAAI,CACF,OAAOV,YAAAA,CAAaQ,CAAAA,CAAKC,CAAAA,CAAO,OAAO,CACzC,CAAA,MAASE,CAAAA,CAAO,CACd,GAAM,CAAE,yBAAA,CAAAC,CAA0B,CAAA,CAAI,OAAA,CAAQ,GAAA,CACxCC,CAAAA,CACJP,CAAAA,EAAoBM,CAAAA,CAChB,CAAE,IAAA,CAAAT,CAAAA,CAAM,MAAA,CAAAM,CAAO,CAAA,CACfA,CAAAA,CACN,OAAAJ,CAAAA,CACE,CAAA,wEAAA,EAA2EK,CAAC,CAAA,EAAA,EAC1EC,CAAAA,YAAiB,KAAA,CAAQA,CAAAA,CAAM,OAAA,CAAU,EAC3C,CAAA,CAAA,CACAE,CACF,CAAA,CACAN,CAAAA,CAAc,KAAK,CAAE,MAAA,CAAAE,CAAAA,CAAQ,KAAA,CAAAE,CAAM,CAAC,CAAA,CAC7BH,CACT,CACF,CAAA,CAAGL,CAAI,CAAA,CACgB,aAAA,CAAAI,CAAc,CACvC,CAnCgBN,EAAAC,CAAAA,CAAA,oBAAA,CAAA","file":"immer.mjs","sourcesContent":["import {\n type Patch,\n applyPatches,\n enablePatches,\n produceWithPatches,\n produce,\n isDraft,\n type Draft,\n type Objectish,\n} from 'immer';\n\nexport { produce, produceWithPatches, applyPatches, isDraft };\nexport type { Patch, Draft };\n\nenablePatches();\n\n/**\n * Take an array of Immer patches and compress them down to the smallest amount of patches\n * @link https://medium.com/@dedels/using-immer-to-compress-immer-patches-f382835b6c69\n */\nexport function compressPatches<Data extends Objectish>({\n baseData,\n patches: allPatches,\n}: {\n baseData: Data;\n patches: Patch[][] | Patch[];\n}) {\n return produceWithPatches(baseData, (draft) => {\n applyPatches(draft, allPatches.flat());\n });\n}\n\n/**\n * Loop over changes to applyPatches in small batches (safer) instead of all at once.\n * If a change's patches fail to apply, it's skipped (not the whole batch) and\n * returned in `failedChanges` instead of being silently dropped - callers decide\n * whether/how to surface that a change didn't make it in.\n */\nexport function applyPatchesSafely<\n Data extends Objectish,\n Change extends { patches: Patch[] } = { patches: Patch[] },\n>({\n data,\n changes,\n logError = console.error,\n logAppClientData = false,\n}: {\n data: Data;\n changes: Change[];\n logError?: (msg: unknown, ...optionalMsgs: unknown[]) => void;\n logAppClientData?: boolean;\n}): { data: Data; failedChanges: Array<{ change: Change; error: unknown }> } {\n const failedChanges: Array<{ change: Change; error: unknown }> = [];\n const result = changes.reduce((acc, change, i) => {\n try {\n return applyPatches(acc, change.patches);\n } catch (error) {\n const { LOG_IMMER_APP_CLIENT_DATA } = process.env;\n const metadata =\n logAppClientData || LOG_IMMER_APP_CLIENT_DATA\n ? { data, change }\n : change;\n logError(\n `applyPatchesSafely had issues (and so will skip) with patches in change ${i}: ${\n error instanceof Error ? error.message : ''\n }`,\n metadata,\n );\n failedChanges.push({ change, error });\n return acc;\n }\n }, data);\n return { data: result, failedChanges };\n}\n"]}
1
+ {"version":3,"sources":["../src/objects.ts","../src/immer.ts"],"names":["sortKeysRecursive","object","newArray","item","index","sortedKeys","sortedObject","key","__name","enablePatches","compressPatches","baseData","allPatches","produceWithPatches","draft","applyPatches","applyEachPatch","data","patches","steps","poisonPatches","acc","patch","next","error","pathKey","path","isAncestor","prefix","segment","i","valueKey","value","getAt","forEachValue","visit","countValues","root","wanted","counts","countIn","items","isMovable","inArray","PROTOTYPE_KEYS","PutDown","content","contentOf","node","tallyPutDown","markPutDown","take","countPutDown","poison","op","stand","all","failed","parent","holder","child","last","intoArray","placed","already","left","at","nthIndexOf","nth","seen","insertionIndex","from","keys","nths","j","continuesArrayEdit","prev","step","restoreMovedValues","salvaged","putDown","unlanded","removals","rewritten","run","previous","before","after","was","now","removed","delta","open","start","relative","parentPath","atStart","lost","count","missing","restoredPatches","putBack","ordered","b","removal","v","applyPatchesSafely","changes","logError","logAppClientData","isDraft","failedChanges","change","salvage","appliedPatches","restored","LOG_IMMER_APP_CLIENT_DATA","describe"],"mappings":"8NAkDO,SAASA,CAAAA,CAAkBC,CAAAA,CAAQ,CACxC,GAAI,OAAOA,CAAAA,EAAW,QAAA,EAAY,CAACA,CAAAA,CAAQ,OAAOA,EAClD,GAAI,KAAA,CAAM,OAAA,CAAQA,CAAM,CAAA,CAAG,CACzB,IAAMC,CAAAA,CAAkB,EAAC,CACzB,OAAAD,CAAAA,CAAO,OAAA,CAAQ,CAACE,CAAAA,CAAMC,CAAAA,GAAU,CAC9BF,CAAAA,CAASE,CAAK,CAAA,CAAIJ,CAAAA,CAAkBG,CAAI,EAC1C,CAAC,CAAA,CACMD,CACT,CACA,IAAMG,EAAa,MAAA,CAAO,IAAA,CAAKJ,CAAM,CAAA,CAAE,IAAA,EAAK,CACtCK,EAAe,EAAC,CACtB,OAAAD,CAAAA,CAAW,OAAA,CAASE,CAAAA,EAAQ,CAC1BD,CAAAA,CAAaC,CAAG,CAAA,CAAIP,CAAAA,CAAkBC,CAAAA,CAAOM,CAAG,CAAC,EACnD,CAAC,CAAA,CACMD,CACT,CAfgBE,CAAAA,CAAAR,CAAAA,CAAA,qBCnChBS,aAAAA,EAAc,CAMP,SAASC,EAAAA,CAAwC,CACtD,QAAA,CAAAC,EACA,OAAA,CAASC,CACX,CAAA,CAGG,CACD,OAAOC,kBAAAA,CAAmBF,CAAAA,CAAWG,CAAAA,EAAU,CAC7CC,YAAAA,CAAaD,CAAAA,CAAOF,CAA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AAc,CAAC,GAAG,KAAA,CACzB,cAAA,CAAA8F,CAAAA,CACA,aAAA,CAAA9F,CAAAA,CACA,eAAA,CAAAgF,CACF,CAAC,CAAA,CACMe,CACT,CACF,CAAA,CAAGlG,CAAI,CAAA,CACgB,aAAA,CAAA8F,CAAc,CACvC,CAvEgBvG,CAAAA,CAAAkG,EAAAA,CAAA,oBAAA,CAAA","file":"immer.mjs","sourcesContent":["import cleanDeep from 'clean-deep';\nimport { isObject } from './is-types';\n\nexport { default as groupBy } from 'lodash/groupBy.js';\n// @todo: look into lodash/merge vs deepMerge behavior differences and use cases (ie. immutable vs not)\n// export { default as deepMerge } from 'lodash/merge.js';\nexport { default as deepMerge } from 'deepmerge';\n\n/**\n * Sort object by alphabetizing keys.\n */\nexport function sortObject<T extends Record<string, unknown>>(theObject: T): T {\n return Object.keys(theObject)\n .sort()\n .reduce(\n (obj, key: keyof T) => {\n obj[key] = theObject[key];\n return obj;\n },\n <T>{},\n );\n}\n\n/**\n * Remove empty objects in nested object.\n * Leverage stringify to convert empty objects to undefined, which is removed\n * during stringification.\n */\nexport const removeEmptyObjects = <T extends Record<string, unknown>>(\n src: T,\n): Partial<T> => cleanDeep(src);\n\n/**\n * Removes keys like `{ x: undefined }` from the object\n */\nexport function removeUndefinedProps<T extends Record<PropertyKey, unknown>>(\n obj: T,\n): T {\n return cleanDeep(obj, {\n undefinedValues: true,\n nullValues: true,\n emptyArrays: false,\n emptyObjects: false,\n emptyStrings: true,\n }) as T;\n}\n\n/**\n * Sort object and arrays recursively by alphabetizing keys.\n */\nexport function sortKeysRecursive(object) {\n if (typeof object !== 'object' || !object) return object;\n if (Array.isArray(object)) {\n const newArray: any[] = [];\n object.forEach((item, index) => {\n newArray[index] = sortKeysRecursive(item);\n });\n return newArray;\n }\n const sortedKeys = Object.keys(object).sort();\n const sortedObject = {};\n sortedKeys.forEach((key) => {\n sortedObject[key] = sortKeysRecursive(object[key]);\n });\n return sortedObject;\n}\n\n/**\n * Turn a nested object into a single-level object with dot notation keys and\n * values equal to the deepest **object** in the nested object.\n */\nexport function flatten(\n obj: Record<string, unknown>,\n): Record<string, Record<string, unknown>> {\n if (!isObject(obj)) {\n throw new Error('Expected an object to flatten');\n }\n const flattenedObj: Record<string, Record<string, unknown>> = {};\n\n function dive(thisObj: Record<string, unknown>, path: string[]) {\n Object.entries(thisObj).forEach(([key, value]) => {\n const thisPath = [...path, key];\n if (isObject(value)) {\n flattenedObj[thisPath.join('.')] = value;\n dive(value, thisPath);\n }\n });\n }\n\n dive(obj, []);\n\n return flattenedObj;\n}\n\n/**\n * This function takes a dictionary of objects and returns an array of objects with the `id` merged into the object.\n * Helpful when you have a dictionary of objects and you want to add the `id` to the object (from dictionary key) then want to use array methods.\n * Example:\n * ```ts\n * const dictionary = {\n * '123': { name: 'foo' },\n * '456': { name: 'bar' },\n * }\n *\n * dictionaryToArray(dictionary).forEach(({ id, name }) => {\n * // stuff\n * })\n * ```\n * @see {@link updateDictionaryWithId}\n * @see {@link arrayToDictionary}\n */\nexport function dictionaryToArray<T extends Record<string, any>>(\n dictionary: Record<string, T>,\n): (T & { id: string })[] {\n return Object.entries(dictionary).map(([id, value]) => ({\n id,\n ...value,\n }));\n}\n\n/**\n * This function takes a dictionary of objects and returns a dictionary of objects with the `id` merged into the object.\n * Helpful when you have a dictionary of objects and you want to add the `id` to the object (from dictionary key)\n * @see {@link dictionaryToArray}\n * @example\n * ```ts\n * const dictionary = {\n * '123': { name: 'foo' },\n * '456': { name: 'bar' },\n * }\n *\n * const dictionaryWithId = updateDictionaryWithId(dictionary)\n * // Which is now:\n * {\n * '123': { id: '123', name: 'foo' },\n * '456': { id: '456', name: 'bar' },\n * }\n * ```\n */\nexport function updateDictionaryWithId<T extends Record<string, any>>(\n dict: Record<string, T>,\n): Record<string, T & { id: string }> {\n return Object.entries(dict).reduce(\n (acc, [id, value]) => {\n acc[id] = {\n id,\n ...value,\n };\n return acc;\n },\n {} as Record<string, T & { id: string }>,\n );\n}\n","import {\n type Patch,\n applyPatches,\n enablePatches,\n produceWithPatches,\n produce,\n isDraft,\n type Draft,\n type Objectish,\n} from 'immer';\nimport { sortKeysRecursive } from './objects';\n\nexport { produce, produceWithPatches, applyPatches, isDraft };\nexport type { Patch, Draft };\n\nenablePatches();\n\n/**\n * Take an array of Immer patches and compress them down to the smallest amount of patches\n * @link https://medium.com/@dedels/using-immer-to-compress-immer-patches-f382835b6c69\n */\nexport function compressPatches<Data extends Objectish>({\n baseData,\n patches: allPatches,\n}: {\n baseData: Data;\n patches: Patch[][] | Patch[];\n}) {\n return produceWithPatches(baseData, (draft) => {\n applyPatches(draft, allPatches.flat());\n });\n}\n\n/** A patch that could not be applied, with the error Immer threw for it */\nexport interface PoisonPatch {\n readonly patch: Patch;\n readonly error: unknown;\n}\n\n/** A change whose patches did not all apply */\nexport interface FailedChange<Change> {\n readonly change: Change;\n /** The error from the first poison patch */\n readonly error: unknown;\n /** The change's patches that did apply, in order. Empty when none did. */\n readonly appliedPatches: Patch[];\n /** The change's patches that threw and were dropped */\n readonly poisonPatches: PoisonPatch[];\n /**\n * Applied after `appliedPatches`: they put back values a poison patch was\n * moving, where they were before the change (see `applyPatchesSafely`)\n */\n readonly restoredPatches: Patch[];\n}\n\n/** An applied patch, with the document just before and just after it */\ninterface AppliedStep<Data> {\n readonly patch: Patch;\n readonly before: Data;\n readonly after: Data;\n}\n\n/** Apply `patches` one at a time, skipping the ones that throw */\nfunction applyEachPatch<Data extends Objectish>({\n data,\n patches,\n}: {\n data: Data;\n patches: Patch[];\n}): {\n data: Data;\n steps: Array<AppliedStep<Data>>;\n poisonPatches: PoisonPatch[];\n} {\n const steps: Array<AppliedStep<Data>> = [];\n const poisonPatches: PoisonPatch[] = [];\n const result = patches.reduce((acc, patch) => {\n try {\n const next = applyPatches(acc, [patch]);\n steps.push({ patch, before: acc, after: next });\n return next;\n } catch (error) {\n poisonPatches.push({ patch, error });\n return acc;\n }\n }, data);\n return { data: result, steps, poisonPatches };\n}\n\ntype Path = ReadonlyArray<string | number>;\n\nconst pathKey = (path: Path): string => JSON.stringify(path.map(String));\n\n/** `prefix` is a proper ancestor of `path` */\nconst isAncestor = (prefix: Path, path: Path): boolean =>\n prefix.length < path.length &&\n prefix.every((segment, i) => String(segment) === String(path[i]));\n\n/**\n * The same for deep-equal JSON values, whatever their key order: saved\n * patches come back from a `jsonb` column, which does not keep it\n */\nconst valueKey = (value: unknown): string =>\n `${typeof value}:${JSON.stringify(sortKeysRecursive(value))}`;\n\nfunction getAt(data: unknown, path: Path): unknown {\n let value = data;\n for (const key of path) {\n if (!value || typeof value !== 'object') return undefined;\n value = (value as Record<string | number, unknown>)[key];\n }\n return value;\n}\n\n/** Call `visit` for `value` and every value nested in it, with its path */\nfunction forEachValue(\n value: unknown,\n visit: (v: unknown, path: Path) => void,\n path: Path = [],\n): void {\n visit(value, path);\n if (Array.isArray(value)) {\n value.forEach((item, i) => forEachValue(item, visit, [...path, i]));\n } else if (value && typeof value === 'object') {\n for (const [key, item] of Object.entries(value)) {\n forEachValue(item, visit, [...path, key]);\n }\n }\n}\n\nfunction countValues(\n data: unknown,\n root: Path,\n wanted: ReadonlySet<string>,\n): Map<string, number> {\n const counts = new Map<string, number>();\n forEachValue(getAt(data, root), (value) => {\n const key = valueKey(value);\n if (wanted.has(key)) counts.set(key, (counts.get(key) ?? 0) + 1);\n });\n return counts;\n}\n\nconst countIn = (items: unknown, key: string): number =>\n Array.isArray(items)\n ? items.filter((item) => valueKey(item) === key).length\n : 0;\n\n/**\n * What a move carries: an id (a string in an array) or an entity (an object\n * or array with something in it). A number, boolean, null, empty container\n * or string under an object key is far more often a setting that happens to\n * equal another than a moved value.\n */\nconst isMovable = (value: unknown, inArray: boolean): boolean =>\n typeof value === 'string'\n ? inArray\n : !!value && typeof value === 'object' && Object.keys(value).length > 0;\n\n/** Path segments that reach a prototype instead of a property */\nconst PROTOTYPE_KEYS: ReadonlySet<string> = new Set([\n '__proto__',\n 'constructor',\n 'prototype',\n]);\n\n/** A movable value a poison patch put down, on the stand-in document */\nclass PutDown {\n constructor(\n readonly key: string,\n readonly content: unknown,\n ) {}\n}\n\nconst contentOf = (node: unknown): unknown =>\n node instanceof PutDown ? node.content : node;\n\n/** How many of each movable value `node` holds that a poison patch put down */\nfunction tallyPutDown(\n node: unknown,\n counts = new Map<string, number>(),\n): Map<string, number> {\n if (node instanceof PutDown) {\n counts.set(node.key, (counts.get(node.key) ?? 0) + 1);\n }\n const content = contentOf(node);\n if (content && typeof content === 'object') {\n Object.values(content).forEach((item) => tallyPutDown(item, counts));\n }\n return counts;\n}\n\n/** `value` for the stand-in, with each movable value `take` accepts marked */\nfunction markPutDown(\n value: unknown,\n inArray: boolean,\n take: (key: string) => boolean,\n): unknown {\n const content = Array.isArray(value)\n ? value.map((item) => markPutDown(item, true, take))\n : value && typeof value === 'object'\n ? Object.fromEntries(\n Object.entries(value).map(([key, item]) => [\n key,\n markPutDown(item, false, take),\n ]),\n )\n : value;\n if (!isMovable(value, inArray)) return content;\n const key = valueKey(value);\n return take(key) ? new PutDown(key, content) : content;\n}\n\n/**\n * How many of each movable value the poison patches put down are still where\n * they put them at the end of the change, as its author saw it. The change's\n * patches are replayed on a stand-in for the part of the document the poison\n * patches needed and did not find. It holds only what they wrote, with an\n * unknown item wherever an index says the author's array had one, so a later\n * patch that removes, overwrites or shifts a value there does so exactly; an\n * applied patch writes an unknown value.\n *\n * The target side of a move is an `add`, or inside an array a `replace`; what\n * it carries counts with everything movable inside it (a new group holding\n * the moved ids). A `replace` of an object key is an edit: it counts for the\n * items of an array it carries (a list rebuilt with the moved id in it), and\n * otherwise only for values that were already put down there.\n *\n * A patch whose path goes through `__proto__`, `constructor` or `prototype`\n * is skipped: Immer refuses it, and following it here would write onto a\n * shared prototype.\n */\nfunction countPutDown(\n patches: ReadonlyArray<Patch>,\n poison: ReadonlySet<Patch>,\n): Map<string, number> {\n if (![...poison].some(({ op }) => op !== 'remove')) return new Map();\n const stand: Record<string, unknown> = {};\n const all = (): boolean => true;\n for (const patch of patches) {\n const failed = poison.has(patch);\n const { op, path, value } = patch;\n if (path.some((segment) => PROTOTYPE_KEYS.has(String(segment)))) continue;\n let parent: unknown = stand;\n for (const [i, segment] of path.slice(0, -1).entries()) {\n const holder = parent as Record<string | number, unknown>;\n let child = contentOf(holder[segment]);\n if (!child || typeof child !== 'object') {\n // Only a poison patch says the author had something here\n if (!failed) {\n parent = undefined;\n break;\n }\n child = typeof path[i + 1] === 'number' ? [] : {};\n holder[segment] = child;\n }\n parent = child;\n }\n if (!parent) continue;\n\n const holder = parent as Record<string | number, unknown>;\n const last = path[path.length - 1];\n const intoArray = Array.isArray(parent);\n let placed: unknown;\n if (failed && op !== 'remove') {\n if (op === 'add' || intoArray) {\n placed = markPutDown(value, intoArray, all);\n } else if (Array.isArray(value)) {\n placed = value.map((item) => markPutDown(item, true, all));\n } else {\n const already = tallyPutDown(holder[last]);\n placed = markPutDown(value, false, (key) => {\n const left = already.get(key) ?? 0;\n already.set(key, left - 1);\n return left > 0;\n });\n }\n }\n if (Array.isArray(parent)) {\n const at = Number(last);\n if (op === 'add') {\n if (parent.length < at) parent.length = at;\n parent.splice(at, 0, placed);\n } else if (op === 'replace') {\n parent[at] = placed;\n } else {\n parent.splice(at, 1);\n }\n } else if (op === 'remove') {\n delete holder[last];\n } else {\n holder[last] = placed;\n }\n }\n return tallyPutDown(stand);\n}\n\n/** Index of the `nth` (from 1) item of `items` equal to `key`, or -1 */\nfunction nthIndexOf(items: unknown, key: string, nth: number): number {\n if (!Array.isArray(items)) return -1;\n let seen = 0;\n return items.findIndex((item) => {\n if (valueKey(item) !== key) return false;\n seen += 1;\n return seen === nth;\n });\n}\n\n/**\n * Where an item that was at `index` in `from` goes back into `items`: just\n * after the nearest item before it in `from` that `items` still holds, else\n * first\n */\nfunction insertionIndex(\n items: ReadonlyArray<unknown>,\n from: ReadonlyArray<unknown>,\n index: number,\n): number {\n const keys = from.slice(0, index).map(valueKey);\n const seen = new Map<string, number>();\n const nths = keys.map((key) => {\n const nth = (seen.get(key) ?? 0) + 1;\n seen.set(key, nth);\n return nth;\n });\n for (let j = index - 1; j >= 0; j--) {\n const at = nthIndexOf(items, keys[j], nths[j]);\n if (at !== -1) return at + 1;\n }\n return 0;\n}\n\n/** An applied patch on one item of an array */\ninterface ItemOp {\n readonly array: string;\n readonly op: Patch['op'];\n readonly index: number;\n}\n\n/**\n * Whether `next` continues the patches Immer saves for one edit of one\n * array: `replace`s in rising index order, then `add`s in rising order or\n * `remove`s in falling order\n */\nfunction continuesArrayEdit(prev?: ItemOp, next?: ItemOp): boolean {\n if (!prev || !next || prev.array !== next.array) return false;\n if (next.op === 'replace') {\n return prev.op === 'replace' && next.index > prev.index;\n }\n if (prev.op === 'replace') return next.index > prev.index;\n const step = next.op === 'add' ? 1 : -1;\n return next.op === prev.op && next.index === prev.index + step;\n}\n\n/** A spot an applied patch took a moving value out of */\ninterface Removal {\n readonly key: string;\n readonly value: unknown;\n /** Where it was in `from` */\n readonly path: Path;\n readonly from: unknown;\n readonly step: number;\n /** The first step of the array edit its step belongs to */\n readonly run: number;\n /** Its order within the run */\n readonly order: number;\n}\n\n/**\n * Put back the values `poisonPatches` put down that an applied patch took\n * out and no later applied patch landed again, as many times as the poison\n * patches left them where they put them (`countPutDown`). A value goes back\n * where it was before the patch that took it out, even when an earlier action\n * in the same saved change put it there (`updateBranchContent` saves several\n * actions as one change): into an array that now holds it fewer times, or,\n * for an entity, at its key on an object that no longer has that key.\n *\n * An array item goes back just after the nearest item that was before it and\n * is still there. Its place is read before the edit that took it out: one\n * edit saved as several patches (a `splice`) passes through orders nobody\n * saw, so those patches are read as one (`continuesArrayEdit`). The most\n * recent edit goes first; within one, items go in their order. An id is only put back into an array,\n * since under an object key a string is a setting as often as a reference.\n * Only the subtree each applied patch changed is counted; the rest of the\n * document is unchanged.\n *\n * Not put back: a value the same change also edited, which no longer matches\n * what was removed; a value whose old container the change deleted; and a\n * value inside an array item when anything above that item was rewritten\n * from then on (the array's items added, removed or replaced, or the array\n * or an object holding it reassigned), since its old index may hold another\n * item.\n */\nfunction restoreMovedValues<Data extends Objectish>({\n salvaged,\n patches,\n steps,\n poisonPatches,\n}: {\n salvaged: Data;\n patches: ReadonlyArray<Patch>;\n steps: ReadonlyArray<AppliedStep<Data>>;\n poisonPatches: ReadonlyArray<PoisonPatch>;\n}): { data: Data; restoredPatches: Patch[] } {\n const putDown = countPutDown(\n patches,\n new Set(poisonPatches.map(({ patch }) => patch)),\n );\n if (putDown.size === 0) return { data: salvaged, restoredPatches: [] };\n const wanted = new Set(putDown.keys());\n\n // Each value's removals that no later applied patch landed again\n const unlanded = new Map<string, number>();\n const removals: Removal[] = [];\n // What each step rewrote: the array for an item op, else the patch's path\n const rewritten: Array<{ step: number; path: Path }> = [];\n let run = 0;\n let previous: ItemOp | undefined;\n steps.forEach(({ patch, before, after }, step) => {\n const parent = patch.path.slice(0, -1);\n const intoArray = Array.isArray(getAt(before, parent));\n const root = intoArray ? parent : patch.path;\n const item = intoArray\n ? {\n array: pathKey(parent),\n op: patch.op,\n index: Number(patch.path[patch.path.length - 1]),\n }\n : undefined;\n if (!continuesArrayEdit(previous, item)) run = step;\n previous = item;\n rewritten.push({ step, path: root });\n const was = countValues(before, root, wanted);\n const now = countValues(after, root, wanted);\n const removed = new Set<string>();\n for (const key of wanted) {\n const delta = (now.get(key) ?? 0) - (was.get(key) ?? 0);\n const open = unlanded.get(key) ?? 0;\n if (delta < 0) {\n unlanded.set(key, open - delta);\n removed.add(key);\n } else if (delta > 0) {\n unlanded.set(key, Math.max(0, open - delta));\n }\n }\n if (removed.size === 0) return;\n const start = steps[run].before;\n forEachValue(getAt(before, root), (value, relative) => {\n const key = valueKey(value);\n if (!removed.has(key)) return;\n const path = [...root, ...relative];\n const parentPath = path.slice(0, -1);\n const gone = Array.isArray(getAt(after, parentPath))\n ? countIn(getAt(after, parentPath), key) <\n countIn(getAt(before, parentPath), key)\n : valueKey(getAt(after, path)) !== key;\n if (!gone) return;\n const items = getAt(before, root);\n if (relative.length === 1 && Array.isArray(items)) {\n const index = Number(relative[0]);\n const nth = countIn(items.slice(0, index + 1), key);\n const atStart = nthIndexOf(getAt(start, root), key, nth);\n if (atStart !== -1) {\n const at = [...root, atStart];\n removals.push({\n key,\n value,\n path: at,\n from: start,\n step,\n run,\n order: atStart,\n });\n return;\n }\n }\n removals.push({\n key,\n value,\n path,\n from: before,\n step,\n run,\n order: -step,\n });\n });\n });\n\n const lost = new Map<string, number>();\n for (const [key, count] of putDown) {\n const missing = Math.min(count, unlanded.get(key) ?? 0);\n if (missing > 0) lost.set(key, missing);\n }\n if (lost.size === 0) return { data: salvaged, restoredPatches: [] };\n\n const [data, restoredPatches] = produceWithPatches(salvaged, (draft) => {\n const putBack = ({ key, value, path, from }: Removal): boolean => {\n const parentPath = path.slice(0, -1);\n const last = path[path.length - 1];\n const parent = getAt(draft, parentPath);\n if (Array.isArray(parent)) {\n const was = getAt(from, parentPath) as unknown[];\n if (countIn(parent, key) >= countIn(was, key)) return false;\n parent.splice(insertionIndex(parent, was, Number(last)), 0, value);\n return true;\n }\n if (\n typeof value === 'object' &&\n parent &&\n typeof parent === 'object' &&\n !(String(last) in parent)\n ) {\n (parent as Record<string | number, unknown>)[last] = value;\n return true;\n }\n return false;\n };\n const ordered = [...removals].sort(\n (a, b) => b.run - a.run || a.order - b.order,\n );\n for (const removal of ordered) {\n if (!lost.get(removal.key)) continue;\n // An array item on the way to its old spot may be another item now if\n // anything above it was rewritten from then on\n const parentPath = removal.path.slice(0, -1);\n const shifted = rewritten.some(\n ({ step, path }) =>\n step >= removal.step &&\n isAncestor(path, parentPath) &&\n parentPath.slice(path.length).some((key) => typeof key === 'number'),\n );\n if (shifted || !putBack(removal)) continue;\n // It came back with everything in it\n forEachValue(removal.value, (v) => {\n const left = lost.get(valueKey(v));\n if (left) lost.set(valueKey(v), left - 1);\n });\n }\n });\n return { data, restoredPatches };\n}\n\n/**\n * Apply `changes` one at a time instead of all at once.\n *\n * When a change fails to apply as a unit, its patches are retried one at a\n * time: each patch that applies is kept and only the ones that throw (the\n * \"poison\" patches) are dropped. One stale patch, e.g. a `replace` under a\n * block another branch deleted, does not take the change's unrelated edits\n * down with it. Immer only throws when a patch's parent path is missing, and\n * a dropped patch changed nothing, so patches that edit under the same\n * missing parent are dropped too.\n *\n * A dependent patch on another path is not caught that way. Moving a value\n * records an `add` at the target and a `remove` at the source; with the\n * target gone, applying only the `remove` would delete the value outright.\n * So a value a poison patch was moving that the change took out and did not\n * land anywhere else is put back where it was just before the patch that\n * took it out (`restoreMovedValues`), after the change's other patches, which\n * keep their effect.\n *\n * A poison patch also means the change was recorded against a different base\n * than `data`. Its surviving index-based array patches (`add`/`remove` at\n * `list/3`) are applied at those indexes, which may now hold different items.\n * A value put back shifts an array the same way for the changes after it,\n * which were recorded without it. That is the same risk every change\n * recorded against a stale base already carries; dropping the whole change\n * instead loses the user's work outright.\n *\n * Every change that lost patches is returned in `failedChanges` with what\n * applied, what threw, and what was put back, so callers can tell exactly\n * what landed.\n *\n * `data` must not be an Immer draft: `applyPatches` mutates a draft in place,\n * so a change that throws partway would leave its earlier patches applied and\n * the one-at-a-time retry would apply them again. Reduce plain data and wrap\n * the result in `produce` afterwards.\n */\nexport function applyPatchesSafely<\n Data extends Objectish,\n Change extends { patches: Patch[]; id?: unknown } = { patches: Patch[] },\n>({\n data,\n changes,\n logError = console.error,\n logAppClientData = false,\n}: {\n data: Data;\n changes: Change[];\n logError?: (msg: unknown, ...optionalMsgs: unknown[]) => void;\n logAppClientData?: boolean;\n}): { data: Data; failedChanges: Array<FailedChange<Change>> } {\n if (isDraft(data)) {\n throw new Error(\n 'applyPatchesSafely: `data` must not be an Immer draft; a change that fails partway would leave its earlier patches applied',\n );\n }\n const failedChanges: Array<FailedChange<Change>> = [];\n const result = changes.reduce((acc, change, i) => {\n try {\n return applyPatches(acc, change.patches);\n } catch {\n const salvage = applyEachPatch({ data: acc, patches: change.patches });\n const { steps, poisonPatches } = salvage;\n if (poisonPatches.length === 0) return salvage.data;\n const appliedPatches = steps.map(({ patch }) => patch);\n\n const { data: restored, restoredPatches } = restoreMovedValues({\n salvaged: salvage.data,\n patches: change.patches,\n steps,\n poisonPatches,\n });\n\n const { LOG_IMMER_APP_CLIENT_DATA } = process.env;\n const describe = (patch: Patch): { op: string; path: string } => ({\n op: patch.op,\n path: patch.path.join('/'),\n });\n logError(\n `applyPatchesSafely had issues with change ${i}: dropped ${poisonPatches.length} of ${change.patches.length} patches and applied the rest`,\n {\n metadata: {\n changeIndex: i,\n changeId: change.id,\n appliedPatchCount: appliedPatches.length,\n poisonPatches: poisonPatches.map(({ patch, error }) => ({\n ...describe(patch),\n error: error instanceof Error ? error.message : String(error),\n })),\n restoredPatches: restoredPatches.map(describe),\n // The document this change was applied to\n ...(logAppClientData || LOG_IMMER_APP_CLIENT_DATA\n ? { data: acc }\n : {}),\n },\n },\n );\n failedChanges.push({\n change,\n error: poisonPatches[0]?.error,\n appliedPatches,\n poisonPatches,\n restoredPatches,\n });\n return restored;\n }\n }, data);\n return { data: result, failedChanges };\n}\n"]}
package/dist/index.js CHANGED
@@ -1,3 +1,3 @@
1
- 'use strict';var uniqBy_js=require('lodash/uniqBy.js'),dateFns=require('date-fns'),W=require('lodash/camelCase.js'),J=require('just-kebab-case'),H=require('lodash/upperFirst.js'),tsExpect=require('ts-expect'),I=require('lodash/isEmpty.js'),snakeCase_js=require('lodash/snakeCase.js'),capitalize_js=require('lodash/capitalize.js'),debounce_js=require('lodash/debounce.js'),throttle_js=require('lodash/throttle.js'),memoizee=require('memoizee'),profile_js=require('memoizee/profile.js'),function_js=require('fp-ts/lib/function.js'),nanoid=require('nanoid'),uuid=require('uuid'),immer=require('immer'),j=require('clean-deep'),groupBy_js=require('lodash/groupBy.js'),deepmerge=require('deepmerge'),dt=require('slugify'),superstruct=require('superstruct');function _interopDefault(e){return e&&e.__esModule?e:{default:e}}var uniqBy_js__default=/*#__PURE__*/_interopDefault(uniqBy_js);var W__default=/*#__PURE__*/_interopDefault(W);var J__default=/*#__PURE__*/_interopDefault(J);var H__default=/*#__PURE__*/_interopDefault(H);var I__default=/*#__PURE__*/_interopDefault(I);var snakeCase_js__default=/*#__PURE__*/_interopDefault(snakeCase_js);var capitalize_js__default=/*#__PURE__*/_interopDefault(capitalize_js);var debounce_js__default=/*#__PURE__*/_interopDefault(debounce_js);var throttle_js__default=/*#__PURE__*/_interopDefault(throttle_js);var memoizee__default=/*#__PURE__*/_interopDefault(memoizee);var profile_js__default=/*#__PURE__*/_interopDefault(profile_js);var j__default=/*#__PURE__*/_interopDefault(j);var groupBy_js__default=/*#__PURE__*/_interopDefault(groupBy_js);var deepmerge__default=/*#__PURE__*/_interopDefault(deepmerge);var dt__default=/*#__PURE__*/_interopDefault(dt);var L=Object.defineProperty;var r=(t,e)=>L(t,"name",{value:e,configurable:true});function yt(t){let e={};return t.forEach(n=>{e[`${n}::${typeof n}`]=n;}),Object.keys(e).map(n=>e[n])}r(yt,"uniqueArray");function wt(t,e){return t.some(n=>e.includes(n))}r(wt,"hasItemsInItems");function Tt({items:t,key:e,errorMsgPrefix:n}){let s=[],o=[];if(t.forEach(i=>{let a=String(i[e]);s.includes(a)?o.push(i):s.push(a);}),o.length>0){let i=o.map(a=>`"${a[e]}"`).join(", ");throw new Error(`${n||`Each item in the array requires unique "${e}" prop.`} These ids are duplicates: ${i}`)}}r(Tt,"assertUniqueIdInArray");function bt(t){let e=new Set(t);return t.length===e.size}r(bt,"isArrayOfStringsUnique");function Et(t){let e=new Set;return t.filter(n=>e.has(n)?true:(e.add(n),false))}r(Et,"getNonUniqueStringsFromArray");function Rt(t,e){return t.reduce((n,s)=>{let{[e]:o}=s;if(n[o])throw new Error(`Duplicate key: ${o}`);return n[o]=s,n},{})}r(Rt,"arrayToDictionary");var S=class{static{r(this,"Queue");}items;constructor(e){this.items=e||[];}add(e){this.items.push(e);}next(){return this.items.shift()}peekAtNext(){return this.items[0]}clear(){this.items=[];}get length(){return this.items.length}isEmpty(){return this.items.length===0}};var O=class{static{r(this,"Stack");}items;constructor(e){this.items=e||[];}add(e){this.items.unshift(e);}next(){return this.items.shift()}peekAtNext(){return this.items[0]}clear(){this.items=[];}get length(){return this.items.length}isEmpty(){return this.items.length===0}};var Ut=r(()=>new Date().toISOString(),"now");function jt({date:t,relative:e,includeTime:n,prefix:s}){if(!dateFns.isValid(t))return console.error("formatDate: Invalid date provided:",t),null;let o,i;if(e)i=Math.abs(dateFns.differenceInSeconds(new Date,t))<60?"just now":dateFns.formatDistanceToNowStrict(t,{addSuffix:true});else {let a=t.getFullYear()===new Date().getFullYear();n?o=a?"MMM dd 'at' hh:mm aaa":"MMM dd, yyyy 'at' hh:mm aaa":o=a?"MMM dd":"MMM dd, yyyy",i=dateFns.format(t,o);}return s?`${s} ${i}`:i}r(jt,"formatDate");var Mt=r(()=>new Date().toISOString(),"nowInIsoDate"),vt=r(()=>dateFns.subDays(new Date,1).toISOString(),"yesterdayInIsoDate");function Nt(t,e){return dateFns.compareAsc(dateFns.parseISO(t.date),dateFns.parseISO(e.date))}r(Nt,"sortDateAsc");function Lt(t,e){return dateFns.compareDesc(dateFns.parseISO(t.date),dateFns.parseISO(e.date))}r(Lt,"sortDateDesc");var _t=r(t=>new Date(Date.now()+t*60*1e3).toISOString(),"minutesFromNowInIsoDate");function Ft({hours:t=0,minutes:e=0,seconds:n=0}){return t*36e5+e*6e4+n*1e3}r(Ft,"toMilliseconds");var Vt=typeof window<"u"&&typeof window.document<"u",qt=typeof self=="object"&&self.constructor&&self.constructor.name==="DedicatedWorkerGlobalScope",y=typeof process<"u"&&process.versions!=null&&process.versions.node!=null,zt=r(()=>typeof window<"u"&&window.name==="nodejs"||navigator.userAgent.includes("Node.js")||navigator.userAgent.includes("jsdom"),"isJsDom");function Ht(t){return Object.keys(t)}r(Ht,"keys");function Gt(t){return Object.entries(t)}r(Gt,"entries");function Xt(t,e){return t in e}r(Xt,"isObjKey");function Zt(t){return t!=null}r(Zt,"isDefined");var G=r(t=>t.split(".").map(J__default.default).join("-"),"cssKebabCase"),ce=r(t=>`--${G(t)}`,"cssVarName");function D(t){return t.replace(/[*+?^${}()|[\]\\]/g,"\\$&")}r(D,"escapeRegEx");function pe(t,e){let n=D(e).toLowerCase();return D(t).toLowerCase().search(n)!==-1}r(pe,"containsString");function X(t){return H__default.default(t)}r(X,"capitalizeFirstLetter");function fe(t){return !t||t.length===0?false:t[0]===t[0].toUpperCase()}r(fe,"isFirstLetterCapital");function Z(t){return X(W__default.default(t))}r(Z,"upperCamelCase");var le=Z;function Q(t){return y?Buffer.from(t,"base64").toString():atob(t)}r(Q,"base64ToString");function de(t){return y?Buffer.from(t).toString("base64"):btoa(t)}r(de,"stringToBase64");function me(t){if(typeof t!="string")return false;let e=t.replace(/\s+/g,"").replace(/={0,2}$/,"");return !/[^\s0-9a-zA-Z+/]/.test(e)||!/[^\s0-9a-zA-Z\-_]/.test(e)}r(me,"isBase64");function ge(t){return t.indexOf(" ")!==-1}r(ge,"stringHasSpaces");function xe(t){if(!t.startsWith("@")&&!t.includes("/"))return t;let[,e]=t.split("/");return e||t}r(xe,"removeNpmScope");function A(t){if(typeof t!="string")return false;try{new URL(t);return true}catch{return false}}r(A,"isUrl");var Y=/^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/,tt=r(t=>typeof t=="string"&&t.length<=320&&Y.test(t),"isEmail"),he=r(t=>tt(t)?t.substring(t.indexOf("@")+1):null,"getDomainFromEmail"),ye=r(t=>{let[e,n]=Q(t).split(":");return {username:e,password:n}},"decodeBasicAuth");function we(t){let e=String(t).trim(),n=/([a-zA-Z%])+$/,s=e.match(n),o,i;if(s){let a=s.index;o=parseFloat(e.slice(0,a)),[i]=s;}else o=parseFloat(e),i="";if(Number.isNaN(o))throw new Error(`Invalid value, not a number: ${t}`);return {value:o,unit:i}}r(we,"parseNumberWithUnit");function Te(t){return /^[a-zA-Z]/.test(t)}r(Te,"startsWithLetter");function be(t){return !t||typeof t!="string"?t:t.replace(/^"(.*)"$/,"$1").replace(/^'(.*)'$/,"$1")}r(be,"removeWrappingQuotes");var Ee=r(t=>{if(!t||I__default.default(t))return;if(!t.includes("="))return t;let e=t.split(","),n=[];return e.forEach(s=>{let[o,i]=s.split("=");if(!(!i||["false","off","no"].includes(i)))return ["true","on","yes"].includes(i)?n.push(o):n.push(i)}),n.join(", ")},"getShortName");var et=new Set(["authorization","proxy-authorization","cookie","set-cookie","x-api-key","www-authenticate"]),w=1e4,g=class extends Error{static{r(this,"FetcherError");}status;statusText;url;responseBody;responseHeaders;constructor(e,{status:n,statusText:s,url:o,cause:i,responseBody:a,responseHeaders:c}){super(e,{cause:i}),this.status=n,this.statusText=s,this.url=o,this.responseBody=a,this.responseHeaders=c;}};async function Ae({url:t,query:e,body:n,headers:s={},signal:o}){try{if(typeof t=="string"&&!A(t))throw new Error(`Cannot fetch from an invalid url: "${t}"`);if(typeof t!="string"&&!(t instanceof URL))throw new Error(`Url must be a string or URL instance: "${t}"`);let i=n?"POST":"GET",a="";try{let p=t instanceof URL?t:new URL(t);e&&Object.entries(e).forEach(([l,d])=>{typeof d>"u"||d!==null&&p.searchParams.set(l,`${d}`);}),a=p.toString();}catch(p){throw new Error(`Could not start fetcher because was not able to add query params to URL successfully. Url: ${t}, Query params: ${JSON.stringify(e??{})}. ${p instanceof Error?p.message:""}`)}let c={Accept:"application/json"};n&&(c["Content-Type"]="application/json");let u=await fetch(a,{method:i,headers:{...c,...s},body:n?JSON.stringify(n):void 0,signal:o}),m=u.headers.get("Content-Type")?.includes("json");if(!u.ok){let p={};u.headers.forEach((N,k)=>{p[k]=et.has(k.toLowerCase())?"[redacted]":N;});let l=await u.text(),d={};if(m)try{d=JSON.parse(l);}catch{}let M=d?.error?.message??d?.message??`${u.statusText} ${u.status}`,v=l.length>w?`${l.slice(0,w)}\u2026 [truncated ${l.length-w} chars]`:l;throw new g(M,{status:u.status,statusText:u.statusText,url:a,responseHeaders:p,responseBody:v})}if(!m){let p=await u.text();throw new g(`Expected JSON response but received text instead: ${p}`,{status:u.status,statusText:u.statusText,url:a})}return await u.json()}catch(i){throw i instanceof g?i:new g(i.message,{url:t.toString(),cause:i})}}r(Ae,"fetcher");var Ue=r(t=>new Promise(e=>setTimeout(e,t)),"delay");function je(t){if(typeof t=="function")try{let e=t();return e instanceof Promise?e.then(n=>({data:n,error:null}),n=>({data:null,error:n})):{data:e,error:null}}catch(e){return {data:null,error:e}}return t.then(e=>({data:e,error:null}),e=>({data:null,error:e}))}r(je,"tryCatch");var Ge=r(()=>uuid.v4(),"makeUuid"),Xe=r(()=>uuid.v7(),"makeUuidV7"),ot="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",it=nanoid.customAlphabet(ot,10),Ze=r(()=>it(),"makeShortId");immer.enablePatches();function nr({baseData:t,patches:e}){return immer.produceWithPatches(t,n=>{immer.applyPatches(n,e.flat());})}r(nr,"compressPatches");function sr({data:t,changes:e,logError:n=console.error,logAppClientData:s=false}){let o=[];return {data:e.reduce((a,c,u)=>{try{return immer.applyPatches(a,c.patches)}catch(m){let{LOG_IMMER_APP_CLIENT_DATA:P}=process.env,p=s||P?{data:t,change:c}:c;return n(`applyPatchesSafely had issues (and so will skip) with patches in change ${u}: ${m instanceof Error?m.message:""}`,p),o.push({change:c,error:m}),a}},t),failedChanges:o}}r(sr,"applyPatchesSafely");var f=r(t=>t!==null&&typeof t=="object"&&!Array.isArray(t),"isObject");function ar(t){return f(t)&&Object.keys(t).length===0}r(ar,"isObjectEmpty");var ct=Object.prototype.toString,h=r(t=>ct.call(t),"toTypeString"),T=Array.isArray,ur=r(t=>h(t)==="[object Map]","isMap"),cr=r(t=>h(t)==="[object Set]","isSet"),b=r(t=>t instanceof Date,"isDate"),C=r(t=>typeof t=="function","isFunction"),pt=r(t=>typeof t=="string","isString"),pr=r(t=>typeof t=="number","isNumber"),fr=r(t=>typeof t=="symbol","isSymbol"),lr=r(t=>f(t)&&C(t.then)&&C(t.catch),"isPromise"),dr=r(t=>h(t).slice(8,-1),"toRawType"),mr=r(t=>h(t)==="[object Object]","isPlainObject"),gr=r(t=>pt(t)&&t!=="NaN"&&t[0]!=="-"&&`${parseInt(t,10)}`===t,"isIntegerKey");function ft(t,e){if(t.length!==e.length)return false;let n=true;for(let s=0;n&&s<t.length;s++)n=E(t[s],e[s]);return n}r(ft,"looseCompareArrays");function E(t,e){if(t===e)return true;if(b(t)&&b(e))return t.getTime()===e.getTime();if(T(t)&&T(e))return ft(t,e);if(f(t)&&f(e)){let n=Object.keys(t).length,s=Object.keys(e).length;if(n!==s)return false;for(let o in t){let i=t.hasOwnProperty(o),a=e.hasOwnProperty(o);if(i&&!a||!i&&a||!E(t[o],e[o]))return false}}return String(t)===String(e)}r(E,"looseEqual");function wr(t,e){return t.findIndex(n=>E(n,e))}r(wr,"looseIndexOf");function Er(t){return Math.floor(Math.random()*Math.floor(t))}r(Er,"getRandomInt");var lt=r(()=>{let t=new Date().getTime();return ()=>new Date().getTime()-t},"timer"),Rr=r(()=>{let t=lt();return ()=>t()/1e3},"timerInSeconds");function Ir(t){return Object.keys(t).sort().reduce((e,n)=>(e[n]=t[n],e),{})}r(Ir,"sortObject");var Dr=r(t=>j__default.default(t),"removeEmptyObjects");function Ar(t){return j__default.default(t,{undefinedValues:true,nullValues:true,emptyArrays:false,emptyObjects:false,emptyStrings:true})}r(Ar,"removeUndefinedProps");function U(t){if(typeof t!="object"||!t)return t;if(Array.isArray(t)){let s=[];return t.forEach((o,i)=>{s[i]=U(o);}),s}let e=Object.keys(t).sort(),n={};return e.forEach(s=>{n[s]=U(t[s]);}),n}r(U,"sortKeysRecursive");function $r(t){if(!f(t))throw new Error("Expected an object to flatten");let e={};function n(s,o){Object.entries(s).forEach(([i,a])=>{let c=[...o,i];f(a)&&(e[c.join(".")]=a,n(a,c));});}return r(n,"dive"),n(t,[]),e}r($r,"flatten");function Cr(t){return Object.entries(t).map(([e,n])=>({id:e,...n}))}r(Cr,"dictionaryToArray");function Ur(t){return Object.entries(t).reduce((e,[n,s])=>(e[n]={id:n,...s},e),{})}r(Ur,"updateDictionaryWithId");var Fr=r(t=>{try{if(!t)return "";let e=t.split(/[/\\]/),s=e[e.length-1].split(".");return s.length===1?s[0]:s.slice(0,-1).join(".")}catch{return t}},"getFileNameFromPath");function mt({params:t,urlSearchParams:e}){return Object.entries(t??{}).forEach(([n,s])=>{if(s!=null)if(s instanceof URL)e.set(n,s.toString());else if(Array.isArray(s))e.set(n,s.join(" "));else {let o=`${s}`;if(o==="")return;e.set(n,o);}}),e}r(mt,"addQueryParams");function qr({url:t,origin:e,queryParams:n}){if(!e&&typeof t=="string"&&!t.startsWith("http"))throw new Error('When using "createUrl" either pass in a full "url" or provide an "origin"');let s=typeof t=="string"?new URL(t,e):e?new URL(t.toString(),e):t;return mt({params:n,urlSearchParams:s.searchParams}),s}r(qr,"createUrlWithParams");function zr({a:t,b:e}){return new URL(t).toString()===new URL(e).toString()}r(zr,"areUrlsSame");function gt(t){if(typeof t!="string")return false;try{let e=new URL(t);return e.protocol.startsWith("http:")||e.protocol.startsWith("https:")}catch{return t.startsWith("//")}}r(gt,"isRemoteUrl");var Wr=r(t=>t.startsWith("data:"),"isDataUrl"),R=r(t=>{let{string:e,strict:n=true,lowerCase:s=true}=typeof t=="string"?{string:t}:t;return dt__default.default(e,{lower:s,trim:true,strict:n})},"slugify"),Jr=r(t=>{let e=/^\/([^/]+)\/([^/]+)/,n=t.match(e);if(!n)return null;let[s,o,i]=n;return [o,i]},"extractPathParts");function Hr({fileId:t,nodeId:e,version:n}){if(!t||t.trim().length===0)throw new Error(`Invalid Figma URL, missing file id: ${t}`);let s=new URL(`https://www.figma.com/file/${t}`);return e&&s.searchParams.set("node-id",e),n&&s.searchParams.set("version-id",n.toString()),s.toString()}r(Hr,"createFigmaUrl");function Gr(t){let e=new URL(t);if(e.hostname!=="www.figma.com"&&e.hostname!=="figma.com"||!gt(t))throw new Error(`Please provide a valid Figma URL, got ${t}`);let n=e.searchParams.get("node-id")||void 0,s=e.searchParams.get("version-id")||void 0,[,o,i]=e.pathname.split("/");switch(o){case "proto":case "file":case "board":case "design":{if(!i)throw new Error(`Invalid Figma URL, missing file id: ${t}`);return {type:o,fileId:i,nodeId:n,version:s}}default:throw new Error(`Please provide a valid Figma URL, got ${t}`)}}r(Gr,"parseFigmaUrl");function Xr(t){return new URLSearchParams(Object.fromEntries(Object.entries(t).filter(([,e])=>typeof e=="string"?e.length>0:e!=null).map(([e,n])=>[e,`${n}`]))).toString()}r(Xr,"createQueryParams");function Zr({filename:t}){let e=R([...t.split(".")].pop()||""),n=R(e?t.substring(0,t.lastIndexOf(".")):t);if(!n)throw new Error(`Invalid filename: ${t}`);return e?`${n}.${e}`:n}r(Zr,"createSafeFilename");function en(t){if(t instanceof superstruct.StructError){let[e]=t.failures();if(!e)return "";let{path:n,message:s}=e;return n.length===0?s:`At path: ${n.join(".")} -- ${s}`}return t instanceof Error?t.message:""}r(en,"getSuperstructErrorMsg");
2
- Object.defineProperty(exports,"uniqBy",{enumerable:true,get:function(){return uniqBy_js__default.default}});Object.defineProperty(exports,"camelCase",{enumerable:true,get:function(){return W__default.default}});Object.defineProperty(exports,"kebabCase",{enumerable:true,get:function(){return J__default.default}});Object.defineProperty(exports,"paramCase",{enumerable:true,get:function(){return J__default.default}});Object.defineProperty(exports,"expectNever",{enumerable:true,get:function(){return tsExpect.expectNever}});Object.defineProperty(exports,"expectType",{enumerable:true,get:function(){return tsExpect.expectType}});Object.defineProperty(exports,"isEmpty",{enumerable:true,get:function(){return I__default.default}});Object.defineProperty(exports,"snakeCase",{enumerable:true,get:function(){return snakeCase_js__default.default}});Object.defineProperty(exports,"capitalize",{enumerable:true,get:function(){return capitalize_js__default.default}});Object.defineProperty(exports,"debounce",{enumerable:true,get:function(){return debounce_js__default.default}});Object.defineProperty(exports,"throttle",{enumerable:true,get:function(){return throttle_js__default.default}});Object.defineProperty(exports,"memoize",{enumerable:true,get:function(){return memoizee__default.default}});Object.defineProperty(exports,"memoizeeProfile",{enumerable:true,get:function(){return profile_js__default.default}});Object.defineProperty(exports,"flow",{enumerable:true,get:function(){return function_js.flow}});Object.defineProperty(exports,"applyPatches",{enumerable:true,get:function(){return immer.applyPatches}});Object.defineProperty(exports,"isDraft",{enumerable:true,get:function(){return immer.isDraft}});Object.defineProperty(exports,"produce",{enumerable:true,get:function(){return immer.produce}});Object.defineProperty(exports,"produceWithPatches",{enumerable:true,get:function(){return immer.produceWithPatches}});Object.defineProperty(exports,"groupBy",{enumerable:true,get:function(){return groupBy_js__default.default}});Object.defineProperty(exports,"deepMerge",{enumerable:true,get:function(){return deepmerge__default.default}});exports.FetcherError=g;exports.Queue=S;exports.Stack=O;exports.addQueryParams=mt;exports.applyPatchesSafely=sr;exports.areUrlsSame=zr;exports.arrayToDictionary=Rt;exports.assertUniqueIdInArray=Tt;exports.base64ToString=Q;exports.capitalizeFirstLetter=X;exports.compressPatches=nr;exports.containsString=pe;exports.createFigmaUrl=Hr;exports.createQueryParams=Xr;exports.createSafeFilename=Zr;exports.createUrlWithParams=qr;exports.cssKebabCase=G;exports.cssVarName=ce;exports.decodeBasicAuth=ye;exports.delay=Ue;exports.dictionaryToArray=Cr;exports.entries=Gt;exports.escapeRegEx=D;exports.extractPathParts=Jr;exports.fetcher=Ae;exports.flatten=$r;exports.formatDate=jt;exports.getDomainFromEmail=he;exports.getFileNameFromPath=Fr;exports.getNonUniqueStringsFromArray=Et;exports.getRandomInt=Er;exports.getShortName=Ee;exports.getSuperstructErrorMsg=en;exports.hasItemsInItems=wt;exports.isArray=T;exports.isArrayOfStringsUnique=bt;exports.isBase64=me;exports.isBrowser=Vt;exports.isDataUrl=Wr;exports.isDate=b;exports.isDefined=Zt;exports.isEmail=tt;exports.isFirstLetterCapital=fe;exports.isFunction=C;exports.isIntegerKey=gr;exports.isJsDom=zt;exports.isMap=ur;exports.isNode=y;exports.isNumber=pr;exports.isObjKey=Xt;exports.isObject=f;exports.isObjectEmpty=ar;exports.isPlainObject=mr;exports.isPromise=lr;exports.isRemoteUrl=gt;exports.isSet=cr;exports.isString=pt;exports.isSymbol=fr;exports.isUrl=A;exports.isWebWorker=qt;exports.keys=Ht;exports.looseEqual=E;exports.looseIndexOf=wr;exports.makeShortId=Ze;exports.makeUuid=Ge;exports.makeUuidV7=Xe;exports.minutesFromNowInIsoDate=_t;exports.now=Ut;exports.nowInIsoDate=Mt;exports.objectToString=ct;exports.parseFigmaUrl=Gr;exports.parseNumberWithUnit=we;exports.pascalCase=le;exports.removeEmptyObjects=Dr;exports.removeNpmScope=xe;exports.removeUndefinedProps=Ar;exports.removeWrappingQuotes=be;exports.slugify=R;exports.sortDateAsc=Nt;exports.sortDateDesc=Lt;exports.sortKeysRecursive=U;exports.sortObject=Ir;exports.startsWithLetter=Te;exports.stringHasSpaces=ge;exports.stringToBase64=de;exports.timer=lt;exports.timerInSeconds=Rr;exports.toMilliseconds=Ft;exports.toRawType=dr;exports.toTypeString=h;exports.tryCatch=je;exports.uniqueArray=yt;exports.updateDictionaryWithId=Ur;exports.upperCamelCase=Z;exports.yesterdayInIsoDate=vt;//# sourceMappingURL=index.js.map
1
+ 'use strict';var uniqBy_js=require('lodash/uniqBy.js'),dateFns=require('date-fns'),Pt=require('lodash/camelCase.js'),Tt=require('just-kebab-case'),kt=require('lodash/upperFirst.js'),tsExpect=require('ts-expect'),et=require('lodash/isEmpty.js'),snakeCase_js=require('lodash/snakeCase.js'),capitalize_js=require('lodash/capitalize.js'),debounce_js=require('lodash/debounce.js'),throttle_js=require('lodash/throttle.js'),memoizee=require('memoizee'),profile_js=require('memoizee/profile.js'),function_js=require('fp-ts/lib/function.js'),nanoid=require('nanoid'),uuid=require('uuid'),immer=require('immer'),st=require('clean-deep'),groupBy_js=require('lodash/groupBy.js'),deepmerge=require('deepmerge'),Zt=require('slugify'),superstruct=require('superstruct');function _interopDefault(e){return e&&e.__esModule?e:{default:e}}var uniqBy_js__default=/*#__PURE__*/_interopDefault(uniqBy_js);var Pt__default=/*#__PURE__*/_interopDefault(Pt);var Tt__default=/*#__PURE__*/_interopDefault(Tt);var kt__default=/*#__PURE__*/_interopDefault(kt);var et__default=/*#__PURE__*/_interopDefault(et);var snakeCase_js__default=/*#__PURE__*/_interopDefault(snakeCase_js);var capitalize_js__default=/*#__PURE__*/_interopDefault(capitalize_js);var debounce_js__default=/*#__PURE__*/_interopDefault(debounce_js);var throttle_js__default=/*#__PURE__*/_interopDefault(throttle_js);var memoizee__default=/*#__PURE__*/_interopDefault(memoizee);var profile_js__default=/*#__PURE__*/_interopDefault(profile_js);var st__default=/*#__PURE__*/_interopDefault(st);var groupBy_js__default=/*#__PURE__*/_interopDefault(groupBy_js);var deepmerge__default=/*#__PURE__*/_interopDefault(deepmerge);var Zt__default=/*#__PURE__*/_interopDefault(Zt);var dt=Object.defineProperty;var r=(t,e)=>dt(t,"name",{value:e,configurable:true});function re(t){let e={};return t.forEach(n=>{e[`${n}::${typeof n}`]=n;}),Object.keys(e).map(n=>e[n])}r(re,"uniqueArray");function oe(t,e){return t.some(n=>e.includes(n))}r(oe,"hasItemsInItems");function se({items:t,key:e,errorMsgPrefix:n}){let o=[],s=[];if(t.forEach(a=>{let i=String(a[e]);o.includes(i)?s.push(a):o.push(i);}),s.length>0){let a=s.map(i=>`"${i[e]}"`).join(", ");throw new Error(`${n||`Each item in the array requires unique "${e}" prop.`} These ids are duplicates: ${a}`)}}r(se,"assertUniqueIdInArray");function ae(t){let e=new Set(t);return t.length===e.size}r(ae,"isArrayOfStringsUnique");function ie(t){let e=new Set;return t.filter(n=>e.has(n)?true:(e.add(n),false))}r(ie,"getNonUniqueStringsFromArray");function ce(t,e){return t.reduce((n,o)=>{let{[e]:s}=o;if(n[s])throw new Error(`Duplicate key: ${s}`);return n[s]=o,n},{})}r(ce,"arrayToDictionary");var Y=class{static{r(this,"Queue");}items;constructor(e){this.items=e||[];}add(e){this.items.push(e);}next(){return this.items.shift()}peekAtNext(){return this.items[0]}clear(){this.items=[];}get length(){return this.items.length}isEmpty(){return this.items.length===0}};var tt=class{static{r(this,"Stack");}items;constructor(e){this.items=e||[];}add(e){this.items.unshift(e);}next(){return this.items.shift()}peekAtNext(){return this.items[0]}clear(){this.items=[];}get length(){return this.items.length}isEmpty(){return this.items.length===0}};var xe=r(()=>new Date().toISOString(),"now");function we({date:t,relative:e,includeTime:n,prefix:o}){if(!dateFns.isValid(t))return console.error("formatDate: Invalid date provided:",t),null;let s,a;if(e)a=Math.abs(dateFns.differenceInSeconds(new Date,t))<60?"just now":dateFns.formatDistanceToNowStrict(t,{addSuffix:true});else {let i=t.getFullYear()===new Date().getFullYear();n?s=i?"MMM dd 'at' hh:mm aaa":"MMM dd, yyyy 'at' hh:mm aaa":s=i?"MMM dd":"MMM dd, yyyy",a=dateFns.format(t,s);}return o?`${o} ${a}`:a}r(we,"formatDate");var be=r(()=>new Date().toISOString(),"nowInIsoDate"),Pe=r(()=>dateFns.subDays(new Date,1).toISOString(),"yesterdayInIsoDate");function Te(t,e){return dateFns.compareAsc(dateFns.parseISO(t.date),dateFns.parseISO(e.date))}r(Te,"sortDateAsc");function ke(t,e){return dateFns.compareDesc(dateFns.parseISO(t.date),dateFns.parseISO(e.date))}r(ke,"sortDateDesc");var Re=r(t=>new Date(Date.now()+t*60*1e3).toISOString(),"minutesFromNowInIsoDate");function Se({hours:t=0,minutes:e=0,seconds:n=0}){return t*36e5+e*6e4+n*1e3}r(Se,"toMilliseconds");var Oe=typeof window<"u"&&typeof window.document<"u",Ie=typeof self=="object"&&self.constructor&&self.constructor.name==="DedicatedWorkerGlobalScope",V=typeof process<"u"&&process.versions!=null&&process.versions.node!=null,De=r(()=>typeof window<"u"&&window.name==="nodejs"||navigator.userAgent.includes("Node.js")||navigator.userAgent.includes("jsdom"),"isJsDom");function $e(t){return Object.keys(t)}r($e,"keys");function Me(t){return Object.entries(t)}r(Me,"entries");function Ue(t,e){return t in e}r(Ue,"isObjKey");function Ne(t){return t!=null}r(Ne,"isDefined");var Rt=r(t=>t.split(".").map(Tt__default.default).join("-"),"cssKebabCase"),He=r(t=>`--${Rt(t)}`,"cssVarName");function nt(t){return t.replace(/[*+?^${}()|[\]\\]/g,"\\$&")}r(nt,"escapeRegEx");function Ge(t,e){let n=nt(e).toLowerCase();return nt(t).toLowerCase().search(n)!==-1}r(Ge,"containsString");function St(t){return kt__default.default(t)}r(St,"capitalizeFirstLetter");function Xe(t){return !t||t.length===0?false:t[0]===t[0].toUpperCase()}r(Xe,"isFirstLetterCapital");function Et(t){return St(Pt__default.default(t))}r(Et,"upperCamelCase");var Ze=Et;function At(t){return V?Buffer.from(t,"base64").toString():atob(t)}r(At,"base64ToString");function Qe(t){return V?Buffer.from(t).toString("base64"):btoa(t)}r(Qe,"stringToBase64");function Ye(t){if(typeof t!="string")return false;let e=t.replace(/\s+/g,"").replace(/={0,2}$/,"");return !/[^\s0-9a-zA-Z+/]/.test(e)||!/[^\s0-9a-zA-Z\-_]/.test(e)}r(Ye,"isBase64");function tn(t){return t.indexOf(" ")!==-1}r(tn,"stringHasSpaces");function en(t){if(!t.startsWith("@")&&!t.includes("/"))return t;let[,e]=t.split("/");return e||t}r(en,"removeNpmScope");function rt(t){if(typeof t!="string")return false;try{new URL(t);return true}catch{return false}}r(rt,"isUrl");var Ot=/^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/,It=r(t=>typeof t=="string"&&t.length<=320&&Ot.test(t),"isEmail"),nn=r(t=>It(t)?t.substring(t.indexOf("@")+1):null,"getDomainFromEmail"),rn=r(t=>{let[e,n]=At(t).split(":");return {username:e,password:n}},"decodeBasicAuth");function on(t){let e=String(t).trim(),n=/([a-zA-Z%])+$/,o=e.match(n),s,a;if(o){let i=o.index;s=parseFloat(e.slice(0,i)),[a]=o;}else s=parseFloat(e),a="";if(Number.isNaN(s))throw new Error(`Invalid value, not a number: ${t}`);return {value:s,unit:a}}r(on,"parseNumberWithUnit");function sn(t){return /^[a-zA-Z]/.test(t)}r(sn,"startsWithLetter");function an(t){return !t||typeof t!="string"?t:t.replace(/^"(.*)"$/,"$1").replace(/^'(.*)'$/,"$1")}r(an,"removeWrappingQuotes");var cn=r(t=>{if(!t||et__default.default(t))return;if(!t.includes("="))return t;let e=t.split(","),n=[];return e.forEach(o=>{let[s,a]=o.split("=");if(!(!a||["false","off","no"].includes(a)))return ["true","on","yes"].includes(a)?n.push(s):n.push(a)}),n.join(", ")},"getShortName");var Dt=new Set(["authorization","proxy-authorization","cookie","set-cookie","x-api-key","www-authenticate"]),z=1e4,C=class extends Error{static{r(this,"FetcherError");}status;statusText;url;responseBody;responseHeaders;constructor(e,{status:n,statusText:o,url:s,cause:a,responseBody:i,responseHeaders:c}){super(e,{cause:a}),this.status=n,this.statusText=o,this.url=s,this.responseBody=i,this.responseHeaders=c;}};async function hn({url:t,query:e,body:n,headers:o={},signal:s}){try{if(typeof t=="string"&&!rt(t))throw new Error(`Cannot fetch from an invalid url: "${t}"`);if(typeof t!="string"&&!(t instanceof URL))throw new Error(`Url must be a string or URL instance: "${t}"`);let a=n?"POST":"GET",i="";try{let f=t instanceof URL?t:new URL(t);e&&Object.entries(e).forEach(([x,h])=>{typeof h>"u"||h!==null&&f.searchParams.set(x,`${h}`);}),i=f.toString();}catch(f){throw new Error(`Could not start fetcher because was not able to add query params to URL successfully. Url: ${t}, Query params: ${JSON.stringify(e??{})}. ${f instanceof Error?f.message:""}`)}let c={Accept:"application/json"};n&&(c["Content-Type"]="application/json");let d=await fetch(i,{method:a,headers:{...c,...o},body:n?JSON.stringify(n):void 0,signal:s}),l=d.headers.get("Content-Type")?.includes("json");if(!d.ok){let f={};d.headers.forEach((g,u)=>{f[u]=Dt.has(u.toLowerCase())?"[redacted]":g;});let x=await d.text(),h={};if(l)try{h=JSON.parse(x);}catch{}let p=h?.error?.message??h?.message??`${d.statusText} ${d.status}`,m=x.length>z?`${x.slice(0,z)}\u2026 [truncated ${x.length-z} chars]`:x;throw new C(p,{status:d.status,statusText:d.statusText,url:i,responseHeaders:f,responseBody:m})}if(!l){let f=await d.text();throw new C(`Expected JSON response but received text instead: ${f}`,{status:d.status,statusText:d.statusText,url:i})}return await d.json()}catch(a){throw a instanceof C?a:new C(a.message,{url:t.toString(),cause:a})}}r(hn,"fetcher");var wn=r(t=>new Promise(e=>setTimeout(e,t)),"delay");function bn(t){if(typeof t=="function")try{let e=t();return e instanceof Promise?e.then(n=>({data:n,error:null}),n=>({data:null,error:n})):{data:e,error:null}}catch(e){return {data:null,error:e}}return t.then(e=>({data:e,error:null}),e=>({data:null,error:e}))}r(bn,"tryCatch");var Un=r(()=>uuid.v4(),"makeUuid"),Nn=r(()=>uuid.v7(),"makeUuidV7"),Mt="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",Ut=nanoid.customAlphabet(Mt,10),_n=r(()=>Ut(),"makeShortId");var O=r(t=>t!==null&&typeof t=="object"&&!Array.isArray(t),"isObject");function Fn(t){return O(t)&&Object.keys(t).length===0}r(Fn,"isObjectEmpty");var Nt=Object.prototype.toString,L=r(t=>Nt.call(t),"toTypeString"),q=Array.isArray,Kn=r(t=>L(t)==="[object Map]","isMap"),Bn=r(t=>L(t)==="[object Set]","isSet"),J=r(t=>t instanceof Date,"isDate"),ot=r(t=>typeof t=="function","isFunction"),_t=r(t=>typeof t=="string","isString"),Vn=r(t=>typeof t=="number","isNumber"),zn=r(t=>typeof t=="symbol","isSymbol"),qn=r(t=>O(t)&&ot(t.then)&&ot(t.catch),"isPromise"),Jn=r(t=>L(t).slice(8,-1),"toRawType"),Wn=r(t=>L(t)==="[object Object]","isPlainObject"),Hn=r(t=>_t(t)&&t!=="NaN"&&t[0]!=="-"&&`${parseInt(t,10)}`===t,"isIntegerKey");function Yn(t){return Object.keys(t).sort().reduce((e,n)=>(e[n]=t[n],e),{})}r(Yn,"sortObject");var tr=r(t=>st__default.default(t),"removeEmptyObjects");function er(t){return st__default.default(t,{undefinedValues:true,nullValues:true,emptyArrays:false,emptyObjects:false,emptyStrings:true})}r(er,"removeUndefinedProps");function v(t){if(typeof t!="object"||!t)return t;if(Array.isArray(t)){let o=[];return t.forEach((s,a)=>{o[a]=v(s);}),o}let e=Object.keys(t).sort(),n={};return e.forEach(o=>{n[o]=v(t[o]);}),n}r(v,"sortKeysRecursive");function nr(t){if(!O(t))throw new Error("Expected an object to flatten");let e={};function n(o,s){Object.entries(o).forEach(([a,i])=>{let c=[...s,a];O(i)&&(e[c.join(".")]=i,n(i,c));});}return r(n,"dive"),n(t,[]),e}r(nr,"flatten");function rr(t){return Object.entries(t).map(([e,n])=>({id:e,...n}))}r(rr,"dictionaryToArray");function or(t){return Object.entries(t).reduce((e,[n,o])=>(e[n]={id:n,...o},e),{})}r(or,"updateDictionaryWithId");immer.enablePatches();function mr({baseData:t,patches:e}){return immer.produceWithPatches(t,n=>{immer.applyPatches(n,e.flat());})}r(mr,"compressPatches");function Ft({data:t,patches:e}){let n=[],o=[];return {data:e.reduce((a,i)=>{try{let c=immer.applyPatches(a,[i]);return n.push({patch:i,before:a,after:c}),c}catch(c){return o.push({patch:i,error:c}),a}},t),steps:n,poisonPatches:o}}r(Ft,"applyEachPatch");var Kt=r(t=>JSON.stringify(t.map(String)),"pathKey"),Bt=r((t,e)=>t.length<e.length&&t.every((n,o)=>String(n)===String(e[o])),"isAncestor"),E=r(t=>`${typeof t}:${JSON.stringify(v(t))}`,"valueKey");function T(t,e){let n=t;for(let o of e){if(!n||typeof n!="object")return;n=n[o];}return n}r(T,"getAt");function U(t,e,n=[]){if(e(t,n),Array.isArray(t))t.forEach((o,s)=>U(o,e,[...n,s]));else if(t&&typeof t=="object")for(let[o,s]of Object.entries(t))U(s,e,[...n,o]);}r(U,"forEachValue");function at(t,e,n){let o=new Map;return U(T(t,e),s=>{let a=E(s);n.has(a)&&o.set(a,(o.get(a)??0)+1);}),o}r(at,"countValues");var $=r((t,e)=>Array.isArray(t)?t.filter(n=>E(n)===e).length:0,"countIn"),Vt=r((t,e)=>typeof t=="string"?e:!!t&&typeof t=="object"&&Object.keys(t).length>0,"isMovable"),zt=new Set(["__proto__","constructor","prototype"]),N=class{constructor(e,n){this.key=e;this.content=n;}static{r(this,"PutDown");}},ct=r(t=>t instanceof N?t.content:t,"contentOf");function W(t,e=new Map){t instanceof N&&e.set(t.key,(e.get(t.key)??0)+1);let n=ct(t);return n&&typeof n=="object"&&Object.values(n).forEach(o=>W(o,e)),e}r(W,"tallyPutDown");function M(t,e,n){let o=Array.isArray(t)?t.map(a=>M(a,true,n)):t&&typeof t=="object"?Object.fromEntries(Object.entries(t).map(([a,i])=>[a,M(i,false,n)])):t;if(!Vt(t,e))return o;let s=E(t);return n(s)?new N(s,o):o}r(M,"markPutDown");function qt(t,e){if(![...e].some(({op:s})=>s!=="remove"))return new Map;let n={},o=r(()=>true,"all");for(let s of t){let a=e.has(s),{op:i,path:c,value:d}=s;if(c.some(p=>zt.has(String(p))))continue;let l=n;for(let[p,m]of c.slice(0,-1).entries()){let g=l,u=ct(g[m]);if(!u||typeof u!="object"){if(!a){l=void 0;break}u=typeof c[p+1]=="number"?[]:{},g[m]=u;}l=u;}if(!l)continue;let k=l,f=c[c.length-1],x=Array.isArray(l),h;if(a&&i!=="remove")if(i==="add"||x)h=M(d,x,o);else if(Array.isArray(d))h=d.map(p=>M(p,true,o));else {let p=W(k[f]);h=M(d,false,m=>{let g=p.get(m)??0;return p.set(m,g-1),g>0});}if(Array.isArray(l)){let p=Number(f);i==="add"?(l.length<p&&(l.length=p),l.splice(p,0,h)):i==="replace"?l[p]=h:l.splice(p,1);}else i==="remove"?delete k[f]:k[f]=h;}return W(n)}r(qt,"countPutDown");function ut(t,e,n){if(!Array.isArray(t))return -1;let o=0;return t.findIndex(s=>E(s)!==e?false:(o+=1,o===n))}r(ut,"nthIndexOf");function Jt(t,e,n){let o=e.slice(0,n).map(E),s=new Map,a=o.map(i=>{let c=(s.get(i)??0)+1;return s.set(i,c),c});for(let i=n-1;i>=0;i--){let c=ut(t,o[i],a[i]);if(c!==-1)return c+1}return 0}r(Jt,"insertionIndex");function Wt(t,e){if(!t||!e||t.array!==e.array)return false;if(e.op==="replace")return t.op==="replace"&&e.index>t.index;if(t.op==="replace")return e.index>t.index;let n=e.op==="add"?1:-1;return e.op===t.op&&e.index===t.index+n}r(Wt,"continuesArrayEdit");function Ht({salvaged:t,patches:e,steps:n,poisonPatches:o}){let s=qt(e,new Set(o.map(({patch:p})=>p)));if(s.size===0)return {data:t,restoredPatches:[]};let a=new Set(s.keys()),i=new Map,c=[],d=[],l=0,k;n.forEach(({patch:p,before:m,after:g},u)=>{let y=p.path.slice(0,-1),I=Array.isArray(T(m,y)),w=I?y:p.path,b=I?{array:Kt(y),op:p.op,index:Number(p.path[p.path.length-1])}:void 0;Wt(k,b)||(l=u),k=b,d.push({step:u,path:w});let D=at(m,w,a),R=at(g,w,a),j=new Set;for(let S of a){let A=(R.get(S)??0)-(D.get(S)??0),P=i.get(S)??0;A<0?(i.set(S,P-A),j.add(S)):A>0&&i.set(S,Math.max(0,P-A));}if(j.size===0)return;let Z=n[l].before;U(T(m,w),(S,A)=>{let P=E(S);if(!j.has(P))return;let F=[...w,...A],K=F.slice(0,-1);if(!(Array.isArray(T(g,K))?$(T(g,K),P)<$(T(m,K),P):E(T(g,F))!==P))return;let Q=T(m,w);if(A.length===1&&Array.isArray(Q)){let pt=Number(A[0]),ft=$(Q.slice(0,pt+1),P),B=ut(T(Z,w),P,ft);if(B!==-1){let lt=[...w,B];c.push({key:P,value:S,path:lt,from:Z,step:u,run:l,order:B});return}}c.push({key:P,value:S,path:F,from:m,step:u,run:l,order:-u});});});let f=new Map;for(let[p,m]of s){let g=Math.min(m,i.get(p)??0);g>0&&f.set(p,g);}if(f.size===0)return {data:t,restoredPatches:[]};let[x,h]=immer.produceWithPatches(t,p=>{let m=r(({key:u,value:y,path:I,from:w})=>{let b=I.slice(0,-1),D=I[I.length-1],R=T(p,b);if(Array.isArray(R)){let j=T(w,b);return $(R,u)>=$(j,u)?false:(R.splice(Jt(R,j,Number(D)),0,y),true)}return typeof y=="object"&&R&&typeof R=="object"&&!(String(D)in R)?(R[D]=y,true):false},"putBack"),g=[...c].sort((u,y)=>y.run-u.run||u.order-y.order);for(let u of g){if(!f.get(u.key))continue;let y=u.path.slice(0,-1);d.some(({step:w,path:b})=>w>=u.step&&Bt(b,y)&&y.slice(b.length).some(D=>typeof D=="number"))||!m(u)||U(u.value,w=>{let b=f.get(E(w));b&&f.set(E(w),b-1);});}});return {data:x,restoredPatches:h}}r(Ht,"restoreMovedValues");function gr({data:t,changes:e,logError:n=console.error,logAppClientData:o=false}){if(immer.isDraft(t))throw new Error("applyPatchesSafely: `data` must not be an Immer draft; a change that fails partway would leave its earlier patches applied");let s=[];return {data:e.reduce((i,c,d)=>{try{return immer.applyPatches(i,c.patches)}catch{let l=Ft({data:i,patches:c.patches}),{steps:k,poisonPatches:f}=l;if(f.length===0)return l.data;let x=k.map(({patch:u})=>u),{data:h,restoredPatches:p}=Ht({salvaged:l.data,patches:c.patches,steps:k,poisonPatches:f}),{LOG_IMMER_APP_CLIENT_DATA:m}=process.env,g=r(u=>({op:u.op,path:u.path.join("/")}),"describe");return n(`applyPatchesSafely had issues with change ${d}: dropped ${f.length} of ${c.patches.length} patches and applied the rest`,{metadata:{changeIndex:d,changeId:c.id,appliedPatchCount:x.length,poisonPatches:f.map(({patch:u,error:y})=>({...g(u),error:y instanceof Error?y.message:String(y)})),restoredPatches:p.map(g),...o||m?{data:i}:{}}}),s.push({change:c,error:f[0]?.error,appliedPatches:x,poisonPatches:f,restoredPatches:p}),h}},t),failedChanges:s}}r(gr,"applyPatchesSafely");function Gt(t,e){if(t.length!==e.length)return false;let n=true;for(let o=0;n&&o<t.length;o++)n=G(t[o],e[o]);return n}r(Gt,"looseCompareArrays");function G(t,e){if(t===e)return true;if(J(t)&&J(e))return t.getTime()===e.getTime();if(q(t)&&q(e))return Gt(t,e);if(O(t)&&O(e)){let n=Object.keys(t).length,o=Object.keys(e).length;if(n!==o)return false;for(let s in t){let a=t.hasOwnProperty(s),i=e.hasOwnProperty(s);if(a&&!i||!a&&i||!G(t[s],e[s]))return false}}return String(t)===String(e)}r(G,"looseEqual");function wr(t,e){return t.findIndex(n=>G(n,e))}r(wr,"looseIndexOf");function Tr(t){return Math.floor(Math.random()*Math.floor(t))}r(Tr,"getRandomInt");var Xt=r(()=>{let t=new Date().getTime();return ()=>new Date().getTime()-t},"timer"),kr=r(()=>{let t=Xt();return ()=>t()/1e3},"timerInSeconds");var Er=r(t=>{try{if(!t)return "";let e=t.split(/[/\\]/),o=e[e.length-1].split(".");return o.length===1?o[0]:o.slice(0,-1).join(".")}catch{return t}},"getFileNameFromPath");function Qt({params:t,urlSearchParams:e}){return Object.entries(t??{}).forEach(([n,o])=>{if(o!=null)if(o instanceof URL)e.set(n,o.toString());else if(Array.isArray(o))e.set(n,o.join(" "));else {let s=`${o}`;if(s==="")return;e.set(n,s);}}),e}r(Qt,"addQueryParams");function Dr({url:t,origin:e,queryParams:n}){if(!e&&typeof t=="string"&&!t.startsWith("http"))throw new Error('When using "createUrl" either pass in a full "url" or provide an "origin"');let o=typeof t=="string"?new URL(t,e):e?new URL(t.toString(),e):t;return Qt({params:n,urlSearchParams:o.searchParams}),o}r(Dr,"createUrlWithParams");function jr({a:t,b:e}){return new URL(t).toString()===new URL(e).toString()}r(jr,"areUrlsSame");function Yt(t){if(typeof t!="string")return false;try{let e=new URL(t);return e.protocol.startsWith("http:")||e.protocol.startsWith("https:")}catch{return t.startsWith("//")}}r(Yt,"isRemoteUrl");var Cr=r(t=>t.startsWith("data:"),"isDataUrl"),X=r(t=>{let{string:e,strict:n=true,lowerCase:o=true}=typeof t=="string"?{string:t}:t;return Zt__default.default(e,{lower:o,trim:true,strict:n})},"slugify"),$r=r(t=>{let e=/^\/([^/]+)\/([^/]+)/,n=t.match(e);if(!n)return null;let[o,s,a]=n;return [s,a]},"extractPathParts");function Mr({fileId:t,nodeId:e,version:n}){if(!t||t.trim().length===0)throw new Error(`Invalid Figma URL, missing file id: ${t}`);let o=new URL(`https://www.figma.com/file/${t}`);return e&&o.searchParams.set("node-id",e),n&&o.searchParams.set("version-id",n.toString()),o.toString()}r(Mr,"createFigmaUrl");function Ur(t){let e=new URL(t);if(e.hostname!=="www.figma.com"&&e.hostname!=="figma.com"||!Yt(t))throw new Error(`Please provide a valid Figma URL, got ${t}`);let n=e.searchParams.get("node-id")||void 0,o=e.searchParams.get("version-id")||void 0,[,s,a]=e.pathname.split("/");switch(s){case "proto":case "file":case "board":case "design":{if(!a)throw new Error(`Invalid Figma URL, missing file id: ${t}`);return {type:s,fileId:a,nodeId:n,version:o}}default:throw new Error(`Please provide a valid Figma URL, got ${t}`)}}r(Ur,"parseFigmaUrl");function Nr(t){return new URLSearchParams(Object.fromEntries(Object.entries(t).filter(([,e])=>typeof e=="string"?e.length>0:e!=null).map(([e,n])=>[e,`${n}`]))).toString()}r(Nr,"createQueryParams");function _r({filename:t}){let e=X([...t.split(".")].pop()||""),n=X(e?t.substring(0,t.lastIndexOf(".")):t);if(!n)throw new Error(`Invalid filename: ${t}`);return e?`${n}.${e}`:n}r(_r,"createSafeFilename");function Kr(t){if(t instanceof superstruct.StructError){let[e]=t.failures();if(!e)return "";let{path:n,message:o}=e;return n.length===0?o:`At path: ${n.join(".")} -- ${o}`}return t instanceof Error?t.message:""}r(Kr,"getSuperstructErrorMsg");
2
+ Object.defineProperty(exports,"uniqBy",{enumerable:true,get:function(){return uniqBy_js__default.default}});Object.defineProperty(exports,"camelCase",{enumerable:true,get:function(){return Pt__default.default}});Object.defineProperty(exports,"kebabCase",{enumerable:true,get:function(){return Tt__default.default}});Object.defineProperty(exports,"paramCase",{enumerable:true,get:function(){return Tt__default.default}});Object.defineProperty(exports,"expectNever",{enumerable:true,get:function(){return tsExpect.expectNever}});Object.defineProperty(exports,"expectType",{enumerable:true,get:function(){return tsExpect.expectType}});Object.defineProperty(exports,"isEmpty",{enumerable:true,get:function(){return et__default.default}});Object.defineProperty(exports,"snakeCase",{enumerable:true,get:function(){return snakeCase_js__default.default}});Object.defineProperty(exports,"capitalize",{enumerable:true,get:function(){return capitalize_js__default.default}});Object.defineProperty(exports,"debounce",{enumerable:true,get:function(){return debounce_js__default.default}});Object.defineProperty(exports,"throttle",{enumerable:true,get:function(){return throttle_js__default.default}});Object.defineProperty(exports,"memoize",{enumerable:true,get:function(){return memoizee__default.default}});Object.defineProperty(exports,"memoizeeProfile",{enumerable:true,get:function(){return profile_js__default.default}});Object.defineProperty(exports,"flow",{enumerable:true,get:function(){return function_js.flow}});Object.defineProperty(exports,"applyPatches",{enumerable:true,get:function(){return immer.applyPatches}});Object.defineProperty(exports,"isDraft",{enumerable:true,get:function(){return immer.isDraft}});Object.defineProperty(exports,"produce",{enumerable:true,get:function(){return immer.produce}});Object.defineProperty(exports,"produceWithPatches",{enumerable:true,get:function(){return immer.produceWithPatches}});Object.defineProperty(exports,"groupBy",{enumerable:true,get:function(){return groupBy_js__default.default}});Object.defineProperty(exports,"deepMerge",{enumerable:true,get:function(){return deepmerge__default.default}});exports.FetcherError=C;exports.Queue=Y;exports.Stack=tt;exports.addQueryParams=Qt;exports.applyPatchesSafely=gr;exports.areUrlsSame=jr;exports.arrayToDictionary=ce;exports.assertUniqueIdInArray=se;exports.base64ToString=At;exports.capitalizeFirstLetter=St;exports.compressPatches=mr;exports.containsString=Ge;exports.createFigmaUrl=Mr;exports.createQueryParams=Nr;exports.createSafeFilename=_r;exports.createUrlWithParams=Dr;exports.cssKebabCase=Rt;exports.cssVarName=He;exports.decodeBasicAuth=rn;exports.delay=wn;exports.dictionaryToArray=rr;exports.entries=Me;exports.escapeRegEx=nt;exports.extractPathParts=$r;exports.fetcher=hn;exports.flatten=nr;exports.formatDate=we;exports.getDomainFromEmail=nn;exports.getFileNameFromPath=Er;exports.getNonUniqueStringsFromArray=ie;exports.getRandomInt=Tr;exports.getShortName=cn;exports.getSuperstructErrorMsg=Kr;exports.hasItemsInItems=oe;exports.isArray=q;exports.isArrayOfStringsUnique=ae;exports.isBase64=Ye;exports.isBrowser=Oe;exports.isDataUrl=Cr;exports.isDate=J;exports.isDefined=Ne;exports.isEmail=It;exports.isFirstLetterCapital=Xe;exports.isFunction=ot;exports.isIntegerKey=Hn;exports.isJsDom=De;exports.isMap=Kn;exports.isNode=V;exports.isNumber=Vn;exports.isObjKey=Ue;exports.isObject=O;exports.isObjectEmpty=Fn;exports.isPlainObject=Wn;exports.isPromise=qn;exports.isRemoteUrl=Yt;exports.isSet=Bn;exports.isString=_t;exports.isSymbol=zn;exports.isUrl=rt;exports.isWebWorker=Ie;exports.keys=$e;exports.looseEqual=G;exports.looseIndexOf=wr;exports.makeShortId=_n;exports.makeUuid=Un;exports.makeUuidV7=Nn;exports.minutesFromNowInIsoDate=Re;exports.now=xe;exports.nowInIsoDate=be;exports.objectToString=Nt;exports.parseFigmaUrl=Ur;exports.parseNumberWithUnit=on;exports.pascalCase=Ze;exports.removeEmptyObjects=tr;exports.removeNpmScope=en;exports.removeUndefinedProps=er;exports.removeWrappingQuotes=an;exports.slugify=X;exports.sortDateAsc=Te;exports.sortDateDesc=ke;exports.sortKeysRecursive=v;exports.sortObject=Yn;exports.startsWithLetter=sn;exports.stringHasSpaces=tn;exports.stringToBase64=Qe;exports.timer=Xt;exports.timerInSeconds=kr;exports.toMilliseconds=Se;exports.toRawType=Jn;exports.toTypeString=L;exports.tryCatch=bn;exports.uniqueArray=re;exports.updateDictionaryWithId=or;exports.upperCamelCase=Et;exports.yesterdayInIsoDate=Pe;//# sourceMappingURL=index.js.map
3
3
  //# sourceMappingURL=index.js.map