@pritzlaff/nano-app 0.0.0-stage → 0.5.1

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.
Files changed (85) hide show
  1. package/AGENTS.md +66 -0
  2. package/LICENSE +21 -0
  3. package/README.md +6 -2
  4. package/app/app.css +160 -0
  5. package/app/bundle/nano-ui.js +2553 -0
  6. package/app/examples/auth/example.auth.js +6 -0
  7. package/app/examples/auth/nano.json +46 -0
  8. package/app/examples/chat/example.chat.js +6 -0
  9. package/app/examples/chat/example.messaging.js +3 -0
  10. package/app/examples/chat/nano.json +115 -0
  11. package/app/examples/drift/example.drift.js +3 -0
  12. package/app/examples/drift/nano.json +31 -0
  13. package/app/examples/kv/example.kv.js +3 -0
  14. package/app/examples/nano.json +353 -0
  15. package/app/examples/originkey/_nano/bundle/nano-ui.js +212 -0
  16. package/app/examples/originkey/_nano/sandbox/boot.js +1 -0
  17. package/app/examples/originkey/_nano/shared/chunks/nano-core-2gg2vg5g.js +2 -0
  18. package/app/examples/originkey/_nano/shared/chunks/nano-core-5h5dssvv.js +3 -0
  19. package/app/examples/originkey/_nano/shared/chunks/nano-core-72b5e6vd.js +17 -0
  20. package/app/examples/originkey/_nano/shared/chunks/nano-core-87v2yejk.js +2 -0
  21. package/app/examples/originkey/_nano/shared/chunks/nano-core-hm29e227.js +7 -0
  22. package/app/examples/originkey/_nano/shared/chunks/nano-core-jtgk4ch8.js +2 -0
  23. package/app/examples/originkey/_nano/shared/chunks/nano-core-mqaje7vc.js +2 -0
  24. package/app/examples/originkey/_nano/shared/chunks/nano-core-mxgap7rs.js +2 -0
  25. package/app/examples/originkey/_nano/shared/chunks/nano-core-qy0mwf7y.js +1 -0
  26. package/app/examples/originkey/_nano/shared/chunks/nano-core-wanb7xw1.js +1 -0
  27. package/app/examples/originkey/_nano/shared/lit-class-map.js +1 -0
  28. package/app/examples/originkey/_nano/shared/lit-decorators.js +1 -0
  29. package/app/examples/originkey/_nano/shared/lit-directive.js +1 -0
  30. package/app/examples/originkey/_nano/shared/lit-if-defined.js +1 -0
  31. package/app/examples/originkey/_nano/shared/lit-ref.js +1 -0
  32. package/app/examples/originkey/_nano/shared/lit-repeat.js +1 -0
  33. package/app/examples/originkey/_nano/shared/lit-style-map.js +1 -0
  34. package/app/examples/originkey/_nano/shared/lit.js +1 -0
  35. package/app/examples/originkey/_nano/shared/nano-core.js +1 -0
  36. package/app/examples/originkey/_nano/shared/nano-elements.js +280 -0
  37. package/app/examples/originkey/_nano/shared/typebox-value.js +1 -0
  38. package/app/examples/originkey/_nano/shared/typebox.js +1 -0
  39. package/app/examples/originkey/example.originkey.js +6 -0
  40. package/app/examples/originkey/frame.html +1 -0
  41. package/app/examples/originkey/nano.json +50 -0
  42. package/app/examples/raft/example.raft.js +30 -0
  43. package/app/examples/raft/nano.json +74 -0
  44. package/app/examples/slice/nano.json +63 -0
  45. package/app/examples/slice/shout.js +14 -0
  46. package/app/examples/template/acme.template.js +11 -0
  47. package/app/examples/template/index.js +194 -0
  48. package/app/examples/template/nano.json +32 -0
  49. package/app/examples/todo/example.todo.js +8 -0
  50. package/app/examples/todo/nano.json +77 -0
  51. package/app/examples/typing/nano.json +33 -0
  52. package/app/favicon.svg +1 -0
  53. package/app/index.html +152 -0
  54. package/app/main.js +15906 -0
  55. package/app/react/index.html +50 -0
  56. package/app/react/main.js +9 -0
  57. package/app/sandbox/boot.js +980 -0
  58. package/app/shared/chunks/nano-core-296y9rgd.js +4321 -0
  59. package/app/shared/chunks/nano-core-2zz7d74m.js +16 -0
  60. package/app/shared/chunks/nano-core-35ryhkm1.js +33 -0
  61. package/app/shared/chunks/nano-core-5a3r312d.js +866 -0
  62. package/app/shared/chunks/nano-core-89mtxedm.js +186 -0
  63. package/app/shared/chunks/nano-core-bf13r20v.js +77 -0
  64. package/app/shared/chunks/nano-core-g3414rnc.js +248 -0
  65. package/app/shared/chunks/nano-core-hyg0qdwg.js +547 -0
  66. package/app/shared/chunks/nano-core-sxgrxy03.js +53 -0
  67. package/app/shared/chunks/nano-core-wg5c961d.js +4564 -0
  68. package/app/shared/lit-class-map.js +60 -0
  69. package/app/shared/lit-decorators.js +228 -0
  70. package/app/shared/lit-directive.js +11 -0
  71. package/app/shared/lit-if-defined.js +10 -0
  72. package/app/shared/lit-ref.js +12 -0
  73. package/app/shared/lit-repeat.js +141 -0
  74. package/app/shared/lit-style-map.js +67 -0
  75. package/app/shared/lit.js +47 -0
  76. package/app/shared/nano-core.js +2348 -0
  77. package/app/shared/nano-elements.js +1178 -0
  78. package/app/shared/typebox-value.js +78 -0
  79. package/app/shared/typebox.js +580 -0
  80. package/app/shared/versions.json +6 -0
  81. package/bin/nano-app.ts +34 -0
  82. package/package.json +22 -4
  83. package/src/events.ts +11 -0
  84. package/src/serve.ts +68 -0
  85. package/src/watch.ts +27 -0
@@ -0,0 +1,50 @@
1
+ {
2
+ "pods": {
3
+ "originKey": {
4
+ "implementation": "example.originkey/passkey",
5
+ "eager": true,
6
+ "isolation": "home-origin"
7
+ },
8
+ "keyLog": {
9
+ "implementation": "nano.ui/log",
10
+ "eager": false
11
+ }
12
+ },
13
+ "runtimes": {
14
+ "example.originkey.main": {
15
+ "pods": [
16
+ "originKey",
17
+ "keyLog"
18
+ ],
19
+ "subscriptions": [
20
+ {
21
+ "kind": "pipe",
22
+ "from": "originKey",
23
+ "source": "example.auth.Auth/authenticated",
24
+ "to": "keyLog",
25
+ "target": "nano.ui.Log/log"
26
+ }
27
+ ]
28
+ }
29
+ },
30
+ "modules": {
31
+ "example.originkey": "./example.originkey.js"
32
+ },
33
+ "frames": {
34
+ "example.originkey": "./frame.html"
35
+ },
36
+ "layout": {
37
+ "slots": [
38
+ {
39
+ "id": "originKey",
40
+ "runtime": "example.originkey.main",
41
+ "pod": "originKey"
42
+ },
43
+ {
44
+ "id": "keyLog",
45
+ "runtime": "example.originkey.main",
46
+ "pod": "keyLog"
47
+ }
48
+ ]
49
+ }
50
+ }
@@ -0,0 +1,30 @@
1
+ import{Coord as KQ}from"@pritzlaff/nano-core";import{Type as p}from"typebox";import{Coord as RJ,Implementation as NJ,Schema as kJ,failure as wY,provide as xJ,success as TJ}from"@pritzlaff/nano-core";import{HostDeploy as ZY}from"@pritzlaff/nano-ui";import{Type as B}from"typebox";import{Coord as QJ,Schema as O,Op as V}from"@pritzlaff/nano-core";import{Any as XJ,Nothing as H}from"@pritzlaff/nano-ui";var h=QJ.namespace("example.raft"),G=B.Integer({minimum:0}),EY=B.Object({index:G,term:G,value:B.Unknown(),at:B.Number()}),f=O.define(B.Object({currentTerm:G,votedFor:B.Union([B.String(),B.Null()]),log:B.Array(EY)}),"Persistent"),u=(Y,J)=>B.Object({kind:B.Literal(Y),term:G,from:B.String(),...J}),AY=O.define(B.Union([u("vote",{lastIndex:G,lastTerm:G}),u("vote-reply",{granted:B.Boolean()}),u("append",{prevIndex:G,prevTerm:G,entries:B.Array(EY),commit:G}),u("append-reply",{success:B.Boolean(),match:G})]),"RaftMessage"),ZJ=O.define(B.Object({to:B.String(),message:AY}),"Envelope"),x=B.Object({electionMin:G,electionMax:G,heartbeat:G}),$J=B.Object({next:G,match:G,granted:B.Boolean(),rpcDue:B.Number(),heartbeatDue:B.Number()}),DY=O.define(B.Object({id:B.String(),peers:B.Array(B.String()),p:f,role:B.Union([B.Literal("follower"),B.Literal("candidate"),B.Literal("leader")]),commitIndex:G,leader:B.Union([B.String(),B.Null()]),electionAlarm:B.Number(),stopped:B.Boolean(),progress:B.Record(B.String(),$J),timing:x}),"NodeStatus"),BJ=O.define(B.Object({name:B.String(),size:B.Union([B.Literal(3),B.Literal(5)]),seed:B.Integer(),heartbeatMs:B.Optional(B.Integer({minimum:10,maximum:60000}))}),"ClusterSpec"),WJ=O.define(B.Object({name:B.String()}),"ClusterName"),KJ=O.define(B.Array(B.String()),"Names"),b=h.interface("Messaging",{send:V.action(ZJ,H)}),q=h.interface("RaftNode",{receive:V.action(AY,H),request:V.action(XJ,H),timeOut:V.action(H,H),stop:V.action(H,H),resume:V.action(H,H),restart:V.action(H,H),status:V.action(H,DY),changed:V.event(DY)}),D=h.interface("Ledger",{read:V.action(H,f),write:V.action(f,H),written:V.event(f)}),T=h.interface("Cluster",{create:V.action(BJ,H),remove:V.action(WJ,H),list:V.action(H,KJ)});import{Pod as JY}from"@pritzlaff/nano-core";import{seededRandom as IJ}from"@pritzlaff/nano-ui";import{Coord as _J,Implementation as jJ,provide as UJ,success as LY}from"@pritzlaff/nano-core";var qJ=_J.namespace("example.raft"),FJ={currentTerm:0,votedFor:null,log:[]},m=jJ.define(qJ.implementationId("ledger"),{provides:[D],make:(Y)=>{let J=FJ;return[UJ(D,{read:async()=>LY(J),write:async(Q)=>{return J=Q,await Y.publish(D.ops.written,Q),LY(null)}})]}});import{Type as y}from"typebox";import{Coord as SJ,Implementation as OJ,Schema as CJ,failure as RY,provide as MJ,success as I}from"@pritzlaff/nano-core";import{Clock as YY,Random as NY}from"@pritzlaff/nano-ui";var E=(Y)=>Y.log.length,w=(Y,J)=>J===0?0:Y.log[J-1].term,c=(Y)=>w(Y,E(Y)),l=(Y)=>Math.floor((Y.peers.length+1)/2)+1,i=(Y)=>2*Y.timing.heartbeat;var C=(Y,J,Q)=>J+Y.electionMin+Q()*(Y.electionMax-Y.electionMin);function SY(Y,J){let{n:Q}=Y;if(Q.role==="leader")Q.electionAlarm=C(Q.timing,Y.now,Y.draw);Q.p={...Q.p,currentTerm:J,votedFor:null},Q.role="follower",Q.leader=null}function t(Y){let{n:J}=Y;J.p={...J.p,currentTerm:J.p.currentTerm+1,votedFor:J.id},J.role="candidate",J.leader=null,J.electionAlarm=C(J.timing,Y.now,Y.draw);for(let Q of Object.values(J.progress))Object.assign(Q,{granted:!1,rpcDue:0})}function OY(Y){let{n:J}=Y;for(let Q of J.peers){let X=J.progress[Q];if(X.rpcDue>Y.now)continue;X.rpcDue=Y.now+i(J),Y.out.push({kind:"send",to:Q,rpc:{kind:"vote",term:J.p.currentTerm,lastIndex:E(J.p),lastTerm:c(J.p)}})}}function CY(Y,J,Q){let{n:X}=Y,Z=Q.lastTerm>c(X.p)||Q.lastTerm===c(X.p)&&Q.lastIndex>=E(X.p),$=Q.term===X.p.currentTerm&&(X.p.votedFor??J)===J&&Z;if($){if(X.p.votedFor!==J)X.p={...X.p,votedFor:J};X.electionAlarm=C(X.timing,Y.now,Y.draw)}Y.out.push({kind:"send",to:J,rpc:{kind:"vote-reply",term:X.p.currentTerm,granted:$}})}function MY(Y,J,Q){let{n:X}=Y;if(X.role!=="candidate"||Q.term!==X.p.currentTerm)return;let Z=X.progress[J];if(Z.granted=Q.granted,Z.rpcDue=X.electionAlarm,1+X.peers.filter(($)=>X.progress[$].granted).length>=l(X))HJ(Y)}function HJ(Y){let{n:J}=Y;J.role="leader",J.leader=J.id;for(let Q of Object.values(J.progress))Object.assign(Q,{next:E(J.p)+1,match:0,rpcDue:0,heartbeatDue:0})}function zY(Y){let{n:J}=Y;for(let Q of J.peers){let X=J.progress[Q];if(!(X.next<=E(J.p)&&X.rpcDue<=Y.now)&&X.heartbeatDue>Y.now)continue;let $=X.next-1;Y.out.push({kind:"send",to:Q,rpc:{kind:"append",term:J.p.currentTerm,prevIndex:$,prevTerm:w(J.p,$),entries:J.p.log.slice($),commit:J.commitIndex}}),X.rpcDue=Y.now+i(J),X.heartbeatDue=Y.now+J.timing.heartbeat}}function vY(Y,J,Q){let{n:X}=Y,Z=(W,F)=>Y.out.push({kind:"send",to:J,rpc:{kind:"append-reply",term:X.p.currentTerm,success:W,match:F}});if(Q.term<X.p.currentTerm)return Z(!1,0);if(X.role="follower",X.leader=J,X.electionAlarm=C(X.timing,Y.now,Y.draw),Q.prevIndex>E(X.p)||w(X.p,Q.prevIndex)!==Q.prevTerm)return Z(!1,0);let $=GJ(X.p.log,Q.entries);if($!==X.p.log)X.p={...X.p,log:$};let _=Q.prevIndex+Q.entries.length;X.commitIndex=Math.max(X.commitIndex,Math.min(Q.commit,_)),Z(!0,_)}function GJ(Y,J){for(let Q of J)if(Y[Q.index-1]?.term!==Q.term)Y=[...Y.slice(0,Q.index-1),Q];return Y}function bY(Y,J,Q){let{n:X}=Y;if(X.role!=="leader"||Q.term!==X.p.currentTerm)return;let Z=X.progress[J];if(Q.success)Z.match=Math.max(Z.match,Q.match),Z.next=Z.match+1;else Z.next=Math.max(1,Z.next-1);Z.rpcDue=0,PJ(Y)}function PJ(Y){let{n:J}=Y;for(let Q=E(J.p);Q>J.commitIndex&&w(J.p,Q)===J.p.currentTerm;Q--)if(1+J.peers.filter((X)=>J.progress[X].match>=Q).length>=l(J))return void(J.commitIndex=Q)}var VJ={electionMin:150,electionMax:300,heartbeat:50};function e(Y,J,Q,X,Z,$=VJ){return{id:Y,peers:J,p:Q,role:"follower",commitIndex:0,leader:null,electionAlarm:C($,X,Z),stopped:!1,progress:Object.fromEntries(J.map((_)=>[_,{next:1,match:0,granted:!1,rpcDue:0,heartbeatDue:0}])),timing:$}}function IY(Y,J,Q,X){let Z=Object.fromEntries(Object.entries(Y.progress).map(([_,W])=>[_,{...W}])),$={n:{...Y,progress:Z},now:Q,draw:X,out:[]};if(DJ($,J),$.n.p!==(J.kind==="restart"?J.p:Y.p))$.out.unshift({kind:"persist",p:$.n.p});return{node:$.n,effects:$.out}}function DJ(Y,J){let{n:Q}=Y;if(Q.stopped){if(J.kind==="resume")Q.stopped=!1;if(J.kind==="request")Y.out.push({kind:"refused",reason:"stopped"});return}switch(J.kind){case"tick":return EJ(Y);case"time-out":return t(Y);case"stop":Q.stopped=!0;return;case"resume":return;case"restart":Y.n=e(Q.id,Q.peers,J.p,Y.now,Y.draw,Q.timing);return;case"request":return AJ(Y,J.value);case"receive":return LJ(Y,J.from,J.rpc)}}function EJ(Y){if(Y.n.role!=="leader"&&Y.now>=Y.n.electionAlarm)t(Y);if(Y.n.role==="candidate")OY(Y);if(Y.n.role==="leader")zY(Y)}function AJ(Y,J){let{n:Q}=Y;if(Q.role==="leader")Q.p={...Q.p,log:[...Q.p.log,{index:E(Q.p)+1,term:Q.p.currentTerm,value:J,at:Y.now}]};else if(Q.leader)Y.out.push({kind:"refused",reason:"not leader",leader:Q.leader});else Y.out.push({kind:"refused",reason:"no leader known"})}function LJ(Y,J,Q){if(Q.term>Y.n.p.currentTerm)SY(Y,Q.term);switch(Q.kind){case"vote":return CY(Y,J,Q);case"vote-reply":return MY(Y,J,Q);case"append":return vY(Y,J,Q);case"append-reply":return bY(Y,J,Q)}}var zJ=SJ.namespace("example.raft"),vJ=3;function bJ(Y){if(Y.stopped)return;let J=Object.values(Y.progress);if(Y.role==="leader")return Math.min(...J.map((Q)=>Q.next<=E(Y.p)?Math.min(Q.rpcDue,Q.heartbeatDue):Q.heartbeatDue));if(Y.role==="candidate")return Math.min(Y.electionAlarm,...J.map((Q)=>Q.rpcDue));return Y.electionAlarm}var o=OJ.define(zJ.implementationId("node"),{provides:[q],config:CJ.define(y.Object({id:y.String(),peers:y.Array(y.String()),timing:y.Optional(x)}),"NodeConfig"),dependencies:{messaging:b,ledger:D,clock:YY,random:NY},make:(Y,{id:J,peers:Q,timing:X})=>{let Z=(K,P)=>{if(!K.ok)throw Error(`node ${J} needs ${P}: ${K.fail.reason}`);return K.value},$=Z(Y.one(b),"messaging"),_=Z(Y.one(D),"a ledger"),W=Z(Y.one(YY),"a clock"),F=Z(Y.one(NY),"a random"),j,U,A=!1,z=Promise.resolve(),s=(K)=>z=z.then(K,K),r=[],FY=async()=>{while(r.length<vJ){let K=await F.call.next(null);if(!K.ok)return K;r.push(K.value)}},HY=()=>{let K=r.shift();if(K===void 0)throw Error("more draws than DRAWS");return K},GY=async(K)=>{let P=bJ(j);if(P===U?.due)return;if(U)W.call.cancel(U.id);if(U=void 0,P===void 0||A)return;let v=await W.call.after({ms:Math.max(0,Math.ceil(P-K)),tag:J});if(v.ok)U={id:v.value,due:P}},L=(K,P)=>s(async()=>{if(A)return RY("not-found",`node ${J} is closed`);let v=typeof K==="function"?await K():I(K);if(!v.ok)return v;let g=P===void 0?await W.call.now(null):I(P);if(!g.ok)return g;let PY=await FY();if(PY)return PY;let JJ=JSON.stringify(j),n=IY(j,v.value,g.value,HY);j=n.node;try{for(let S of n.effects){let VY=S.kind==="persist"?await _.call.write(S.p):S.kind==="send"?await $.call.send({to:S.to,message:{...S.rpc,from:J}}):I(null);if(!VY.ok)return VY}}finally{if(JSON.stringify(j)!==JJ)await Y.publish(q.ops.changed,j);await GY(g.value)}let k=n.effects.find((S)=>S.kind==="refused");return k?RY("invalid-input",k.leader?`${k.reason}: the leader is ${k.leader}`:k.reason):I(null)});return s(async()=>{let K=await _.call.read(null),P=await W.call.now(null);if(!K.ok||!P.ok||await FY())return;j=e(J,Q,K.value,P.value,HY,X),await GY(P.value)}),W.on(YY.ops.fired,({output:K})=>{if(K.id!==U?.id)return;U=void 0,L({kind:"tick"},K.at)}),Y.addOnCloseListener(()=>{if(A=!0,U)W.call.cancel(U.id)}),[MJ(q,{receive:async({from:K,...P})=>L({kind:"receive",from:K,rpc:P}),request:async(K)=>L({kind:"request",value:K}),timeOut:async()=>L({kind:"time-out"}),stop:async()=>L({kind:"stop"}),resume:async()=>L({kind:"resume"}),restart:async()=>L(async()=>{let K=await _.call.read(null);return K.ok?I({kind:"restart",p:K.value}):K}),status:()=>s(async()=>I(j))})]}});var QY="raft-messaging",kY="raft-clock",xY=(Y,J)=>Y===void 0?J:{heartbeat:Y,electionMin:3*Y,electionMax:6*Y},XY=(Y,J)=>Array.from({length:J},(Q,X)=>`${Y}-${X+1}`);function TY(Y,J,Q,X){let Z=XY(Y,J),$={},_={};return Z.forEach((W,F)=>{let j=`${W}-raft`,U=`${W}-ledger`,A=`${W}-random`;$[j]=JY.eager(o,{config:{id:W,peers:Z.filter((z)=>z!==W),...X&&{timing:X}}}),$[U]=JY.eager(m),$[A]=JY.eager(IJ,{config:{seed:Q+F+1}}),_[W]={pods:[QY,kY,j,U,A],subscriptions:[...[QY,U,kY,A].map((z)=>({kind:"call",from:j,to:z})),{kind:"call",from:QY,to:j}]}}),{pods:$,runtimes:_}}var wJ=RJ.namespace("example.raft"),yY=NJ.define(wJ.implementationId("cluster"),{provides:[T],config:kJ.define(p.Union([p.Object({timing:p.Optional(x)}),p.Undefined()]),"ClusterConfig"),dependencies:{deploy:ZY},make:(Y,J)=>{let Q=new Map;return[xJ(T,{create:async({name:X,size:Z,seed:$,heartbeatMs:_})=>{if(!/^[a-z][a-z0-9-]*$/.test(X))return wY("invalid-input",`cluster name ${JSON.stringify(X)}: lowercase letters, digits and hyphens, starting with a letter`);let W=Y.one(ZY);if(!W.ok)return W;let F=await W.value.call.deploy(TY(X,Z,$,xY(_,J?.timing)));if(F.ok)Q.set(X,Z);return F},remove:async({name:X})=>{let Z=Y.one(ZY);if(!Z.ok)return Z;let $=wY("not-found",`no cluster ${X}`);for(let _ of Q.has(X)?[Q.get(X)]:[5,3])if($=await Z.value.call.undeploy({runtimes:XY(X,_)}),$.ok||$.fail.type!=="not-found")break;if($.ok)Q.delete(X);return $},list:async()=>TJ([...Q.keys()])})]}});import{Type as a}from"typebox";import{Coord as fY,Implementation as yJ,Schema as gJ,Selector as uJ,provide as fJ,success as hJ}from"@pritzlaff/nano-core";import{Clock as $Y,Random as gY}from"@pritzlaff/nano-ui";var mJ=fY.namespace("example.raft"),uY=a.Integer({minimum:0,maximum:60000}),cJ="delivery",hY=yJ.define(mJ.implementationId("messaging"),{provides:[b],config:gJ.define(a.Union([a.Object({minMs:uY,maxMs:uY}),a.Undefined()]),"MessagingConfig"),dependencies:{clock:$Y,random:gY,node:q},make:(Y,J)=>{let{minMs:Q,maxMs:X}=J??{minMs:10,maxMs:30},Z=Y.one($Y),$=Y.one(gY);if(!Z.ok)throw Error(`messaging needs a clock: ${Z.fail.reason}`);if(!$.ok)throw Error(`messaging needs a random: ${$.fail.reason}`);let _=new Map;return Z.value.on($Y.ops.fired,async({output:W})=>{let F=_.get(W.id);if(!F)return;_.delete(W.id);let j=Y.one(uJ.of(q,{runtime:fY.runtime(F.to)}));if(j.ok)await j.value.call.receive(F.message)}),[fJ(b,{send:async({to:W,message:F})=>{let j=await $.value.call.next(null);if(!j.ok)return j;let U=await Z.value.call.after({ms:Q+Math.floor(j.value*(X-Q+1)),tag:cJ});if(!U.ok)return U;return _.set(U.value,{to:W,message:F}),hJ(null)}})]}});import{LitElement as dJ,css as sJ,html as N,svg as rJ}from"lit";import{base as nJ}from"@pritzlaff/nano-elements";import{Clock as oY}from"@pritzlaff/nano-ui";import{LitElement as iJ,css as oJ,html as R}from"lit";import{base as pJ,kit as aJ}from"@pritzlaff/nano-elements";var BY=(Y,J)=>{let Q=Y-J;return`${Q>=0?"+":"-"}${Math.abs(Q).toFixed(1)} ms`};function lJ(Y,J,Q){let X=Y.progress[J];if(Y.role==="candidate"&&X.granted)return"granted";let Z=X.rpcDue>Q&&!(Y.role==="candidate"&&X.rpcDue===Y.electionAlarm);return Y.role!=="follower"&&!Y.stopped&&Z?"pending":"idle"}function WY(Y,J){let Q=Y.role==="leader"?0:(Y.electionAlarm-J)/Y.timing.electionMax;return{term:Y.p.currentTerm,role:Y.role,stopped:Y.stopped,arc:Math.min(1,Math.max(0,Q)),peers:Y.peers.map((X)=>({id:X,state:lJ(Y,X,J)}))}}function mY(Y,J){return{rows:[["state",Y.stopped?"stopped":Y.role],["currentTerm",String(Y.p.currentTerm)],["votedFor",Y.p.votedFor??"—"],["commitIndex",String(Y.commitIndex)],["election alarm",BY(Y.electionAlarm,J)]],peers:Y.peers.map((Q)=>{let X=Y.progress[Q];return{peer:Q,next:X.next,match:X.match,granted:X.granted,rpcDue:BY(X.rpcDue,J),heartbeatDue:BY(X.heartbeatDue,J)}})}}var cY=(Y,J)=>({currentTerm:Y.currentTerm,votedFor:Y.votedFor,rows:Y.log.map((Q)=>({index:Q.index,term:Q.term,value:typeof Q.value==="string"?Q.value:JSON.stringify(Q.value),at:Q.at.toFixed(1),committed:Q.index<=J}))});function lY(Y){let J=Math.max(10,...Y.map((Q)=>Q.p.log.length));return{columns:J,rows:Y.map((Q)=>({id:Q.id,cells:Array.from({length:J},(X,Z)=>{let $=Q.p.log[Z];return $?{term:$.term,committed:$.index<=Q.commitIndex}:null})}))}}function KY(Y,J,Q){if(!Y||Q-Y.wall>2000)return{sim:J,wall:Q,rate:Y?.rate??1,from:{sim:J,wall:Q}};let X=Q-Y.from.wall,Z=X>=500&&J>=Y.from.sim;return{sim:J,wall:Q,rate:Z?(J-Y.from.sim)/X:Y.rate,from:Z?{sim:J,wall:Q}:Y.from}}var _Y=[["stop","stop"],["resume","resume"],["restart","restart"],["time out","timeOut"],["request","request"]];async function jY(Y,J,Q){let X=await Y.app.call(Y.runtime,Y.pod)[q.ops[J].name](J==="request"?Q:null);return X.ok?void 0:X.fail.reason}class iY extends iJ{static properties={target:{attribute:!1},status:{attribute:!1},now:{attribute:!1},error:{state:!0},text:{state:!0}};static styles=[pJ,aJ,oJ`table { border-collapse: collapse; font-size: 12px } td, th { padding: 2px 8px; text-align: left } .row { flex-wrap: wrap } textarea { width: 100%; font: inherit }`];n=0;constructor(){super();this.now=0,this.text=""}act(Y){++this.n,jY(this.target,Y,this.text||`v${this.n}`).then((J)=>{this.error=J})}render(){if(!this.status)return R``;let Y=mY(this.status,this.now),J=this.status.role==="leader",Q=(X,Z)=>R`<button class="btn small" type="button" ?disabled=${Z==="request"&&!J} @click=${()=>this.act(Z)}>${X}</button>`;return R`<div class="col">
2
+ <table class="rows">${Y.rows.map(([X,Z])=>R`<tr><th>${X}</th><td>${Z}</td></tr>`)}</table>
3
+ <table class="peers"><tr><th>peer</th><th>next</th><th>match</th><th>vote granted</th><th>RPC due</th><th>heartbeat due</th></tr>
4
+ ${Y.peers.map((X)=>R`<tr><td>${X.peer}</td><td>${X.next}</td><td>${X.match}</td><td>${X.granted?"yes":"no"}</td><td>${X.rpcDue}</td><td>${X.heartbeatDue}</td></tr>`)}</table>
5
+ <textarea rows="3" aria-label="request value" placeholder=${J?"request value (empty: v<n>)":"only the leader takes a request"} ?disabled=${!J} .value=${this.text} @input=${(X)=>{this.text=X.target.value}}></textarea>
6
+ <div class="row">${_Y.map(([X,Z])=>Q(X,Z))}</div>
7
+ ${this.error?R`<p class="alert bad" role="alert">${this.error}</p>`:""}</div>`}}if(!customElements.get("raft-detail"))customElements.define("raft-detail",iY);var tJ={follower:"#8b949e",candidate:"#F5A524",leader:"#7EE787"},UY=40,pY=2*Math.PI;class aY extends dJ{static properties={target:{attribute:!1},status:{state:!0},now:{state:!0},open:{state:!0},menu:{state:!0},error:{state:!0}};static styles=[nJ,sJ`svg { cursor: pointer; width: 120px; height: 120px } dialog { color: inherit; background: Canvas; padding: 0 } .pad { padding: 1em } .menu { position: fixed; display: flex; flex-direction: column; background: Canvas; border: 1px solid currentColor; z-index: 10 } text { fill: currentColor; text-anchor: middle; font-size: 22px } .role { text-align: center; font-size: 12px; font-weight: 600 }`];n=0;close=(Y)=>{if(Y instanceof KeyboardEvent?Y.key==="Escape":!(Y.type==="contextmenu"&&Y.composedPath().includes(this)))this.menu=void 0};stop;watching;pace;frame=0;constructor(){super();this.now=0,this.open=!1}tick=()=>{let Y=this.shadowRoot?.querySelector("circle.arc");if(Y&&this.status)Y.setAttribute("stroke-dasharray",this.dash(this.status));this.frame=requestAnimationFrame(this.tick)};dash(Y){let J=this.pace,Q=pY*UY;return`${WY(Y,J?J.sim+(performance.now()-J.wall)*J.rate:this.now).arc*Q} ${Q}`}connectedCallback(){super.connectedCallback(),this.frame=requestAnimationFrame(this.tick),this.watch(),window.addEventListener("click",this.close),window.addEventListener("keydown",this.close),window.addEventListener("contextmenu",this.close)}disconnectedCallback(){super.disconnectedCallback(),cancelAnimationFrame(this.frame),window.removeEventListener("click",this.close),window.removeEventListener("keydown",this.close),window.removeEventListener("contextmenu",this.close),this.stop?.(),this.stop=this.watching=void 0}willUpdate(Y){if(Y.has("target"))this.watch()}watch(){let Y=this.target;if(!Y||!this.isConnected||this.watching===Y)return;this.stop?.(),this.watching=Y,this.status=void 0,this.now=0,this.pace=void 0;let J={status:!1,now:!1},Q=[];this.stop=()=>Q.forEach((X)=>X());try{let X=Y.app.runtime(Y.runtime);Q.push(X.subscribe(q.ops.changed,({output:Z})=>{J.status=!0,this.status=Z})),Q.push(X.subscribe(oY.ops.fired,({output:Z})=>{J.now=!0,this.now=Z.at,this.pace=KY(this.pace,Z.at,performance.now())})),Promise.all([X.get(q,{pod:Y.pod}).status(),X.get(oY).now()]).then(([Z,$])=>{if(this.watching!==Y)return;if(!J.status)this.status=Z;if(!J.now)this.now=$,this.pace=KY(this.pace,$,performance.now())},()=>{})}catch{}}updated(){let Y=this.shadowRoot?.querySelector("dialog");if(Y&&!Y.hasAttribute("open"))if(Y.showModal)Y.showModal();else Y.setAttribute("open","")}pick(Y){this.menu=void 0,jY(this.target,Y,`v${++this.n}`).then((J)=>{this.error=J})}menuItem=(Y,J)=>N`<button class="btn small" role="menuitem" type="button" ?disabled=${J==="request"&&this.status?.role!=="leader"} @click=${()=>this.pick(J)}>${Y}</button>`;render(){if(!this.status)return N``;let Y=WY(this.status,this.now),J=tJ[Y.role],Q=Y.peers.map((X,Z)=>{let $=pY*Z/Y.peers.length-Math.PI/2;return rJ`<circle class="dot ${X.state}" cx=${60+52*Math.cos($)} cy=${60+52*Math.sin($)} r="5" stroke=${J} stroke-opacity=${X.state==="idle"?0.2:1} fill=${X.state==="granted"?J:"none"}><title>${X.id}: ${X.state}</title></circle>`});return N`<svg viewBox="0 0 120 120" opacity=${Y.stopped?0.35:1} @click=${()=>{this.open=!0}} @contextmenu=${(X)=>{X.preventDefault(),this.error=void 0,this.menu={x:X.clientX,y:X.clientY}}}>
8
+ <circle cx="60" cy="60" r=${UY} fill="none" stroke=${J} stroke-opacity="0.25" stroke-width="6"/>
9
+ <circle class="arc" cx="60" cy="60" r=${UY} fill="none" stroke=${J} stroke-width="6" stroke-dasharray=${this.dash(this.status)} transform="rotate(-90 60 60)"/>
10
+ <text x="60" y="68">${Y.term}</text>${Q}</svg>
11
+ <div class="role">${Y.role}</div>
12
+ ${this.menu?N`<div class="menu" role="menu" style="left: ${this.menu.x}px; top: ${this.menu.y}px">${_Y.map(([X,Z])=>this.menuItem(X,Z))}</div>`:""}
13
+ ${this.error?N`<p class="alert bad" role="alert">${this.error}</p>`:""}
14
+ ${this.open?N`<dialog @click=${(X)=>{if(X.target===X.currentTarget)this.open=!1}} @cancel=${()=>{this.open=!1}} @keydown=${(X)=>{if(X.key==="Escape")this.open=!1}}>
15
+ <div class="pad"><div class="row"><strong>${this.status.id}</strong><button class="btn small" type="button" aria-label="close" @click=${()=>{this.open=!1}}>✕</button></div>
16
+ <raft-detail .target=${this.target} .status=${this.status} .now=${this.now}></raft-detail></div></dialog>`:""}`}}if(!customElements.get("raft-node"))customElements.define("raft-node",aY);import{LitElement as eJ,css as YQ,html as qY}from"lit";import{base as JQ,kit as QQ}from"@pritzlaff/nano-elements";class dY extends eJ{static properties={target:{attribute:!1},model:{state:!0}};static styles=[JQ,QQ,YQ`table { border-collapse: collapse; font-size: 12px } td, th { padding: 2px 8px; text-align: left } .committed { color: var(--nano-good, #7EE787) } .head { margin: 0 0 4px; font-size: 12px }`];stop;watching;p;commit=0;connectedCallback(){super.connectedCallback(),this.watch()}disconnectedCallback(){super.disconnectedCallback(),this.stop?.(),this.stop=this.watching=void 0}willUpdate(Y){if(Y.has("target"))this.watch()}watch(){let Y=this.target;if(!Y||!this.isConnected||this.watching===Y)return;this.stop?.(),this.watching=Y,this.p=void 0,this.commit=0,this.model=void 0;let J=()=>{if(this.p)this.model=cY(this.p,this.commit)},Q={p:!1,commit:!1},X=[];this.stop=()=>X.forEach((Z)=>Z());try{let Z=Y.app.runtime(Y.runtime);X.push(Z.subscribe(D.ops.written,({output:$})=>{Q.p=!0,this.p=$,J()})),X.push(Z.subscribe(q.ops.changed,({output:$})=>{Q.commit=!0,this.commit=$.commitIndex,J()})),Promise.all([Z.get(D,{pod:Y.pod}).read(),Z.get(q).status()]).then(([$,_])=>{if(this.watching!==Y)return;if(!Q.p)this.p=$;if(!Q.commit)this.commit=_.commitIndex;J()},()=>{})}catch{}}render(){let Y=this.model;if(!Y)return qY``;return qY`<p class="head">currentTerm <b>${Y.currentTerm}</b> · votedFor <b>${Y.votedFor??"—"}</b></p>
17
+ <table><tr><th>index</th><th>term</th><th>value</th><th>at</th></tr>
18
+ ${Y.rows.map((J)=>qY`<tr class=${J.committed?"committed":""}><td>${J.index}</td><td>${J.term}</td><td>${J.value}</td><td>${J.at}</td></tr>`)}</table>`}}if(!customElements.get("raft-ledger"))customElements.define("raft-ledger",dY);import{LitElement as ZQ,css as $Q,html as d}from"lit";import{base as BQ,kit as WQ}from"@pritzlaff/nano-elements";import{LitElement as sY,css as rY,html as M}from"lit";import{base as nY,kit as XQ}from"@pritzlaff/nano-elements";class tY extends sY{static properties={target:{attribute:!1},ids:{attribute:!1}};static styles=[nY,rY`.ring { position: relative; width: 420px; height: 420px; margin: 8px 0 } .at { position: absolute; margin: -60px 0 0 -60px; text-align: center; font-size: 12px }`];targets=[];constructor(){super();this.ids=[]}willUpdate(Y){let J=this.target;if(J&&(Y.has("target")||Y.has("ids")))this.targets=this.ids.map((Q)=>({...J,runtime:Q,pod:`${Q}-raft`}))}render(){let Y=this.ids.length;return M`<div class="ring">${this.ids.map((J,Q)=>{let X=2*Math.PI*Q/Y-Math.PI/2;return M`<div class="at" style="left:${50+36*Math.cos(X)}%;top:${50+36*Math.sin(X)}%"><raft-node .target=${this.targets[Q]}></raft-node><div>${J}</div></div>`})}</div>`}}if(!customElements.get("raft-ring"))customElements.define("raft-ring",tY);class eY extends sY{static properties={target:{attribute:!1},ids:{attribute:!1},rows:{state:!0}};static styles=[nY,XQ,rY`table { border-collapse: collapse; font-size: 12px } td, th { padding: 2px 8px; border: 1px solid var(--nano-border, #8b949e55); text-align: center } .committed { color: var(--nano-good, #7EE787) }`];stop;watching;constructor(){super();this.ids=[],this.rows=[]}disconnectedCallback(){super.disconnectedCallback(),this.stop?.(),this.stop=this.watching=void 0}connectedCallback(){super.connectedCallback(),this.watch()}willUpdate(Y){if(Y.has("target")||Y.has("ids"))this.watch()}watch(){let Y=this.target,J=this.ids;if(this.watching?.t===Y&&this.watching?.ids===J&&this.isConnected)return;this.stop?.(),this.stop=void 0,this.watching={t:Y,ids:J};let Q=()=>this.ids===J&&this.target===Y;if(this.rows=[],!Y||!this.isConnected)return;let X=new Map,Z=[];this.stop=()=>Z.forEach((_)=>_());let $=()=>{this.rows=J.flatMap((_)=>{let W=X.get(_);return W?.p?[{id:_,p:W.p,commitIndex:W.commitIndex}]:[]})};for(let _ of J){let W={commitIndex:0},F={p:!1,c:!1};X.set(_,W);try{let j=Y.app.runtime(_);Z.push(j.subscribe(D.ops.written,({output:U})=>{F.p=!0,W.p=U,$()})),Z.push(j.subscribe(q.ops.changed,({output:U})=>{F.c=!0,W.commitIndex=U.commitIndex,$()})),Promise.all([j.get(D,{pod:`${_}-ledger`}).read(),j.get(q).status()]).then(([U,A])=>{if(!Q())return;if(!F.p)W.p=U;if(!F.c)W.commitIndex=A.commitIndex;$()},()=>{})}catch{}}}render(){if(!this.rows.length)return M``;let Y=lY(this.rows);return M`<table><tr><th></th>${Array.from({length:Y.columns},(J,Q)=>M`<th>${Q+1}</th>`)}</tr>
19
+ ${Y.rows.map((J)=>M`<tr><th>${J.id}</th>${J.cells.map((Q)=>M`<td class=${Q?.committed?"committed":""}>${Q?.term??""}</td>`)}</tr>`)}</table>`}}if(!customElements.get("raft-log"))customElements.define("raft-log",eY);class YJ extends ZQ{static properties={target:{attribute:!1},names:{state:!0},chosen:{state:!0},ids:{state:!0},error:{state:!0}};static styles=[BQ,WQ,$Q`ul { list-style: none; margin: 0; padding: 0 } label { display: inline-flex; align-items: center; gap: .35em; font-size: .85em; color: var(--nano-muted, inherit) }`];loaded;loadedFor;stop;watching;constructor(){super();this.names=[],this.ids=[]}connectedCallback(){super.connectedCallback(),this.watch()}disconnectedCallback(){super.disconnectedCallback(),this.stop?.(),this.stop=this.watching=void 0}willUpdate(Y){if(Y.has("target"))this.watch();this.draw()}get shown(){return this.chosen!==void 0&&this.names.includes(this.chosen)?this.chosen:this.names[0]}draw(){let Y=this.target,J=this.shown,Q=Y&&J!==void 0?`${J}`:void 0;if(this.loaded===Q&&this.loadedFor===Y)return;if(this.loaded=Q,this.loadedFor=Y,this.ids=[],!Y||!J)return;try{Y.app.runtime(`${J}-1`).get(q,{pod:`${J}-1-raft`}).status().then((X)=>{if(this.loaded===Q&&this.loadedFor===Y)this.ids=[X.id,...X.peers].sort()},()=>{if(this.loadedFor===Y)this.loaded=void 0})}catch{}}pod(Y){return Y.app.runtime(Y.runtime).get(T,{pod:Y.pod})}watch(){let Y=this.target;if(!Y||!this.isConnected||this.watching===Y)return;this.stop?.(),this.watching=Y,this.stop=void 0;try{this.pod(Y).list().then((J)=>{this.names=J},()=>{})}catch{}}async run(Y,J){this.error=void 0;try{await Y(),await this.pod(this.target).list().then((Q)=>{this.names=Q}),J()}catch(Q){this.error=Q.fail?.reason??String(Q)}}field=(Y)=>this.renderRoot.querySelector(`[name=${Y}]`).value;render(){let Y=this.target;if(!Y)return d``;return d`<div class="col"><div class="row">
20
+ <label>cluster <input class="input" name="name" placeholder="name" value="example"></label>
21
+ <label>nodes <select class="input" name="size"><option>3</option><option>5</option></select></label>
22
+ <label title="seeds the election timeouts: the same seed replays the same election">seed <input class="input" name="seed" type="number" value="1"></label>
23
+ <label>heartbeat ms <input class="input" name="heartbeat" type="number" value="1000"></label>
24
+ <button class="btn" name="create" type="button" @click=${()=>void this.run(()=>this.pod(Y).create({name:this.field("name"),size:Number(this.field("size")),seed:Number(this.field("seed")),heartbeatMs:Number(this.field("heartbeat"))}),()=>{this.chosen=this.field("name")})}>Create</button>
25
+ <button class="btn" name="remove" type="button" @click=${()=>void this.run(()=>this.pod(Y).remove({name:this.field("name")}),()=>{if(this.chosen===this.field("name"))this.chosen=void 0})}>Remove</button></div>
26
+ ${this.error?d`<p class="alert bad" role="alert">${this.error}</p>`:""}
27
+ <ul>${this.names.map((J)=>d`<li><button class="btn" type="button" aria-pressed=${J===this.shown} @click=${()=>{this.chosen=J,this.renderRoot.querySelector("[name=name]").value=J}}>${J}</button></li>`)}</ul>
28
+ <raft-ring .target=${Y} .ids=${this.ids}></raft-ring><raft-log .target=${Y} .ids=${this.ids}></raft-log></div>`}}if(!customElements.get("raft-cluster"))customElements.define("raft-cluster",YJ);var vX=KQ.namespace("example.raft").provider([hY,o,m,yY]),bX={"example.raft/node":"raft-node","example.raft/ledger":"raft-ledger","example.raft/cluster":"raft-cluster"};export{bX as views,vX as default};
29
+
30
+ export const built = {"@pritzlaff/nano-core":"0.5.0"}
@@ -0,0 +1,74 @@
1
+ {
2
+ "pods": {
3
+ "cluster": {
4
+ "implementation": "example.raft/cluster",
5
+ "config": {
6
+ "timing": {
7
+ "electionMin": 3000,
8
+ "electionMax": 6000,
9
+ "heartbeat": 1000
10
+ }
11
+ },
12
+ "eager": false
13
+ },
14
+ "raft-messaging": {
15
+ "implementation": "example.raft/messaging",
16
+ "config": {
17
+ "minMs": 200,
18
+ "maxMs": 600
19
+ },
20
+ "eager": true
21
+ },
22
+ "raft-clock": {
23
+ "implementation": "nano.ui/sim-clock",
24
+ "eager": true
25
+ },
26
+ "raft-random": {
27
+ "implementation": "nano.ui/seeded-random",
28
+ "config": {
29
+ "seed": 1
30
+ },
31
+ "eager": true
32
+ }
33
+ },
34
+ "runtimes": {
35
+ "raft": {
36
+ "pods": [
37
+ "cluster",
38
+ "raft-messaging",
39
+ "raft-clock",
40
+ "raft-random"
41
+ ],
42
+ "subscriptions": [
43
+ {
44
+ "kind": "call",
45
+ "from": "raft-messaging",
46
+ "to": "raft-clock"
47
+ },
48
+ {
49
+ "kind": "call",
50
+ "from": "raft-messaging",
51
+ "to": "raft-random"
52
+ }
53
+ ]
54
+ }
55
+ },
56
+ "modules": {
57
+ "example.raft": "./example.raft.js"
58
+ },
59
+ "layout": {
60
+ "slots": [
61
+ {
62
+ "id": "cluster",
63
+ "runtime": "raft",
64
+ "pod": "cluster"
65
+ }
66
+ ],
67
+ "ring": {
68
+ "show": [
69
+ "example.raft/node",
70
+ "example.raft/messaging"
71
+ ]
72
+ }
73
+ }
74
+ }
@@ -0,0 +1,63 @@
1
+ {
2
+ "pods": {
3
+ "in": {
4
+ "implementation": "nano.ui/input",
5
+ "eager": true
6
+ },
7
+ "wait": {
8
+ "implementation": "nano.ui/debounce",
9
+ "config": {
10
+ "quietMs": 10
11
+ },
12
+ "eager": true
13
+ },
14
+ "up": {
15
+ "implementation": "nano.ui/map",
16
+ "config": {
17
+ "code": "return String(x).toUpperCase()"
18
+ },
19
+ "eager": false
20
+ },
21
+ "out": {
22
+ "implementation": "nano.ui/log",
23
+ "eager": false
24
+ }
25
+ },
26
+ "runtimes": {
27
+ "main": {
28
+ "pods": [
29
+ "in",
30
+ "wait",
31
+ "up",
32
+ "out"
33
+ ],
34
+ "subscriptions": [
35
+ {
36
+ "kind": "pipe",
37
+ "from": "in",
38
+ "source": "nano.ui.Input/submit",
39
+ "to": "wait",
40
+ "target": "nano.ui.Debounce/push"
41
+ },
42
+ {
43
+ "kind": "pipe",
44
+ "from": "wait",
45
+ "source": "nano.ui.Debounce/flushed",
46
+ "to": "up",
47
+ "target": "nano.ui.Map/map"
48
+ },
49
+ {
50
+ "kind": "pipe",
51
+ "from": "up",
52
+ "source": "nano.ui.Map/map",
53
+ "to": "out",
54
+ "target": "nano.ui.Log/log"
55
+ }
56
+ ]
57
+ }
58
+ },
59
+ "modules": {
60
+ "nano.ui": "../../bundle/nano-ui.js",
61
+ "example.slice": "./shout.js"
62
+ }
63
+ }
@@ -0,0 +1,14 @@
1
+ // ../../examples/slice/shout.ts
2
+ import { Coord, Implementation, provide, success } from "@pritzlaff/nano-core";
3
+ import { MapIface } from "@pritzlaff/nano-ui";
4
+ var ns = Coord.namespace("example.slice");
5
+ var shout = Implementation.define(ns.implementationId("shout"), {
6
+ provides: [MapIface],
7
+ make: () => [provide(MapIface, { map: async (x) => success(`${x}!`) })]
8
+ });
9
+ var shout_default = ns.provider([shout]);
10
+ var views = { "example.slice/shout": "nano-map" };
11
+ export {
12
+ views,
13
+ shout_default as default
14
+ };
@@ -0,0 +1,11 @@
1
+ import{Coord as Q}from"@pritzlaff/nano-core";import{Type as h}from"typebox";import{Coord as U}from"@pritzlaff/nano-core";import{Type as a}from"typebox";import{Coord as L,Schema as v,Op as n}from"@pritzlaff/nano-core";var k=L.namespace("acme.template"),V=a.Union([a.Literal("+"),a.Literal("-"),a.Literal("*"),a.Literal("/")]),M=v.define(a.Object({a:a.Number(),op:V,b:a.Number()}),"Sum"),f=v.define(a.Object({a:a.Number(),op:V,b:a.Number(),result:a.Number()}),"Calculated"),c=k.interface("Calculator",{calculate:n.action(M,f),calculated:n.event(f)}),w=k.interface("History",{save:n.action(f,a.Null()),load:n.action(a.Null(),a.Array(f))});var j=U.namespace("acme.template"),q=(t)=>Object.assign(Error(t),{fail:{type:"invalid-input",reason:t}}),_=c.impl(j.implementationId("calculator")).config(h.Union([h.Object({precision:h.Optional(h.Integer({minimum:0,maximum:15}))}),h.Undefined()])).make((t)=>({async calculate({a:i,op:e,b:r}){if(e==="/"&&r===0)throw q("division by zero");let m=e==="+"?i+r:e==="-"?i-r:e==="*"?i*r:i/r,u=t.config?.precision,p=u===void 0?m:Number(m.toFixed(u));return await t.publish(c.ops.calculated,{a:i,op:e,b:r,result:p}),{a:i,op:e,b:r,result:p}},async*calculated(){}}));import{html as d}from"lit";import{LitElement as B,html as E}from"lit";import{base as D,kit as F}from"@pritzlaff/nano-elements";class s extends B{static properties={target:{attribute:!1}};static styles=[D,F];off;watching;connectedCallback(){super.connectedCallback(),this.watch()}disconnectedCallback(){super.disconnectedCallback(),this.off?.(),this.off=this.watching=void 0}willUpdate(t){if(t.has("target"))this.watch()}watch(){let t=this.target;if(!t||!this.isConnected||this.watching===t)return;this.off?.(),this.watching=t,this.off=t.app.listen((i)=>this.hear(i,t)),this.started(t)}pod(t){return t.app.call(t.runtime,t.pod)}started(t){}hear(t,i){}face(t){return E``}render(){return this.target?this.face(this.target):E``}}var G=["+","-","*","/"];class g extends s{static properties={...s.properties,a:{state:!0},op:{state:!0},b:{state:!0},result:{state:!0},error:{state:!0},saved:{state:!0}};constructor(){super();this.a=this.b="",this.op="+",this.saved=[]}iter;disconnectedCallback(){super.disconnectedCallback(),this.end()}end(){this.iter?.return?.(),this.iter=void 0}async started(t){this.end(),this.load(t);let i=this.iter=t.app.runtime(t.runtime).get(c,{pod:t.pod}).calculated()[Symbol.asyncIterator]();try{while(!(await i.next()).done&&this.iter===i)await this.load(t)}catch{}}async load(t){try{this.saved=await t.app.runtime(t.runtime).get(w).load()}catch{this.saved=[]}}async equals(t){let i=await this.pod(t).calculate({a:Number(this.a),op:this.op,b:Number(this.b)});if(i.ok)this.result=i.value.result,this.error=void 0;else this.result=void 0,this.error=i.fail.reason}face(t){let i=(e)=>{if(e.key==="Enter")this.equals(t)};return d`<div class="row">
2
+ <input class="input" type="number" aria-label="a" .value=${this.a} @input=${(e)=>{this.a=e.target.value}} @keydown=${i}>
3
+ <select class="input" aria-label="operator" .value=${this.op} @change=${(e)=>{this.op=e.target.value}}>
4
+ ${G.map((e)=>d`<option value=${e} ?selected=${e===this.op}>${e}</option>`)}</select>
5
+ <input class="input" type="number" aria-label="b" .value=${this.b} @input=${(e)=>{this.b=e.target.value}} @keydown=${i}>
6
+ <button class="btn" aria-label="equals" @click=${()=>this.equals(t)}>=</button>
7
+ <output class="badge accent" aria-label="result">${this.result??""}</output></div>
8
+ ${this.error?d`<p class="alert bad" role="alert">${this.error}</p>`:""}
9
+ <ol aria-label="history">${this.saved.map((e)=>d`<li>${e.a} ${e.op} ${e.b} = ${e.result}</li>`)}</ol>`}}import{Coord as I}from"@pritzlaff/nano-core";var J=I.namespace("acme.template"),A="acme.template:history",N=()=>{try{return globalThis.localStorage??void 0}catch{return}},o=w.impl(J.implementationId("history")).make(()=>{let t=N(),i=[],e=()=>t?JSON.parse(t.getItem(A)??"[]"):i;return{async save(r){let m=[...e(),r];if(t)t.setItem(A,JSON.stringify(m));else i=m},async load(){return e()}}});var R=Q.namespace("acme.template"),rt=R.provider([_,o]),mt={"acme.template/calculator":"nano-calculator"};if(!customElements.get("nano-calculator"))customElements.define("nano-calculator",g);export{mt as views,rt as default};
10
+
11
+ export const built = {"@pritzlaff/nano-core":"0.5.0"}
@@ -0,0 +1,194 @@
1
+ // ../../templates/nano-template/src/index.ts
2
+ import { Coord as Coord4 } from "@pritzlaff/nano-core";
3
+
4
+ // ../../templates/nano-template/src/calculator.ts
5
+ import { Type as Type2 } from "typebox";
6
+ import { Coord as Coord2 } from "@pritzlaff/nano-core";
7
+
8
+ // ../../templates/nano-template/src/interfaces.ts
9
+ import { Type } from "typebox";
10
+ import { Coord, Schema, Op } from "@pritzlaff/nano-core";
11
+ var ns = Coord.namespace("acme.template");
12
+ var Operator = Type.Union([Type.Literal("+"), Type.Literal("-"), Type.Literal("*"), Type.Literal("/")]);
13
+ var Sum = Schema.define(Type.Object({ a: Type.Number(), op: Operator, b: Type.Number() }), "Sum");
14
+ var Calculated = Schema.define(Type.Object({ a: Type.Number(), op: Operator, b: Type.Number(), result: Type.Number() }), "Calculated");
15
+ var Calculator = ns.interface("Calculator", {
16
+ calculate: Op.action(Sum, Calculated),
17
+ calculated: Op.event(Calculated)
18
+ });
19
+ var History = ns.interface("History", {
20
+ save: Op.action(Calculated, Type.Null()),
21
+ load: Op.action(Type.Null(), Type.Array(Calculated))
22
+ });
23
+
24
+ // ../../templates/nano-template/src/calculator.ts
25
+ var ns2 = Coord2.namespace("acme.template");
26
+ var invalid = (reason) => Object.assign(new Error(reason), { fail: { type: "invalid-input", reason } });
27
+ var calculator = Calculator.impl(ns2.implementationId("calculator")).config(Type2.Union([Type2.Object({ precision: Type2.Optional(Type2.Integer({ minimum: 0, maximum: 15 })) }), Type2.Undefined()])).make((ctx) => ({
28
+ async calculate({ a, op, b }) {
29
+ if (op === "/" && b === 0)
30
+ throw invalid("division by zero");
31
+ const exact = op === "+" ? a + b : op === "-" ? a - b : op === "*" ? a * b : a / b;
32
+ const p = ctx.config?.precision;
33
+ const result = p === undefined ? exact : Number(exact.toFixed(p));
34
+ await ctx.publish(Calculator.ops.calculated, { a, op, b, result });
35
+ return { a, op, b, result };
36
+ },
37
+ async* calculated() {}
38
+ }));
39
+
40
+ // ../../templates/nano-template/src/calculator-view.ts
41
+ import { html as html2 } from "lit";
42
+
43
+ // ../../templates/nano-template/src/view.ts
44
+ import { LitElement, html } from "lit";
45
+ import { base, kit } from "@pritzlaff/nano-elements";
46
+
47
+ class View extends LitElement {
48
+ static properties = { target: { attribute: false } };
49
+ static styles = [base, kit];
50
+ off;
51
+ watching;
52
+ connectedCallback() {
53
+ super.connectedCallback();
54
+ this.watch();
55
+ }
56
+ disconnectedCallback() {
57
+ super.disconnectedCallback();
58
+ this.off?.();
59
+ this.off = this.watching = undefined;
60
+ }
61
+ willUpdate(changed) {
62
+ if (changed.has("target"))
63
+ this.watch();
64
+ }
65
+ watch() {
66
+ const t = this.target;
67
+ if (!t || !this.isConnected || this.watching === t)
68
+ return;
69
+ this.off?.();
70
+ this.watching = t;
71
+ this.off = t.app.listen((e) => this.hear(e, t));
72
+ this.started(t);
73
+ }
74
+ pod(t) {
75
+ return t.app.call(t.runtime, t.pod);
76
+ }
77
+ started(_t) {}
78
+ hear(_e, _t) {}
79
+ face(_t) {
80
+ return html``;
81
+ }
82
+ render() {
83
+ return this.target ? this.face(this.target) : html``;
84
+ }
85
+ }
86
+
87
+ // ../../templates/nano-template/src/calculator-view.ts
88
+ var OPS = ["+", "-", "*", "/"];
89
+
90
+ class CalculatorView extends View {
91
+ static properties = { ...View.properties, a: { state: true }, op: { state: true }, b: { state: true }, result: { state: true }, error: { state: true }, saved: { state: true } };
92
+ constructor() {
93
+ super();
94
+ this.a = this.b = "";
95
+ this.op = "+";
96
+ this.saved = [];
97
+ }
98
+ iter;
99
+ disconnectedCallback() {
100
+ super.disconnectedCallback();
101
+ this.end();
102
+ }
103
+ end() {
104
+ this.iter?.return?.();
105
+ this.iter = undefined;
106
+ }
107
+ async started(t) {
108
+ this.end();
109
+ this.load(t);
110
+ const it = this.iter = t.app.runtime(t.runtime).get(Calculator, { pod: t.pod }).calculated()[Symbol.asyncIterator]();
111
+ try {
112
+ while (!(await it.next()).done && this.iter === it)
113
+ await this.load(t);
114
+ } catch {}
115
+ }
116
+ async load(t) {
117
+ try {
118
+ this.saved = await t.app.runtime(t.runtime).get(History).load();
119
+ } catch {
120
+ this.saved = [];
121
+ }
122
+ }
123
+ async equals(t) {
124
+ const r = await this.pod(t).calculate({ a: Number(this.a), op: this.op, b: Number(this.b) });
125
+ if (r.ok) {
126
+ this.result = r.value.result;
127
+ this.error = undefined;
128
+ } else {
129
+ this.result = undefined;
130
+ this.error = r.fail.reason;
131
+ }
132
+ }
133
+ face(t) {
134
+ const enter = (e) => {
135
+ if (e.key === "Enter")
136
+ this.equals(t);
137
+ };
138
+ return html2`<div class="row">
139
+ <input class="input" type="number" aria-label="a" .value=${this.a} @input=${(e) => {
140
+ this.a = e.target.value;
141
+ }} @keydown=${enter}>
142
+ <select class="input" aria-label="operator" .value=${this.op} @change=${(e) => {
143
+ this.op = e.target.value;
144
+ }}>
145
+ ${OPS.map((o) => html2`<option value=${o} ?selected=${o === this.op}>${o}</option>`)}</select>
146
+ <input class="input" type="number" aria-label="b" .value=${this.b} @input=${(e) => {
147
+ this.b = e.target.value;
148
+ }} @keydown=${enter}>
149
+ <button class="btn" aria-label="equals" @click=${() => this.equals(t)}>=</button>
150
+ <output class="badge accent" aria-label="result">${this.result ?? ""}</output></div>
151
+ ${this.error ? html2`<p class="alert bad" role="alert">${this.error}</p>` : ""}
152
+ <ol aria-label="history">${this.saved.map((s) => html2`<li>${s.a} ${s.op} ${s.b} = ${s.result}</li>`)}</ol>`;
153
+ }
154
+ }
155
+
156
+ // ../../templates/nano-template/src/history.ts
157
+ import { Coord as Coord3 } from "@pritzlaff/nano-core";
158
+ var ns3 = Coord3.namespace("acme.template");
159
+ var KEY = "acme.template:history";
160
+ var local = () => {
161
+ try {
162
+ return globalThis.localStorage ?? undefined;
163
+ } catch {
164
+ return;
165
+ }
166
+ };
167
+ var history = History.impl(ns3.implementationId("history")).make(() => {
168
+ const ls = local();
169
+ let memory = [];
170
+ const load = () => ls ? JSON.parse(ls.getItem(KEY) ?? "[]") : memory;
171
+ return {
172
+ async save(c) {
173
+ const all = [...load(), c];
174
+ if (ls)
175
+ ls.setItem(KEY, JSON.stringify(all));
176
+ else
177
+ memory = all;
178
+ },
179
+ async load() {
180
+ return load();
181
+ }
182
+ };
183
+ });
184
+
185
+ // ../../templates/nano-template/src/index.ts
186
+ var ns4 = Coord4.namespace("acme.template");
187
+ var src_default = ns4.provider([calculator, history]);
188
+ var views = { "acme.template/calculator": "nano-calculator" };
189
+ if (!customElements.get("nano-calculator"))
190
+ customElements.define("nano-calculator", CalculatorView);
191
+ export {
192
+ views,
193
+ src_default as default
194
+ };
@@ -0,0 +1,32 @@
1
+ {
2
+ "pods": {
3
+ "calculator": {
4
+ "implementation": "acme.template/calculator",
5
+ "eager": false
6
+ },
7
+ "history": {
8
+ "implementation": "acme.template/history",
9
+ "eager": false
10
+ }
11
+ },
12
+ "runtimes": {
13
+ "main": {
14
+ "pods": [
15
+ "calculator",
16
+ "history"
17
+ ],
18
+ "subscriptions": [
19
+ {
20
+ "kind": "pipe",
21
+ "from": "calculator",
22
+ "source": "acme.template.Calculator/calculated",
23
+ "to": "history",
24
+ "target": "acme.template.History/save"
25
+ }
26
+ ]
27
+ }
28
+ },
29
+ "modules": {
30
+ "acme.template": "./acme.template.js"
31
+ }
32
+ }
@@ -0,0 +1,8 @@
1
+ import{LitElement as q,css as C,html as X}from"lit";import{base as E,kit as b}from"@pritzlaff/nano-elements";import{Type as H}from"typebox";import{Coord as k,Op as R,Schema as $}from"@pritzlaff/nano-core";var N;((J)=>(J.ns=k.namespace("example.todo"),J.Todo=$.define(H.Object({id:H.String(),title:H.String(),done:H.Boolean()})),J.Change=$.define(H.Object({id:H.String(),title:H.Optional(H.String()),done:H.Optional(H.Boolean())})),J.api=J.ns.interface("TodoList",{add:R.action(H.String(),J.Todo),list:R.action(H.Null(),H.Array(J.Todo)),update:R.action(J.Change,H.Union([J.Todo,H.Null()])),put:R.action(J.Todo,J.Todo),remove:R.action(H.String(),H.Boolean()),items:R.event(J.Todo)})))(N||={});class Z extends q{static properties={target:{attribute:!1},todos:{state:!0},error:{state:!0}};static styles=[E,b,C`ul { list-style: none; margin: 0; padding: 0 } li > span { flex: 1 } [role='alert'] { margin: 0 }`];watching;iter;constructor(){super();this.todos=[]}connectedCallback(){super.connectedCallback(),this.watch()}disconnectedCallback(){super.disconnectedCallback(),this.stop()}willUpdate(j){if(j.has("target"))this.watch()}stop(){this.iter?.return?.(),this.iter=this.watching=void 0}pod(j){return j.app.runtime(j.runtime).get(N.api,{pod:j.pod})}async watch(){let j=this.target;if(!j||!this.isConnected||this.watching===j)return;this.stop(),this.watching=j,this.error=void 0;let B=this.pod(j),w=this.iter=B.items()[Symbol.asyncIterator]();try{let A=await B.list();if(this.iter!==w)return;this.todos=A;while(!(await w.next()).done&&this.iter===w){let G=await B.list();if(this.iter===w)this.todos=G}}catch(A){if(this.iter===w)this.error=String(A)}}async add(j,B){let w=B.value.trim();if(!w)return;B.value="",await this.pod(j).add(w).catch((A)=>{this.error=String(A)})}run(j){j.catch((B)=>{this.error=String(B)})}render(){let j=this.target;if(!j)return X``;let B=this.pod(j);return X`<div class="col">${this.error?X`<p class="alert bad" role="alert">${this.error}</p>`:""}<div class="row">
2
+ <input class="input" aria-label="New todo" placeholder="What needs doing?" @keydown=${(w)=>{if(w.key==="Enter"&&!w.isComposing)this.add(j,w.target)}}><button class="btn" type="button" @click=${()=>void this.add(j,this.renderRoot.querySelector("input"))}>Add</button></div>
3
+ <ul>${this.todos.map((w)=>X`<li class="list-row">
4
+ <input type="checkbox" aria-label="Done: ${w.title}" .checked=${w.done} @change=${(A)=>this.run(B.update({id:w.id,done:A.target.checked}))}>
5
+ <span>${w.title}</span>
6
+ <button class="btn small" aria-label="Remove ${w.title}" @click=${()=>this.run(B.remove(w.id))}>×</button></li>`)}</ul></div>`}}import{Implementation as z}from"@pritzlaff/nano-core";import{Type as M}from"typebox";import{Coord as v,Op as Y,Schema as _}from"@pritzlaff/nano-core";var U;((F)=>(F.ns=v.namespace("example.kv"),F.Path=_.define(M.Array(M.String())),F.Value=_.define(M.Unsafe(M.Unknown())),F.Entry=_.define(M.Object({key:F.Path,value:F.Value})),F.api=F.ns.interface("KeyValueStore",{get:Y.action(F.Path,F.Value),put:Y.action(F.Entry,M.Null()),delete:Y.action(F.Path,M.Null()),list:Y.action(M.Object({prefix:F.Path}),M.Array(F.Entry))})))(U||={});var Q=U.api.ops,W=(j)=>["todos",j],I=0,P=()=>`${Date.now().toString(36).padStart(9,"0")}${(I++%1679616).toString(36).padStart(4,"0")}-${crypto.randomUUID().slice(0,8)}`;function g(j,B=P){return{async add(w){let A={id:B(),title:w,done:!1};return await j.put({key:W(A.id),value:A}),A},async list(){return(await j.list({prefix:["todos"]})).map((w)=>w.value)},async put(w){return await j.put({key:W(w.id),value:w}),w},async update(w){let A=await j.get(W(w.id));if(!A)return null;let G={...A,...w.title!==void 0&&{title:w.title},...w.done!==void 0&&{done:w.done}};return await j.put({key:W(w.id),value:G}),G},async remove(w){if(await j.get(W(w))===null)return!1;return await j.delete(W(w)),!0}}}var m=z.define(N.ns.implementationId("kv"),{provides:[N.api],description:"Todos kept in whichever KeyValueStore its call edge reaches.",dependencies:{store:U.api},calls:{add:{store:[Q.put]},list:{store:[Q.list]},put:{store:[Q.put]},update:{store:[Q.get,Q.put]},remove:{store:[Q.get,Q.delete]}},make:(j)=>{let B=setInterval(()=>{j.deps.store.list({prefix:["todos"]}).catch(()=>{})},1000);j.addOnCloseListener(()=>clearInterval(B));let w=(A)=>g(A.deps.store);return{add:(A,G)=>w(G).add(A),list:(A,G)=>w(G).list(),put:(A,G)=>w(G).put(A),update:(A,G)=>w(G).update(A),remove:(A,G)=>w(G).remove(A),async*items(){let A=j.one(U.api);if(A.ok){for await(let{input:G}of A.value.on(U.api.ops.put))if(G.key[0]==="todos")yield G.value}}}}}),L=N.ns.provider([m]);var p={"example.todo/kv":"todo-list"};if(!customElements.get("todo-list"))customElements.define("todo-list",Z);export{p as views,L as default};
7
+
8
+ export const built = {"@pritzlaff/nano-core":"0.5.0"}
@@ -0,0 +1,77 @@
1
+ {
2
+ "pods": {
3
+ "todoStore": {
4
+ "implementation": "example.kv/memory",
5
+ "eager": false
6
+ },
7
+ "todos": {
8
+ "implementation": "example.todo/kv",
9
+ "eager": false
10
+ }
11
+ },
12
+ "runtimes": {
13
+ "example.todo.frontend": {
14
+ "pods": [
15
+ "todos"
16
+ ],
17
+ "subscriptions": []
18
+ },
19
+ "example.todo.backend": {
20
+ "pods": [
21
+ "todoStore"
22
+ ],
23
+ "subscriptions": [
24
+ {
25
+ "kind": "call",
26
+ "from": "todos",
27
+ "to": "todoStore"
28
+ }
29
+ ],
30
+ "policy": {
31
+ "kind": "rules",
32
+ "rules": [
33
+ {
34
+ "allow": [
35
+ "call",
36
+ "subscribe"
37
+ ],
38
+ "from": "todos",
39
+ "outside": true,
40
+ "toInterface": "example.kv.KeyValueStore"
41
+ },
42
+ {
43
+ "allow": "subscribe",
44
+ "from": "host",
45
+ "outside": true,
46
+ "toInterface": "example.kv.KeyValueStore"
47
+ },
48
+ {
49
+ "allow": "*",
50
+ "outside": false
51
+ },
52
+ {
53
+ "allow": "start",
54
+ "from": "host",
55
+ "outside": true
56
+ },
57
+ {
58
+ "deny": "*"
59
+ }
60
+ ]
61
+ }
62
+ }
63
+ },
64
+ "modules": {
65
+ "example.todo": "./example.todo.js",
66
+ "example.kv": "../kv/example.kv.js"
67
+ },
68
+ "layout": {
69
+ "slots": [
70
+ {
71
+ "id": "todos",
72
+ "runtime": "example.todo.frontend",
73
+ "pod": "todos"
74
+ }
75
+ ]
76
+ }
77
+ }