kuriko 0.5.0 → 0.7.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/kuriko.mjs +3 -3
- package/package.json +1 -1
package/kuriko.mjs
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
import { createRequire as __kurikoRequire } from "node:module"; const require = __kurikoRequire(import.meta.url);
|
|
3
|
-
var kf=Object.create;var jo=Object.defineProperty;var $f=Object.getOwnPropertyDescriptor;var Sf=Object.getOwnPropertyNames;var vf=Object.getPrototypeOf,Af=Object.prototype.hasOwnProperty;var jn=(t=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(t,{get:(e,n)=>(typeof require<"u"?require:e)[n]}):t)(function(t){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+t+'" is not supported')});var Ef=(t,e,n)=>()=>{if(n)throw n[0];try{return t&&(e=t(t=0)),e}catch(s){throw n=[s],s}};var E=(t,e)=>()=>{try{return e||t((e={exports:{}}).exports,e),e.exports}catch(n){throw e=0,n}};var _f=(t,e,n,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of Sf(e))!Af.call(t,r)&&r!==n&&jo(t,r,{get:()=>e[r],enumerable:!(s=$f(e,r))||s.enumerable});return t};var Cf=(t,e,n)=>(n=t!=null?kf(vf(t)):{},_f(e||!t||!t.__esModule?jo(n,"default",{value:t,enumerable:!0}):n,t));var w,p=Ef(()=>{w={version:"0.
|
|
3
|
+
var kf=Object.create;var jo=Object.defineProperty;var $f=Object.getOwnPropertyDescriptor;var Sf=Object.getOwnPropertyNames;var vf=Object.getPrototypeOf,Af=Object.prototype.hasOwnProperty;var jn=(t=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(t,{get:(e,n)=>(typeof require<"u"?require:e)[n]}):t)(function(t){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+t+'" is not supported')});var Ef=(t,e,n)=>()=>{if(n)throw n[0];try{return t&&(e=t(t=0)),e}catch(s){throw n=[s],s}};var E=(t,e)=>()=>{try{return e||t((e={exports:{}}).exports,e),e.exports}catch(n){throw e=0,n}};var _f=(t,e,n,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of Sf(e))!Af.call(t,r)&&r!==n&&jo(t,r,{get:()=>e[r],enumerable:!(s=$f(e,r))||s.enumerable});return t};var Cf=(t,e,n)=>(n=t!=null?kf(vf(t)):{},_f(e||!t||!t.__esModule?jo(n,"default",{value:t,enumerable:!0}):n,t));var w,p=Ef(()=>{w={version:"0.7.0"}});var B=E(Z=>{"use strict";p();var kr=Symbol.for("yaml.alias"),Ho=Symbol.for("yaml.document"),Dn=Symbol.for("yaml.map"),Qo=Symbol.for("yaml.pair"),$r=Symbol.for("yaml.scalar"),Bn=Symbol.for("yaml.seq"),ve=Symbol.for("yaml.node.type"),Xf=t=>!!t&&typeof t=="object"&&t[ve]===kr,ed=t=>!!t&&typeof t=="object"&&t[ve]===Ho,td=t=>!!t&&typeof t=="object"&&t[ve]===Dn,nd=t=>!!t&&typeof t=="object"&&t[ve]===Qo,Zo=t=>!!t&&typeof t=="object"&&t[ve]===$r,sd=t=>!!t&&typeof t=="object"&&t[ve]===Bn;function Xo(t){if(t&&typeof t=="object")switch(t[ve]){case Dn:case Bn:return!0}return!1}function rd(t){if(t&&typeof t=="object")switch(t[ve]){case kr:case Dn:case $r:case Bn:return!0}return!1}var id=t=>(Zo(t)||Xo(t))&&!!t.anchor;Z.ALIAS=kr;Z.DOC=Ho;Z.MAP=Dn;Z.NODE_TYPE=ve;Z.PAIR=Qo;Z.SCALAR=$r;Z.SEQ=Bn;Z.hasAnchor=id;Z.isAlias=Xf;Z.isCollection=Xo;Z.isDocument=ed;Z.isMap=td;Z.isNode=rd;Z.isPair=nd;Z.isScalar=Zo;Z.isSeq=sd});var Dt=E(Sr=>{"use strict";p();var J=B(),re=Symbol("break visit"),ea=Symbol("skip children"),ye=Symbol("remove node");function Un(t,e){let n=ta(e);J.isDocument(t)?lt(null,t.contents,n,Object.freeze([t]))===ye&&(t.contents=null):lt(null,t,n,Object.freeze([]))}Un.BREAK=re;Un.SKIP=ea;Un.REMOVE=ye;function lt(t,e,n,s){let r=na(t,e,n,s);if(J.isNode(r)||J.isPair(r))return sa(t,s,r),lt(t,r,n,s);if(typeof r!="symbol"){if(J.isCollection(e)){s=Object.freeze(s.concat(e));for(let i=0;i<e.items.length;++i){let o=lt(i,e.items[i],n,s);if(typeof o=="number")i=o-1;else{if(o===re)return re;o===ye&&(e.items.splice(i,1),i-=1)}}}else if(J.isPair(e)){s=Object.freeze(s.concat(e));let i=lt("key",e.key,n,s);if(i===re)return re;i===ye&&(e.key=null);let o=lt("value",e.value,n,s);if(o===re)return re;o===ye&&(e.value=null)}}return r}async function Gn(t,e){let n=ta(e);J.isDocument(t)?await ut(null,t.contents,n,Object.freeze([t]))===ye&&(t.contents=null):await ut(null,t,n,Object.freeze([]))}Gn.BREAK=re;Gn.SKIP=ea;Gn.REMOVE=ye;async function ut(t,e,n,s){let r=await na(t,e,n,s);if(J.isNode(r)||J.isPair(r))return sa(t,s,r),ut(t,r,n,s);if(typeof r!="symbol"){if(J.isCollection(e)){s=Object.freeze(s.concat(e));for(let i=0;i<e.items.length;++i){let o=await ut(i,e.items[i],n,s);if(typeof o=="number")i=o-1;else{if(o===re)return re;o===ye&&(e.items.splice(i,1),i-=1)}}}else if(J.isPair(e)){s=Object.freeze(s.concat(e));let i=await ut("key",e.key,n,s);if(i===re)return re;i===ye&&(e.key=null);let o=await ut("value",e.value,n,s);if(o===re)return re;o===ye&&(e.value=null)}}return r}function ta(t){return typeof t=="object"&&(t.Collection||t.Node||t.Value)?Object.assign({Alias:t.Node,Map:t.Node,Scalar:t.Node,Seq:t.Node},t.Value&&{Map:t.Value,Scalar:t.Value,Seq:t.Value},t.Collection&&{Map:t.Collection,Seq:t.Collection},t):t}function na(t,e,n,s){if(typeof n=="function")return n(t,e,s);if(J.isMap(e))return n.Map?.(t,e,s);if(J.isSeq(e))return n.Seq?.(t,e,s);if(J.isPair(e))return n.Pair?.(t,e,s);if(J.isScalar(e))return n.Scalar?.(t,e,s);if(J.isAlias(e))return n.Alias?.(t,e,s)}function sa(t,e,n){let s=e[e.length-1];if(J.isCollection(s))s.items[t]=n;else if(J.isPair(s))t==="key"?s.key=n:s.value=n;else if(J.isDocument(s))s.contents=n;else{let r=J.isAlias(s)?"alias":"scalar";throw new Error(`Cannot replace node with ${r} parent`)}}Sr.visit=Un;Sr.visitAsync=Gn});var vr=E(ia=>{"use strict";p();var ra=B(),od=Dt(),ad={"!":"%21",",":"%2C","[":"%5B","]":"%5D","{":"%7B","}":"%7D"},cd=t=>t.replace(/[!,[\]{}]/g,e=>ad[e]),Bt=class t{constructor(e,n){this.docStart=null,this.docEnd=!1,this.yaml=Object.assign({},t.defaultYaml,e),this.tags=Object.assign({},t.defaultTags,n)}clone(){let e=new t(this.yaml,this.tags);return e.docStart=this.docStart,e}atDocument(){let e=new t(this.yaml,this.tags);switch(this.yaml.version){case"1.1":this.atNextDocument=!0;break;case"1.2":this.atNextDocument=!1,this.yaml={explicit:t.defaultYaml.explicit,version:"1.2"},this.tags=Object.assign({},t.defaultTags);break}return e}add(e,n){this.atNextDocument&&(this.yaml={explicit:t.defaultYaml.explicit,version:"1.1"},this.tags=Object.assign({},t.defaultTags),this.atNextDocument=!1);let s=e.trim().split(/[ \t]+/),r=s.shift();switch(r){case"%TAG":{if(s.length!==2&&(n(0,"%TAG directive should contain exactly two parts"),s.length<2))return!1;let[i,o]=s;return this.tags[i]=o,!0}case"%YAML":{if(this.yaml.explicit=!0,s.length!==1)return n(0,"%YAML directive should contain exactly one part"),!1;let[i]=s;if(i==="1.1"||i==="1.2")return this.yaml.version=i,!0;{let o=/^\d+\.\d+$/.test(i);return n(6,`Unsupported YAML version ${i}`,o),!1}}default:return n(0,`Unknown directive ${r}`,!0),!1}}tagName(e,n){if(e==="!")return"!";if(e[0]!=="!")return n(`Not a valid tag: ${e}`),null;if(e[1]==="<"){let o=e.slice(2,-1);return o==="!"||o==="!!"?(n(`Verbatim tags aren't resolved, so ${e} is invalid.`),null):(e[e.length-1]!==">"&&n("Verbatim tags must end with a >"),o)}let[,s,r]=e.match(/^(.*!)([^!]*)$/s);r||n(`The ${e} tag has no suffix`);let i=this.tags[s];if(i)try{return i+decodeURIComponent(r)}catch(o){return n(String(o)),null}return s==="!"?e:(n(`Could not resolve tag: ${e}`),null)}tagString(e){for(let[n,s]of Object.entries(this.tags))if(e.startsWith(s))return n+cd(e.substring(s.length));return e[0]==="!"?e:`!<${e}>`}toString(e){let n=this.yaml.explicit?[`%YAML ${this.yaml.version||"1.2"}`]:[],s=Object.entries(this.tags),r;if(e&&s.length>0&&ra.isNode(e.contents)){let i={};od.visit(e.contents,(o,a)=>{ra.isNode(a)&&a.tag&&(i[a.tag]=!0)}),r=Object.keys(i)}else r=[];for(let[i,o]of s)i==="!!"&&o==="tag:yaml.org,2002:"||(!e||r.some(a=>a.startsWith(o)))&&n.push(`%TAG ${i} ${o}`);return n.join(`
|
|
4
4
|
`)}};Bt.defaultYaml={explicit:!1,version:"1.2"};Bt.defaultTags={"!!":"tag:yaml.org,2002:"};ia.Directives=Bt});var Fn=E(Ut=>{"use strict";p();var oa=B(),ld=Dt();function ud(t){if(/[\x00-\x19\s,[\]{}]/.test(t)){let n=`Anchor must not contain whitespace or control characters: ${JSON.stringify(t)}`;throw new Error(n)}return!0}function aa(t){let e=new Set;return ld.visit(t,{Value(n,s){s.anchor&&e.add(s.anchor)}}),e}function ca(t,e){for(let n=1;;++n){let s=`${t}${n}`;if(!e.has(s))return s}}function fd(t,e){let n=[],s=new Map,r=null;return{onAnchor:i=>{n.push(i),r??(r=aa(t));let o=ca(e,r);return r.add(o),o},setAnchors:()=>{for(let i of n){let o=s.get(i);if(typeof o=="object"&&o.anchor&&(oa.isScalar(o.node)||oa.isCollection(o.node)))o.node.anchor=o.anchor;else{let a=new Error("Failed to resolve repeated object (this should not happen)");throw a.source=i,a}}},sourceObjects:s}}Ut.anchorIsValid=ud;Ut.anchorNames=aa;Ut.createNodeAnchors=fd;Ut.findNewAnchor=ca});var Ar=E(la=>{"use strict";p();function Gt(t,e,n,s){if(s&&typeof s=="object")if(Array.isArray(s))for(let r=0,i=s.length;r<i;++r){let o=s[r],a=Gt(t,s,String(r),o);a===void 0?delete s[r]:a!==o&&(s[r]=a)}else if(s instanceof Map)for(let r of Array.from(s.keys())){let i=s.get(r),o=Gt(t,s,r,i);o===void 0?s.delete(r):o!==i&&s.set(r,o)}else if(s instanceof Set)for(let r of Array.from(s)){let i=Gt(t,s,r,r);i===void 0?s.delete(r):i!==r&&(s.delete(r),s.add(i))}else for(let[r,i]of Object.entries(s)){let o=Gt(t,s,r,i);o===void 0?delete s[r]:o!==i&&(s[r]=o)}return t.call(e,n,s)}la.applyReviver=Gt});var Pe=E(fa=>{"use strict";p();var dd=B();function ua(t,e,n){if(Array.isArray(t))return t.map((s,r)=>ua(s,String(r),n));if(t&&typeof t.toJSON=="function"){if(!n||!dd.hasAnchor(t))return t.toJSON(e,n);let s={aliasCount:0,count:1,res:void 0};n.anchors.set(t,s),n.onCreate=i=>{s.res=i,delete n.onCreate};let r=t.toJSON(e,n);return n.onCreate&&n.onCreate(r),r}return typeof t=="bigint"&&!n?.keep?Number(t):t}fa.toJS=ua});var Wn=E(pa=>{"use strict";p();var pd=Ar(),da=B(),hd=Pe(),Er=class{constructor(e){Object.defineProperty(this,da.NODE_TYPE,{value:e})}clone(){let e=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return this.range&&(e.range=this.range.slice()),e}toJS(e,{mapAsMap:n,maxAliasCount:s,onAnchor:r,reviver:i}={}){if(!da.isDocument(e))throw new TypeError("A document argument is required");let o={anchors:new Map,doc:e,keep:!0,mapAsMap:n===!0,mapKeyWarned:!1,maxAliasCount:typeof s=="number"?s:100},a=hd.toJS(this,"",o);if(typeof r=="function")for(let{count:c,res:l}of o.anchors.values())r(l,c);return typeof i=="function"?pd.applyReviver(i,{"":a},"",a):a}};pa.NodeBase=Er});var Ft=E(ha=>{"use strict";p();var gd=Fn(),md=Dt(),ft=B(),yd=Wn(),wd=Pe(),_r=class extends yd.NodeBase{constructor(e){super(ft.ALIAS),this.source=e,Object.defineProperty(this,"tag",{set(){throw new Error("Alias nodes cannot have tags")}})}resolve(e,n){let s;n?.aliasResolveCache?s=n.aliasResolveCache:(s=[],md.visit(e,{Node:(i,o)=>{(ft.isAlias(o)||ft.hasAnchor(o))&&s.push(o)}}),n&&(n.aliasResolveCache=s));let r;for(let i of s){if(i===this)break;i.anchor===this.source&&(r=i)}return r}toJSON(e,n){if(!n)return{source:this.source};let{anchors:s,doc:r,maxAliasCount:i}=n,o=this.resolve(r,n);if(!o){let c=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw new ReferenceError(c)}let a=s.get(o);if(a||(wd.toJS(o,null,n),a=s.get(o)),!a||a.res===void 0){let c="This should not happen: Alias anchor was not resolved?";throw new ReferenceError(c)}if(i>=0&&(a.count+=1,a.aliasCount===0&&(a.aliasCount=Yn(r,o,s)),a.count*a.aliasCount>i)){let c="Excessive alias count indicates a resource exhaustion attack";throw new ReferenceError(c)}return a.res}toString(e,n,s){let r=`*${this.source}`;if(e){if(gd.anchorIsValid(this.source),e.options.verifyAliasOrder&&!e.anchors.has(this.source)){let i=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw new Error(i)}if(e.implicitKey)return`${r} `}return r}};function Yn(t,e,n){if(ft.isAlias(e)){let s=e.resolve(t),r=n&&s&&n.get(s);return r?r.count*r.aliasCount:0}else if(ft.isCollection(e)){let s=0;for(let r of e.items){let i=Yn(t,r,n);i>s&&(s=i)}return s}else if(ft.isPair(e)){let s=Yn(t,e.key,n),r=Yn(t,e.value,n);return Math.max(s,r)}return 1}ha.Alias=_r});var Y=E(Cr=>{"use strict";p();var bd=B(),kd=Wn(),$d=Pe(),Sd=t=>!t||typeof t!="function"&&typeof t!="object",je=class extends kd.NodeBase{constructor(e){super(bd.SCALAR),this.value=e}toJSON(e,n){return n?.keep?this.value:$d.toJS(this.value,e,n)}toString(){return String(this.value)}};je.BLOCK_FOLDED="BLOCK_FOLDED";je.BLOCK_LITERAL="BLOCK_LITERAL";je.PLAIN="PLAIN";je.QUOTE_DOUBLE="QUOTE_DOUBLE";je.QUOTE_SINGLE="QUOTE_SINGLE";Cr.Scalar=je;Cr.isScalarValue=Sd});var Wt=E(ma=>{"use strict";p();var vd=Ft(),Qe=B(),ga=Y(),Ad="tag:yaml.org,2002:";function Ed(t,e,n){if(e){let s=n.filter(i=>i.tag===e),r=s.find(i=>!i.format)??s[0];if(!r)throw new Error(`Tag ${e} not found`);return r}return n.find(s=>s.identify?.(t)&&!s.format)}function _d(t,e,n){if(Qe.isDocument(t)&&(t=t.contents),Qe.isNode(t))return t;if(Qe.isPair(t)){let u=n.schema[Qe.MAP].createNode?.(n.schema,null,n);return u.items.push(t),u}(t instanceof String||t instanceof Number||t instanceof Boolean||typeof BigInt<"u"&&t instanceof BigInt)&&(t=t.valueOf());let{aliasDuplicateObjects:s,onAnchor:r,onTagObj:i,schema:o,sourceObjects:a}=n,c;if(s&&t&&typeof t=="object"){if(c=a.get(t),c)return c.anchor??(c.anchor=r(t)),new vd.Alias(c.anchor);c={anchor:null,node:null},a.set(t,c)}e?.startsWith("!!")&&(e=Ad+e.slice(2));let l=Ed(t,e,o.tags);if(!l){if(t&&typeof t.toJSON=="function"&&(t=t.toJSON()),!t||typeof t!="object"){let u=new ga.Scalar(t);return c&&(c.node=u),u}l=t instanceof Map?o[Qe.MAP]:Symbol.iterator in Object(t)?o[Qe.SEQ]:o[Qe.MAP]}i&&(i(l),delete n.onTagObj);let h=l?.createNode?l.createNode(n.schema,t,n):typeof l?.nodeClass?.from=="function"?l.nodeClass.from(n.schema,t,n):new ga.Scalar(t);return e?h.tag=e:l.default||(h.tag=l.tag),c&&(c.node=h),h}ma.createNode=_d});var Jn=E(Vn=>{"use strict";p();var Cd=Wt(),we=B(),Nd=Wn();function Nr(t,e,n){let s=n;for(let r=e.length-1;r>=0;--r){let i=e[r];if(typeof i=="number"&&Number.isInteger(i)&&i>=0){let o=[];o[i]=s,s=o}else s=new Map([[i,s]])}return Cd.createNode(s,void 0,{aliasDuplicateObjects:!1,keepUndefined:!1,onAnchor:()=>{throw new Error("This should not happen, please report a bug.")},schema:t,sourceObjects:new Map})}var ya=t=>t==null||typeof t=="object"&&!!t[Symbol.iterator]().next().done,Tr=class extends Nd.NodeBase{constructor(e,n){super(e),Object.defineProperty(this,"schema",{value:n,configurable:!0,enumerable:!1,writable:!0})}clone(e){let n=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return e&&(n.schema=e),n.items=n.items.map(s=>we.isNode(s)||we.isPair(s)?s.clone(e):s),this.range&&(n.range=this.range.slice()),n}addIn(e,n){if(ya(e))this.add(n);else{let[s,...r]=e,i=this.get(s,!0);if(we.isCollection(i))i.addIn(r,n);else if(i===void 0&&this.schema)this.set(s,Nr(this.schema,r,n));else throw new Error(`Expected YAML collection at ${s}. Remaining path: ${r}`)}}deleteIn(e){let[n,...s]=e;if(s.length===0)return this.delete(n);let r=this.get(n,!0);if(we.isCollection(r))return r.deleteIn(s);throw new Error(`Expected YAML collection at ${n}. Remaining path: ${s}`)}getIn(e,n){let[s,...r]=e,i=this.get(s,!0);return r.length===0?!n&&we.isScalar(i)?i.value:i:we.isCollection(i)?i.getIn(r,n):void 0}hasAllNullValues(e){return this.items.every(n=>{if(!we.isPair(n))return!1;let s=n.value;return s==null||e&&we.isScalar(s)&&s.value==null&&!s.commentBefore&&!s.comment&&!s.tag})}hasIn(e){let[n,...s]=e;if(s.length===0)return this.has(n);let r=this.get(n,!0);return we.isCollection(r)?r.hasIn(s):!1}setIn(e,n){let[s,...r]=e;if(r.length===0)this.set(s,n);else{let i=this.get(s,!0);if(we.isCollection(i))i.setIn(r,n);else if(i===void 0&&this.schema)this.set(s,Nr(this.schema,r,n));else throw new Error(`Expected YAML collection at ${s}. Remaining path: ${r}`)}}};Vn.Collection=Tr;Vn.collectionFromPath=Nr;Vn.isEmptyPath=ya});var Yt=E(zn=>{"use strict";p();var Td=t=>t.replace(/^(?!$)(?: $)?/gm,"#");function Or(t,e){return/^\n+$/.test(t)?t.substring(1):e?t.replace(/^(?! *$)/gm,e):t}var Od=(t,e,n)=>t.endsWith(`
|
|
5
5
|
`)?Or(n,e):n.includes(`
|
|
6
6
|
`)?`
|
|
@@ -140,7 +140,7 @@ ${n.comment}`:n.comment}this.doc.range[2]=n.offset;break}default:this.errors.pus
|
|
|
140
140
|
`)+1;for(;n!==0;)this.onNewLine(this.offset+n),n=this.source.indexOf(`
|
|
141
141
|
`,n)+1}return{type:e,offset:this.offset,indent:this.indent,source:this.source}}startBlockValue(e){switch(this.type){case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return this.flowScalar(this.type);case"block-scalar-header":return{type:"block-scalar",offset:this.offset,indent:this.indent,props:[this.sourceToken],source:""};case"flow-map-start":case"flow-seq-start":return{type:"flow-collection",offset:this.offset,indent:this.indent,start:this.sourceToken,items:[],end:[]};case"seq-item-ind":return{type:"block-seq",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken]}]};case"explicit-key-ind":{this.onKeyLine=!0;let n=Rs(e),s=bt(n);return s.push(this.sourceToken),{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:s,explicitKey:!0}]}}case"map-value-ind":{this.onKeyLine=!0;let n=Rs(e),s=bt(n);return{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:s,key:null,sep:[this.sourceToken]}]}}}return null}atIndentedComment(e,n){return this.type!=="comment"||this.indent<=n?!1:e.every(s=>s.type==="newline"||s.type==="space")}*documentEnd(e){this.type!=="doc-mode"&&(e.end?e.end.push(this.sourceToken):e.end=[this.sourceToken],this.type==="newline"&&(yield*this.pop()))}*lineEnd(e){switch(this.type){case"comma":case"doc-start":case"doc-end":case"flow-seq-end":case"flow-map-end":case"map-value-ind":yield*this.pop(),yield*this.step();break;case"newline":this.onKeyLine=!1;default:e.end?e.end.push(this.sourceToken):e.end=[this.sourceToken],this.type==="newline"&&(yield*this.pop())}}};Ol.Parser=Qi});var Ll=E(yn=>{"use strict";p();var Il=Mi(),am=cn(),mn=fn(),cm=xr(),lm=B(),um=Hi(),Pl=Zi();function jl(t){let e=t.prettyErrors!==!1;return{lineCounter:t.lineCounter||e&&new um.LineCounter||null,prettyErrors:e}}function fm(t,e={}){let{lineCounter:n,prettyErrors:s}=jl(e),r=new Pl.Parser(n?.addNewLine),i=new Il.Composer(e),o=Array.from(i.compose(r.parse(t)));if(s&&n)for(let a of o)a.errors.forEach(mn.prettifyError(t,n)),a.warnings.forEach(mn.prettifyError(t,n));return o.length>0?o:Object.assign([],{empty:!0},i.streamInfo())}function Rl(t,e={}){let{lineCounter:n,prettyErrors:s}=jl(e),r=new Pl.Parser(n?.addNewLine),i=new Il.Composer(e),o=null;for(let a of i.compose(r.parse(t),!0,t.length))if(!o)o=a;else if(o.options.logLevel!=="silent"){o.errors.push(new mn.YAMLParseError(a.range.slice(0,2),"MULTIPLE_DOCS","Source contains multiple documents; please use YAML.parseAllDocuments()"));break}return s&&n&&(o.errors.forEach(mn.prettifyError(t,n)),o.warnings.forEach(mn.prettifyError(t,n))),o}function dm(t,e,n){let s;typeof e=="function"?s=e:n===void 0&&e&&typeof e=="object"&&(n=e);let r=Rl(t,n);if(!r)return null;if(r.warnings.forEach(i=>cm.warn(r.options.logLevel,i)),r.errors.length>0){if(r.options.logLevel!=="silent")throw r.errors[0];r.errors=[]}return r.toJS(Object.assign({reviver:s},n))}function pm(t,e,n){let s=null;if(typeof e=="function"||Array.isArray(e)?s=e:n===void 0&&e&&(n=e),typeof n=="string"&&(n=n.length),typeof n=="number"){let r=Math.round(n);n=r<1?void 0:r>8?{indent:8}:{indent:r}}if(t===void 0){let{keepUndefined:r}=n??e??{};if(!r)return}return lm.isDocument(t)&&!s?t.toString(n):new am.Document(t,s,n).toString(n)}yn.parse=dm;yn.parseAllDocuments=fm;yn.parseDocument=Rl;yn.stringify=pm});var ql=E(G=>{"use strict";p();var hm=Mi(),gm=cn(),mm=wi(),Xi=fn(),ym=Ft(),Be=B(),wm=xe(),bm=Y(),km=Me(),$m=Ke(),Sm=Ps(),vm=Ji(),Am=Hi(),Em=Zi(),Ls=Ll(),xl=Dt();G.Composer=hm.Composer;G.Document=gm.Document;G.Schema=mm.Schema;G.YAMLError=Xi.YAMLError;G.YAMLParseError=Xi.YAMLParseError;G.YAMLWarning=Xi.YAMLWarning;G.Alias=ym.Alias;G.isAlias=Be.isAlias;G.isCollection=Be.isCollection;G.isDocument=Be.isDocument;G.isMap=Be.isMap;G.isNode=Be.isNode;G.isPair=Be.isPair;G.isScalar=Be.isScalar;G.isSeq=Be.isSeq;G.Pair=wm.Pair;G.Scalar=bm.Scalar;G.YAMLMap=km.YAMLMap;G.YAMLSeq=$m.YAMLSeq;G.CST=Sm;G.Lexer=vm.Lexer;G.LineCounter=Am.LineCounter;G.Parser=Em.Parser;G.parse=Ls.parse;G.parseAllDocuments=Ls.parseAllDocuments;G.parseDocument=Ls.parseDocument;G.stringify=Ls.stringify;G.visit=xl.visit;G.visitAsync=xl.visitAsync});p();import{parseArgs as Zy}from"node:util";p();import{existsSync as gy,readFileSync as my}from"node:fs";import{join as yy}from"node:path";p();p();p();function Ro(t,e,n=s=>s.length>0&&s.length<=100){let s=[];if(typeof t!="object"||t===null||Array.isArray(t))return{rule:null,problems:[`${e}: rows should map a field to a value, e.g. rows: { rep_email: $me }.`]};let r=Object.entries(t);r.length||s.push(`${e}: rows is empty. Leave it out to grant every row.`);let i={},o=a=>typeof a=="string"||typeof a=="number"||typeof a=="boolean";for(let[a,c]of r)n(a)||s.push(`${e}: "${a}" isn't a field name rows can use.`),Array.isArray(c)?!c.length||!c.every(o)?s.push(`${e}.${a}: give one value, or a list of values, e.g. [won, lost].`):i[a]=[...new Set(c.map(l=>typeof l=="string"?l.trim():l))].sort((l,h)=>String(l).localeCompare(String(h))):o(c)?i[a]=typeof c=="string"?c.trim():c:s.push(`${e}.${a}: give a value (text, a number, true/false or $me), or a list of them.`);return{rule:s.length?null:i,problems:s}}var Rn="*";p();p();var Of=/^[a-z][a-z0-9_-]{0,40}$/,Lo=/^[A-Za-z0-9-]{1,64}$/,If=new Set(["authorization","proxy-authorization","cookie","host","content-length","content-type","transfer-encoding","connection","user-agent"]),Ln=/^[A-Za-z0-9_$@-]+(\.[A-Za-z0-9_$@-]+)*$/,qo=/^[A-Za-z0-9_.[\]-]{1,64}$/,Mo=2e4;function xo(t){let e;try{e=new URL(t)}catch{return"isn't a URL"}if(e.protocol!=="https:")return"should start with https://";if(e.username||e.password)return"shouldn't have a user or password in it";let n=e.hostname.toLowerCase();return/^\[|^[0-9.]+$/.test(n)?"should be a hostname, not an IP address":!n.includes(".")||/(^|\.)(localhost|internal|local|localdomain|home\.arpa)$/.test(n)?"should be a public hostname":null}function Pf(t,e){let n=new URL(t+e);return jf(t,n)?n:null}function jf(t,e){let n=new URL(t),s=n.pathname.replace(/\/$/,"");return e.protocol==="https:"&&e.origin===n.origin&&!e.username&&!e.password&&(e.pathname===s||e.pathname.startsWith(s+"/")||!s)}var ge=t=>typeof t=="object"&&t!==null&&!Array.isArray(t);function Ko(t,e,n){let s=[],r={base_url:"",resources:{}},i=typeof t.base_url=="string"?xo(t.base_url.trim()):"is missing";if(i)s.push(`${e}: base_url ${i} (e.g. https://api.hubapi.com).`);else{let c=new URL(t.base_url.trim());(c.search||c.hash)&&s.push(`${e}: base_url shouldn't have a ? or # part; put query settings in each resource's path.`),r.base_url=`${c.origin}${c.pathname.replace(/\/+$/,"")}`}if(n)t.auth!==void 0&&s.push(`${e}: a per-person source signs in with each person's own token; leave auth out.`);else if(t.auth!==void 0){let c=typeof t.auth=="string"?t.auth.trim():"",l=/^header\s+(\S+)$/i.exec(c)?.[1];c==="bearer"||c==="basic"?r.auth=c:l&&Lo.test(l)&&!["cookie","host"].includes(l.toLowerCase())?r.auth=`header ${l}`:s.push(`${e}: auth should be bearer, basic, or header <Name> (e.g. header X-Api-Key).`)}if(t.headers!==void 0)if(!ge(t.headers))s.push(`${e}.headers should map a header name to its value.`);else{let c={};for(let[l,h]of Object.entries(t.headers)){let u=typeof h=="number"?String(h):h;Lo.test(l)?If.has(l.toLowerCase())?s.push(`${e}.headers: Kuriko sets ${l} itself${/auth/i.test(l)?" (the credential goes in Secret Manager: name it in secret)":""}.`):typeof u!="string"||/[\r\n]/.test(u)||u.length>500?s.push(`${e}.headers.${l} should be one line of text.`):xn(u)||/key|token|secret|auth/i.test(l)?s.push(`${e}.headers.${l} looks like it carries a credential. Put it in Secret Manager and use auth: header ${l}.`):c[l]=u:s.push(`${e}.headers: "${l}" isn't a header name.`)}Object.keys(c).length&&(r.headers=c)}let o=t.resources;if(!ge(o)||!Object.keys(o).length)s.push(`${e}.resources should map a name tools use to the API path that lists it.`);else for(let[c,l]of Object.entries(o)){let h=`${e}.resources.${c}`;Of.test(c)||s.push(`${e}.resources: "${c}" should be lowercase letters, digits, - and _.`);let u=typeof l=="string"?{path:l}:l;if(!ge(u)){s.push(`${h} should be a path (e.g. /v1/contacts), or settings with a path.`);continue}for(let m of Object.keys(u))["path","method","body","rows","next","add"].includes(m)||s.push(`${h}: unknown setting "${m}".`);let f={path:""},d=Do(u.path,r.base_url,h,"/crm/v3/objects/contacts?limit=100",s);if(d&&(f.path=d),u.method!==void 0){let m=typeof u.method=="string"?u.method.toUpperCase():"";m!=="GET"&&m!=="POST"?s.push(`${h}: method should be GET or POST (POST for search or GraphQL endpoints). It's how the resource is listed; adding rows goes under add.`):m==="POST"&&(f.method="POST")}if(u.body!==void 0&&(f.method!=="POST"?s.push(`${h}: a body needs method: POST.`):ge(u.body)?JSON.stringify(u.body).length>Mo?s.push(`${h}.body is too long.`):f.body=u.body:s.push(`${h}.body should be the JSON object sent.`)),u.rows!==void 0&&(typeof u.rows!="string"||!Ln.test(u.rows)?s.push(`${h}: rows should say where the list is in the answer, e.g. results or data.items.`):f.rows=u.rows),u.next!==void 0){let m=Mf(u.next,`${h}.next`,f.method==="POST",s);m&&(f.next=m)}if(u.add!==void 0){let m=qf(u.add,`${h}.add`,r.base_url,s);m&&(f.add=m)}r.resources[c]=f}if(n){let c=t.oauth;if(!ge(c))s.push(`${e}: a per-person source needs oauth (authorize_url, token_url, client_id, scopes).`);else{for(let f of Object.keys(c))["authorize_url","token_url","client_id","scopes","scope_separator","authorize_params","client_auth","account"].includes(f)||s.push(`${e}.oauth: unknown setting "${f}".`);let l={};for(let f of["authorize_url","token_url"]){let d=typeof c[f]=="string"?xo(c[f].trim()):"is missing";d?s.push(`${e}.oauth: ${f} ${d}.`):l[f]=c[f].trim()}let h=Rf(c.client_id,e,s);h&&(l.client_id=h);let u=Lf(c.scopes,e,s);if(u&&(l.scopes=u),c.scope_separator!==void 0&&(c.scope_separator!==" "&&c.scope_separator!==","?s.push(`${e}.oauth: scope_separator should be " " or ",".`):c.scope_separator===","&&(l.scope_separator=",")),c.authorize_params!==void 0){let f=new Set(["client_id","redirect_uri","state","response_type","scope"]);!ge(c.authorize_params)||!Object.entries(c.authorize_params).every(([d,m])=>qo.test(d)&&!f.has(d)&&typeof m=="string"&&m.length<=200)?s.push(`${e}.oauth: authorize_params should map extra settings to text (not client_id, redirect_uri, state, response_type or scope).`):Object.keys(c.authorize_params).length&&(l.authorize_params=c.authorize_params)}c.client_auth!==void 0&&(c.client_auth!=="body"&&c.client_auth!=="basic"?s.push(`${e}.oauth: client_auth should be body or basic.`):c.client_auth==="basic"&&(l.client_auth="basic")),c.account!==void 0&&(typeof c.account!="string"||!Ln.test(c.account)?s.push(`${e}.oauth: account should say where the account's email or name is in the token answer, e.g. user.email.`):l.account=c.account),l.authorize_url&&l.token_url&&l.client_id&&(r.oauth=l)}}else t.oauth!==void 0&&s.push(`${e}: oauth is for per-person sources (credentials: per-person).`);let a=Object.keys(r.resources);return{config:r,resources:a,writable:a.filter(c=>r.resources[c].add),problems:s}}function Rf(t,e,n){return typeof t!="string"||!/^[A-Za-z0-9._~:@-]{4,200}$/.test(t.trim())?(n.push(`${e}.oauth: client_id should be your OAuth app's client ID.`),null):xn(t.trim())&&/secret/i.test(t)?(n.push(`${e}.oauth: client_id looks like a client secret; that goes in Secret Manager.`),null):t.trim()}function Lf(t,e,n){if(t===void 0)return null;let s=Array.isArray(t)?t:typeof t=="string"?t.split(/\s+/).filter(Boolean):null;return!s||!s.every(r=>typeof r=="string"&&/^[\x21-\x7e]{1,200}$/.test(r)&&!r.includes(","))?(n.push(`${e}.oauth: scopes should be a list, e.g. [crm.objects.contacts.read].`),null):s.length?s:null}function Do(t,e,n,s,r){let i=typeof t=="string"?t.trim():"";return!/^\/(?!\/)[^\s#\\]*$/.test(i)||i.length>1e3||/(^|\/)\.\.?(\/|\?|$)/.test(i)||/%2e|%2f/i.test(i)?(r.push(`${n}: path should be the API path under base_url, starting with / (e.g. ${s}).`),null):e&&!Pf(e,i)?(r.push(`${n}: path leaves base_url.`),null):i}var wr=t=>t===xf?1:Array.isArray(t)?t.reduce((e,n)=>e+wr(n),0):ge(t)?Object.values(t).reduce((e,n)=>e+wr(n),0):0,xf="$row";function qf(t,e,n,s){let r=typeof t=="string"?{path:t}:t;if(!ge(r))return s.push(`${e} should be a path (e.g. /v1/contacts), or settings with a path.`),null;for(let a of Object.keys(r))["path","body","row"].includes(a)||s.push(a==="method"?`${e}: new rows are always sent with POST; leave method out.`:`${e}: unknown setting "${a}" (add takes path, body and row).`);let i={path:""},o=Do(r.path,n,e,"/crm/v3/objects/contacts",s);return o&&(i.path=o),r.body!==void 0&&(ge(r.body)?JSON.stringify(r.body).length>Mo?s.push(`${e}.body is too long.`):wr(r.body)!==1?s.push(`${e}.body should have $row exactly once, where the tool's values go (e.g. { properties: $row }).`):i.body=r.body:s.push(`${e}.body should be the JSON object sent, with $row where the tool's values go, e.g. { properties: $row }.`)),r.row!==void 0&&r.row!==""&&(typeof r.row!="string"||!Ln.test(r.row)?s.push(`${e}: row should say where the new row is in the answer, e.g. data.issueCreate.issue (or leave it out if the answer is the row).`):i.row=r.row),o?i:null}function Mf(t,e,n,s){let r=c=>(s.push(`${e}: ${c}`),null);if(t==="link")return"link";if(!ge(t))return r("should be link, or { cursor, param }, { cursor, body }, { url }, { page } or { offset }.");let i=Object.keys(t),o=c=>typeof t[c]=="string"&&Ln.test(t[c]),a=c=>typeof t[c]=="string"&&qo.test(t[c]);return"cursor"in t?i.some(c=>!["cursor","param","body","more"].includes(c))?r("a cursor takes cursor, param or body, and more."):o("cursor")?"param"in t=="body"in t?r("say where the cursor goes: param (a query parameter) or body (a field in a POST's body)."):"param"in t&&!a("param")?r("param should be a query parameter name, e.g. after."):"body"in t&&(!n||!o("body"))?r(n?"body should be the field it goes in, e.g. variables.after.":"body needs method: POST."):"more"in t&&!o("more")?r("more should say where the has-more flag is, e.g. has_more."):{cursor:t.cursor,..."param"in t?{param:t.param}:{body:t.body},..."more"in t?{more:t.more}:{}}:r("cursor should say where the next cursor is in the answer, e.g. paging.next.after."):"url"in t?i.length===1&&o("url")?{url:t.url}:r("url should say where the next page's URL is in the answer, e.g. links.next."):"page"in t?i.some(c=>c!=="page"&&c!=="start")||!a("page")?r("page should be the page-number parameter, e.g. page."):"start"in t&&(typeof t.start!="number"||!Number.isInteger(t.start)||t.start<0)?r("start should be the first page's number (0 or 1)."):{page:t.page,...t.start!==void 0&&t.start!==1?{start:t.start}:{}}:"offset"in t?i.length===1&&a("offset")?{offset:t.offset}:r("offset should be the offset parameter, e.g. offset."):r("should be link, or { cursor, param }, { cursor, body }, { url }, { page } or { offset }.")}p();var me=[{id:"claude-code",name:"Claude Code",where:"terminal and IDEs",documents:["https://claude.ai/oauth/claude-code-client-metadata"]},{id:"claude",name:"Claude",where:"claude.ai, desktop and mobile apps",documents:["https://claude.ai/oauth/mcp-oauth-client-metadata"]},{id:"codex",name:"Codex",where:"OpenAI's CLI and IDE extension",documents:["https://chatgpt.com/oauth/codex/client.json","https://chatgpt.com/oauth/codex/*/client.json"]},{id:"chatgpt",name:"ChatGPT",where:"chatgpt.com and its apps, including Codex there",documents:["https://chatgpt.com/oauth/client.json"]},{id:"vscode",name:"VS Code",where:"GitHub Copilot's agent mode",documents:["https://vscode.dev/oauth/client-metadata.json"]},{id:"cursor",name:"Cursor",where:"Cursor's editor and cloud agents",documents:["https://cursor.com/oauth/mcp-client.json"]},{id:"lovable",name:"Lovable",where:"Lovable's workspace connectors",documents:["https://api.lovable.dev/.well-known/oauth-client"]},{id:"replit",name:"Replit",where:"Replit Agent's MCP servers",documents:[],notYet:"signs in without a metadata document"},{id:"bolt",name:"Bolt",where:"Bolt's connectors",documents:[],notYet:"signs in without a metadata document"},{id:"v0",name:"v0",where:"Vercel's v0",documents:[],notYet:"custom MCP sign-in unconfirmed"}],Bo=me.filter(t=>!t.notYet),Ie=["claude-code","claude"],Uo=new Map(me.map(t=>[t.id,t])),qn=t=>Uo.get(t);function Go(t){let e;try{e=new URL(t)}catch{return!1}return e.protocol==="https:"&&e.pathname.length>1&&!e.hash&&!e.username&&!e.password&&e.href===t}var Lt=t=>Uo.get(t)?.name??t;var Kf="*",ct=class extends Error{name="PolicyFileError";problems;constructor(e){super(`policy.yaml has ${e.length===1?"a problem":`${e.length} problems`}:
|
|
142
142
|
${e.map(n=>` - ${n}`).join(`
|
|
143
|
-
`)}`),this.problems=e}},Df=new Set(["Viewer","Builder","Admin"]),Fo=new Set(["postgres","bigquery","snowflake","api"]);var Bf=/^[A-Za-z_][A-Za-z0-9_]{0,62}$/,Wo=/^[A-Za-z_][A-Za-z0-9_]{0,254}$/,Uf=/^[a-z][a-z0-9-]{4,28}[a-z0-9]$/,Gf=/^(?:([a-z][a-z0-9-]{4,28}[a-z0-9])[.:])?([A-Za-z0-9_]{1,1024})$/,Ff=/^[A-Za-z0-9][A-Za-z0-9_.-]{1,254}$/,Wf=/^[A-Za-z0-9_.@$-]{1,255}$/,Mn=/^[A-Za-z_][A-Za-z0-9_$]{0,254}$/,Yf=/^[a-z][a-z0-9-]{1,30}$/;var Vf=/^(?:projects\/[a-z][a-z0-9-]{4,28}[a-z0-9]\/secrets\/)?[A-Za-z0-9_-]{1,255}$/,xn=t=>/^(ntn_|secret_|sk-|sk_live_|sk_test_|rk_live_|ghp_|gho_|github_pat_|xox[abpr]-|AKIA|ASIA|AIza|ya29\.)/.test(t)||t.length>=32&&/[A-Z]/.test(t)&&/[a-z]/.test(t)&&/[0-9]/.test(t)&&!/[-_].*[-_]/.test(t),Jf=t=>{let e=t.split("/").pop();return e.startsWith("kuriko-")&&!e.startsWith("kuriko-connector-")},zf=new Set(["roles","connectors","access","clients"]);function Yo(t){let e=t.trim();return e.toLowerCase()==="everyone"?Rn:e.includes("@")?e.toLowerCase():e}var Mt=t=>t===Rn?"everyone":t,xt=t=>typeof t=="object"&&t!==null&&!Array.isArray(t),qt=t=>[...new Set(t)].sort();function Vo(t,e){let n=[],s={roles:[],connectors:[],grants:[],clients:[]};if(t==null&&(t={}),!xt(t))throw new ct(["The file should be a map with roles, connectors, access and clients."]);for(let u of Object.keys(t))zf.has(u)||n.push(`Unknown section "${u}" (expected roles, connectors, access, clients).`);let r=t.roles??{};if(!xt(r))n.push("roles should map a group to Admin, Builder or Viewer.");else for(let[u,f]of Object.entries(r)){let d=Yo(u);d===Rn?n.push("roles: everyone can't be given a role (roles need a real group)."):typeof f!="string"||!Df.has(f)?n.push(`roles: ${u} should be Admin, Builder or Viewer, not ${JSON.stringify(f)}.`):s.roles.some(m=>m.group===d)?n.push(`roles: ${u} is listed twice.`):s.roles.push({group:d,role:f})}let i=t.connectors??{},o=new Map,a=new Map,c=new Map;if(!xt(i))n.push("connectors should map an id (e.g. hubspot) to its settings.");else for(let[u,f]of Object.entries(i)){let d=`connectors.${u}`;if(Yf.test(u)||n.push(`${d}: the id should be lowercase letters, digits and dashes.`),!xt(f)){n.push(`${d} should have a name and a kind.`);continue}let m=typeof f.kind=="string"&&Fo.has(f.kind)?f.kind:null;m||n.push(`${d}: kind should be one of ${[...Fo].join(", ")}.`);let g=f.credentials==="per-person";f.credentials!==void 0&&f.credentials!=="shared"&&!g&&n.push(`${d}: credentials should be shared or per-person.`),g&&m&&m!=="api"&&n.push(`${d}: only api sources can be per-person so far.`);let y=new Set(m==="postgres"?["name","kind","secret","schema","credentials"]:m==="bigquery"?["name","kind","dataset","project","credentials"]:m==="snowflake"?["name","kind","secret","account","user","warehouse","database","schema","role","credentials"]:m==="api"?["name","kind","secret","credentials","base_url","auth","headers","resources","oauth"]:["name","kind"]);for(let $ of Object.keys(f))y.has($)||n.push($==="secret"&&m==="bigquery"?`${d}: BigQuery needs no secret: Kuriko's own identity is given access to the dataset.`:`${d}: unknown setting "${$}".`);let S=typeof f.name=="string"&&f.name.trim()?f.name.trim():null;S||n.push(`${d}: needs a name.`);let C=null;if(m==="postgres"||m==="snowflake"||m==="api"){let $=g?"the OAuth client secret":m==="postgres"?"the connection URL":m==="snowflake"?"the private key Kuriko signs in with":"the API key or token";typeof f.secret!="string"||!Vf.test(f.secret)?n.push(`${d}: secret should name the secret in Secret Manager holding ${$} (e.g. warehouse-readonly, or projects/<project>/secrets/<name>), never the secret itself.`):xn(f.secret.split("/").pop())?n.push(`${d}: secret looks like a credential itself. Put it in Secret Manager and name the secret here instead (then rotate it: it's been in this file).`):Jf(f.secret)?n.push(`${d}: ${f.secret} is one of Kuriko's own secrets; a data source needs its own credential.`):C=f.secret}let O={};if(m==="postgres")f.schema!==void 0&&(typeof f.schema!="string"||!f.schema)&&n.push(`${d}.schema should be a schema name.`),O={schema:typeof f.schema=="string"&&f.schema?f.schema:"public"},o.set(u,null);else if(m==="bigquery"){let $=typeof f.dataset=="string"?Gf.exec(f.dataset.trim()):null;if(!$)n.push(`${d}: dataset should be a BigQuery dataset, e.g. analytics (in this project) or other-project.analytics.`);else if(f.project!==void 0&&(typeof f.project!="string"||!Uf.test(f.project)))n.push(`${d}: project should be the Google Cloud project the dataset is in, e.g. acme-data.`);else if($[1]&&f.project!==void 0&&$[1]!==f.project)n.push(`${d}: dataset says project ${$[1]} but project says ${f.project}; keep one.`);else{let T=$[1]??f.project;O={dataset:$[2],...T?{project:T}:{}}}o.set(u,null),a.set(u,Wo)}else if(m==="snowflake"){let $=(T,j,b,v)=>{let K=f[T]??v;typeof K!="string"||!j.test(K.trim())?n.push(`${d}: ${T} should be ${b}.`):O[T]=K.trim()};$("account",Ff,"your Snowflake account identifier, e.g. acme-analytics (orgname-accountname)"),$("user",Wf,"the Snowflake user Kuriko signs in as, e.g. KURIKO_READER"),$("warehouse",Mn,"the warehouse queries run on, e.g. COMPUTE_WH"),$("database",Mn,"the database tools read, e.g. ANALYTICS"),$("schema",Mn,"a schema in that database, e.g. PUBLIC","PUBLIC"),f.role!==void 0&&$("role",Mn,"a Snowflake role the user has, e.g. KURIKO_READ"),o.set(u,null),a.set(u,Wo)}else if(m==="api"){let $=Ko(f,d,g);n.push(...$.problems),O=$.config,o.set(u,new Set($.resources)),c.set(u,new Set($.writable))}S&&m==="bigquery"?s.connectors.push({id:u,name:S,kind:m,config:O,mode:"identity",secretRef:null}):S&&m&&C&&s.connectors.push({id:u,name:S,kind:m,config:O,mode:g?"delegated":"service",secretRef:e(C)})}let l=t.access??[];Array.isArray(l)?l.forEach((u,f)=>{let d=`access[${f+1}]`;if(!xt(u))return void n.push(`${d} should have group, connector, resources and access.`);for(let b of Object.keys(u))["group","connector","resources","access","mask","rows"].includes(b)||n.push(`${d}: unknown setting "${b}".`);let m=typeof u.group=="string"&&u.group.trim()?Yo(u.group):null;m||n.push(`${d}: needs a group (a group email, or everyone).`);let g=typeof u.connector=="string"?u.connector:"";o.has(g)||n.push(`${d}: there's no connector "${g}" in connectors.`);let y=Array.isArray(u.resources)?u.resources.filter(b=>typeof b=="string"):typeof u.resources=="string"?[u.resources]:[];(!y.length||Array.isArray(u.resources)&&y.length!==u.resources.length)&&n.push(`${d}: resources should list what's granted, e.g. [interviews].`);let S=o.get(g);if(S)for(let b of y)S.has(b)||n.push(`${d}: ${g} has no resource "${b}" (it has: ${[...S].join(", ")||"none"}).`);let C=a.get(g)??Bf;if(S===null)for(let b of y)b!==Kf&&!C.test(b)&&n.push(`${d}: "${b}" isn't a table name (or "*" for every table).`);if(u.access==="write"&&o.has(g)){let b=c.get(g)??new Set,v=y.filter(K=>(S?S.has(K):!0)&&!b.has(K));v.length&&n.push(S?`${d}: ${g} can't take new rows in ${v.join(", ")} (read-only: no add in its connector). Use access: read, or describe how to add rows under the resource's add.`:`${d}: ${g} is read-only in Kuriko; use access: read.`)}u.access!=="read"&&u.access!=="write"&&n.push(`${d}: access should be read or write (write includes read).`);let O=u.mask===void 0?[]:Array.isArray(u.mask)&&u.mask.every(b=>typeof b=="string")?u.mask:null;O||n.push(`${d}: mask should be a list of field names.`);let $=u.rows===void 0||u.rows===null?{rule:void 0,problems:[]}:Ro(u.rows,`${d}.rows`,S===null?b=>C.test(b):void 0);if(n.push(...$.problems),!m||!g||!y.length||!O||$.rule===null||u.access!=="read"&&u.access!=="write")return;let T=s.grants.filter(b=>b.group===m&&b.connector===g&&b.access===u.access),j=y.filter(b=>T.some(v=>v.resources.includes(b)));if(j.length)return void n.push(`${d}: ${Mt(m)} already has ${u.access} on ${g}: ${j.join(", ")}. A table can be in one ${u.access} grant per group.`);if(T.some(b=>JSON.stringify(b.rows??null)===JSON.stringify($.rule??null)))return void n.push(`${d}: ${Mt(m)} already has ${u.access} on ${g}${$.rule?" with the same rows":""}; put the resources in one grant.`);s.grants.push({group:m,connector:g,resources:qt(y),access:u.access,mask:qt(O),...$.rule?{rows:$.rule}:{}})}):n.push("access should be a list of grants.");let h=t.clients===void 0||t.clients===null?[...Ie]:t.clients;if(Array.isArray(h)?h.forEach((u,f)=>{let d=`clients[${f+1}]`;if(typeof u!="string"||!u.trim())return void n.push(`${d} should be a client's name or its metadata document URL.`);let m=u.trim(),g=qn(m);if(g?.notYet)return void n.push(`${d}: ${g.name} can't connect to Kuriko yet (${g.notYet}). Leave it commented out for now.`);if(!g&&!Go(m))return void n.push(/^https?:/.test(m)?`${d}: ${m} isn't a client metadata document URL (https, with a path).`:`${d}: Kuriko doesn't know a client called "${m}". Use one of ${Bo.map(y=>y.id).join(", ")}, or the client's metadata document URL.`);if(s.clients.includes(m))return void n.push(`${d}: ${m} is listed twice.`);s.clients.push(m)}):n.push("clients should be a list, e.g. [claude-code, codex]."),n.length)throw new ct(n);return br(s)}var Kt=t=>Array.isArray(t)?t.map(Kt):t&&typeof t=="object"?Object.fromEntries(Object.keys(t).sort().map(e=>[e,Kt(t[e])])):t;function br(t){let e=n=>(s,r)=>n(s).localeCompare(n(r));return{roles:t.roles.map(({group:n,role:s})=>({group:n,role:s})).sort(e(n=>n.group)),connectors:t.connectors.map(({id:n,name:s,kind:r,mode:i,secretRef:o,config:a})=>({id:n,name:s,kind:r,mode:i,secretRef:o,config:Kt(a)})).sort(e(n=>n.id)),grants:t.grants.map(({group:n,connector:s,resources:r,access:i,mask:o,rows:a})=>({group:n,connector:s,resources:qt(r),access:i,mask:qt(o),...a?{rows:Kt(a)}:{}})).sort(e(Hf)),clients:qt(t.clients??[...Ie])}}var Hf=t=>`${t.connector}\0${t.group}\0${t.access}\0${JSON.stringify(t.rows?Kt(t.rows):null)}`;function Jo(t,e){let n=[],s=a=>typeof a=="string"?a:JSON.stringify(a);for(let a of["name","kind","mode","secretRef"])t[a]!==e[a]&&n.push(`${a} ${s(t[a])} \u2192 ${s(e[a])}`);let r=(a,c="")=>Object.entries(a).flatMap(([l,h])=>h&&typeof h=="object"&&!Array.isArray(h)?r(h,`${c}${l}.`):[[`${c}${l}`,h]]),i=new Map(r(t.config)),o=new Map(r(e.config));for(let a of new Set([...i.keys(),...o.keys()]))JSON.stringify(i.get(a))!==JSON.stringify(o.get(a))&&n.push(`${a} ${i.has(a)?s(i.get(a)):"(none)"} \u2192 ${o.has(a)?s(o.get(a)):"(none)"}`);return n.length?n:["(settings differ only in form)"]}var ze=(t,e)=>{let n=/^projects\/([^/]+)\/secrets\/(.+)$/.exec(t);return n&&(!e||n[1]===e)?n[2]:t};function Kn(t){switch(t.kind){case"role":return t.op==="add"?`${t.group} becomes ${t.to}`:t.op==="change"?`${t.group}: ${t.from} \u2192 ${t.to}`:`${t.group} is no longer ${t.from}`;case"connector":return`data source ${t.id}: ${t.summary}`;case"grant":return`${Mt(t.group)}: ${t.summary}`;case"client":return t.op==="add"?`people can connect with ${Lt(t.client)}`:`people can no longer connect with ${Lt(t.client)}`}}p();import{spawn as Qf}from"node:child_process";import{stripVTControlCharacters as Zf}from"node:util";var ee=class extends Error{command;code;stderr;constructor(e,n,s){let r=Zf(s);super(`${e} failed (exit ${n})${r.trim()?`:
|
|
143
|
+
`)}`),this.problems=e}},Df=new Set(["Viewer","Builder","Admin"]),Fo=new Set(["postgres","bigquery","snowflake","api"]);var Bf=/^[A-Za-z_][A-Za-z0-9_]{0,62}$/,Wo=/^[A-Za-z_][A-Za-z0-9_]{0,254}$/,Uf=/^[a-z][a-z0-9-]{4,28}[a-z0-9]$/,Gf=/^(?:([a-z][a-z0-9-]{4,28}[a-z0-9])[.:])?([A-Za-z0-9_]{1,1024})$/,Ff=/^[A-Za-z0-9][A-Za-z0-9_.-]{1,254}$/,Wf=/^[A-Za-z0-9_.@$-]{1,255}$/,Mn=/^[A-Za-z_][A-Za-z0-9_$]{0,254}$/,Yf=/^[a-z][a-z0-9-]{1,30}$/;var Vf=/^(?:projects\/[a-z][a-z0-9-]{4,28}[a-z0-9]\/secrets\/)?[A-Za-z0-9_-]{1,255}$/,xn=t=>/^(ntn_|secret_|sk-|sk_live_|sk_test_|rk_live_|ghp_|gho_|github_pat_|xox[abpr]-|AKIA|ASIA|AIza|ya29\.)/.test(t)||t.length>=32&&/[A-Z]/.test(t)&&/[a-z]/.test(t)&&/[0-9]/.test(t)&&!/[-_].*[-_]/.test(t),Jf=t=>{let e=t.split("/").pop();return e.startsWith("kuriko-")&&!e.startsWith("kuriko-connector-")},zf=new Set(["roles","connectors","access","clients"]);function Yo(t){let e=t.trim();return e.toLowerCase()==="everyone"?Rn:e.includes("@")?e.toLowerCase():e}var Mt=t=>t===Rn?"everyone":t,xt=t=>typeof t=="object"&&t!==null&&!Array.isArray(t),qt=t=>[...new Set(t)].sort();function Vo(t,e){let n=[],s={roles:[],connectors:[],grants:[],clients:[]};if(t==null&&(t={}),!xt(t))throw new ct(["The file should be a map with roles, connectors, access and clients."]);for(let u of Object.keys(t))zf.has(u)||n.push(`Unknown section "${u}" (expected roles, connectors, access, clients).`);let r=t.roles??{};if(!xt(r))n.push("roles should map a group to Admin, Builder or Viewer.");else for(let[u,f]of Object.entries(r)){let d=Yo(u);d===Rn?n.push("roles: everyone can't be given a role (roles need a real group)."):typeof f!="string"||!Df.has(f)?n.push(`roles: ${u} should be Admin, Builder or Viewer, not ${JSON.stringify(f)}.`):s.roles.some(m=>m.group===d)?n.push(`roles: ${u} is listed twice.`):s.roles.push({group:d,role:f})}let i=t.connectors??{},o=new Map,a=new Map,c=new Map;if(!xt(i))n.push("connectors should map an id (e.g. hubspot) to its settings.");else for(let[u,f]of Object.entries(i)){let d=`connectors.${u}`;if(Yf.test(u)||n.push(`${d}: the id should be lowercase letters, digits and dashes.`),!xt(f)){n.push(`${d} should have a name and a kind.`);continue}let m=typeof f.kind=="string"&&Fo.has(f.kind)?f.kind:null;m||n.push(`${d}: kind should be one of ${[...Fo].join(", ")}.`);let g=f.credentials==="per-person";f.credentials!==void 0&&f.credentials!=="shared"&&!g&&n.push(`${d}: credentials should be shared or per-person.`),g&&m&&m!=="api"&&n.push(`${d}: only api sources can be per-person so far.`);let y=new Set(m==="postgres"?["name","kind","secret","schema","credentials"]:m==="bigquery"?["name","kind","dataset","project","credentials"]:m==="snowflake"?["name","kind","secret","account","user","warehouse","database","schema","role","credentials"]:m==="api"?["name","kind","secret","credentials","base_url","auth","headers","resources","oauth"]:["name","kind"]);for(let $ of Object.keys(f))y.has($)||n.push($==="secret"&&m==="bigquery"?`${d}: BigQuery needs no secret: Kuriko's own identity is given access to the dataset.`:`${d}: unknown setting "${$}".`);let S=typeof f.name=="string"&&f.name.trim()?f.name.trim():null;S||n.push(`${d}: needs a name.`);let C=null;if(m==="postgres"||m==="snowflake"||m==="api"){let $=g?"the OAuth client secret":m==="postgres"?"the connection URL":m==="snowflake"?"the private key Kuriko signs in with":"the API key or token";typeof f.secret!="string"||!Vf.test(f.secret)?n.push(`${d}: secret should name the secret in Secret Manager holding ${$} (e.g. warehouse-readonly, or projects/<project>/secrets/<name>), never the secret itself.`):xn(f.secret.split("/").pop())?n.push(`${d}: secret looks like a credential itself. Put it in Secret Manager and name the secret here instead (then rotate it: it's been in this file).`):Jf(f.secret)?n.push(`${d}: ${f.secret} is one of Kuriko's own secrets; a data source needs its own credential.`):C=f.secret}let O={};if(m==="postgres")f.schema!==void 0&&(typeof f.schema!="string"||!f.schema)&&n.push(`${d}.schema should be a schema name.`),O={schema:typeof f.schema=="string"&&f.schema?f.schema:"public"},o.set(u,null);else if(m==="bigquery"){let $=typeof f.dataset=="string"?Gf.exec(f.dataset.trim()):null;if(!$)n.push(`${d}: dataset should be a BigQuery dataset, e.g. analytics (in this project) or other-project.analytics.`);else if(f.project!==void 0&&(typeof f.project!="string"||!Uf.test(f.project)))n.push(`${d}: project should be the Google Cloud project the dataset is in, e.g. acme-data.`);else if($[1]&&f.project!==void 0&&$[1]!==f.project)n.push(`${d}: dataset says project ${$[1]} but project says ${f.project}; keep one.`);else{let T=$[1]??f.project;O={dataset:$[2],...T?{project:T}:{}}}o.set(u,null),a.set(u,Wo)}else if(m==="snowflake"){let $=(T,j,b,v)=>{let K=f[T]??v;typeof K!="string"||!j.test(K.trim())?n.push(`${d}: ${T} should be ${b}.`):O[T]=K.trim()};$("account",Ff,"your Snowflake account identifier, e.g. acme-analytics (orgname-accountname)"),$("user",Wf,"the Snowflake user Kuriko signs in as, e.g. KURIKO_READER"),$("warehouse",Mn,"the warehouse queries run on, e.g. COMPUTE_WH"),$("database",Mn,"the database tools read, e.g. ANALYTICS"),$("schema",Mn,"a schema in that database, e.g. PUBLIC","PUBLIC"),f.role!==void 0&&$("role",Mn,"a Snowflake role the user has, e.g. KURIKO_READ"),o.set(u,null),a.set(u,Wo)}else if(m==="api"){let $=Ko(f,d,g);n.push(...$.problems),O=$.config,o.set(u,new Set($.resources)),c.set(u,new Set($.writable))}S&&m==="bigquery"?s.connectors.push({id:u,name:S,kind:m,config:O,mode:"identity",secretRef:null}):S&&m&&C&&s.connectors.push({id:u,name:S,kind:m,config:O,mode:g?"delegated":"service",secretRef:e(C)})}let l=t.access??[];Array.isArray(l)?l.forEach((u,f)=>{let d=`access[${f+1}]`;if(!xt(u))return void n.push(`${d} should have group, connector, resources and access.`);for(let b of Object.keys(u))["group","connector","resources","access","mask","rows"].includes(b)||n.push(`${d}: unknown setting "${b}".`);let m=typeof u.group=="string"&&u.group.trim()?Yo(u.group):null;m||n.push(`${d}: needs a group (a group email, or everyone).`);let g=typeof u.connector=="string"?u.connector:"";o.has(g)||n.push(`${d}: there's no connector "${g}" in connectors.`);let y=Array.isArray(u.resources)?u.resources.filter(b=>typeof b=="string"):typeof u.resources=="string"?[u.resources]:[];(!y.length||Array.isArray(u.resources)&&y.length!==u.resources.length)&&n.push(`${d}: resources should list what's granted, e.g. [interviews].`);let S=o.get(g);if(S)for(let b of y)S.has(b)||n.push(`${d}: ${g} has no resource "${b}" (it has: ${[...S].join(", ")||"none"}).`);let C=a.get(g)??Bf;if(S===null)for(let b of y)b!==Kf&&!C.test(b)&&n.push(`${d}: "${b}" isn't a table name (or "*" for every table).`);if(u.access==="write"&&o.has(g)){let b=c.get(g)??new Set,v=y.filter(K=>(S?S.has(K):!0)&&!b.has(K));v.length&&n.push(S?`${d}: ${g} can't take new rows in ${v.join(", ")} (read-only: no add in its connector). Use access: read, or describe how to add rows under the resource's add.`:`${d}: ${g} is read-only in Kuriko; use access: read.`)}u.access!=="read"&&u.access!=="write"&&n.push(`${d}: access should be read or write (write includes read).`);let O=u.mask===void 0?[]:Array.isArray(u.mask)&&u.mask.every(b=>typeof b=="string")?u.mask:null;O||n.push(`${d}: mask should be a list of field names.`);let $=u.rows===void 0||u.rows===null?{rule:void 0,problems:[]}:Ro(u.rows,`${d}.rows`,S===null?b=>C.test(b):void 0);if(n.push(...$.problems),!m||!g||!y.length||!O||$.rule===null||u.access!=="read"&&u.access!=="write")return;let T=s.grants.filter(b=>b.group===m&&b.connector===g&&b.access===u.access),j=y.filter(b=>T.some(v=>v.resources.includes(b)));if(j.length)return void n.push(`${d}: ${Mt(m)} already has ${u.access} on ${g}: ${j.join(", ")}. A table can be in one ${u.access} grant per group.`);if(T.some(b=>JSON.stringify(b.rows??null)===JSON.stringify($.rule??null)))return void n.push(`${d}: ${Mt(m)} already has ${u.access} on ${g}${$.rule?" with the same rows":""}; put the resources in one grant.`);s.grants.push({group:m,connector:g,resources:qt(y),access:u.access,mask:qt(O),...$.rule?{rows:$.rule}:{}})}):n.push("access should be a list of grants.");let h=t.clients===void 0||t.clients===null?[...Ie]:t.clients;if(Array.isArray(h)?h.forEach((u,f)=>{let d=`clients[${f+1}]`;if(typeof u!="string"||!u.trim())return void n.push(`${d} should be a client's name or its metadata document URL.`);let m=u.trim(),g=qn(m);if(g?.notYet)return void n.push(`${d}: ${g.name} can't connect to Kuriko yet (${g.notYet}). Leave it commented out for now.`);if(!g&&!Go(m))return void n.push(/^https?:/.test(m)?`${d}: ${m} isn't a client metadata document URL (https, with a path).`:`${d}: Kuriko doesn't know a client called "${m}". Use one of ${Bo.map(y=>y.id).join(", ")}, or the client's metadata document URL.`);if(s.clients.includes(m))return void n.push(`${d}: ${m} is listed twice.`);s.clients.push(m)}):n.push("clients should be a list, e.g. [claude-code, codex]."),n.length)throw new ct(n);return br(s)}var Kt=t=>Array.isArray(t)?t.map(Kt):t&&typeof t=="object"?Object.fromEntries(Object.keys(t).sort().map(e=>[e,Kt(t[e])])):t;function br(t){let e=n=>(s,r)=>n(s).localeCompare(n(r));return{roles:t.roles.map(({group:n,role:s})=>({group:n,role:s})).sort(e(n=>n.group)),connectors:t.connectors.map(({id:n,name:s,kind:r,mode:i,secretRef:o,config:a})=>({id:n,name:s,kind:r,mode:i,secretRef:o,config:Kt(a)})).sort(e(n=>n.id)),grants:t.grants.map(({group:n,connector:s,resources:r,access:i,mask:o,rows:a})=>({group:n,connector:s,resources:qt(r),access:i,mask:qt(o),...a?{rows:Kt(a)}:{}})).sort(e(Hf)),clients:qt(t.clients??[...Ie])}}var Hf=t=>`${t.connector}\0${t.group}\0${t.access}\0${JSON.stringify(t.rows?Kt(t.rows):null)}`;function Jo(t,e){let n=[],s=a=>typeof a=="string"?a:JSON.stringify(a);for(let a of["name","kind","mode","secretRef"])t[a]!==e[a]&&n.push(`${a} ${s(t[a])} \u2192 ${s(e[a])}`);let r=(a,c="")=>Object.entries(a).flatMap(([l,h])=>h&&typeof h=="object"&&!Array.isArray(h)?r(h,`${c}${l}.`):[[`${c}${l}`,h]]),i=new Map(r(t.config)),o=new Map(r(e.config));for(let a of new Set([...i.keys(),...o.keys()]))JSON.stringify(i.get(a))!==JSON.stringify(o.get(a))&&n.push(`${a} ${i.has(a)?s(i.get(a)):"(none)"} \u2192 ${o.has(a)?s(o.get(a)):"(none)"}`);return n.length?n:["(settings differ only in form)"]}var ze=(t,e)=>{let n=/^projects\/([^/]+)\/secrets\/(.+)$/.exec(t);return n&&(!e||n[1]===e)?n[2]:t};function Kn(t){switch(t.kind){case"role":return t.op==="add"?`${t.group} becomes ${t.to}`:t.op==="change"?`${t.group}: ${t.from} \u2192 ${t.to}`:`${t.group} is no longer ${t.from}`;case"connector":return`data source ${t.id}: ${t.summary}`;case"grant":return`${Mt(t.group)}: ${t.summary}`;case"client":return t.op==="add"?`people can connect with ${Lt(t.client)}`:`people can no longer connect with ${Lt(t.client)}`}}p();p();import{spawn as Qf}from"node:child_process";import{stripVTControlCharacters as Zf}from"node:util";var ee=class extends Error{command;code;stderr;constructor(e,n,s){let r=Zf(s);super(`${e} failed (exit ${n})${r.trim()?`:
|
|
144
144
|
${r.trim().split(`
|
|
145
145
|
`).slice(-15).join(`
|
|
146
146
|
`)}`:""}`),this.command=e,this.code=n,this.stderr=r}get reason(){let e=this.stderr.split(`
|
|
@@ -393,7 +393,7 @@ ${fy(t.clients??Ie)}`}function Ne(t,e){let n;try{n=(0,pr.parse)(t,{prettyErrors:
|
|
|
393
393
|
${i.map(o=>` ${o}`).join(`
|
|
394
394
|
`)}`:" (no logs yet; try again)"}`)}async function Xu(t,e){M("Checking this machine"),await ke(Fe(process.cwd(),e.dir)),await te();let n=await Ye(e.dir,"Which install's policy?",["installed"],{partial:"finish it with kuriko install"}),s=It(n);if(!await at(n,"module.kuriko.google_cloud_run_v2_job.migrate"))throw new Error(`${s.project} isn't fully installed yet. Finish it with kuriko install`);N(`Install ${_(s.project)} ${A(`(${D(n)})`)}`);let r=Co(n,U);if(!Eo(r))throw Qu(r,Zu(s)),new Error(`${s.project} had no ${U}, so one was started at ${D(r)} with just the two roles.
|
|
395
395
|
Add any data sources and access this install already has (the plan would remove them otherwise), then run this again.`);M(`Reading ${U}`);let i=Ne(_o(r,"utf8"),s.project),o=(b,v)=>`${b} ${v}${b===1?"":"s"}`;N(`${o(i.roles.length,"role rule")}, ${o(i.connectors.length,"data source")}, ${o(i.grants.length,"grant")}, ${o(i.clients.length,"AI app")}`),i.clients.length||x("clients is empty: nobody can connect to Kuriko from an AI app (Claude Code, Codex, \u2026).");let a=dr(i),c=[];if(await P("Checking the secrets it names exist",async()=>{for(let b of a)await An(b)||c.push(b)}),c.length){let[b,v]=c[0].split("/").filter((K,I)=>I%2===1);throw new Error(`Secret Manager has no ${c.map(K=>ze(K,s.project)).join(", ")} (or your account can't see ${c.length>1?"them":"it"}). Whoever manages credentials creates it, e.g.:
|
|
396
|
-
read -s TOKEN && printf '%s' "$TOKEN" | gcloud secrets create ${v} --project ${b} --data-file=- && unset TOKEN`)}a.length&&N(`Secrets exist: ${a.map(b=>ze(b,s.project)).join(", ")}`),M("What changes");let l=Buffer.from(JSON.stringify(i)).toString("base64"),h=await fr(s,"Comparing with the install, in the cloud",["policy-plan",l]);h.changes=h.changes.filter(b=>{if(b.kind!=="connector"||b.op!=="change")return!0;let v=h.connectors.find(q=>q.id===b.id),K=i.connectors.find(q=>q.id===b.id);if(!v||!K)return!0;let I=q=>br({roles:[],grants:[],clients:[],connectors:[q]}).connectors[0],R=Jo(I(v),I(K));return R[0]==="(settings differ only in form)"?!1:(b.summary=`${K.name}: ${R.join("; ")}`,!0)});let u={roles:[],grants:[],clients:[],connectors:h.connectors},f=await P("Checking which secrets the gateway can read",()=>ef(s,u,i)),d=await P("Checking which BigQuery datasets the gateway can read",()=>tf(s,u,i));h.lastApply?k(A(` Last applied ${new Date(h.lastApply.at).toLocaleString()} by ${h.lastApply.appliedBy}`)):k(A(" This would be the first apply. After it, access changes go through this file
|
|
396
|
+
read -s TOKEN && printf '%s' "$TOKEN" | gcloud secrets create ${v} --project ${b} --data-file=- && unset TOKEN`)}a.length&&N(`Secrets exist: ${a.map(b=>ze(b,s.project)).join(", ")}`),M("What changes");let l=Buffer.from(JSON.stringify(i)).toString("base64"),h=await fr(s,"Comparing with the install, in the cloud",["policy-plan",l]);h.changes=h.changes.filter(b=>{if(b.kind!=="connector"||b.op!=="change")return!0;let v=h.connectors.find(q=>q.id===b.id),K=i.connectors.find(q=>q.id===b.id);if(!v||!K)return!0;let I=q=>br({roles:[],grants:[],clients:[],connectors:[q]}).connectors[0],R=Jo(I(v),I(K));return R[0]==="(settings differ only in form)"?!1:(b.summary=`${K.name}: ${R.join("; ")}`,!0)});let u={roles:[],grants:[],clients:[],connectors:h.connectors},f=await P("Checking which secrets the gateway can read",()=>ef(s,u,i)),d=await P("Checking which BigQuery datasets the gateway can read",()=>tf(s,u,i));h.lastApply?k(A(` Last applied ${new Date(h.lastApply.at).toLocaleString()} by ${h.lastApply.appliedBy}`)):k(A(" This would be the first apply. After it, access changes only go through this file."));let m=!h.changes.length&&!f.allow.length&&!f.disallow.length;if(m&&(N(`${s.project} already matches ${U}.`),t==="plan"||h.lastApply))return;dy(h.changes);for(let b of f.allow)k(` ${Ao.add} the gateway can read secret ${ze(b,s.project)}`);for(let b of f.disallow)k(` ${Ao.remove} ${be(`the gateway can no longer read secret ${ze(b,s.project)}`)}`);let g=i.connectors.filter(b=>b.mode==="delegated");if(g.length){let b=(await Ge(s.project))?.number;if(b){let v=st(s,b).mcp.replace(/\/mcp$/,"");for(let K of g)k(A(` ${K.id}: set the OAuth redirect URI to ${v}/connect/callback; people connect at ${st(s,b).web}/connect/${K.id}`))}}let y=h.changes.filter(b=>b.op==="remove").length+f.disallow.length,S=h.changes.filter(b=>b.op==="remove"&&(b.kind==="role"||b.kind==="grant")).length,C=h.changes.filter(b=>b.op==="remove"&&b.kind==="connector").length;S&&x(`${S} role${S===1?" or grant is":"s or grants are"} removed: people lose that access on their next request.`),C&&x(`${C} data source${C===1?" is":"s are"} removed: tools using ${C===1?"it":"them"} stop getting its data, and everyone's own connections to ${C===1?"it":"them"} are deleted.`);let O=h.changes.filter(b=>b.kind==="client"&&b.op==="remove");if(O.length&&x(`${O.map(b=>Lt(b.client)).join(", ")} can't sign anyone in any more, and ${O.length===1?"its":"their"} current sessions stop within an hour. People's access is unchanged in the apps that remain.`),f.disallow.length&&x(`Kuriko gives up ${f.disallow.length===1?"a secret":"secrets"} the file no longer names. Nobody loses access; the secret${f.disallow.length===1?" itself is":"s themselves are"} kept.`),nf(s,d),t==="plan"){k(`
|
|
397
397
|
${A("Plan only: nothing was changed. Apply with: kuriko policy apply")}`);return}if(!e.yes&&!await z(`
|
|
398
398
|
Apply ${m?`${U} (no changes; records it as the source of truth)`:"these changes"}?`,!y)){k("Nothing was changed.");return}await sf(s,f);let $=await Et(),T=await fr(s,"Applying, in the cloud",["policy-apply",l,$,h.hash]);await hy(s,f);let j=T.changes.length+f.allow.length+f.disallow.length;N(`${s.project} matches ${U} (${j} change${j===1?"":"s"}, recorded in the audit log as ${$})`),f.allow.length&&k(A(" New secret access can take a minute or two to reach Google's servers.")),await We([r],`Policy for ${s.project}: ${T.changes.length?T.changes.map(Kn).slice(0,3).join("; ")+(T.changes.length>3?"; \u2026":""):"first apply"}`)}var dr=t=>[...new Set(t.connectors.flatMap(e=>e.secretRef?[e.secretRef]:[]))].sort(),No=t=>`kuriko-gateway@${t.project}.iam.gserviceaccount.com`,jt=t=>`serviceAccount:${No(t)}`,Hu=(t,e)=>[...new Set(t.connectors.filter(n=>n.kind==="bigquery").map(n=>`${n.config.project??e}.${n.config.dataset}`))].sort(),py=t=>t.split(".");async function ef(t,e,n){let s=dr(n),r=[];for(let o of s)await En(o,jt(t))||r.push(o);let i=[];for(let o of dr(e))o.startsWith("projects/")&&!s.includes(o)&&await An(o)&&await En(o,jt(t))&&i.push(o);return{allow:r,disallow:i}}async function tf(t,e,n){let s=Hu(n,t.project),r={waiting:[],unknown:[],unused:Hu(e,t.project).filter(i=>!s.includes(i))};for(let i of s){let o=await vu(...py(i),No(t));if(o==="missing")throw new Error(`BigQuery has no dataset ${i} (or your account can't see it). Check the dataset in ${U}.`);o==="not-readable"&&r.waiting.push(i),o==="unknown"&&r.unknown.push(i)}return r}function nf(t,e){let n=[...e.waiting,...e.unknown];e.waiting.length&&x(`Kuriko can't read ${e.waiting.join(", ")} yet. Tools get "no access yet" from ${e.waiting.length===1?"it":"them"} until it's granted.`),e.unknown.length&&x(`Couldn't check who can read ${e.unknown.join(", ")} (your account can't see ${e.unknown.length===1?"its":"their"} access). If reads fail, it needs this grant.`),n.length&&(k(A(` Whoever manages ${n.length===1?"that dataset":"those datasets"} adds this to their Terraform (Kuriko never changes data it doesn't own):
|
|
399
399
|
`)),k(Wu(n,No(t)).split(`
|