@notionhq/custom-blocks-host 0.5.0 → 0.5.2
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/README.md +3 -0
- package/dist/browser.js +1 -1
- package/dist/compatibility/normalizeSandboxToHostMessage.d.ts +1 -0
- package/dist/compatibility/normalizeSandboxToHostMessage.d.ts.map +1 -1
- package/dist/createCustomBlockHost.d.ts +2 -2
- package/dist/createCustomBlockHost.d.ts.map +1 -1
- package/dist/createCustomBlockHost.js +49 -34
- package/dist/messages/getInvalidSandboxMessageResponse.d.ts.map +1 -1
- package/dist/messages/getInvalidSandboxMessageResponse.js +3 -0
- package/dist/protocol/context/parent.d.ts +2 -0
- package/dist/protocol/index.d.ts +3 -2
- package/dist/protocol/index.js +1 -0
- package/dist/protocol/messages/hostToSandbox.d.ts +2 -0
- package/dist/protocol/messages/invalidHostMessage.d.ts +2 -0
- package/dist/protocol/messages/invalidHostMessage.js +2 -0
- package/dist/protocol/messages/invalidSandboxMessage.d.ts +2 -0
- package/dist/protocol/messages/invalidSandboxMessage.js +2 -0
- package/dist/protocol/messages/sandboxToHost.d.ts +1 -0
- package/dist/protocol/navigation/openExternalUrl.d.ts +2 -2
- package/dist/protocol/pages/messages/createPage.d.ts +2 -2
- package/dist/protocol/pages/messages/getPage.d.ts +2 -2
- package/dist/protocol/pages/messages/openPage.d.ts +2 -2
- package/dist/protocol/pages/messages/updatePage.d.ts +2 -2
- package/dist/protocol/users/messages/getUser.d.ts +2 -2
- package/dist/protocol/users/messages/listUsers.d.ts +2 -2
- package/dist/protocol/utils/errors.d.ts +2 -0
- package/dist/protocol/utils/readRequestId.d.ts +2 -0
- package/dist/protocol/utils/readRequestId.js +7 -0
- package/docs/bridge/changelog.md +7 -0
- package/docs/bridge/protocol.md +19 -1
- package/docs/handlers.md +6 -3
- package/package.json +1 -1
- package/src/createCustomBlockHost.ts +58 -39
- package/src/messages/getInvalidSandboxMessageResponse.ts +3 -0
package/README.md
CHANGED
|
@@ -9,6 +9,9 @@ Create the host before navigating the iframe. Pass the full block URL as `sandbo
|
|
|
9
9
|
|
|
10
10
|
For configuration and lifecycle details, see [Initialization and lifecycle](docs/lifecycle.md).
|
|
11
11
|
|
|
12
|
+
Use `BridgeParent` from `@notionhq/custom-blocks-host/protocol` to construct parent references with
|
|
13
|
+
plain string IDs. The host validates the parent before sending it to the block.
|
|
14
|
+
|
|
12
15
|
Implement `CustomBlockHostHandlers` to connect the host to your application. Handlers return shared
|
|
13
16
|
bridge data using `CustomBlockHostResult`. Use `makeBridgePage` to construct a complete `BridgePage`
|
|
14
17
|
from your records. See [Return bridge data](docs/handlers.md#return-bridge-data).
|
package/dist/browser.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
var Le,Jo={lang:void 0,message:void 0,abortEarly:void 0,abortPipeEarly:void 0};function st(e){return!e&&!Le?Jo:{lang:e?.lang??Le?.lang,message:e?.message,abortEarly:e?.abortEarly??Le?.abortEarly,abortPipeEarly:e?.abortPipeEarly??Le?.abortPipeEarly}}var Yo;function en(e){return Yo?.get(e)}var tn;function rn(e){return tn?.get(e)}var on;function nn(e,t){return on?.get(e)?.get(t)}function ke(e){let t=typeof e;return t==="string"?`"${e}"`:t==="number"||t==="bigint"||t==="boolean"?`${e}`:t==="object"||t==="function"?(e&&Object.getPrototypeOf(e)?.constructor?.name)??"null":t}function w(e,t,i,s,c){let p=c&&"input"in c?c.input:i.value,f=c?.expected??e.expects??null,h=c?.received??ke(p),y={kind:e.kind,type:e.type,input:p,expected:f,received:h,message:`Invalid ${t}: ${f?`Expected ${f} but r`:"R"}eceived ${h}`,requirement:e.requirement,path:c?.path,issues:c?.issues,lang:s.lang,abortEarly:s.abortEarly,abortPipeEarly:s.abortPipeEarly},C=e.kind==="schema",_=c?.message??e.message??nn(e.reference,y.lang)??(C?rn(y.lang):null)??s.message??en(y.lang);_!==void 0&&(y.message=typeof _=="function"?_(y):_),C&&(i.typed=!1),i.issues?i.issues.push(y):i.issues=[y]}function sn(e,t){return e===t||Number.isNaN(e)&&Number.isNaN(t)}function an(e,t){return Object.prototype.hasOwnProperty.call(e,t)&&t!=="__proto__"&&t!=="prototype"&&t!=="constructor"}function at(e,t){let i=[...new Set(e)];return i.length>1?`(${i.join(` ${t} `)})`:i[0]??"never"}function W(e){return e["~standard"]={version:1,vendor:"valibot",validate:t=>e["~run"]({value:t},st())},e}var un=class extends Error{constructor(e){super(e[0].message),this.name="ValiError",this.issues=e}};function ce(e){return{kind:"transformation",type:"brand",reference:ce,async:!1,name:e,"~run"(t){return t}}}function De(e){return{kind:"validation",type:"finite",reference:De,async:!1,expects:null,requirement:Number.isFinite,message:e,"~run"(t,i){return t.typed&&!this.requirement(t.value)&&w(this,"finite",t,i),t}}}function ut(e,t){let i=ke(e);return{kind:"validation",type:"includes",reference:ut,async:!1,expects:i,requirement:e,message:t,"~run"(s,c){return s.typed&&!s.value.includes(this.requirement)&&w(this,"content",s,c,{received:`!${i}`}),s}}}function we(e,t){return{kind:"validation",type:"max_length",reference:we,async:!1,expects:`<=${e}`,requirement:e,message:t,"~run"(i,s){return i.typed&&i.value.length>this.requirement&&w(this,"length",i,s,{received:`${i.value.length}`}),i}}}function he(e,t){return{kind:"validation",type:"min_length",reference:he,async:!1,expects:`>=${e}`,requirement:e,message:t,"~run"(i,s){return i.typed&&i.value.length<this.requirement&&w(this,"length",i,s,{received:`${i.value.length}`}),i}}}function Te(e,t){return{kind:"validation",type:"min_value",reference:Te,async:!1,expects:`>=${e instanceof Date?e.toJSON():ke(e)}`,requirement:e,message:t,"~run"(i,s){return i.typed&&!(i.value>=this.requirement)&&w(this,"value",i,s,{received:i.value instanceof Date?i.value.toJSON():ke(i.value)}),i}}}function ct(e,t){return{kind:"validation",type:"regex",reference:ct,async:!1,expects:`${e}`,requirement:e,message:t,"~run"(i,s){return i.typed&&!this.requirement.test(i.value)&&w(this,"format",i,s),i}}}function lt(e){return{kind:"transformation",type:"transform",reference:lt,async:!1,operation:e,"~run"(t){return t.value=this.operation(t.value),t}}}var Dt={abortEarly:!0};function wt(e,t,i){return typeof e.fallback=="function"?e.fallback(t,i):e.fallback}function Ve(e,t,i){return typeof e.default=="function"?e.default(t,i):e.default}function Tt(e,t){return!e["~run"]({value:t},Dt).issues}function E(e,t){return W({kind:"schema",type:"array",reference:E,expects:"Array",async:!1,item:e,message:t,"~run"(i,s){let c=i.value;if(Array.isArray(c)){i.typed=!0,i.value=[];for(let p=0;p<c.length;p++){let f=c[p],h=this.item["~run"]({value:f},s);if(h.issues){let y={type:"array",origin:"value",input:c,key:p,value:f};for(let C of h.issues)C.path?C.path.unshift(y):C.path=[y],i.issues?.push(C);if(i.issues||(i.issues=h.issues),s.abortEarly){i.typed=!1;break}}h.typed||(i.typed=!1),i.value.push(h.value)}}else w(this,"type",i,s);return i}})}function b(e){return W({kind:"schema",type:"boolean",reference:b,expects:"boolean",async:!1,message:e,"~run"(t,i){return typeof t.value=="boolean"?t.typed=!0:w(this,"type",t,i),t}})}function n(e,t){return W({kind:"schema",type:"literal",reference:n,expects:ke(e),async:!1,literal:e,message:t,"~run"(i,s){return sn(i.value,this.literal)?i.typed=!0:w(this,"type",i,s),i}})}function pt(e){return W({kind:"schema",type:"nan",reference:pt,expects:"NaN",async:!1,message:e,"~run"(t,i){return Number.isNaN(t.value)?t.typed=!0:w(this,"type",t,i),t}})}function mt(e){return W({kind:"schema",type:"never",reference:mt,expects:"never",async:!1,message:e,"~run"(t,i){return w(this,"type",t,i),t}})}function D(e,t){return W({kind:"schema",type:"nullable",reference:D,expects:`(${e.expects} | null)`,async:!1,wrapped:e,default:t,"~run"(i,s){return i.value===null&&(this.default!==void 0&&(i.value=Ve(this,i,s)),i.value===null)?(i.typed=!0,i):this.wrapped["~run"](i,s)}})}function O(e){return W({kind:"schema",type:"number",reference:O,expects:"number",async:!1,message:e,"~run"(t,i){return typeof t.value=="number"&&!isNaN(t.value)?t.typed=!0:w(this,"type",t,i),t}})}function o(e,t){return W({kind:"schema",type:"object",reference:o,expects:"Object",async:!1,entries:e,message:t,"~run"(i,s){let c=i.value;if(c&&typeof c=="object"){i.typed=!0,i.value={};for(let p in this.entries){let f=this.entries[p];if(p in c||(f.type==="exact_optional"||f.type==="optional"||f.type==="nullish")&&f.default!==void 0){let h=p in c?c[p]:Ve(f),y=f["~run"]({value:h},s);if(y.issues){let C={type:"object",origin:"value",input:c,key:p,value:h};for(let _ of y.issues)_.path?_.path.unshift(C):_.path=[C],i.issues?.push(_);if(i.issues||(i.issues=y.issues),s.abortEarly){i.typed=!1;break}}y.typed||(i.typed=!1),i.value[p]=y.value}else if(f.fallback!==void 0)i.value[p]=wt(f);else if(f.type!=="exact_optional"&&f.type!=="optional"&&f.type!=="nullish"&&(w(this,"key",i,s,{input:void 0,expected:`"${p}"`,path:[{type:"object",origin:"key",input:c,key:p,value:c[p]}]}),s.abortEarly))break}}else w(this,"type",i,s);return i}})}function a(e,t){return W({kind:"schema",type:"optional",reference:a,expects:`(${e.expects} | undefined)`,async:!1,wrapped:e,default:t,"~run"(i,s){return i.value===void 0&&(this.default!==void 0&&(i.value=Ve(this,i,s)),i.value===void 0)?(i.typed=!0,i):this.wrapped["~run"](i,s)}})}function T(e,t){return W({kind:"schema",type:"picklist",reference:T,expects:at(e.map(ke),"|"),async:!1,options:e,message:t,"~run"(i,s){return this.options.includes(i.value)?i.typed=!0:w(this,"type",i,s),i}})}function $(e,t,i){return W({kind:"schema",type:"record",reference:$,expects:"Object",async:!1,key:e,value:t,message:i,"~run"(s,c){let p=s.value;if(p&&typeof p=="object"){s.typed=!0,s.value={};for(let f in p)if(an(p,f)){let h=p[f],y=this.key["~run"]({value:f},c);if(y.issues){let _={type:"object",origin:"key",input:p,key:f,value:h};for(let M of y.issues)M.path=[_],s.issues?.push(M);if(s.issues||(s.issues=y.issues),c.abortEarly){s.typed=!1;break}}let C=this.value["~run"]({value:h},c);if(C.issues){let _={type:"object",origin:"value",input:p,key:f,value:h};for(let M of C.issues)M.path?M.path.unshift(_):M.path=[_],s.issues?.push(M);if(s.issues||(s.issues=C.issues),c.abortEarly){s.typed=!1;break}}(!y.typed||!C.typed)&&(s.typed=!1),y.typed&&(s.value[y.value]=C.value)}}else w(this,"type",s,c);return s}})}function l(e,t){return W({kind:"schema",type:"strict_object",reference:l,expects:"Object",async:!1,entries:e,message:t,"~run"(i,s){let c=i.value;if(c&&typeof c=="object"){i.typed=!0,i.value={};for(let p in this.entries){let f=this.entries[p];if(p in c||(f.type==="exact_optional"||f.type==="optional"||f.type==="nullish")&&f.default!==void 0){let h=p in c?c[p]:Ve(f),y=f["~run"]({value:h},s);if(y.issues){let C={type:"object",origin:"value",input:c,key:p,value:h};for(let _ of y.issues)_.path?_.path.unshift(C):_.path=[C],i.issues?.push(_);if(i.issues||(i.issues=y.issues),s.abortEarly){i.typed=!1;break}}y.typed||(i.typed=!1),i.value[p]=y.value}else if(f.fallback!==void 0)i.value[p]=wt(f);else if(f.type!=="exact_optional"&&f.type!=="optional"&&f.type!=="nullish"&&(w(this,"key",i,s,{input:void 0,expected:`"${p}"`,path:[{type:"object",origin:"key",input:c,key:p,value:c[p]}]}),s.abortEarly))break}if(!i.issues||!s.abortEarly){for(let p in c)if(!Object.prototype.hasOwnProperty.call(this.entries,p)){w(this,"key",i,s,{input:p,expected:"never",path:[{type:"object",origin:"key",input:c,key:p,value:c[p]}]});break}}}else w(this,"type",i,s);return i}})}function r(e){return W({kind:"schema",type:"string",reference:r,expects:"string",async:!1,message:e,"~run"(t,i){return typeof t.value=="string"?t.typed=!0:w(this,"type",t,i),t}})}function Mt(e){let t;if(e)for(let i of e)if(t)for(let s of i.issues)t.push(s);else t=i.issues;return t}function d(e,t){return W({kind:"schema",type:"union",reference:d,expects:at(e.map(i=>i.expects),"|"),async:!1,options:e,message:t,"~run"(i,s){let c,p,f;for(let h of this.options){let y=h["~run"]({value:i.value},s);if(y.typed)if(y.issues)p?p.push(y):p=[y];else{c=y;break}else f?f.push(y):f=[y]}if(c)return c;if(p){if(p.length===1)return p[0];w(this,"type",i,s,{issues:Mt(p)}),i.typed=!0}else{if(f?.length===1)return f[0];w(this,"type",i,s,{issues:Mt(f)})}return i}})}function qe(){return W({kind:"schema",type:"unknown",reference:qe,expects:"unknown",async:!1,"~run"(e){return e.typed=!0,e}})}function v(e,t,i){return W({kind:"schema",type:"variant",reference:v,expects:"Object",async:!1,key:e,options:t,message:i,"~run"(s,c){let p=s.value;if(p&&typeof p=="object"){let f,h=0,y=this.key,C=[],_=(M,X)=>{for(let V of M.options){if(V.type==="variant")_(V,new Set(X).add(V.key));else{let g=!0,N=0;for(let j of X){let z=V.entries[j];if(j in p?z["~run"]({typed:!1,value:p[j]},Dt).issues:z.type!=="exact_optional"&&z.type!=="optional"&&z.type!=="nullish"){g=!1,y!==j&&(h<N||h===N&&j in p&&!(y in p))&&(h=N,y=j,C=[]),y===j&&C.push(V.entries[j].expects);break}N++}if(g){let j=V["~run"]({value:p},c);(!f||!f.typed&&j.typed)&&(f=j)}}if(f&&!f.issues)break}};if(_(this,new Set([this.key])),f)return f;w(this,"type",s,c,{input:p[y],expected:at(C,"|"),path:[{type:"object",origin:"value",input:p,key:y,value:p[y]}]})}else w(this,"type",s,c);return s}})}function qt(e,t){let i={...e.entries};for(let s of t)delete i[s];return W({...e,entries:i})}function se(e,t,i){let s=e["~run"]({value:t},st(i));if(s.issues)throw new un(s.issues);return s.value}function A(...e){return W({...e[0],pipe:e,"~run"(t,i){for(let s of e)if(s.kind!=="metadata"){if(t.issues&&(s.kind==="schema"||s.kind==="transformation")){t.typed=!1;break}(!t.issues||!i.abortEarly&&!i.abortPipeEarly)&&(t=s["~run"](t,i))}return t}})}function Ie(e,t,i){let s=e["~run"]({value:t},st(i));return{typed:s.typed,success:!s.issues,output:s.value,issues:s.issues}}var le=A(r(),ce("NotionBlockId")),Z=A(r(),ce("NotionDataSourceId")),F=A(r(),ce("NotionPageId")),At=A(r(),ce("NotionAgentId")),Nt=A(r(),ce("NotionSpaceId"));var Ut=o({id:Z,table:r(),spaceId:a(Nt)});var Ft=T(["default","gray","brown","orange","yellow","green","blue","purple","pink","red","gray_background","brown_background","orange_background","yellow_background","green_background","blue_background","purple_background","pink_background","red_background","default_background"]),ft=o({id:r(),name:r(),color:a(Ft),description:a(r())}),cn=o({id:r(),name:r(),color:a(Ft),option_ids:E(r())}),ln=o({synced_property_id:r(),synced_property_name:r()}),B=o({name:r(),description:a(r())}),pn=["title","rich_text","number","checkbox","url","email","phone_number","select","multi_select","status","date","people","files","unique_id","relation","place","formula","rollup","button","verification","last_visited_time","location","created_time","last_edited_time","created_by","last_edited_by"],zt=T(pn),Ht=["title","rich_text","number","checkbox","url","email","phone_number","date","created_time","last_edited_time","people","created_by"],Lt=v("type",[o({...B.entries,type:n("title")}),o({...B.entries,type:n("rich_text")}),o({...B.entries,type:n("number")}),o({...B.entries,type:n("checkbox")}),o({...B.entries,type:n("url")}),o({...B.entries,type:n("email")}),o({...B.entries,type:n("phone_number")}),o({...B.entries,type:n("select"),options:E(ft)}),o({...B.entries,type:n("multi_select"),options:E(ft)}),o({...B.entries,type:n("status"),options:E(ft),groups:E(cn)}),o({...B.entries,type:n("date")}),o({...B.entries,type:n("people")}),o({...B.entries,type:n("files")}),o({...B.entries,type:n("unique_id")}),o({...B.entries,type:n("relation"),data_source_id:a(r()),dual_property:a(ln)}),o({...B.entries,type:n("place")}),o({...B.entries,type:n("formula")}),o({...B.entries,type:n("rollup")}),o({...B.entries,type:n("button")}),o({...B.entries,type:n("verification")}),o({...B.entries,type:n("last_visited_time")}),o({...B.entries,type:n("location")}),o({...B.entries,type:n("created_time")}),o({...B.entries,type:n("last_edited_time")}),o({...B.entries,type:n("created_by")}),o({...B.entries,type:n("last_edited_by")})]);var Vt={created_time:{type:"created_time",name:"Created time"},last_edited_time:{type:"last_edited_time",name:"Last edited time"},created_by:{type:"created_by",name:"Created by"},last_edited_by:{type:"last_edited_by",name:"Last edited by"}};var Gt=o({id:a(Z),propertiesById:$(r(),Lt)});var $t=o({collectionPointer:a(Ut),collectionSchema:a(Gt),propertyIdsByKey:a($(r(),a(r()))),inaccessible:a(n(!0))});var ye=$(r(),$t);function Qt(e){let t=Object.entries(e.manifestDataSource.properties??{}).map(([i,s])=>{let c=e.propertyIdsByKey?.[i],p=c===void 0?void 0:e.collectionSchema?.propertiesById[c];return mn(i,c,p?.type,s.type)});return e.collectionSchema===void 0?{status:"missing_schema",properties:t}:t.every(i=>i.status==="mapped")?{status:"complete",properties:t}:{status:"incomplete",properties:t}}function mn(e,t,i,s){return t===void 0?{status:"missing",propertyKey:e,propertyId:t}:i===void 0?{status:"invalid",propertyKey:e,propertyId:t}:{status:i===s?"mapped":"incompatible",propertyKey:e,propertyId:t}}var Ge=o({type:n("page_id"),page_id:F}),$e=o({type:n("data_source_id"),data_source_id:Z}),fn=o({type:n("workspace"),workspace:n(!0)}),yn=o({type:n("block_id"),block_id:le}),dn=o({type:n("agent_id"),agent_id:At}),vn=o({type:n("unavailable")}),re=v("type",[Ge,$e,fn,yn,dn,vn]);var _e=v("type",[o({type:n("unavailable")}),o({type:n("page"),id:F,parent:re})]);var xe=T(["standard","high"]),Wt="standard";var Ce=T(["light","dark"]);var Xt=o({capability:r(),resource:r()});var hn=v("type",[o({type:n("emoji"),emoji:r()}),o({type:n("external"),url:r()})]),gn=o({name:r(),description:a(r()),type:zt}),bn=o({name:r(),description:a(r()),icon:a(hn),properties:a($(r(),gn),{})}),de=o({version:n(1),name:a(r()),description:a(r()),slashCommand:a(r()),icon:a(o({type:n("emoji"),emoji:r()})),dataSources:a($(r(),bn),{}),capabilities:a(E(Xt))});var Qe=A(r(),ce("NotionUserId"));var ae=o({object:n("user"),id:Qe,name:a(r()),avatar_url:D(r()),type:n("person"),person:o({email:r()})});var Sn=r(),Ne=o({code:Sn,message:r(),isRetryable:b()}),Ae=class extends Error{constructor(t){super(t.message),this.name="CustomBlockInitializationError",this.code=t.code,this.isRetryable=t.isRetryable}code;isRetryable},We=v("status",[o({type:n("init"),initializationId:r(),status:n("success"),theme:Ce,contrastMode:xe,blockId:le,parent:re,page:_e,manifest:de,dataSources:o({bindings:ye}),currentUser:ae}),o({type:n("init"),initializationId:r(),status:n("error"),error:Ne})]);var Kt=o({type:n("contrastModeChanged"),contrastMode:xe});var Zt=o({type:n("pageChanged"),page:_e});var Jt=o({type:n("parentChanged"),parent:re});var Yt=o({type:n("themeChanged"),theme:Ce});var er=o({type:n("dataSourcesChanged"),dataSources:o({bindings:ye})});var Xe=o({unit:T(["year","month","week","day"]),value:O(),time:r(),defaultTimeZone:a(r())}),kn=o({unit:T(["hour","minute"]),value:O()}),Ue=o({unit:n("none")}),yt=d([Xe,kn]),tr=a(d([Xe,Ue])),rr=a(d([yt,Ue])),In=o({type:n("date"),start_date:r(),reminder:tr}),_n=o({type:n("daterange"),start_date:r(),end_date:r(),reminder:tr}),xn=o({type:n("datetime"),start_date:r(),start_time:r(),time_zone:a(r()),reminder:rr}),Cn=o({type:n("datetimerange"),start_date:r(),start_time:r(),end_date:r(),end_time:r(),time_zone:a(r()),reminder:rr}),or=v("type",[In,_n,xn,Cn]);var Ke=o({id:r(),table:r()});var nr=d([r(),O(),b(),or,E(r()),E(Ke)]);var ir=o({id:F,is_archived:b(),in_trash:b(),propertiesById:$(r(),a(nr))});var Pn=o({type:n("emoji"),emoji:r()}),En=o({type:n("custom_emoji"),custom_emoji:o({id:r(),name:a(r()),url:a(r())})}),sr=o({type:n("external"),external:o({url:r()})}),ar=o({type:n("file"),file:o({url:r(),expiry_time:a(r())})}),Pe=v("type",[Pn,En,sr,ar]),Ee=v("type",[sr,ar]);var L=D(r());var dt={start:r(),end:a(L),time_zone:a(L),reminder:a(d([yt,Ue]))},ur=d([o({...dt,start:A(r(),ut("T"))}),o({...dt,time_zone:r()}),o({...dt,reminder:a(d([Xe,Ue]))})]);var cr=d([o({type:n("external"),name:r(),external:o({url:r()})}),o({type:n("file"),name:r(),file:o({url:r(),expiry_time:a(r())})})]);var Oe=D(o({...Ke.entries,table:T(["notion_user","bot","organization_bot"]),spaceId:a(r())}));var lr=o({lat:O(),lon:O(),name:a(L),address:a(L),aws_place_id:a(L),google_place_id:a(L)});var pr=o({id:r()});var vt=$(r(),qe());var Ze=d([o({id:r(),name:a(r()),color:a(r()),description:a(L)}),o({name:r(),id:a(r()),color:a(r()),description:a(L)})]);var mr=d([o({object:a(n("user")),id:r()}),o({object:n("group"),id:r(),name:a(L)})]);var R={id:r()},ht=v("type",[o({...R,type:n("title"),title:E(vt)}),o({...R,type:n("rich_text"),rich_text:E(vt)}),o({...R,type:n("number"),number:D(O())}),o({...R,type:n("url"),url:L}),o({...R,type:n("email"),email:L}),o({...R,type:n("phone_number"),phone_number:L}),o({...R,type:n("checkbox"),checkbox:b()}),o({...R,type:n("select"),select:D(Ze)}),o({...R,type:n("status"),status:D(Ze)}),o({...R,type:n("multi_select"),multi_select:E(Ze)}),o({...R,type:n("date"),date:D(ur)}),o({...R,type:n("people"),people:E(mr)}),o({...R,type:n("relation"),has_more:a(b()),relation:E(pr)}),o({...R,type:n("files"),files:E(cr)}),o({...R,type:n("place"),place:D(lr)}),o({...R,type:n("created_time"),created_time:L}),o({...R,type:n("last_edited_time"),last_edited_time:L}),o({...R,type:n("created_by"),created_by:Oe}),o({...R,type:n("last_edited_by"),last_edited_by:Oe}),o({...R,type:n("last_visited_time"),last_visited_time:L}),o({...R,type:n("unique_id"),unique_id:r()}),o({...R,type:n("button"),button:r()}),o({...R,type:n("formula"),formula:r()}),o({...R,type:n("location"),location:r()}),o({...R,type:n("rollup"),rollup:r()}),o({...R,type:n("verification"),verification:r()})]);var je=$(r(),ht),fr=$(r(),D(ht));var oe=o({object:n("page"),id:F,parent:re,properties:fr,created_by:a(Oe,null),last_edited_by:a(Oe,null),last_visited_time:a(D(r()),null),created_time:a(D(r()),null),last_edited_time:a(D(r()),null),icon:a(D(Pe),null),cover:a(D(Ee),null),url:a(D(r()),null),public_url:a(D(r()),null),is_archived:b(),in_trash:b()});var yr=d([l({equals:b()}),l({does_not_equal:b()})]);var ue=d([l({is_empty:n(!0)}),l({is_not_empty:n(!0)})]);var ge=d([r(),E(r())]);var dr=d([l({contains:ge}),l({contains_all:ge}),l({does_not_contain:ge}),ue]);var vr=l({object:n("user"),id:A(r(),he(1),we(2e3))}),hr=d([l({contains:vr}),l({does_not_contain:vr}),l({is_empty:n(!0)}),l({is_not_empty:n(!0)})]);var J=T(["start_date","end_date"]),On=T(["today","tomorrow","yesterday","one_week_ago","one_week_from_now","one_month_ago","one_month_from_now"]),Fe=d([On,r()]),gr=d([l({target:a(J),equals:Fe}),l({target:a(J),before:Fe}),l({target:a(J),after:Fe}),l({target:a(J),on_or_before:Fe}),l({target:a(J),on_or_after:Fe}),l({target:a(J),this_week:l({})}),l({target:a(J),past_week:l({})}),l({target:a(J),past_month:l({})}),l({target:a(J),past_year:l({})}),l({target:a(J),next_week:l({})}),l({target:a(J),next_month:l({})}),l({target:a(J),next_year:l({})}),l({target:a(J),is_empty:n(!0)}),l({target:a(J),is_not_empty:n(!0)})]);var br=d([l({equals:O()}),l({does_not_equal:O()}),l({greater_than:O()}),l({less_than:O()}),l({greater_than_or_equal_to:O()}),l({less_than_or_equal_to:O()}),ue]);var Je=d([l({equals:ge}),l({does_not_equal:ge}),ue]);var Sr=l({object:T(["user","group"]),id:A(r(),he(1))}),kr=d([l({contains:Sr}),l({does_not_contain:Sr}),ue]);var Ir=A(F,ct(/^(?:[0-9a-f]{32}|[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12})$/i),lt(e=>e.replaceAll("-","").toLowerCase().replace(/^(.{8})(.{4})(.{4})(.{4})(.{12})$/,"$1-$2-$3-$4-$5"))),Ye=d([l({contains:Ir}),l({does_not_contain:Ir}),l({is_empty:n(!0)}),l({is_not_empty:n(!0)})]);var _r=T(["To-do","In progress","Complete","Current","Future"]),xr=d([_r,A(E(_r),he(1),we(5))]),Cr=d([l({group_equals:xr}),l({group_does_not_equal:xr})]);var Pr=d([Je,Cr]);var Be=d([l({equals:r()}),l({does_not_equal:r()}),l({contains:r()}),l({does_not_contain:r()}),l({starts_with:r()}),l({ends_with:r()}),ue]);var gt=d([l({propertyId:r(),relation:Ye}),l({propertyId:r(),created_by:hr}),l({propertyId:r(),title:Be}),l({propertyId:r(),rich_text:Be}),l({propertyId:r(),url:Be}),l({propertyId:r(),email:Be}),l({propertyId:r(),phone_number:Be}),l({propertyId:r(),number:br}),l({propertyId:r(),checkbox:yr}),l({propertyId:r(),select:Je}),l({propertyId:r(),multi_select:dr}),l({propertyId:r(),status:Pr}),l({propertyId:r(),date:gr}),l({propertyId:r(),people:kr})]);var Er=d([gt,l({and:E(gt)})]);var Or=T(["ascending","descending"]);var bt=10,jr=l({propertyId:r(),direction:Or});var Br=o({type:n("queryDataSource"),subscriptionId:r(),dataSourceId:Z,limit:O(),filter:a(Er),sorts:a(E(jr))}),jn=r(),Rr=o({code:jn,message:r(),isRetryable:b()}),Mr=v("status",[o({type:n("queryDataSourceResult"),subscriptionId:r(),status:n("success"),items:E(oe),hasMore:b()}),o({type:n("queryDataSourceResult"),subscriptionId:r(),status:n("error"),error:Rr})]),Dr=v("status",[o({type:n("queryDataSourceResult"),subscriptionId:r(),status:n("success"),items:E(d([oe,ir])),hasMore:b()}),o({type:n("queryDataSourceResult"),subscriptionId:r(),status:n("error"),error:Rr})]);var Bn=r(),Rn=o({code:Bn,message:r(),isRetryable:b()}),wr=o({type:n("openExternalUrl"),requestId:r(),url:r()}),Tr=v("status",[o({type:n("openExternalUrlResult"),requestId:r(),status:n("success")}),o({type:n("openExternalUrlResult"),requestId:r(),status:n("error"),error:Rn})]);var Re=o({object:n("page"),id:F,parent:re,properties:je,created_time:a(r()),last_edited_time:a(r()),icon:a(Pe),cover:a(Ee),url:a(r()),public_url:a(r()),is_archived:b(),in_trash:b()});var Mn=r(),Ar=o({code:Mn,message:r(),isRetryable:b()}),Nr=v("status",[o({type:n("createPageResult"),requestId:r(),status:n("success"),page:oe}),o({type:n("createPageResult"),requestId:r(),status:n("error"),error:Ar})]),Ur=v("status",[o({type:n("createPageResult"),requestId:r(),status:n("success"),page:d([oe,Re])}),o({type:n("createPageResult"),requestId:r(),status:n("error"),error:Ar})]),Dn=v("type",[o({type:n("start")}),o({type:n("end")}),o({type:n("before"),blockId:le}),o({type:n("after"),blockId:le})]),Wa=v("type",[Ge,$e]),qr={type:n("createPage"),requestId:r(),properties:je},Fr=v("type",[o({...qr,parent:Ge,position:a(Dn)}),o({...qr,parent:$e,position:a(mt())})]);var wn=r(),zr=o({code:wn,message:r(),isRetryable:b()}),Hr=o({type:n("getPage"),requestId:r(),pageId:F,dataSourceId:a(Z)}),Lr=v("status",[o({type:n("getPageResult"),requestId:r(),status:n("success"),page:oe}),o({type:n("getPageResult"),requestId:r(),status:n("error"),error:zr})]),Vr=v("status",[o({type:n("getPageResult"),requestId:r(),status:n("success"),page:d([oe,Re])}),o({type:n("getPageResult"),requestId:r(),status:n("error"),error:zr})]);var Tn=T(["side_peek","center_peek"]),qn=r(),An=o({code:qn,message:r(),isRetryable:b()}),Gr=o({type:n("openPage"),requestId:r(),pageId:F,mode:Tn}),$r=v("status",[o({type:n("openPageResult"),requestId:r(),status:n("success"),pageId:F}),o({type:n("openPageResult"),requestId:r(),status:n("error"),error:An})]);var Nn=r(),Qr=o({code:Nn,message:r(),isRetryable:b()}),Wr=v("status",[o({type:n("updatePageResult"),requestId:r(),status:n("success"),page:oe}),o({type:n("updatePageResult"),requestId:r(),status:n("error"),error:Qr})]),Xr=v("status",[o({type:n("updatePageResult"),requestId:r(),status:n("success"),page:d([oe,Re])}),o({type:n("updatePageResult"),requestId:r(),status:n("error"),error:Qr})]),Kr=o({type:n("updatePage"),requestId:r(),pageId:F,dataSourceId:a(Z),properties:a(je),icon:a(Pe),cover:a(Ee),archived:a(b())});var Zr=o({type:n("currentUserChanged"),currentUser:ae});var Un=r(),Fn=o({code:Un,message:r(),isRetryable:b()}),Jr=o({type:n("getUser"),requestId:r(),userId:Qe}),Yr=v("status",[o({type:n("getUserResult"),requestId:r(),status:n("success"),user:ae}),o({type:n("getUserResult"),requestId:r(),status:n("error"),error:Fn})]);var eo=o({object:n("list"),results:E(ae),next_cursor:D(r()),has_more:b(),type:n("user"),user:$(r(),qe())});var zn=r(),Hn=o({code:zn,message:r(),isRetryable:b()}),to=o({type:n("listUsers"),requestId:r(),startCursor:a(r()),pageSize:a(O())}),ro=v("status",[o({type:n("listUsersResult"),requestId:r(),status:n("success"),list:eo}),o({type:n("listUsersResult"),requestId:r(),status:n("error"),error:Hn})]);var oo=o({type:n("invalidSandboxMessage"),reason:r()});var no=v("type",[We,Yt,Kt,Jt,Zt,Zr,er,Yr,ro,$r,Tr,oo]),io=v("type",[...no.options,Mr,Lr,Nr,Wr]),wu=v("type",[...no.options,Dr,Vr,Ur,Xr]);function so(e){return{...e,dataSources:{bindings:Object.fromEntries(Object.entries(e.dataSources.bindings).map(([t,i])=>[t,{...i,collectionSchema:{...i.collectionSchema,propertiesById:{...i.collectionSchema?.propertiesById,...Vt}}}]))}}}function ee(e){throw new Error(`[custom-blocks-host] Unexpected value encountered: ${JSON.stringify(e)}`)}function ze(e){return{...e,properties:Object.fromEntries(Object.entries(e.properties).map(([t,i])=>{switch(i?.type){case"unique_id":case"button":case"formula":case"location":case"rollup":case"verification":return[t,null];case"title":case"rich_text":case"number":case"url":case"email":case"phone_number":case"checkbox":case"select":case"status":case"multi_select":case"date":case"people":case"relation":case"files":case"place":case"created_time":case"last_edited_time":case"created_by":case"last_edited_by":case"last_visited_time":case void 0:return[t,i];default:return ee(i)}}))}}function ao(e){return{...e,properties:Object.fromEntries(Object.values(e.properties).flatMap(t=>t?[[t.id,t]]:[])),icon:e.icon??void 0,cover:e.cover??void 0,created_time:e.created_time??void 0,last_edited_time:e.last_edited_time??void 0,url:e.url??void 0,public_url:e.public_url??void 0}}function be(e){if(e==null||e==="")return;let t=new Date(e);if(Number.isFinite(t.getTime()))return{type:"datetime",start_date:t.toISOString().slice(0,10),start_time:t.toISOString().slice(11,16),time_zone:"UTC"}}var Se=class extends Error{};function St(e){try{return Ln(e)}catch(t){throw t instanceof RangeError?new Se(t.message):t}}function Ln(e){let{start:t,end:i,time_zone:s,reminder:c}=e;if(!t.split("T")[0])throw new Se("Date values must include a date.");let p=t.includes("T")||s!=null,f=t.match(/([+-])(\d{2}):(\d{2})$/),h=f?(Number(f[2])*60+Number(f[3]))*(f[1]==="-"?-1:1):0,y=s?.match(/^UTC(?:([+-])(\d{1,2})(?::(\d{2}))?)?$/),C=y?(Number(y[2]??0)*60+Number(y[3]??0))*(y[1]==="-"?-1:1):h,_=g=>{if(!g.split("T")[0])throw new Se("Date values must include a date.");if(!g.includes("T"))return{date:g,time:"00:00"};let N=g.match(/^(\d{4}-\d{2}-\d{2})T(\d{2}:\d{2})(?::\d{2}(?:\.\d+)?)?$/);if(N)return{date:N[1],time:N[2]};if(!s||y){let U=new Date(new Date(g).getTime()+C*6e4).toISOString();return{date:U.slice(0,10),time:U.slice(11,16)}}let j=new Intl.DateTimeFormat("en-CA",{timeZone:s,year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit",hourCycle:"h23"}).formatToParts(new Date(g)),z=U=>j.find(te=>te.type===U)?.value;return{date:`${z("year")}-${z("month")}-${z("day")}`,time:`${z("hour")}:${z("minute")}`}},M=_(t),X=i?_(i):void 0;if(!p){if(c&&!("time"in c)&&c.unit!=="none")throw new Se("Hour and minute reminders require a date with a time.");return X?{type:"daterange",start_date:M.date,end_date:X.date,reminder:c}:{type:"date",start_date:M.date,reminder:c}}let V=s??(h===0?"UTC":`UTC${h<0?"-":"+"}${Math.floor(Math.abs(h)/60)}${Math.abs(h)%60===0?"":`:${String(Math.abs(h)%60).padStart(2,"0")}`}`);return X?{type:"datetimerange",start_date:M.date,start_time:M.time,end_date:X.date,end_time:X.time,time_zone:V,reminder:c}:{type:"datetime",start_date:M.date,start_time:M.time,time_zone:V,reminder:c}}function co(e){switch(e.type){case"title":return uo(e.title);case"rich_text":return uo(e.rich_text);case"number":return e.number??void 0;case"checkbox":return e.checkbox;case"url":return e.url??"";case"email":return e.email??"";case"phone_number":return e.phone_number??"";case"select":return e.select?.name;case"status":return e.status?.name;case"multi_select":return e.multi_select.flatMap(t=>t.name??[]);case"date":return e.date?St(e.date):void 0;case"people":return e.people.map(t=>t.object==="group"?{id:t.id,table:"space_permission_group",spaceId:t.id.split("|")[1]}:{id:t.id,table:"notion_user"});case"relation":return e.relation.map(t=>({id:t.id,table:"block"}));case"files":return e.files.map(t=>t.name).join(",");case"unique_id":return e.unique_id;case"button":return e.button;case"formula":return e.formula;case"location":return e.location;case"rollup":return e.rollup;case"verification":return e.verification;case"place":return"";case"created_time":return be(e.created_time);case"last_edited_time":return be(e.last_edited_time);case"last_visited_time":return be(e.last_visited_time);case"created_by":return e.created_by?[e.created_by]:void 0;case"last_edited_by":return e.last_edited_by?[e.last_edited_by]:void 0;default:return ee(e)}}function uo(e){return e.map(t=>{if(typeof t.plain_text=="string")return t.plain_text;let i=t.text;return i&&typeof i=="object"&&"content"in i&&typeof i.content=="string"?i.content:""}).join("")}function lo(e){let t={};for(let i of Object.values(e.properties))i&&(t[i.id]=co(i));return{id:e.id,is_archived:e.is_archived,in_trash:e.in_trash,propertiesById:{...t,created_time:be(e.created_time),last_edited_time:be(e.last_edited_time),created_by:e.created_by?[e.created_by]:void 0,last_edited_by:e.last_edited_by?[e.last_edited_by]:void 0}}}function po(e){return e.type==="queryDataSourceResult"?{...e,items:e.items.map(lo)}:{...e,page:ao(ze(e.page))}}function mo(e){return e.type==="queryDataSourceResult"?{...e,items:e.items.map(ze)}:{...e,page:ze(e.page)}}function fo(e,t){return e.type==="init"&&e.status==="success"||e.type==="dataSourcesChanged"?t<5?so(e):e:e.type!=="queryDataSourceResult"&&e.type!=="getPageResult"&&e.type!=="createPageResult"&&e.type!=="updatePageResult"||e.status==="error"?e:t<6?po(e):t<7?mo(e):e}var kt=o({theme:Ce,contrastMode:a(xe),blockId:le,parent:re,page:_e,manifest:de,dataSources:o({bindings:ye}),currentUser:ae}),yo=v("status",[o({status:n("success"),initialState:qt(kt,["manifest"])}),o({status:n("error"),error:Ne})]);var et=class{constructor(t){this.onUnsubscribe=t}onUnsubscribe;bySubscriptionId=new Map;subscribe(t){this.unsubscribe(t.subscriptionId);let i={_tag:"QuerySubscriptionToken"};return this.bySubscriptionId.set(t.subscriptionId,{message:t,token:i,isRefreshing:!0,shouldRefreshAgain:!1}),i}isCurrent(t,i){return this.bySubscriptionId.get(t)?.token===i}unsubscribe(t){this.bySubscriptionId.delete(t)&&this.onUnsubscribe(t)}refresh(t){let i=[],s=!1;for(let c of this.bySubscriptionId.values())if(c.message.dataSourceId===t){if(s=!0,c.isRefreshing){c.shouldRefreshAgain=!0;continue}c.isRefreshing=!0,i.push({message:c.message,token:c.token})}return s?i:void 0}finish(t,i){let s=this.bySubscriptionId.get(t);if(s?.token===i&&(s.isRefreshing=!1,!!s.shouldRefreshAgain))return s.shouldRefreshAgain=!1,s.isRefreshing=!0,{message:s.message,token:s.token}}unsubscribeAll(){for(let t of this.bySubscriptionId.keys())this.unsubscribe(t)}};function vo(e,t){if(e===void 0)return;let i="and"in e?e.and:[e];for(let s of i){let c=$n(s,t);if(c!==void 0)return c}}function $n(e,t){if(!Object.hasOwn(t.propertiesById,e.propertyId))return{code:"invalid_data_source_query_filter",message:`Data source query filter property ID "${e.propertyId}" is not defined in the bound data source schema.`,isRetryable:!1};let i=t.propertiesById[e.propertyId],s=Object.keys(e).find(h=>h!=="propertyId");if(s!==i.type)return{code:"invalid_data_source_query_filter",message:`Data source query filter branch "${s}" does not match property type "${i.type}".`,isRetryable:!1};if("status"in e&&i.type==="status"){let h=e.status;if("group_equals"in h||"group_does_not_equal"in h){let y="group_equals"in h?h.group_equals:h.group_does_not_equal,_=(Array.isArray(y)?y:[y]).find(M=>!i.groups.some(X=>X.name===M));return _===void 0?void 0:{code:"invalid_data_source_query_filter",message:`Unknown status group "${_}".`,isRetryable:!1}}}if("relation"in e&&!Tt(Ye,e.relation))return{code:"invalid_data_source_query_filter",message:"Relation filters require a page ID.",isRetryable:!1};let c=Qn(e);if(c===void 0||i.type!==c.propertyType)return;let p=new Set(i.options.map(h=>h.name)),f=Wn(c.operator).find(h=>!p.has(h));if(f!==void 0)return{code:"invalid_data_source_query_filter",message:`Data source query filter option "${f}" is not defined for property "${e.propertyId}".`,isRetryable:!1}}function Qn(e){if("select"in e)return{propertyType:"select",operator:e.select};if("multi_select"in e)return{propertyType:"multi_select",operator:e.multi_select};if("status"in e){let t=e.status;return"group_equals"in t||"group_does_not_equal"in t?void 0:{propertyType:"status",operator:t}}}function Wn(e){let t;if("equals"in e)t=e.equals;else if("does_not_equal"in e)t=e.does_not_equal;else if("contains"in e)t=e.contains;else if("contains_all"in e)t=e.contains_all;else if("does_not_contain"in e)t=e.does_not_contain;else return"is_empty"in e||"is_not_empty"in e?[]:ee(e);return Array.isArray(t)?t:[t]}var Xn=new Set(Ht);function ho(e,t){if(e===void 0)return;if(e.length>bt)return{code:"invalid_data_source_query_sort",message:`Data source query sorts may contain at most ${bt} entries.`,isRetryable:!1};let i=new Set;for(let s of e){if(i.has(s.propertyId))return{code:"invalid_data_source_query_sort",message:`Data source query sorts cannot contain duplicate property ID "${s.propertyId}".`,isRetryable:!1};if(i.add(s.propertyId),!Object.hasOwn(t.propertiesById,s.propertyId))return{code:"invalid_data_source_query_sort",message:`Data source query sort property ID "${s.propertyId}" is not defined in the bound data source schema.`,isRetryable:!1};let c=t.propertiesById[s.propertyId];if(!Xn.has(c.type))return{code:"invalid_data_source_query_sort",message:`Data source query sorts do not yet support property type "${c.type}".`,isRetryable:!1}}}function go(){return{code:"initial_state_timeout",message:"Host did not prepare initial state before the timeout.",isRetryable:!0}}function It(e){let{currentBridgeProtocolVersion:t}=e;return{code:"invalid_protocol_version",message:`Sandbox reported an invalid bridge protocol version: ${t}`,isRetryable:!1}}function bo(){return{code:"no_connect",message:"Sandbox did not send a connect message.",isRetryable:!0}}function So(){return{code:"no_init_result",message:"Sandbox did not acknowledge initialization.",isRetryable:!0}}function tt(){return{code:"unknown_error",message:"Unexpected error while initializing custom block.",isRetryable:!1}}function _t(e){let{currentBridgeProtocolVersion:t,minBridgeProtocolVersion:i}=e;return{code:"unsupported_protocol_version",message:`Sandbox bridge protocol version ${t} is not supported. Minimum supported version is ${i}.`,isRetryable:!1}}function xt(e){return Number.isFinite(e)&&Number.isInteger(e)&&e>=1}var Kn=5e3,Zn=5e3,Jn=5e3;function ko(e){let{manifestSource:t,prepareInit:i,sendInitMessage:s,warn:c,flushPendingHostStateChanges:p,minBridgeProtocolVersion:f,noConnectTimeoutMs:h=Kn,initialStateTimeoutMs:y=Zn,noInitResultTimeoutMs:C=Jn,stopHostWithFailure:_,onInitResult:M,onInitSent:X,onConnectionFailure:V}=e,g="waitingForConnect",N,j,z,U,te=!1,pe=!1;function K(){N!==void 0&&(window.clearTimeout(N),N=void 0)}function H(){j!==void 0&&(window.clearTimeout(j),j=void 0)}function Q(){z!==void 0&&(window.clearTimeout(z),z=void 0)}function G(k){let{initializationId:P,error:I,phase:ie,source:ot}=k;switch(g){case"waitingForConnect":case"preparingInit":break;case"waitingForInitResult":case"initialized":case"failed":case"stopped":return;default:return ee(g)}g="failed",U=P,K(),H(),s({type:"init",initializationId:P,status:"error",error:I}),V({...I,phase:ie,source:ot})}async function ne(k){if(g==="waitingForConnect"){g="preparingInit",U=k.initializationId,K(),j=window.setTimeout(()=>{if(g!=="preparingInit")return;let P=go();c({...P,initializationId:k.initializationId}),G({initializationId:k.initializationId,error:P,phase:"init",source:"host"})},y);try{let P=await i(k);if(g!=="preparingInit")return;if(H(),P.status==="error"){G({initializationId:k.initializationId,error:P.error,phase:"init",source:"host"});return}g="waitingForInitResult";let I={type:"init",initializationId:k.initializationId,status:"success",theme:P.initialState.theme,contrastMode:P.initialState.contrastMode??Wt,blockId:P.initialState.blockId,parent:P.initialState.parent,page:P.initialState.page,currentUser:P.initialState.currentUser,manifest:P.initialState.manifest,dataSources:P.initialState.dataSources};if(s(I),g!=="waitingForInitResult"||(X(),g!=="waitingForInitResult"))return;z=window.setTimeout(()=>{if(g!=="waitingForInitResult")return;g="failed";let ie=So();V({...ie,phase:"initResult",source:"host"}),c({...ie,initializationId:k.initializationId})},C)}catch(P){if(g!=="preparingInit")return;c({message:"Failed to prepare custom block initialization",error:P}),G({initializationId:k.initializationId,error:tt(),phase:"init",source:"host"})}}}function q(k){if(g!=="stopped"&&g==="waitingForConnect"){if(!xt(k.bridgeProtocolVersion)){let P=It({currentBridgeProtocolVersion:k.bridgeProtocolVersion});G({initializationId:k.initializationId,error:P,phase:"connect",source:"host"});return}if(k.bridgeProtocolVersion<f){let P=_t({currentBridgeProtocolVersion:k.bridgeProtocolVersion,minBridgeProtocolVersion:f});G({initializationId:k.initializationId,error:P,phase:"connect",source:"host"});return}if(k.status==="error"&&(t==="sandbox"||k.error.code!=="manifest_invalid")){G({initializationId:k.initializationId,error:k.error,phase:"connect",source:"sandbox"});return}pe=!0,ne(k)}}function Y(k){if(g==="stopped"||g!=="waitingForConnect")return"handled";let{initializationId:P,bridgeProtocolVersion:I}=k;if(P===void 0)return"nack";let ie=k.error;return I!==void 0&&(xt(I)?I<f&&(ie=_t({currentBridgeProtocolVersion:I,minBridgeProtocolVersion:f})):ie=It({currentBridgeProtocolVersion:I})),G({initializationId:P,error:ie,phase:"connect",source:"host"}),"handled"}function me(k){let{initializationId:P,error:I}=k;g!=="waitingForInitResult"||P===void 0||P!==U||(K(),Q(),g="failed",c(I),V({...I,phase:"initResult",source:"host"}))}function He(){if(g!=="stopped"){if(te){_({phase:"runtime",source:"host",code:"iframe_reloaded",message:"The iframe reloaded. Create a new host and iframe to reconnect.",isRetryable:!0});return}te=!0,K(),g==="waitingForConnect"&&(N=window.setTimeout(()=>{if(g!=="waitingForConnect")return;g="failed";let k=bo();c(k),V({...k,phase:"connect",source:"host"})},h))}}function Me(k){if(g!=="waitingForInitResult"||k.initializationId!==U){c({message:"Ignored stale or unexpected initResult",payload:k});return}Q(),g=k.status==="success"?"initialized":"failed",k.status==="success"?p():V({...k.error,phase:"initResult",source:"sandbox"}),M(k)}function fe(){g="stopped",K(),H(),Q()}return{get status(){return g},get hasConnectedSandbox(){return pe},handleConnect:q,handleInitResult:Me,handleInvalidConnect:Y,handleInvalidInitResult:me,onIframeLoad:He,stop:fe}}function Ct(){return{code:"context_unavailable",message:"Host page context is unavailable.",isRetryable:!0}}function Pt(){return{code:"invalid_local_preview_url",message:"Local custom blocks require an HTTP(S) URL on localhost, a .localhost subdomain, or 127.0.0.1, without credentials and on a different origin from the host.",isRetryable:!1}}function Io(){return{code:"invalid_property_binding",message:"A mapped data source property is missing or incompatible.",isRetryable:!1}}function _o(){return{code:"missing_data_source_binding",message:"A required data source is not mapped.",isRetryable:!1}}function xo(){return{code:"missing_property_binding",message:"A required data source property is not mapped.",isRetryable:!1}}function Co(e){return(e.protocol==="http:"||e.protocol==="https:")&&(e.hostname==="localhost"||e.hostname==="127.0.0.1"||e.hostname.endsWith(".localhost"))&&e.username===""&&e.password===""}function rt({url:e,hostOrigin:t}){return typeof t=="string"&&t!==""&&e.origin!==t&&Co(e)}async function Po(e){return e.manifestSource==="host"?e.hostManifest:e.connectManifest!==void 0?{status:"success",manifest:e.connectManifest}:{status:"error",error:{code:"manifest_unavailable",message:"The sandbox did not provide a manifest in connect.",isRetryable:!1}}}var Eo=v("status",[o({status:n("success"),manifest:de}),o({status:n("error"),error:Ne})]);function Oo(e){switch(e.type){case"connect":case"init":case"initResult":return!0;default:return!1}}var jo=o({type:n("resize"),height:A(O(),De(),Te(0))});var Bo=o({type:n("unsubscribeDataSourceQuery"),subscriptionId:r()});var Ro=o({code:r(),message:r(),isRetryable:b()});var Mo={type:n("connect"),initializationId:r(),bridgeProtocolVersion:O(),sdkVersion:r()},Do=v("status",[o({status:n("success"),manifest:a(de),...Mo}),o({status:n("error"),error:Ro,...Mo})]);var Yn=r(),ei=o({code:Yn,message:r(),isRetryable:b()}),wo=v("status",[o({type:n("initResult"),initializationId:r(),status:n("success"),initialHeight:a(A(O(),De(),Te(0)))}),o({type:n("initResult"),initializationId:r(),status:n("error"),error:ei})]);var To=o({type:n("invalidHostMessage"),reason:r()});var qo=v("type",[Do,wo,Br,Bo,Fr,Hr,Jr,to,Gr,wr,Kr,jo,To]);function Ao(e){return Ie(qo,e)}function No(){return{code:"invalid_connect_payload",message:"Sandbox sent an invalid connect message.",isRetryable:!1}}function Uo(){return{code:"invalid_init_result_payload",message:"Sandbox sent an invalid initialization result.",isRetryable:!1}}function Fo(e){if(typeof e=="object"&&e!==null&&"type"in e&&typeof e.type=="string")return e.type}function zo(e){let t=Fo(e);return t==="invalidHostMessage"||t==="invalidSandboxMessage"?{incomingType:t}:{incomingType:t,nack:{type:"invalidSandboxMessage",reason:ti(t)}}}function ti(e){return e!==void 0?`Unsupported sandbox message of type "${e}"`:"Unsupported sandbox message (no `type` field or non-object payload)"}var Ho=o({initializationId:r()}),ri=o({bridgeProtocolVersion:d([O(),pt()])});function Lo(e){let{iframe:t,sandboxOrigin:i,getInitStatus:s,emit:c,sendNack:p,onInvalidConnect:f,onInvalidInitResult:h,onConnect:y,onInitResult:C,onQueryDataSource:_,onUnsubscribeDataSourceQuery:M,onCreatePage:X,onGetPage:V,onOpenPage:g,onOpenExternalUrl:N,onGetUser:j,onListUsers:z,onUpdatePage:U,onResize:te}=e;function pe(K,H){c("warn",{message:"Ignored unsupported sandbox message",payload:Et(K),issues:H});let Q=zo(K);if(Q.incomingType==="connect"){let G=Ie(Ho,K),ne=Ie(ri,K);if(f({initializationId:G.success?G.output.initializationId:void 0,error:No(),bridgeProtocolVersion:ne.success?ne.output.bridgeProtocolVersion:void 0})==="handled")return}if(Q.incomingType==="initResult"){let G=Ie(Ho,K);h({initializationId:G.success?G.output.initializationId:void 0,error:Uo()})}Q.nack!==void 0&&s()!=="stopped"&&p(Q.nack)}return function(H){let Q=H.source===t.contentWindow,G=H.origin===i;if(!Q||!G)return;let ne=Ao(H.data);if(!ne.success){pe(H.data,ne.issues);return}let q=ne.output;if(!Oo(q)&&s()!=="initialized"){c("warn",{message:`Ignored ${q.type} before initialization completed`,payload:Et(q)});return}switch(c("in",Et(q)),q.type){case"connect":y(q);return;case"initResult":C(q);return;case"queryDataSource":_(q);return;case"unsubscribeDataSourceQuery":M(q);return;case"createPage":X(q);return;case"openPage":g(q);return;case"openExternalUrl":N(q);return;case"getPage":V(q);return;case"getUser":j(q);return;case"listUsers":z(q);return;case"updatePage":U(q);return;case"resize":te(q);return;case"invalidHostMessage":return;default:ee(q)}}}function Et(e){return typeof e=="object"&&e!==null&&"type"in e&&e.type==="openExternalUrl"?{type:"openExternalUrl",..."requestId"in e?{requestId:e.requestId}:{}}:e}function Vo(e){if(e.length>2048||!URL.canParse(e))return;let t=new URL(e);if(!(t.protocol!=="http:"&&t.protocol!=="https:"||t.username!==""||t.password!==""||t.href.length>2048))return t.href}var $o=5;function ni(e){let{iframe:t,prepareInitialState:i,handlers:s,onStatusChange:c,onLog:p,onQueryUnsubscribed:f,minBridgeProtocolVersion:h,noConnectTimeoutMs:y,initialStateTimeoutMs:C,noInitResultTimeoutMs:_}=e,M=ii(e.sandboxUrl,e.manifestSource),X=M.origin,V=Math.max(h??3,3),g=new AbortController,N,j={},z=!1,U=new AbortController,te,pe,K=8,H=new et(u=>{f?.(u)});function Q(u,S){p?.(u,S)}function G(u){let S=I.status;switch(S){case"waitingForConnect":case"preparingInit":case"waitingForInitResult":case"initialized":case"failed":break;case"stopped":return;default:return ee(S)}let x=fo(u,K);Q("out",x),t.contentWindow?.postMessage(x,X)}function ne(u){G(se(We,u))}function q(u){G(u)}function Y(u){let S=I.status;switch(S){case"initialized":G(se(io,u));return;case"waitingForConnect":case"preparingInit":case"waitingForInitResult":case"failed":case"stopped":return;default:ee(S)}}async function me(u,S){if(S===void 0)return;let x=await S(u);Y({type:`${u.type}Result`,requestId:u.requestId,...x})}function He(u){let S=u.response.status==="error"?{type:"queryDataSourceResult",subscriptionId:u.subscriptionId,status:"error",error:u.response.error}:{type:"queryDataSourceResult",subscriptionId:u.subscriptionId,status:"success",items:u.response.items,hasMore:u.response.hasMore};Y(S)}async function Me(u,S=H.subscribe(u)){try{let x=si(pe,u.dataSourceId),ve=ai(u,x);if(ve!==void 0){H.isCurrent(u.subscriptionId,S)&&(H.unsubscribe(u.subscriptionId),He({subscriptionId:u.subscriptionId,response:{status:"error",error:ve}}));return}let it=await s.queryDataSource(u);if(!H.isCurrent(u.subscriptionId,S))return;it.status==="error"&&!it.error.isRetryable&&H.unsubscribe(u.subscriptionId),He({subscriptionId:u.subscriptionId,response:it})}finally{let x=H.finish(u.subscriptionId,S);x!==void 0&&Me(x.message,x.token)}}function fe(u){I.status==="stopped"||I.status==="failed"||(Object.assign(j,u),P())}async function k(u){if(s.openExternalUrl===void 0||g.signal.aborted||N===u.requestId)return;if(N!==void 0){let x={type:"openExternalUrlResult",requestId:u.requestId,status:"error",error:{code:"pending_navigation",message:"Another external navigation request is pending.",isRetryable:!0}};Y(x);return}let S=Vo(u.url);if(S===void 0){let x={type:"openExternalUrlResult",requestId:u.requestId,status:"error",error:{code:"invalid_url",message:"Only valid HTTP or HTTPS URLs without credentials, up to 2,048 characters, can be opened.",isRetryable:!1}};Y(x);return}N=u.requestId;try{let x=await s.openExternalUrl({...u,url:S},{signal:g.signal});if(g.signal.aborted)return;let ve={type:"openExternalUrlResult",requestId:u.requestId,...x};Y(ve)}catch(x){if(!g.signal.aborted)throw x}finally{N===u.requestId&&(N=void 0)}}function P(){if(I.status!=="initialized")return;let u=j;j={},u.theme!==void 0&&Y({type:"themeChanged",theme:u.theme}),u.contrastMode!==void 0&&Y({type:"contrastModeChanged",contrastMode:u.contrastMode}),u.parent!==void 0&&Y({type:"parentChanged",parent:u.parent}),u.page!==void 0&&Y({type:"pageChanged",page:u.page}),u.dataSources!==void 0&&Y({type:"dataSourcesChanged",dataSources:u.dataSources}),u.currentUser!==void 0&&Y({type:"currentUserChanged",currentUser:u.currentUser})}let I=ko({manifestSource:e.manifestSource,async prepareInit(u){let S=u.status==="success"?u.manifest:void 0;K=u.bridgeProtocolVersion,c({status:"preparingInit",localManifest:rt({url:M,hostOrigin:window.location.origin})?S:void 0,bridgeProtocolVersion:u.bridgeProtocolVersion,sdkVersion:u.sdkVersion});let x=await(Xo??jt(S));return I.status!=="preparingInit"?x:ie(x)},sendInitMessage:ne,onInitSent:()=>c({status:"waitingForInitResult"}),warn:u=>Q("warn",u),flushPendingHostStateChanges:P,minBridgeProtocolVersion:V,noConnectTimeoutMs:y,initialStateTimeoutMs:C,noInitResultTimeoutMs:_,stopHostWithFailure:Rt,onInitResult(u){u.status==="success"&&te!==void 0&&c({status:"initialized",resolvedManifest:te,initialHeight:u.initialHeight})},onConnectionFailure:u=>{U.abort(),c({status:"failed",error:u})}});function ie(u){if(u.status==="error")return u;let S=se(kt,{...u.initialState,...j});if(te=S.manifest,j={},K<$o&&S.page.type==="unavailable")return{status:"error",error:Ct()};let x=Qo(S.manifest,S.dataSources);return x!==void 0?{status:"error",error:x}:(pe=S.dataSources,z=!0,{status:"success",initialState:S})}let ot=Ko().catch(Ot),Xo=e.manifestSource==="host"?jt(void 0).catch(Ot):void 0;async function Ko(){U.signal.throwIfAborted();let u=await e.getPersistedManifest({signal:U.signal});return U.signal.throwIfAborted(),se(Eo,u)}function Ot(u){return U.signal.aborted||Q("warn",{message:"Failed to prepare custom block initialization",error:u}),{status:"error",error:tt()}}async function jt(u){U.signal.throwIfAborted();let S=await Po({manifestSource:e.manifestSource,hostManifest:ot,connectManifest:u});if(U.signal.throwIfAborted(),S.status==="error")return S;let x=se(yo,await i({manifest:S.manifest,signal:U.signal}));return x.status==="error"?x:{status:"success",initialState:{...x.initialState,manifest:S.manifest}}}let Bt=Lo({iframe:t,sandboxOrigin:X,getInitStatus:()=>I.status,emit:Q,sendNack:q,onInvalidConnect:I.handleInvalidConnect,onInvalidInitResult:I.handleInvalidInitResult,onConnect:I.handleConnect,onInitResult:I.handleInitResult,onQueryDataSource:Me,onUnsubscribeDataSourceQuery:u=>H.unsubscribe(u.subscriptionId),onOpenExternalUrl:k,onCreatePage:u=>me(u,s.createPage),onGetPage:u=>me(u,s.getPage),onOpenPage:u=>me(u,s.openPage),onGetUser:u=>me(u,s.getUser),onListUsers:u=>me(u,s.listUsers),onUpdatePage:u=>me(u,s.updatePage),onResize:u=>s.resize?.(u)});window.addEventListener("message",Bt),t.addEventListener("load",I.onIframeLoad);function nt(){g.abort(),U.abort(),window.removeEventListener("message",Bt),t.removeEventListener("load",I.onIframeLoad),I.stop(),H.unsubscribeAll()}function Zo(){let u=I.status;nt(),u!=="stopped"&&u!=="failed"&&c({status:"stopped"})}function Rt(u){if(I.status!=="stopped"){if(I.status==="failed"){nt();return}nt(),Q("warn",u),c({status:"failed",error:u})}}return c({status:"waitingForConnect"}),{stop:Zo,setTheme(u){fe({theme:u})},setContrastMode(u){fe({contrastMode:u})},setParent(u){fe({parent:u})},setPage(u){if(u.type==="unavailable"&&K<$o&&(I.status==="preparingInit"&&z||I.status==="waitingForInitResult"||I.status==="initialized")){Rt({...Ct(),phase:"runtime",source:"host"});return}fe({page:u})},setCurrentUser(u){fe({currentUser:u})},setDataSources(u){let S={bindings:se(ye,u.bindings)},x=I.hasConnectedSandbox&&te!==void 0?Qo(te,S):void 0;return x!==void 0?(Q("warn",{message:"Ignored invalid data source bindings update",payload:S}),{status:"error",error:x}):(pe=S,fe({dataSources:S}),{status:"success"})},refreshQuery({dataSourceId:u}){if(I.status!=="initialized")return;let S=se(Z,u),x=H.refresh(S);if(x===void 0){Q("warn",`No active query exists for data source "${u}"`);return}for(let ve of x)Me(ve.message,ve.token)}}}function ii(e,t){let i;try{i=new URL(e)}catch(s){throw t==="host"?s:new Ae(Pt())}if(t==="sandbox"&&!rt({url:i,hostOrigin:window.location.origin}))throw new Ae(Pt());return i}function si(e,t){return Object.values(e?.bindings??{}).find(i=>i.collectionPointer?.id===t)?.collectionSchema}function Qo(e,t){for(let[i,s]of Object.entries(e.dataSources)){let c=t.bindings[i];if(c?.inaccessible===!0)continue;let p=Qt({manifestDataSource:s,collectionSchema:c?.collectionSchema,propertyIdsByKey:c?.propertyIdsByKey});if(c?.collectionPointer===void 0||p.status==="missing_schema")return _o();for(let f of p.properties){if(f.status==="missing")return xo();if(f.status!=="mapped")return Io()}}}function ai(e,t){return t===void 0?e.filter===void 0&&(e.sorts?.length??0)===0?void 0:{code:"data_source_schema_unavailable",message:"You cannot query this data source with filters or sorts because its schema is unavailable.",isRetryable:!1}:vo(e.filter,t)??ho(e.sorts,t)}function ui(e){let{manifestProperties:t,propertySchemasById:i}=e,s=[];for(let[c,p]of Object.entries(t)){let f=ci({propertyKey:c,manifestProperty:p,propertySchemasById:i});f!==void 0&&s.push([c,f])}return Object.fromEntries(s)}function ci(e){let{propertyKey:t,manifestProperty:i,propertySchemasById:s}=e,c=Wo(i.name),p=Object.entries(s).filter(([f,h])=>h.type===i.type&&(f===t||Wo(h.name)===c));return p.length===1?p[0][0]:void 0}function Wo(e){return e.trim().toLowerCase()}function li(e){return se(F,e)}export{Se as InvalidNotionDateError,ni as createCustomBlockHost,ui as getAutoBoundPropertyIdsByKey,rt as isAllowedLocalPreviewUrl,St as toNotionDateValue,li as toNotionPageId};
|
|
1
|
+
var Le,Yo={lang:void 0,message:void 0,abortEarly:void 0,abortPipeEarly:void 0};function st(e){return!e&&!Le?Yo:{lang:e?.lang??Le?.lang,message:e?.message,abortEarly:e?.abortEarly??Le?.abortEarly,abortPipeEarly:e?.abortPipeEarly??Le?.abortPipeEarly}}var en;function tn(e){return en?.get(e)}var rn;function on(e){return rn?.get(e)}var nn;function sn(e,t){return nn?.get(e)?.get(t)}function _e(e){let t=typeof e;return t==="string"?`"${e}"`:t==="number"||t==="bigint"||t==="boolean"?`${e}`:t==="object"||t==="function"?(e&&Object.getPrototypeOf(e)?.constructor?.name)??"null":t}function w(e,t,n,s,c){let p=c&&"input"in c?c.input:n.value,f=c?.expected??e.expects??null,h=c?.received??_e(p),y={kind:e.kind,type:e.type,input:p,expected:f,received:h,message:`Invalid ${t}: ${f?`Expected ${f} but r`:"R"}eceived ${h}`,requirement:e.requirement,path:c?.path,issues:c?.issues,lang:s.lang,abortEarly:s.abortEarly,abortPipeEarly:s.abortPipeEarly},x=e.kind==="schema",I=c?.message??e.message??sn(e.reference,y.lang)??(x?on(y.lang):null)??s.message??tn(y.lang);I!==void 0&&(y.message=typeof I=="function"?I(y):I),x&&(n.typed=!1),n.issues?n.issues.push(y):n.issues=[y]}function an(e,t){return e===t||Number.isNaN(e)&&Number.isNaN(t)}function un(e,t){return Object.prototype.hasOwnProperty.call(e,t)&&t!=="__proto__"&&t!=="prototype"&&t!=="constructor"}function at(e,t){let n=[...new Set(e)];return n.length>1?`(${n.join(` ${t} `)})`:n[0]??"never"}function W(e){return e["~standard"]={version:1,vendor:"valibot",validate:t=>e["~run"]({value:t},st())},e}var cn=class extends Error{constructor(e){super(e[0].message),this.name="ValiError",this.issues=e}};function pe(e){return{kind:"transformation",type:"brand",reference:pe,async:!1,name:e,"~run"(t){return t}}}function De(e){return{kind:"validation",type:"finite",reference:De,async:!1,expects:null,requirement:Number.isFinite,message:e,"~run"(t,n){return t.typed&&!this.requirement(t.value)&&w(this,"finite",t,n),t}}}function ut(e,t){let n=_e(e);return{kind:"validation",type:"includes",reference:ut,async:!1,expects:n,requirement:e,message:t,"~run"(s,c){return s.typed&&!s.value.includes(this.requirement)&&w(this,"content",s,c,{received:`!${n}`}),s}}}function we(e,t){return{kind:"validation",type:"max_length",reference:we,async:!1,expects:`<=${e}`,requirement:e,message:t,"~run"(n,s){return n.typed&&n.value.length>this.requirement&&w(this,"length",n,s,{received:`${n.value.length}`}),n}}}function ge(e,t){return{kind:"validation",type:"min_length",reference:ge,async:!1,expects:`>=${e}`,requirement:e,message:t,"~run"(n,s){return n.typed&&n.value.length<this.requirement&&w(this,"length",n,s,{received:`${n.value.length}`}),n}}}function Te(e,t){return{kind:"validation",type:"min_value",reference:Te,async:!1,expects:`>=${e instanceof Date?e.toJSON():_e(e)}`,requirement:e,message:t,"~run"(n,s){return n.typed&&!(n.value>=this.requirement)&&w(this,"value",n,s,{received:n.value instanceof Date?n.value.toJSON():_e(n.value)}),n}}}function ct(e,t){return{kind:"validation",type:"regex",reference:ct,async:!1,expects:`${e}`,requirement:e,message:t,"~run"(n,s){return n.typed&&!this.requirement.test(n.value)&&w(this,"format",n,s),n}}}function lt(e){return{kind:"transformation",type:"transform",reference:lt,async:!1,operation:e,"~run"(t){return t.value=this.operation(t.value),t}}}var Dt={abortEarly:!0};function wt(e,t,n){return typeof e.fallback=="function"?e.fallback(t,n):e.fallback}function Ve(e,t,n){return typeof e.default=="function"?e.default(t,n):e.default}function Tt(e,t){return!e["~run"]({value:t},Dt).issues}function E(e,t){return W({kind:"schema",type:"array",reference:E,expects:"Array",async:!1,item:e,message:t,"~run"(n,s){let c=n.value;if(Array.isArray(c)){n.typed=!0,n.value=[];for(let p=0;p<c.length;p++){let f=c[p],h=this.item["~run"]({value:f},s);if(h.issues){let y={type:"array",origin:"value",input:c,key:p,value:f};for(let x of h.issues)x.path?x.path.unshift(y):x.path=[y],n.issues?.push(x);if(n.issues||(n.issues=h.issues),s.abortEarly){n.typed=!1;break}}h.typed||(n.typed=!1),n.value.push(h.value)}}else w(this,"type",n,s);return n}})}function g(e){return W({kind:"schema",type:"boolean",reference:g,expects:"boolean",async:!1,message:e,"~run"(t,n){return typeof t.value=="boolean"?t.typed=!0:w(this,"type",t,n),t}})}function i(e,t){return W({kind:"schema",type:"literal",reference:i,expects:_e(e),async:!1,literal:e,message:t,"~run"(n,s){return an(n.value,this.literal)?n.typed=!0:w(this,"type",n,s),n}})}function pt(e){return W({kind:"schema",type:"nan",reference:pt,expects:"NaN",async:!1,message:e,"~run"(t,n){return Number.isNaN(t.value)?t.typed=!0:w(this,"type",t,n),t}})}function mt(e){return W({kind:"schema",type:"never",reference:mt,expects:"never",async:!1,message:e,"~run"(t,n){return w(this,"type",t,n),t}})}function D(e,t){return W({kind:"schema",type:"nullable",reference:D,expects:`(${e.expects} | null)`,async:!1,wrapped:e,default:t,"~run"(n,s){return n.value===null&&(this.default!==void 0&&(n.value=Ve(this,n,s)),n.value===null)?(n.typed=!0,n):this.wrapped["~run"](n,s)}})}function O(e){return W({kind:"schema",type:"number",reference:O,expects:"number",async:!1,message:e,"~run"(t,n){return typeof t.value=="number"&&!isNaN(t.value)?t.typed=!0:w(this,"type",t,n),t}})}function o(e,t){return W({kind:"schema",type:"object",reference:o,expects:"Object",async:!1,entries:e,message:t,"~run"(n,s){let c=n.value;if(c&&typeof c=="object"){n.typed=!0,n.value={};for(let p in this.entries){let f=this.entries[p];if(p in c||(f.type==="exact_optional"||f.type==="optional"||f.type==="nullish")&&f.default!==void 0){let h=p in c?c[p]:Ve(f),y=f["~run"]({value:h},s);if(y.issues){let x={type:"object",origin:"value",input:c,key:p,value:h};for(let I of y.issues)I.path?I.path.unshift(x):I.path=[x],n.issues?.push(I);if(n.issues||(n.issues=y.issues),s.abortEarly){n.typed=!1;break}}y.typed||(n.typed=!1),n.value[p]=y.value}else if(f.fallback!==void 0)n.value[p]=wt(f);else if(f.type!=="exact_optional"&&f.type!=="optional"&&f.type!=="nullish"&&(w(this,"key",n,s,{input:void 0,expected:`"${p}"`,path:[{type:"object",origin:"key",input:c,key:p,value:c[p]}]}),s.abortEarly))break}}else w(this,"type",n,s);return n}})}function a(e,t){return W({kind:"schema",type:"optional",reference:a,expects:`(${e.expects} | undefined)`,async:!1,wrapped:e,default:t,"~run"(n,s){return n.value===void 0&&(this.default!==void 0&&(n.value=Ve(this,n,s)),n.value===void 0)?(n.typed=!0,n):this.wrapped["~run"](n,s)}})}function T(e,t){return W({kind:"schema",type:"picklist",reference:T,expects:at(e.map(_e),"|"),async:!1,options:e,message:t,"~run"(n,s){return this.options.includes(n.value)?n.typed=!0:w(this,"type",n,s),n}})}function Q(e,t,n){return W({kind:"schema",type:"record",reference:Q,expects:"Object",async:!1,key:e,value:t,message:n,"~run"(s,c){let p=s.value;if(p&&typeof p=="object"){s.typed=!0,s.value={};for(let f in p)if(un(p,f)){let h=p[f],y=this.key["~run"]({value:f},c);if(y.issues){let I={type:"object",origin:"key",input:p,key:f,value:h};for(let M of y.issues)M.path=[I],s.issues?.push(M);if(s.issues||(s.issues=y.issues),c.abortEarly){s.typed=!1;break}}let x=this.value["~run"]({value:h},c);if(x.issues){let I={type:"object",origin:"value",input:p,key:f,value:h};for(let M of x.issues)M.path?M.path.unshift(I):M.path=[I],s.issues?.push(M);if(s.issues||(s.issues=x.issues),c.abortEarly){s.typed=!1;break}}(!y.typed||!x.typed)&&(s.typed=!1),y.typed&&(s.value[y.value]=x.value)}}else w(this,"type",s,c);return s}})}function l(e,t){return W({kind:"schema",type:"strict_object",reference:l,expects:"Object",async:!1,entries:e,message:t,"~run"(n,s){let c=n.value;if(c&&typeof c=="object"){n.typed=!0,n.value={};for(let p in this.entries){let f=this.entries[p];if(p in c||(f.type==="exact_optional"||f.type==="optional"||f.type==="nullish")&&f.default!==void 0){let h=p in c?c[p]:Ve(f),y=f["~run"]({value:h},s);if(y.issues){let x={type:"object",origin:"value",input:c,key:p,value:h};for(let I of y.issues)I.path?I.path.unshift(x):I.path=[x],n.issues?.push(I);if(n.issues||(n.issues=y.issues),s.abortEarly){n.typed=!1;break}}y.typed||(n.typed=!1),n.value[p]=y.value}else if(f.fallback!==void 0)n.value[p]=wt(f);else if(f.type!=="exact_optional"&&f.type!=="optional"&&f.type!=="nullish"&&(w(this,"key",n,s,{input:void 0,expected:`"${p}"`,path:[{type:"object",origin:"key",input:c,key:p,value:c[p]}]}),s.abortEarly))break}if(!n.issues||!s.abortEarly){for(let p in c)if(!Object.prototype.hasOwnProperty.call(this.entries,p)){w(this,"key",n,s,{input:p,expected:"never",path:[{type:"object",origin:"key",input:c,key:p,value:c[p]}]});break}}}else w(this,"type",n,s);return n}})}function r(e){return W({kind:"schema",type:"string",reference:r,expects:"string",async:!1,message:e,"~run"(t,n){return typeof t.value=="string"?t.typed=!0:w(this,"type",t,n),t}})}function Mt(e){let t;if(e)for(let n of e)if(t)for(let s of n.issues)t.push(s);else t=n.issues;return t}function d(e,t){return W({kind:"schema",type:"union",reference:d,expects:at(e.map(n=>n.expects),"|"),async:!1,options:e,message:t,"~run"(n,s){let c,p,f;for(let h of this.options){let y=h["~run"]({value:n.value},s);if(y.typed)if(y.issues)p?p.push(y):p=[y];else{c=y;break}else f?f.push(y):f=[y]}if(c)return c;if(p){if(p.length===1)return p[0];w(this,"type",n,s,{issues:Mt(p)}),n.typed=!0}else{if(f?.length===1)return f[0];w(this,"type",n,s,{issues:Mt(f)})}return n}})}function qe(){return W({kind:"schema",type:"unknown",reference:qe,expects:"unknown",async:!1,"~run"(e){return e.typed=!0,e}})}function v(e,t,n){return W({kind:"schema",type:"variant",reference:v,expects:"Object",async:!1,key:e,options:t,message:n,"~run"(s,c){let p=s.value;if(p&&typeof p=="object"){let f,h=0,y=this.key,x=[],I=(M,X)=>{for(let V of M.options){if(V.type==="variant")I(V,new Set(X).add(V.key));else{let b=!0,N=0;for(let B of X){let z=V.entries[B];if(B in p?z["~run"]({typed:!1,value:p[B]},Dt).issues:z.type!=="exact_optional"&&z.type!=="optional"&&z.type!=="nullish"){b=!1,y!==B&&(h<N||h===N&&B in p&&!(y in p))&&(h=N,y=B,x=[]),y===B&&x.push(V.entries[B].expects);break}N++}if(b){let B=V["~run"]({value:p},c);(!f||!f.typed&&B.typed)&&(f=B)}}if(f&&!f.issues)break}};if(I(this,new Set([this.key])),f)return f;w(this,"type",s,c,{input:p[y],expected:at(x,"|"),path:[{type:"object",origin:"value",input:p,key:y,value:p[y]}]})}else w(this,"type",s,c);return s}})}function qt(e,t){let n={...e.entries};for(let s of t)delete n[s];return W({...e,entries:n})}function ae(e,t,n){let s=e["~run"]({value:t},st(n));if(s.issues)throw new cn(s.issues);return s.value}function A(...e){return W({...e[0],pipe:e,"~run"(t,n){for(let s of e)if(s.kind!=="metadata"){if(t.issues&&(s.kind==="schema"||s.kind==="transformation")){t.typed=!1;break}(!t.issues||!n.abortEarly&&!n.abortPipeEarly)&&(t=s["~run"](t,n))}return t}})}function de(e,t,n){let s=e["~run"]({value:t},st(n));return{typed:s.typed,success:!s.issues,output:s.value,issues:s.issues}}var me=A(r(),pe("NotionBlockId")),Z=A(r(),pe("NotionDataSourceId")),F=A(r(),pe("NotionPageId")),At=A(r(),pe("NotionAgentId")),Nt=A(r(),pe("NotionSpaceId"));var Ut=o({id:Z,table:r(),spaceId:a(Nt)});var Ft=T(["default","gray","brown","orange","yellow","green","blue","purple","pink","red","gray_background","brown_background","orange_background","yellow_background","green_background","blue_background","purple_background","pink_background","red_background","default_background"]),ft=o({id:r(),name:r(),color:a(Ft),description:a(r())}),ln=o({id:r(),name:r(),color:a(Ft),option_ids:E(r())}),pn=o({synced_property_id:r(),synced_property_name:r()}),R=o({name:r(),description:a(r())}),mn=["title","rich_text","number","checkbox","url","email","phone_number","select","multi_select","status","date","people","files","unique_id","relation","place","formula","rollup","button","verification","last_visited_time","location","created_time","last_edited_time","created_by","last_edited_by"],zt=T(mn),Ht=["title","rich_text","number","checkbox","url","email","phone_number","date","created_time","last_edited_time","people","created_by"],Lt=v("type",[o({...R.entries,type:i("title")}),o({...R.entries,type:i("rich_text")}),o({...R.entries,type:i("number")}),o({...R.entries,type:i("checkbox")}),o({...R.entries,type:i("url")}),o({...R.entries,type:i("email")}),o({...R.entries,type:i("phone_number")}),o({...R.entries,type:i("select"),options:E(ft)}),o({...R.entries,type:i("multi_select"),options:E(ft)}),o({...R.entries,type:i("status"),options:E(ft),groups:E(ln)}),o({...R.entries,type:i("date")}),o({...R.entries,type:i("people")}),o({...R.entries,type:i("files")}),o({...R.entries,type:i("unique_id")}),o({...R.entries,type:i("relation"),data_source_id:a(r()),dual_property:a(pn)}),o({...R.entries,type:i("place")}),o({...R.entries,type:i("formula")}),o({...R.entries,type:i("rollup")}),o({...R.entries,type:i("button")}),o({...R.entries,type:i("verification")}),o({...R.entries,type:i("last_visited_time")}),o({...R.entries,type:i("location")}),o({...R.entries,type:i("created_time")}),o({...R.entries,type:i("last_edited_time")}),o({...R.entries,type:i("created_by")}),o({...R.entries,type:i("last_edited_by")})]);var Vt={created_time:{type:"created_time",name:"Created time"},last_edited_time:{type:"last_edited_time",name:"Last edited time"},created_by:{type:"created_by",name:"Created by"},last_edited_by:{type:"last_edited_by",name:"Last edited by"}};var Gt=o({id:a(Z),propertiesById:Q(r(),Lt)});var $t=o({collectionPointer:a(Ut),collectionSchema:a(Gt),propertyIdsByKey:a(Q(r(),a(r()))),inaccessible:a(i(!0))});var ve=Q(r(),$t);function Qt(e){let t=Object.entries(e.manifestDataSource.properties??{}).map(([n,s])=>{let c=e.propertyIdsByKey?.[n],p=c===void 0?void 0:e.collectionSchema?.propertiesById[c];return fn(n,c,p?.type,s.type)});return e.collectionSchema===void 0?{status:"missing_schema",properties:t}:t.every(n=>n.status==="mapped")?{status:"complete",properties:t}:{status:"incomplete",properties:t}}function fn(e,t,n,s){return t===void 0?{status:"missing",propertyKey:e,propertyId:t}:n===void 0?{status:"invalid",propertyKey:e,propertyId:t}:{status:n===s?"mapped":"incompatible",propertyKey:e,propertyId:t}}var Ge=o({type:i("page_id"),page_id:F}),$e=o({type:i("data_source_id"),data_source_id:Z}),yn=o({type:i("workspace"),workspace:i(!0)}),dn=o({type:i("block_id"),block_id:me}),vn=o({type:i("agent_id"),agent_id:At}),hn=o({type:i("unavailable")}),re=v("type",[Ge,$e,yn,dn,vn,hn]);var Ie=v("type",[o({type:i("unavailable")}),o({type:i("page"),id:F,parent:re})]);var xe=T(["standard","high"]),Wt="standard";var Ce=T(["light","dark"]);var Xt=o({capability:r(),resource:r()});var gn=v("type",[o({type:i("emoji"),emoji:r()}),o({type:i("external"),url:r()})]),bn=o({name:r(),description:a(r()),type:zt}),Sn=o({name:r(),description:a(r()),icon:a(gn),properties:a(Q(r(),bn),{})}),he=o({version:i(1),name:a(r()),description:a(r()),slashCommand:a(r()),icon:a(o({type:i("emoji"),emoji:r()})),dataSources:a(Q(r(),Sn),{}),capabilities:a(E(Xt))});var Qe=A(r(),pe("NotionUserId"));var ue=o({object:i("user"),id:Qe,name:a(r()),avatar_url:D(r()),type:i("person"),person:o({email:r()})});var kn=r(),Ne=o({code:kn,message:r(),isRetryable:g()}),Ae=class extends Error{constructor(t){super(t.message),this.name="CustomBlockInitializationError",this.code=t.code,this.isRetryable=t.isRetryable}code;isRetryable},We=v("status",[o({type:i("init"),initializationId:r(),status:i("success"),theme:Ce,contrastMode:xe,blockId:me,parent:re,page:Ie,manifest:he,dataSources:o({bindings:ve}),currentUser:ue}),o({type:i("init"),initializationId:r(),status:i("error"),error:Ne})]);var Kt=o({type:i("contrastModeChanged"),contrastMode:xe});var Zt=o({type:i("pageChanged"),page:Ie});var Jt=o({type:i("parentChanged"),parent:re});var Yt=o({type:i("themeChanged"),theme:Ce});var er=o({type:i("dataSourcesChanged"),dataSources:o({bindings:ve})});var Xe=o({unit:T(["year","month","week","day"]),value:O(),time:r(),defaultTimeZone:a(r())}),_n=o({unit:T(["hour","minute"]),value:O()}),Ue=o({unit:i("none")}),yt=d([Xe,_n]),tr=a(d([Xe,Ue])),rr=a(d([yt,Ue])),In=o({type:i("date"),start_date:r(),reminder:tr}),xn=o({type:i("daterange"),start_date:r(),end_date:r(),reminder:tr}),Cn=o({type:i("datetime"),start_date:r(),start_time:r(),time_zone:a(r()),reminder:rr}),Pn=o({type:i("datetimerange"),start_date:r(),start_time:r(),end_date:r(),end_time:r(),time_zone:a(r()),reminder:rr}),or=v("type",[In,xn,Cn,Pn]);var Ke=o({id:r(),table:r()});var nr=d([r(),O(),g(),or,E(r()),E(Ke)]);var ir=o({id:F,is_archived:g(),in_trash:g(),propertiesById:Q(r(),a(nr))});var En=o({type:i("emoji"),emoji:r()}),On=o({type:i("custom_emoji"),custom_emoji:o({id:r(),name:a(r()),url:a(r())})}),sr=o({type:i("external"),external:o({url:r()})}),ar=o({type:i("file"),file:o({url:r(),expiry_time:a(r())})}),Pe=v("type",[En,On,sr,ar]),Ee=v("type",[sr,ar]);var L=D(r());var dt={start:r(),end:a(L),time_zone:a(L),reminder:a(d([yt,Ue]))},ur=d([o({...dt,start:A(r(),ut("T"))}),o({...dt,time_zone:r()}),o({...dt,reminder:a(d([Xe,Ue]))})]);var cr=d([o({type:i("external"),name:r(),external:o({url:r()})}),o({type:i("file"),name:r(),file:o({url:r(),expiry_time:a(r())})})]);var Oe=D(o({...Ke.entries,table:T(["notion_user","bot","organization_bot"]),spaceId:a(r())}));var lr=o({lat:O(),lon:O(),name:a(L),address:a(L),aws_place_id:a(L),google_place_id:a(L)});var pr=o({id:r()});var vt=Q(r(),qe());var Ze=d([o({id:r(),name:a(r()),color:a(r()),description:a(L)}),o({name:r(),id:a(r()),color:a(r()),description:a(L)})]);var mr=d([o({object:a(i("user")),id:r()}),o({object:i("group"),id:r(),name:a(L)})]);var j={id:r()},ht=v("type",[o({...j,type:i("title"),title:E(vt)}),o({...j,type:i("rich_text"),rich_text:E(vt)}),o({...j,type:i("number"),number:D(O())}),o({...j,type:i("url"),url:L}),o({...j,type:i("email"),email:L}),o({...j,type:i("phone_number"),phone_number:L}),o({...j,type:i("checkbox"),checkbox:g()}),o({...j,type:i("select"),select:D(Ze)}),o({...j,type:i("status"),status:D(Ze)}),o({...j,type:i("multi_select"),multi_select:E(Ze)}),o({...j,type:i("date"),date:D(ur)}),o({...j,type:i("people"),people:E(mr)}),o({...j,type:i("relation"),has_more:a(g()),relation:E(pr)}),o({...j,type:i("files"),files:E(cr)}),o({...j,type:i("place"),place:D(lr)}),o({...j,type:i("created_time"),created_time:L}),o({...j,type:i("last_edited_time"),last_edited_time:L}),o({...j,type:i("created_by"),created_by:Oe}),o({...j,type:i("last_edited_by"),last_edited_by:Oe}),o({...j,type:i("last_visited_time"),last_visited_time:L}),o({...j,type:i("unique_id"),unique_id:r()}),o({...j,type:i("button"),button:r()}),o({...j,type:i("formula"),formula:r()}),o({...j,type:i("location"),location:r()}),o({...j,type:i("rollup"),rollup:r()}),o({...j,type:i("verification"),verification:r()})]);var Be=Q(r(),ht),fr=Q(r(),D(ht));var oe=o({object:i("page"),id:F,parent:re,properties:fr,created_by:a(Oe,null),last_edited_by:a(Oe,null),last_visited_time:a(D(r()),null),created_time:a(D(r()),null),last_edited_time:a(D(r()),null),icon:a(D(Pe),null),cover:a(D(Ee),null),url:a(D(r()),null),public_url:a(D(r()),null),is_archived:g(),in_trash:g()});var yr=d([l({equals:g()}),l({does_not_equal:g()})]);var ce=d([l({is_empty:i(!0)}),l({is_not_empty:i(!0)})]);var be=d([r(),E(r())]);var dr=d([l({contains:be}),l({contains_all:be}),l({does_not_contain:be}),ce]);var vr=l({object:i("user"),id:A(r(),ge(1),we(2e3))}),hr=d([l({contains:vr}),l({does_not_contain:vr}),l({is_empty:i(!0)}),l({is_not_empty:i(!0)})]);var J=T(["start_date","end_date"]),Bn=T(["today","tomorrow","yesterday","one_week_ago","one_week_from_now","one_month_ago","one_month_from_now"]),Fe=d([Bn,r()]),gr=d([l({target:a(J),equals:Fe}),l({target:a(J),before:Fe}),l({target:a(J),after:Fe}),l({target:a(J),on_or_before:Fe}),l({target:a(J),on_or_after:Fe}),l({target:a(J),this_week:l({})}),l({target:a(J),past_week:l({})}),l({target:a(J),past_month:l({})}),l({target:a(J),past_year:l({})}),l({target:a(J),next_week:l({})}),l({target:a(J),next_month:l({})}),l({target:a(J),next_year:l({})}),l({target:a(J),is_empty:i(!0)}),l({target:a(J),is_not_empty:i(!0)})]);var br=d([l({equals:O()}),l({does_not_equal:O()}),l({greater_than:O()}),l({less_than:O()}),l({greater_than_or_equal_to:O()}),l({less_than_or_equal_to:O()}),ce]);var Je=d([l({equals:be}),l({does_not_equal:be}),ce]);var Sr=l({object:T(["user","group"]),id:A(r(),ge(1))}),kr=d([l({contains:Sr}),l({does_not_contain:Sr}),ce]);var _r=A(F,ct(/^(?:[0-9a-f]{32}|[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12})$/i),lt(e=>e.replaceAll("-","").toLowerCase().replace(/^(.{8})(.{4})(.{4})(.{4})(.{12})$/,"$1-$2-$3-$4-$5"))),Ye=d([l({contains:_r}),l({does_not_contain:_r}),l({is_empty:i(!0)}),l({is_not_empty:i(!0)})]);var Ir=T(["To-do","In progress","Complete","Current","Future"]),xr=d([Ir,A(E(Ir),ge(1),we(5))]),Cr=d([l({group_equals:xr}),l({group_does_not_equal:xr})]);var Pr=d([Je,Cr]);var Re=d([l({equals:r()}),l({does_not_equal:r()}),l({contains:r()}),l({does_not_contain:r()}),l({starts_with:r()}),l({ends_with:r()}),ce]);var gt=d([l({propertyId:r(),relation:Ye}),l({propertyId:r(),created_by:hr}),l({propertyId:r(),title:Re}),l({propertyId:r(),rich_text:Re}),l({propertyId:r(),url:Re}),l({propertyId:r(),email:Re}),l({propertyId:r(),phone_number:Re}),l({propertyId:r(),number:br}),l({propertyId:r(),checkbox:yr}),l({propertyId:r(),select:Je}),l({propertyId:r(),multi_select:dr}),l({propertyId:r(),status:Pr}),l({propertyId:r(),date:gr}),l({propertyId:r(),people:kr})]);var Er=d([gt,l({and:E(gt)})]);var Or=T(["ascending","descending"]);var bt=10,Br=l({propertyId:r(),direction:Or});var Rr=o({type:i("queryDataSource"),subscriptionId:r(),dataSourceId:Z,limit:O(),filter:a(Er),sorts:a(E(Br))}),Rn=r(),jr=o({code:Rn,message:r(),isRetryable:g()}),Mr=v("status",[o({type:i("queryDataSourceResult"),subscriptionId:r(),status:i("success"),items:E(oe),hasMore:g()}),o({type:i("queryDataSourceResult"),subscriptionId:r(),status:i("error"),error:jr})]),Dr=v("status",[o({type:i("queryDataSourceResult"),subscriptionId:r(),status:i("success"),items:E(d([oe,ir])),hasMore:g()}),o({type:i("queryDataSourceResult"),subscriptionId:r(),status:i("error"),error:jr})]);var jn=r(),Mn=o({code:jn,message:r(),isRetryable:g()}),wr=o({type:i("openExternalUrl"),requestId:r(),url:r()}),Tr=v("status",[o({type:i("openExternalUrlResult"),requestId:r(),status:i("success")}),o({type:i("openExternalUrlResult"),requestId:r(),status:i("error"),error:Mn})]);var je=o({object:i("page"),id:F,parent:re,properties:Be,created_time:a(r()),last_edited_time:a(r()),icon:a(Pe),cover:a(Ee),url:a(r()),public_url:a(r()),is_archived:g(),in_trash:g()});var Dn=r(),Ar=o({code:Dn,message:r(),isRetryable:g()}),Nr=v("status",[o({type:i("createPageResult"),requestId:r(),status:i("success"),page:oe}),o({type:i("createPageResult"),requestId:r(),status:i("error"),error:Ar})]),Ur=v("status",[o({type:i("createPageResult"),requestId:r(),status:i("success"),page:d([oe,je])}),o({type:i("createPageResult"),requestId:r(),status:i("error"),error:Ar})]),wn=v("type",[o({type:i("start")}),o({type:i("end")}),o({type:i("before"),blockId:me}),o({type:i("after"),blockId:me})]),Za=v("type",[Ge,$e]),qr={type:i("createPage"),requestId:r(),properties:Be},Fr=v("type",[o({...qr,parent:Ge,position:a(wn)}),o({...qr,parent:$e,position:a(mt())})]);var Tn=r(),zr=o({code:Tn,message:r(),isRetryable:g()}),Hr=o({type:i("getPage"),requestId:r(),pageId:F,dataSourceId:a(Z)}),Lr=v("status",[o({type:i("getPageResult"),requestId:r(),status:i("success"),page:oe}),o({type:i("getPageResult"),requestId:r(),status:i("error"),error:zr})]),Vr=v("status",[o({type:i("getPageResult"),requestId:r(),status:i("success"),page:d([oe,je])}),o({type:i("getPageResult"),requestId:r(),status:i("error"),error:zr})]);var qn=T(["side_peek","center_peek"]),An=r(),Nn=o({code:An,message:r(),isRetryable:g()}),Gr=o({type:i("openPage"),requestId:r(),pageId:F,mode:qn}),$r=v("status",[o({type:i("openPageResult"),requestId:r(),status:i("success"),pageId:F}),o({type:i("openPageResult"),requestId:r(),status:i("error"),error:Nn})]);var Un=r(),Qr=o({code:Un,message:r(),isRetryable:g()}),Wr=v("status",[o({type:i("updatePageResult"),requestId:r(),status:i("success"),page:oe}),o({type:i("updatePageResult"),requestId:r(),status:i("error"),error:Qr})]),Xr=v("status",[o({type:i("updatePageResult"),requestId:r(),status:i("success"),page:d([oe,je])}),o({type:i("updatePageResult"),requestId:r(),status:i("error"),error:Qr})]),Kr=o({type:i("updatePage"),requestId:r(),pageId:F,dataSourceId:a(Z),properties:a(Be),icon:a(Pe),cover:a(Ee),archived:a(g())});var Zr=o({type:i("currentUserChanged"),currentUser:ue});var Fn=r(),zn=o({code:Fn,message:r(),isRetryable:g()}),Jr=o({type:i("getUser"),requestId:r(),userId:Qe}),Yr=v("status",[o({type:i("getUserResult"),requestId:r(),status:i("success"),user:ue}),o({type:i("getUserResult"),requestId:r(),status:i("error"),error:zn})]);var eo=o({object:i("list"),results:E(ue),next_cursor:D(r()),has_more:g(),type:i("user"),user:Q(r(),qe())});var Hn=r(),Ln=o({code:Hn,message:r(),isRetryable:g()}),to=o({type:i("listUsers"),requestId:r(),startCursor:a(r()),pageSize:a(O())}),ro=v("status",[o({type:i("listUsersResult"),requestId:r(),status:i("success"),list:eo}),o({type:i("listUsersResult"),requestId:r(),status:i("error"),error:Ln})]);var oo=o({type:i("invalidSandboxMessage"),requestId:a(r()),reason:r()});var no=v("type",[We,Yt,Kt,Jt,Zt,Zr,er,Yr,ro,$r,Tr,oo]),io=v("type",[...no.options,Mr,Lr,Nr,Wr]),Au=v("type",[...no.options,Dr,Vr,Ur,Xr]);function so(e){return{...e,dataSources:{bindings:Object.fromEntries(Object.entries(e.dataSources.bindings).map(([t,n])=>[t,{...n,collectionSchema:{...n.collectionSchema,propertiesById:{...n.collectionSchema?.propertiesById,...Vt}}}]))}}}function ee(e){throw new Error(`[custom-blocks-host] Unexpected value encountered: ${JSON.stringify(e)}`)}function ze(e){return{...e,properties:Object.fromEntries(Object.entries(e.properties).map(([t,n])=>{switch(n?.type){case"unique_id":case"button":case"formula":case"location":case"rollup":case"verification":return[t,null];case"title":case"rich_text":case"number":case"url":case"email":case"phone_number":case"checkbox":case"select":case"status":case"multi_select":case"date":case"people":case"relation":case"files":case"place":case"created_time":case"last_edited_time":case"created_by":case"last_edited_by":case"last_visited_time":case void 0:return[t,n];default:return ee(n)}}))}}function ao(e){return{...e,properties:Object.fromEntries(Object.values(e.properties).flatMap(t=>t?[[t.id,t]]:[])),icon:e.icon??void 0,cover:e.cover??void 0,created_time:e.created_time??void 0,last_edited_time:e.last_edited_time??void 0,url:e.url??void 0,public_url:e.public_url??void 0}}function Se(e){if(e==null||e==="")return;let t=new Date(e);if(Number.isFinite(t.getTime()))return{type:"datetime",start_date:t.toISOString().slice(0,10),start_time:t.toISOString().slice(11,16),time_zone:"UTC"}}var ke=class extends Error{};function St(e){try{return Vn(e)}catch(t){throw t instanceof RangeError?new ke(t.message):t}}function Vn(e){let{start:t,end:n,time_zone:s,reminder:c}=e;if(!t.split("T")[0])throw new ke("Date values must include a date.");let p=t.includes("T")||s!=null,f=t.match(/([+-])(\d{2}):(\d{2})$/),h=f?(Number(f[2])*60+Number(f[3]))*(f[1]==="-"?-1:1):0,y=s?.match(/^UTC(?:([+-])(\d{1,2})(?::(\d{2}))?)?$/),x=y?(Number(y[2]??0)*60+Number(y[3]??0))*(y[1]==="-"?-1:1):h,I=b=>{if(!b.split("T")[0])throw new ke("Date values must include a date.");if(!b.includes("T"))return{date:b,time:"00:00"};let N=b.match(/^(\d{4}-\d{2}-\d{2})T(\d{2}:\d{2})(?::\d{2}(?:\.\d+)?)?$/);if(N)return{date:N[1],time:N[2]};if(!s||y){let U=new Date(new Date(b).getTime()+x*6e4).toISOString();return{date:U.slice(0,10),time:U.slice(11,16)}}let B=new Intl.DateTimeFormat("en-CA",{timeZone:s,year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit",hourCycle:"h23"}).formatToParts(new Date(b)),z=U=>B.find(te=>te.type===U)?.value;return{date:`${z("year")}-${z("month")}-${z("day")}`,time:`${z("hour")}:${z("minute")}`}},M=I(t),X=n?I(n):void 0;if(!p){if(c&&!("time"in c)&&c.unit!=="none")throw new ke("Hour and minute reminders require a date with a time.");return X?{type:"daterange",start_date:M.date,end_date:X.date,reminder:c}:{type:"date",start_date:M.date,reminder:c}}let V=s??(h===0?"UTC":`UTC${h<0?"-":"+"}${Math.floor(Math.abs(h)/60)}${Math.abs(h)%60===0?"":`:${String(Math.abs(h)%60).padStart(2,"0")}`}`);return X?{type:"datetimerange",start_date:M.date,start_time:M.time,end_date:X.date,end_time:X.time,time_zone:V,reminder:c}:{type:"datetime",start_date:M.date,start_time:M.time,time_zone:V,reminder:c}}function co(e){switch(e.type){case"title":return uo(e.title);case"rich_text":return uo(e.rich_text);case"number":return e.number??void 0;case"checkbox":return e.checkbox;case"url":return e.url??"";case"email":return e.email??"";case"phone_number":return e.phone_number??"";case"select":return e.select?.name;case"status":return e.status?.name;case"multi_select":return e.multi_select.flatMap(t=>t.name??[]);case"date":return e.date?St(e.date):void 0;case"people":return e.people.map(t=>t.object==="group"?{id:t.id,table:"space_permission_group",spaceId:t.id.split("|")[1]}:{id:t.id,table:"notion_user"});case"relation":return e.relation.map(t=>({id:t.id,table:"block"}));case"files":return e.files.map(t=>t.name).join(",");case"unique_id":return e.unique_id;case"button":return e.button;case"formula":return e.formula;case"location":return e.location;case"rollup":return e.rollup;case"verification":return e.verification;case"place":return"";case"created_time":return Se(e.created_time);case"last_edited_time":return Se(e.last_edited_time);case"last_visited_time":return Se(e.last_visited_time);case"created_by":return e.created_by?[e.created_by]:void 0;case"last_edited_by":return e.last_edited_by?[e.last_edited_by]:void 0;default:return ee(e)}}function uo(e){return e.map(t=>{if(typeof t.plain_text=="string")return t.plain_text;let n=t.text;return n&&typeof n=="object"&&"content"in n&&typeof n.content=="string"?n.content:""}).join("")}function lo(e){let t={};for(let n of Object.values(e.properties))n&&(t[n.id]=co(n));return{id:e.id,is_archived:e.is_archived,in_trash:e.in_trash,propertiesById:{...t,created_time:Se(e.created_time),last_edited_time:Se(e.last_edited_time),created_by:e.created_by?[e.created_by]:void 0,last_edited_by:e.last_edited_by?[e.last_edited_by]:void 0}}}function po(e){return e.type==="queryDataSourceResult"?{...e,items:e.items.map(lo)}:{...e,page:ao(ze(e.page))}}function mo(e){return e.type==="queryDataSourceResult"?{...e,items:e.items.map(ze)}:{...e,page:ze(e.page)}}function fo(e,t){return e.type==="init"&&e.status==="success"||e.type==="dataSourcesChanged"?t<5?so(e):e:e.type!=="queryDataSourceResult"&&e.type!=="getPageResult"&&e.type!=="createPageResult"&&e.type!=="updatePageResult"||e.status==="error"?e:t<6?po(e):t<7?mo(e):e}var kt=o({theme:Ce,contrastMode:a(xe),blockId:me,parent:re,page:Ie,manifest:he,dataSources:o({bindings:ve}),currentUser:ue}),yo=v("status",[o({status:i("success"),initialState:qt(kt,["manifest"])}),o({status:i("error"),error:Ne})]);var et=class{constructor(t){this.onUnsubscribe=t}onUnsubscribe;bySubscriptionId=new Map;subscribe(t){this.unsubscribe(t.subscriptionId);let n={_tag:"QuerySubscriptionToken"};return this.bySubscriptionId.set(t.subscriptionId,{message:t,token:n,isRefreshing:!0,shouldRefreshAgain:!1}),n}isCurrent(t,n){return this.bySubscriptionId.get(t)?.token===n}unsubscribe(t){this.bySubscriptionId.delete(t)&&this.onUnsubscribe(t)}refresh(t){let n=[],s=!1;for(let c of this.bySubscriptionId.values())if(c.message.dataSourceId===t){if(s=!0,c.isRefreshing){c.shouldRefreshAgain=!0;continue}c.isRefreshing=!0,n.push({message:c.message,token:c.token})}return s?n:void 0}finish(t,n){let s=this.bySubscriptionId.get(t);if(s?.token===n&&(s.isRefreshing=!1,!!s.shouldRefreshAgain))return s.shouldRefreshAgain=!1,s.isRefreshing=!0,{message:s.message,token:s.token}}unsubscribeAll(){for(let t of this.bySubscriptionId.keys())this.unsubscribe(t)}};function vo(e,t){if(e===void 0)return;let n="and"in e?e.and:[e];for(let s of n){let c=Qn(s,t);if(c!==void 0)return c}}function Qn(e,t){if(!Object.hasOwn(t.propertiesById,e.propertyId))return{code:"invalid_data_source_query_filter",message:`Data source query filter property ID "${e.propertyId}" is not defined in the bound data source schema.`,isRetryable:!1};let n=t.propertiesById[e.propertyId],s=Object.keys(e).find(h=>h!=="propertyId");if(s!==n.type)return{code:"invalid_data_source_query_filter",message:`Data source query filter branch "${s}" does not match property type "${n.type}".`,isRetryable:!1};if("status"in e&&n.type==="status"){let h=e.status;if("group_equals"in h||"group_does_not_equal"in h){let y="group_equals"in h?h.group_equals:h.group_does_not_equal,I=(Array.isArray(y)?y:[y]).find(M=>!n.groups.some(X=>X.name===M));return I===void 0?void 0:{code:"invalid_data_source_query_filter",message:`Unknown status group "${I}".`,isRetryable:!1}}}if("relation"in e&&!Tt(Ye,e.relation))return{code:"invalid_data_source_query_filter",message:"Relation filters require a page ID.",isRetryable:!1};let c=Wn(e);if(c===void 0||n.type!==c.propertyType)return;let p=new Set(n.options.map(h=>h.name)),f=Xn(c.operator).find(h=>!p.has(h));if(f!==void 0)return{code:"invalid_data_source_query_filter",message:`Data source query filter option "${f}" is not defined for property "${e.propertyId}".`,isRetryable:!1}}function Wn(e){if("select"in e)return{propertyType:"select",operator:e.select};if("multi_select"in e)return{propertyType:"multi_select",operator:e.multi_select};if("status"in e){let t=e.status;return"group_equals"in t||"group_does_not_equal"in t?void 0:{propertyType:"status",operator:t}}}function Xn(e){let t;if("equals"in e)t=e.equals;else if("does_not_equal"in e)t=e.does_not_equal;else if("contains"in e)t=e.contains;else if("contains_all"in e)t=e.contains_all;else if("does_not_contain"in e)t=e.does_not_contain;else return"is_empty"in e||"is_not_empty"in e?[]:ee(e);return Array.isArray(t)?t:[t]}var Kn=new Set(Ht);function ho(e,t){if(e===void 0)return;if(e.length>bt)return{code:"invalid_data_source_query_sort",message:`Data source query sorts may contain at most ${bt} entries.`,isRetryable:!1};let n=new Set;for(let s of e){if(n.has(s.propertyId))return{code:"invalid_data_source_query_sort",message:`Data source query sorts cannot contain duplicate property ID "${s.propertyId}".`,isRetryable:!1};if(n.add(s.propertyId),!Object.hasOwn(t.propertiesById,s.propertyId))return{code:"invalid_data_source_query_sort",message:`Data source query sort property ID "${s.propertyId}" is not defined in the bound data source schema.`,isRetryable:!1};let c=t.propertiesById[s.propertyId];if(!Kn.has(c.type))return{code:"invalid_data_source_query_sort",message:`Data source query sorts do not yet support property type "${c.type}".`,isRetryable:!1}}}function go(){return{code:"initial_state_timeout",message:"Host did not prepare initial state before the timeout.",isRetryable:!0}}function _t(e){let{currentBridgeProtocolVersion:t}=e;return{code:"invalid_protocol_version",message:`Sandbox reported an invalid bridge protocol version: ${t}`,isRetryable:!1}}function bo(){return{code:"no_connect",message:"Sandbox did not send a connect message.",isRetryable:!0}}function So(){return{code:"no_init_result",message:"Sandbox did not acknowledge initialization.",isRetryable:!0}}function tt(){return{code:"unknown_error",message:"Unexpected error while initializing custom block.",isRetryable:!1}}function It(e){let{currentBridgeProtocolVersion:t,minBridgeProtocolVersion:n}=e;return{code:"unsupported_protocol_version",message:`Sandbox bridge protocol version ${t} is not supported. Minimum supported version is ${n}.`,isRetryable:!1}}function xt(e){return Number.isFinite(e)&&Number.isInteger(e)&&e>=1}var Zn=5e3,Jn=5e3,Yn=5e3;function ko(e){let{manifestSource:t,prepareInit:n,sendInitMessage:s,warn:c,flushPendingHostStateChanges:p,minBridgeProtocolVersion:f,noConnectTimeoutMs:h=Zn,initialStateTimeoutMs:y=Jn,noInitResultTimeoutMs:x=Yn,stopHostWithFailure:I,onInitResult:M,onInitSent:X,onConnectionFailure:V}=e,b="waitingForConnect",N,B,z,U,te=!1,fe=!1;function K(){N!==void 0&&(window.clearTimeout(N),N=void 0)}function H(){B!==void 0&&(window.clearTimeout(B),B=void 0)}function G(){z!==void 0&&(window.clearTimeout(z),z=void 0)}function $(k){let{initializationId:C,error:_,phase:se,source:ot}=k;switch(b){case"waitingForConnect":case"preparingInit":break;case"waitingForInitResult":case"initialized":case"failed":case"stopped":return;default:return ee(b)}b="failed",U=C,K(),H(),s({type:"init",initializationId:C,status:"error",error:_}),V({..._,phase:se,source:ot})}async function ne(k){if(b==="waitingForConnect"){b="preparingInit",U=k.initializationId,K(),B=window.setTimeout(()=>{if(b!=="preparingInit")return;let C=go();c({...C,initializationId:k.initializationId}),$({initializationId:k.initializationId,error:C,phase:"init",source:"host"})},y);try{let C=await n(k);if(b!=="preparingInit")return;if(H(),C.status==="error"){$({initializationId:k.initializationId,error:C.error,phase:"init",source:"host"});return}b="waitingForInitResult";let _={type:"init",initializationId:k.initializationId,status:"success",theme:C.initialState.theme,contrastMode:C.initialState.contrastMode??Wt,blockId:C.initialState.blockId,parent:C.initialState.parent,page:C.initialState.page,currentUser:C.initialState.currentUser,manifest:C.initialState.manifest,dataSources:C.initialState.dataSources};if(s(_),b!=="waitingForInitResult"||(X(),b!=="waitingForInitResult"))return;z=window.setTimeout(()=>{if(b!=="waitingForInitResult")return;b="failed";let se=So();V({...se,phase:"initResult",source:"host"}),c({...se,initializationId:k.initializationId})},x)}catch(C){if(b!=="preparingInit")return;c({message:"Failed to prepare custom block initialization",error:C}),$({initializationId:k.initializationId,error:tt(),phase:"init",source:"host"})}}}function q(k){if(b!=="stopped"&&b==="waitingForConnect"){if(!xt(k.bridgeProtocolVersion)){let C=_t({currentBridgeProtocolVersion:k.bridgeProtocolVersion});$({initializationId:k.initializationId,error:C,phase:"connect",source:"host"});return}if(k.bridgeProtocolVersion<f){let C=It({currentBridgeProtocolVersion:k.bridgeProtocolVersion,minBridgeProtocolVersion:f});$({initializationId:k.initializationId,error:C,phase:"connect",source:"host"});return}if(k.status==="error"&&(t==="sandbox"||k.error.code!=="manifest_invalid")){$({initializationId:k.initializationId,error:k.error,phase:"connect",source:"sandbox"});return}fe=!0,ne(k)}}function Y(k){if(b==="stopped"||b!=="waitingForConnect")return"handled";let{initializationId:C,bridgeProtocolVersion:_}=k;if(C===void 0)return"nack";let se=k.error;return _!==void 0&&(xt(_)?_<f&&(se=It({currentBridgeProtocolVersion:_,minBridgeProtocolVersion:f})):se=_t({currentBridgeProtocolVersion:_})),$({initializationId:C,error:se,phase:"connect",source:"host"}),"handled"}function ie(k){let{initializationId:C,error:_}=k;b!=="waitingForInitResult"||C===void 0||C!==U||(K(),G(),b="failed",c(_),V({..._,phase:"initResult",source:"host"}))}function He(){if(b!=="stopped"){if(te){I({phase:"runtime",source:"host",code:"iframe_reloaded",message:"The iframe reloaded. Create a new host and iframe to reconnect.",isRetryable:!0});return}te=!0,K(),b==="waitingForConnect"&&(N=window.setTimeout(()=>{if(b!=="waitingForConnect")return;b="failed";let k=bo();c(k),V({...k,phase:"connect",source:"host"})},h))}}function Me(k){if(b!=="waitingForInitResult"||k.initializationId!==U){c({message:"Ignored stale or unexpected initResult",payload:k});return}G(),b=k.status==="success"?"initialized":"failed",k.status==="success"?p():V({...k.error,phase:"initResult",source:"sandbox"}),M(k)}function ye(){b="stopped",K(),H(),G()}return{get status(){return b},get hasConnectedSandbox(){return fe},handleConnect:q,handleInitResult:Me,handleInvalidConnect:Y,handleInvalidInitResult:ie,onIframeLoad:He,stop:ye}}function Ct(){return{code:"context_unavailable",message:"Host page context is unavailable.",isRetryable:!0}}function Pt(){return{code:"invalid_local_preview_url",message:"Local custom blocks require an HTTP(S) URL on localhost, a .localhost subdomain, or 127.0.0.1, without credentials and on a different origin from the host.",isRetryable:!1}}function _o(){return{code:"invalid_property_binding",message:"A mapped data source property is missing or incompatible.",isRetryable:!1}}function Io(){return{code:"missing_data_source_binding",message:"A required data source is not mapped.",isRetryable:!1}}function xo(){return{code:"missing_property_binding",message:"A required data source property is not mapped.",isRetryable:!1}}function Co(e){return(e.protocol==="http:"||e.protocol==="https:")&&(e.hostname==="localhost"||e.hostname==="127.0.0.1"||e.hostname.endsWith(".localhost"))&&e.username===""&&e.password===""}function rt({url:e,hostOrigin:t}){return typeof t=="string"&&t!==""&&e.origin!==t&&Co(e)}async function Po(e){return e.manifestSource==="host"?e.hostManifest:e.connectManifest!==void 0?{status:"success",manifest:e.connectManifest}:{status:"error",error:{code:"manifest_unavailable",message:"The sandbox did not provide a manifest in connect.",isRetryable:!1}}}var Eo=v("status",[o({status:i("success"),manifest:he}),o({status:i("error"),error:Ne})]);function Oo(e){switch(e.type){case"connect":case"init":case"initResult":return!0;default:return!1}}var Bo=o({type:i("resize"),height:A(O(),De(),Te(0))});var Ro=o({type:i("unsubscribeDataSourceQuery"),subscriptionId:r()});var jo=o({code:r(),message:r(),isRetryable:g()});var Mo={type:i("connect"),initializationId:r(),bridgeProtocolVersion:O(),sdkVersion:r()},Do=v("status",[o({status:i("success"),manifest:a(he),...Mo}),o({status:i("error"),error:jo,...Mo})]);var ei=r(),ti=o({code:ei,message:r(),isRetryable:g()}),wo=v("status",[o({type:i("initResult"),initializationId:r(),status:i("success"),initialHeight:a(A(O(),De(),Te(0)))}),o({type:i("initResult"),initializationId:r(),status:i("error"),error:ti})]);var To=o({type:i("invalidHostMessage"),requestId:a(r()),reason:r()});var qo=v("type",[Do,wo,Rr,Ro,Fr,Hr,Jr,to,Gr,wr,Kr,Bo,To]);function Ao(e){return de(qo,e)}function No(){return{code:"invalid_connect_payload",message:"Sandbox sent an invalid connect message.",isRetryable:!1}}function Uo(){return{code:"invalid_init_result_payload",message:"Sandbox sent an invalid initialization result.",isRetryable:!1}}function Fo(e){if(typeof e=="object"&&e!==null&&"type"in e&&typeof e.type=="string")return e.type}var ri=o({requestId:r()});function zo(e){let t=de(ri,e);return t.success?t.output.requestId:void 0}function Ho(e){let t=Fo(e);if(t==="invalidHostMessage"||t==="invalidSandboxMessage")return{incomingType:t};let n=zo(e);return{incomingType:t,nack:{type:"invalidSandboxMessage",...n!==void 0?{requestId:n}:{},reason:oi(t)}}}function oi(e){return e!==void 0?`Unsupported sandbox message of type "${e}"`:"Unsupported sandbox message (no `type` field or non-object payload)"}var Lo=o({initializationId:r()}),ni=o({bridgeProtocolVersion:d([O(),pt()])});function Vo(e){let{iframe:t,sandboxOrigin:n,getInitStatus:s,emit:c,sendNack:p,onInvalidConnect:f,onInvalidInitResult:h,onConnect:y,onInitResult:x,onQueryDataSource:I,onUnsubscribeDataSourceQuery:M,onCreatePage:X,onGetPage:V,onOpenPage:b,onOpenExternalUrl:N,onGetUser:B,onListUsers:z,onUpdatePage:U,onResize:te}=e;function fe(K,H){c("warn",{message:"Ignored unsupported sandbox message",payload:Et(K),issues:H});let G=Ho(K);if(G.incomingType==="connect"){let $=de(Lo,K),ne=de(ni,K);if(f({initializationId:$.success?$.output.initializationId:void 0,error:No(),bridgeProtocolVersion:ne.success?ne.output.bridgeProtocolVersion:void 0})==="handled")return}if(G.incomingType==="initResult"){let $=de(Lo,K);h({initializationId:$.success?$.output.initializationId:void 0,error:Uo()})}G.nack!==void 0&&s()!=="stopped"&&p(G.nack)}return function(H){let G=H.source===t.contentWindow,$=H.origin===n;if(!G||!$)return;let ne=Ao(H.data);if(!ne.success){fe(H.data,ne.issues);return}let q=ne.output;if(!Oo(q)&&s()!=="initialized"){c("warn",{message:`Ignored ${q.type} before initialization completed`,payload:Et(q)});return}switch(c("in",Et(q)),q.type){case"connect":y(q);return;case"initResult":x(q);return;case"queryDataSource":I(q);return;case"unsubscribeDataSourceQuery":M(q);return;case"createPage":X(q);return;case"openPage":b(q);return;case"openExternalUrl":N(q);return;case"getPage":V(q);return;case"getUser":B(q);return;case"listUsers":z(q);return;case"updatePage":U(q);return;case"resize":te(q);return;case"invalidHostMessage":return;default:ee(q)}}}function Et(e){return typeof e=="object"&&e!==null&&"type"in e&&e.type==="openExternalUrl"?{type:"openExternalUrl",..."requestId"in e?{requestId:e.requestId}:{}}:e}function Go(e){if(e.length>2048||!URL.canParse(e))return;let t=new URL(e);if(!(t.protocol!=="http:"&&t.protocol!=="https:"||t.username!==""||t.password!==""||t.href.length>2048))return t.href}var Qo=5;function si(e){let{iframe:t,prepareInitialState:n,handlers:s,onStatusChange:c,onLog:p,onQueryUnsubscribed:f,minBridgeProtocolVersion:h,noConnectTimeoutMs:y,initialStateTimeoutMs:x,noInitResultTimeoutMs:I}=e,M=ai(e.sandboxUrl,e.manifestSource),X=M.origin,V=Math.max(h??3,3),b=new AbortController,N,B={},z=!1,U=new AbortController,te,fe,K=8,H=new et(u=>{f?.(u)});function G(u,S){p?.(u,S)}function $(u){let S=_.status;switch(S){case"waitingForConnect":case"preparingInit":case"waitingForInitResult":case"initialized":case"failed":break;case"stopped":return;default:return ee(S)}let P=fo(u,K);G("out",P),t.contentWindow?.postMessage(P,X)}function ne(u){$(ae(We,u))}function q(u){$(u)}function Y(u){let S=_.status;switch(S){case"initialized":$(ae(io,u));return;case"waitingForConnect":case"preparingInit":case"waitingForInitResult":case"failed":case"stopped":return;default:ee(S)}}async function ie(u,S){try{let P=S===void 0?ci(u.type):await S(u);Y({...P,type:`${u.type}Result`,requestId:u.requestId})}catch(P){if(_.status!=="initialized")return;G("warn",P),Y({type:`${u.type}Result`,requestId:u.requestId,status:"error",error:{code:"unknown_error",message:`The host could not complete ${u.type}.`,isRetryable:!1}})}}function He(u){let S=u.response.status==="error"?{type:"queryDataSourceResult",subscriptionId:u.subscriptionId,status:"error",error:u.response.error}:{type:"queryDataSourceResult",subscriptionId:u.subscriptionId,status:"success",items:u.response.items,hasMore:u.response.hasMore};Y(S)}async function Me(u,S=H.subscribe(u)){try{let P=ui(fe,u.dataSourceId),le=li(u,P);if(le!==void 0){H.isCurrent(u.subscriptionId,S)&&(H.unsubscribe(u.subscriptionId),He({subscriptionId:u.subscriptionId,response:{status:"error",error:le}}));return}let it=await s.queryDataSource(u);if(!H.isCurrent(u.subscriptionId,S))return;it.status==="error"&&!it.error.isRetryable&&H.unsubscribe(u.subscriptionId),He({subscriptionId:u.subscriptionId,response:it})}finally{let P=H.finish(u.subscriptionId,S);P!==void 0&&Me(P.message,P.token)}}function ye(u){_.status==="stopped"||_.status==="failed"||(Object.assign(B,u),C())}async function k(u){if(b.signal.aborted)return;let S=s.openExternalUrl;if(S===void 0){await ie(u,void 0);return}if(N===u.requestId)return;if(N!==void 0){let le={type:"openExternalUrlResult",requestId:u.requestId,status:"error",error:{code:"pending_navigation",message:"Another external navigation request is pending.",isRetryable:!0}};Y(le);return}let P=Go(u.url);if(P===void 0){let le={type:"openExternalUrlResult",requestId:u.requestId,status:"error",error:{code:"invalid_url",message:"Only valid HTTP or HTTPS URLs without credentials, up to 2,048 characters, can be opened.",isRetryable:!1}};Y(le);return}N=u.requestId;try{await ie(u,()=>S({...u,url:P},{signal:b.signal}))}finally{N===u.requestId&&(N=void 0)}}function C(){if(_.status!=="initialized")return;let u=B;B={},u.theme!==void 0&&Y({type:"themeChanged",theme:u.theme}),u.contrastMode!==void 0&&Y({type:"contrastModeChanged",contrastMode:u.contrastMode}),u.parent!==void 0&&Y({type:"parentChanged",parent:u.parent}),u.page!==void 0&&Y({type:"pageChanged",page:u.page}),u.dataSources!==void 0&&Y({type:"dataSourcesChanged",dataSources:u.dataSources}),u.currentUser!==void 0&&Y({type:"currentUserChanged",currentUser:u.currentUser})}let _=ko({manifestSource:e.manifestSource,async prepareInit(u){let S=u.status==="success"?u.manifest:void 0;K=u.bridgeProtocolVersion,c({status:"preparingInit",localManifest:rt({url:M,hostOrigin:window.location.origin})?S:void 0,bridgeProtocolVersion:u.bridgeProtocolVersion,sdkVersion:u.sdkVersion});let P=await(Ko??Bt(S));return _.status!=="preparingInit"?P:se(P)},sendInitMessage:ne,onInitSent:()=>c({status:"waitingForInitResult"}),warn:u=>G("warn",u),flushPendingHostStateChanges:C,minBridgeProtocolVersion:V,noConnectTimeoutMs:y,initialStateTimeoutMs:x,noInitResultTimeoutMs:I,stopHostWithFailure:jt,onInitResult(u){u.status==="success"&&te!==void 0&&c({status:"initialized",resolvedManifest:te,initialHeight:u.initialHeight})},onConnectionFailure:u=>{U.abort(),c({status:"failed",error:u})}});function se(u){if(u.status==="error")return u;let S=ae(kt,{...u.initialState,...B});if(te=S.manifest,B={},K<Qo&&S.page.type==="unavailable")return{status:"error",error:Ct()};let P=Wo(S.manifest,S.dataSources);return P!==void 0?{status:"error",error:P}:(fe=S.dataSources,z=!0,{status:"success",initialState:S})}let ot=Zo().catch(Ot),Ko=e.manifestSource==="host"?Bt(void 0).catch(Ot):void 0;async function Zo(){U.signal.throwIfAborted();let u=await e.getPersistedManifest({signal:U.signal});return U.signal.throwIfAborted(),ae(Eo,u)}function Ot(u){return U.signal.aborted||G("warn",{message:"Failed to prepare custom block initialization",error:u}),{status:"error",error:tt()}}async function Bt(u){U.signal.throwIfAborted();let S=await Po({manifestSource:e.manifestSource,hostManifest:ot,connectManifest:u});if(U.signal.throwIfAborted(),S.status==="error")return S;let P=ae(yo,await n({manifest:S.manifest,signal:U.signal}));return P.status==="error"?P:{status:"success",initialState:{...P.initialState,manifest:S.manifest}}}let Rt=Vo({iframe:t,sandboxOrigin:X,getInitStatus:()=>_.status,emit:G,sendNack:q,onInvalidConnect:_.handleInvalidConnect,onInvalidInitResult:_.handleInvalidInitResult,onConnect:_.handleConnect,onInitResult:_.handleInitResult,onQueryDataSource:Me,onUnsubscribeDataSourceQuery:u=>H.unsubscribe(u.subscriptionId),onOpenExternalUrl:k,onCreatePage:u=>ie(u,s.createPage),onGetPage:u=>ie(u,s.getPage),onOpenPage:u=>ie(u,s.openPage),onGetUser:u=>ie(u,s.getUser),onListUsers:u=>ie(u,s.listUsers),onUpdatePage:u=>ie(u,s.updatePage),onResize:u=>s.resize?.(u)});window.addEventListener("message",Rt),t.addEventListener("load",_.onIframeLoad);function nt(){b.abort(),U.abort(),window.removeEventListener("message",Rt),t.removeEventListener("load",_.onIframeLoad),_.stop(),H.unsubscribeAll()}function Jo(){let u=_.status;nt(),u!=="stopped"&&u!=="failed"&&c({status:"stopped"})}function jt(u){if(_.status!=="stopped"){if(_.status==="failed"){nt();return}nt(),G("warn",u),c({status:"failed",error:u})}}return c({status:"waitingForConnect"}),{stop:Jo,setTheme(u){ye({theme:u})},setContrastMode(u){ye({contrastMode:u})},setParent(u){ye({parent:u})},setPage(u){if(u.type==="unavailable"&&K<Qo&&(_.status==="preparingInit"&&z||_.status==="waitingForInitResult"||_.status==="initialized")){jt({...Ct(),phase:"runtime",source:"host"});return}ye({page:u})},setCurrentUser(u){ye({currentUser:u})},setDataSources(u){let S={bindings:ae(ve,u.bindings)},P=_.hasConnectedSandbox&&te!==void 0?Wo(te,S):void 0;return P!==void 0?(G("warn",{message:"Ignored invalid data source bindings update",payload:S}),{status:"error",error:P}):(fe=S,ye({dataSources:S}),{status:"success"})},refreshQuery({dataSourceId:u}){if(_.status!=="initialized")return;let S=ae(Z,u),P=H.refresh(S);if(P===void 0){G("warn",`No active query exists for data source "${u}"`);return}for(let le of P)Me(le.message,le.token)}}}function ai(e,t){let n;try{n=new URL(e)}catch(s){throw t==="host"?s:new Ae(Pt())}if(t==="sandbox"&&!rt({url:n,hostOrigin:window.location.origin}))throw new Ae(Pt());return n}function ui(e,t){return Object.values(e?.bindings??{}).find(n=>n.collectionPointer?.id===t)?.collectionSchema}function Wo(e,t){for(let[n,s]of Object.entries(e.dataSources)){let c=t.bindings[n];if(c?.inaccessible===!0)continue;let p=Qt({manifestDataSource:s,collectionSchema:c?.collectionSchema,propertyIdsByKey:c?.propertyIdsByKey});if(c?.collectionPointer===void 0||p.status==="missing_schema")return Io();for(let f of p.properties){if(f.status==="missing")return xo();if(f.status!=="mapped")return _o()}}}function ci(e){return{status:"error",error:{code:"unsupported_operation",message:`The host does not support ${e}.`,isRetryable:!1}}}function li(e,t){return t===void 0?e.filter===void 0&&(e.sorts?.length??0)===0?void 0:{code:"data_source_schema_unavailable",message:"You cannot query this data source with filters or sorts because its schema is unavailable.",isRetryable:!1}:vo(e.filter,t)??ho(e.sorts,t)}function pi(e){let{manifestProperties:t,propertySchemasById:n}=e,s=[];for(let[c,p]of Object.entries(t)){let f=mi({propertyKey:c,manifestProperty:p,propertySchemasById:n});f!==void 0&&s.push([c,f])}return Object.fromEntries(s)}function mi(e){let{propertyKey:t,manifestProperty:n,propertySchemasById:s}=e,c=Xo(n.name),p=Object.entries(s).filter(([f,h])=>h.type===n.type&&(f===t||Xo(h.name)===c));return p.length===1?p[0][0]:void 0}function Xo(e){return e.trim().toLowerCase()}function fi(e){return ae(F,e)}export{ke as InvalidNotionDateError,si as createCustomBlockHost,pi as getAutoBoundPropertyIdsByKey,rt as isAllowedLocalPreviewUrl,St as toNotionDateValue,fi as toNotionPageId};
|
|
@@ -1318,6 +1318,7 @@ export declare function normalizeSandboxToHostMessage(payload: unknown): v.SafeP
|
|
|
1318
1318
|
readonly height: v.SchemaWithPipe<readonly [v.NumberSchema<undefined>, v.FiniteAction<number, undefined>, v.MinValueAction<number, 0, undefined>]>;
|
|
1319
1319
|
}, undefined>, v.ObjectSchema<{
|
|
1320
1320
|
readonly type: v.LiteralSchema<"invalidHostMessage", undefined>;
|
|
1321
|
+
readonly requestId: v.OptionalSchema<v.StringSchema<undefined>, undefined>;
|
|
1321
1322
|
readonly reason: v.StringSchema<undefined>;
|
|
1322
1323
|
}, undefined>], undefined>>;
|
|
1323
1324
|
//# sourceMappingURL=normalizeSandboxToHostMessage.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"normalizeSandboxToHostMessage.d.ts","sourceRoot":"","sources":["../../src/compatibility/normalizeSandboxToHostMessage.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,CAAC,MAAM,SAAS,CAAA;AAE5B;;;GAGG;AACH,wBAAgB,6BAA6B,CAAC,OAAO,EAAE,OAAO
|
|
1
|
+
{"version":3,"file":"normalizeSandboxToHostMessage.d.ts","sourceRoot":"","sources":["../../src/compatibility/normalizeSandboxToHostMessage.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,CAAC,MAAM,SAAS,CAAA;AAE5B;;;GAGG;AACH,wBAAgB,6BAA6B,CAAC,OAAO,EAAE,OAAO;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;4BAE7D"}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import type { customBlockPageSchema } from "./protocol/context/containingPage.js";
|
|
2
2
|
import type { NotionContrastMode } from "./protocol/context/contrast.js";
|
|
3
|
-
import type {
|
|
3
|
+
import type { BridgeParent } from "./protocol/context/parent.js";
|
|
4
4
|
import type { NotionTheme } from "./protocol/context/theme.js";
|
|
5
5
|
import type { BridgeUser } from "./protocol/users/bridgeUser.js";
|
|
6
6
|
import type { CustomBlockErrorInfo } from "./protocol/utils/errors.js";
|
|
@@ -54,7 +54,7 @@ export type CustomBlockHostHandle = {
|
|
|
54
54
|
stop: () => void;
|
|
55
55
|
setTheme: (theme: NotionTheme) => void;
|
|
56
56
|
setContrastMode: (contrastMode: NotionContrastMode) => void;
|
|
57
|
-
setParent: (parent:
|
|
57
|
+
setParent: (parent: BridgeParent) => void;
|
|
58
58
|
setPage: (page: InferInput<typeof customBlockPageSchema>) => void;
|
|
59
59
|
/**
|
|
60
60
|
* Reports synchronous local acceptance, not sandbox delivery or initialization success.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"createCustomBlockHost.d.ts","sourceRoot":"","sources":["../src/createCustomBlockHost.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,qBAAqB,EAAE,MAAM,4DAA4D,CAAA;AACvG,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,sDAAsD,CAAA;AAC9F,OAAO,KAAK,EAAE,
|
|
1
|
+
{"version":3,"file":"createCustomBlockHost.d.ts","sourceRoot":"","sources":["../src/createCustomBlockHost.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,qBAAqB,EAAE,MAAM,4DAA4D,CAAA;AACvG,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,sDAAsD,CAAA;AAC9F,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,oDAAoD,CAAA;AACtF,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,mDAAmD,CAAA;AAuBpF,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,sDAAsD,CAAA;AACtF,OAAO,KAAK,EAAE,oBAAoB,EAAE,MAAM,kDAAkD,CAAA;AAI5F,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,SAAS,CAAA;AAGzC,OAAO,KAAK,EAGX,kCAAkC,EAClC,MAAM,2BAA2B,CAAA;AAOlC,OAAO,KAAK,EACX,iCAAiC,EAGjC,MAAM,wBAAwB,CAAA;AAW/B,OAAO,KAAK,EAEX,qBAAqB,EACrB,MAAM,sBAAsB,CAAA;AAE7B,OAAO,KAAK,EACX,6BAA6B,EAE7B,yBAAyB,EACzB,MAAM,qBAAqB,CAAA;AAG5B,OAAO,KAAK,EAAE,uBAAuB,EAAE,MAAM,wBAAwB,CAAA;AACrE,OAAO,KAAK,EAAE,2BAA2B,EAAE,MAAM,uBAAuB,CAAA;AASxE,MAAM,MAAM,sBAAsB,GAAG;IACpC,cAAc,EAAE,yBAAyB,CAAA;IACzC;;;;;OAKG;IACH,oBAAoB,EAAE,CAAC,IAAI,EAAE;QAC5B,MAAM,EAAE,WAAW,CAAA;KACnB,KAAK,OAAO,CAAC,6BAA6B,CAAC,CAAA;IAC5C,MAAM,EAAE,iBAAiB,CAAA;IACzB,0EAA0E;IAC1E,UAAU,EAAE,MAAM,CAAA;IAClB;;;;OAIG;IACH,wBAAwB,CAAC,EAAE,MAAM,CAAA;IACjC,kBAAkB,CAAC,EAAE,MAAM,CAAA;IAC3B,qBAAqB,CAAC,EAAE,MAAM,CAAA;IAC9B,QAAQ,EAAE,uBAAuB,CAAA;IACjC,6FAA6F;IAC7F,cAAc,EAAE,CAAC,KAAK,EAAE,qBAAqB,KAAK,IAAI,CAAA;IACtD,+FAA+F;IAC/F,mBAAmB,EAAE,CAAC,CAAC,cAAc,EAAE,MAAM,KAAK,IAAI,CAAC,GAAG,SAAS,CAAA;IACnE,KAAK,CAAC,EAAE,CAAC,SAAS,EAAE,2BAA2B,EAAE,OAAO,EAAE,OAAO,KAAK,IAAI,CAAA;IAC1E,2DAA2D;IAC3D,mBAAmB,EAAE,kCAAkC,CAAA;IACvD,qBAAqB,CAAC,EAAE,MAAM,CAAA;CAC9B,CAAA;AAED,gFAAgF;AAChF,MAAM,MAAM,mCAAmC,GAC5C;IAAE,MAAM,EAAE,SAAS,CAAA;CAAE,GACrB;IACA,MAAM,EAAE,OAAO,CAAA;IACf,KAAK,EAAE,oBAAoB,CACxB,6BAA6B,GAC7B,0BAA0B,GAC1B,0BAA0B,CAC5B,CAAA;CACA,CAAA;AAEJ,MAAM,MAAM,qBAAqB,GAAG;IACnC,IAAI,EAAE,MAAM,IAAI,CAAA;IAChB,QAAQ,EAAE,CAAC,KAAK,EAAE,WAAW,KAAK,IAAI,CAAA;IACtC,eAAe,EAAE,CAAC,YAAY,EAAE,kBAAkB,KAAK,IAAI,CAAA;IAC3D,SAAS,EAAE,CAAC,MAAM,EAAE,YAAY,KAAK,IAAI,CAAA;IACzC,OAAO,EAAE,CAAC,IAAI,EAAE,UAAU,CAAC,OAAO,qBAAqB,CAAC,KAAK,IAAI,CAAA;IACjE;;;OAGG;IACH,cAAc,EAAE,CACf,WAAW,EAAE,iCAAiC,KAC1C,mCAAmC,CAAA;IACxC,cAAc,EAAE,CAAC,WAAW,EAAE,UAAU,KAAK,IAAI,CAAA;IACjD,YAAY,EAAE,CAAC,IAAI,EAAE;QAAE,YAAY,EAAE,MAAM,CAAA;KAAE,KAAK,IAAI,CAAA;CACtD,CAAA;AAUD,wBAAgB,qBAAqB,CACpC,OAAO,EAAE,sBAAsB,GAC7B,qBAAqB,CAmkBvB"}
|
|
@@ -96,16 +96,33 @@ export function createCustomBlockHost(options) {
|
|
|
96
96
|
* Invokes a one-shot handler and posts its result with the request's ID.
|
|
97
97
|
* Each result type is named `<request type>Result` by the bridge protocol.
|
|
98
98
|
*/
|
|
99
|
-
async function
|
|
100
|
-
|
|
101
|
-
|
|
99
|
+
async function handleRequest(message, handler) {
|
|
100
|
+
try {
|
|
101
|
+
const response = handler === undefined
|
|
102
|
+
? unsupportedOperation(message.type)
|
|
103
|
+
: await handler(message);
|
|
104
|
+
sendInitializedMessage({
|
|
105
|
+
...response,
|
|
106
|
+
type: `${message.type}Result`,
|
|
107
|
+
requestId: message.requestId,
|
|
108
|
+
});
|
|
109
|
+
}
|
|
110
|
+
catch (error) {
|
|
111
|
+
if (initializationController.status !== "initialized") {
|
|
112
|
+
return;
|
|
113
|
+
}
|
|
114
|
+
emit("warn", error);
|
|
115
|
+
sendInitializedMessage({
|
|
116
|
+
type: `${message.type}Result`,
|
|
117
|
+
requestId: message.requestId,
|
|
118
|
+
status: "error",
|
|
119
|
+
error: {
|
|
120
|
+
code: "unknown_error",
|
|
121
|
+
message: `The host could not complete ${message.type}.`,
|
|
122
|
+
isRetryable: false,
|
|
123
|
+
},
|
|
124
|
+
});
|
|
102
125
|
}
|
|
103
|
-
const response = await handler(message);
|
|
104
|
-
sendInitializedMessage({
|
|
105
|
-
type: `${message.type}Result`,
|
|
106
|
-
requestId: message.requestId,
|
|
107
|
-
...response,
|
|
108
|
-
});
|
|
109
126
|
}
|
|
110
127
|
function postQueryDataSourceResult(args) {
|
|
111
128
|
const message = args.response.status === "error"
|
|
@@ -166,8 +183,12 @@ export function createCustomBlockHost(options) {
|
|
|
166
183
|
flushPendingHostStateChanges();
|
|
167
184
|
}
|
|
168
185
|
async function handleOpenExternalUrl(message) {
|
|
169
|
-
if (
|
|
170
|
-
|
|
186
|
+
if (navigationAbortController.signal.aborted) {
|
|
187
|
+
return;
|
|
188
|
+
}
|
|
189
|
+
const handler = handlers.openExternalUrl;
|
|
190
|
+
if (handler === undefined) {
|
|
191
|
+
await handleRequest(message, undefined);
|
|
171
192
|
return;
|
|
172
193
|
}
|
|
173
194
|
if (pendingOpenExternalUrlRequestId === message.requestId) {
|
|
@@ -204,23 +225,7 @@ export function createCustomBlockHost(options) {
|
|
|
204
225
|
}
|
|
205
226
|
pendingOpenExternalUrlRequestId = message.requestId;
|
|
206
227
|
try {
|
|
207
|
-
|
|
208
|
-
signal: navigationAbortController.signal,
|
|
209
|
-
});
|
|
210
|
-
if (navigationAbortController.signal.aborted) {
|
|
211
|
-
return;
|
|
212
|
-
}
|
|
213
|
-
const result = {
|
|
214
|
-
type: "openExternalUrlResult",
|
|
215
|
-
requestId: message.requestId,
|
|
216
|
-
...response,
|
|
217
|
-
};
|
|
218
|
-
sendInitializedMessage(result);
|
|
219
|
-
}
|
|
220
|
-
catch (error) {
|
|
221
|
-
if (!navigationAbortController.signal.aborted) {
|
|
222
|
-
throw error;
|
|
223
|
-
}
|
|
228
|
+
await handleRequest(message, () => handler({ ...message, url }, { signal: navigationAbortController.signal }));
|
|
224
229
|
}
|
|
225
230
|
finally {
|
|
226
231
|
if (pendingOpenExternalUrlRequestId === message.requestId) {
|
|
@@ -399,12 +404,12 @@ export function createCustomBlockHost(options) {
|
|
|
399
404
|
onQueryDataSource: handleQuery,
|
|
400
405
|
onUnsubscribeDataSourceQuery: message => querySubscriptions.unsubscribe(message.subscriptionId),
|
|
401
406
|
onOpenExternalUrl: handleOpenExternalUrl,
|
|
402
|
-
onCreatePage: message =>
|
|
403
|
-
onGetPage: message =>
|
|
404
|
-
onOpenPage: message =>
|
|
405
|
-
onGetUser: message =>
|
|
406
|
-
onListUsers: message =>
|
|
407
|
-
onUpdatePage: message =>
|
|
407
|
+
onCreatePage: message => handleRequest(message, handlers.createPage),
|
|
408
|
+
onGetPage: message => handleRequest(message, handlers.getPage),
|
|
409
|
+
onOpenPage: message => handleRequest(message, handlers.openPage),
|
|
410
|
+
onGetUser: message => handleRequest(message, handlers.getUser),
|
|
411
|
+
onListUsers: message => handleRequest(message, handlers.listUsers),
|
|
412
|
+
onUpdatePage: message => handleRequest(message, handlers.updatePage),
|
|
408
413
|
onResize: message => handlers.resize?.(message),
|
|
409
414
|
});
|
|
410
415
|
window.addEventListener("message", onMessage);
|
|
@@ -554,6 +559,16 @@ function getBindingError(manifest, dataSources) {
|
|
|
554
559
|
}
|
|
555
560
|
return undefined;
|
|
556
561
|
}
|
|
562
|
+
function unsupportedOperation(type) {
|
|
563
|
+
return {
|
|
564
|
+
status: "error",
|
|
565
|
+
error: {
|
|
566
|
+
code: "unsupported_operation",
|
|
567
|
+
message: `The host does not support ${type}.`,
|
|
568
|
+
isRetryable: false,
|
|
569
|
+
},
|
|
570
|
+
};
|
|
571
|
+
}
|
|
557
572
|
function getQueryValidationError(message, collectionSchema) {
|
|
558
573
|
// The host can omit the database schema. Queries without filters or sorts need no schema validation.
|
|
559
574
|
if (collectionSchema === undefined) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"getInvalidSandboxMessageResponse.d.ts","sourceRoot":"","sources":["../../src/messages/getInvalidSandboxMessageResponse.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,qBAAqB,EAAE,MAAM,oEAAoE,CAAA;
|
|
1
|
+
{"version":3,"file":"getInvalidSandboxMessageResponse.d.ts","sourceRoot":"","sources":["../../src/messages/getInvalidSandboxMessageResponse.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,qBAAqB,EAAE,MAAM,oEAAoE,CAAA;AAG/G,MAAM,MAAM,6BAA6B,GAAG;IAC3C,YAAY,EAAE,MAAM,GAAG,SAAS,CAAA;IAChC,IAAI,CAAC,EAAE,qBAAqB,CAAA;CAC5B,CAAA;AAED,wBAAgB,gCAAgC,CAC/C,IAAI,EAAE,OAAO,GACX,6BAA6B,CAiB/B"}
|
|
@@ -1,14 +1,17 @@
|
|
|
1
1
|
import { readIncomingType } from "../protocol/messages/incomingType.js";
|
|
2
|
+
import { readRequestId } from "../protocol/utils/readRequestId.js";
|
|
2
3
|
export function getInvalidSandboxMessageResponse(data) {
|
|
3
4
|
const incomingType = readIncomingType(data);
|
|
4
5
|
if (incomingType === "invalidHostMessage" ||
|
|
5
6
|
incomingType === "invalidSandboxMessage") {
|
|
6
7
|
return { incomingType };
|
|
7
8
|
}
|
|
9
|
+
const requestId = readRequestId(data);
|
|
8
10
|
return {
|
|
9
11
|
incomingType,
|
|
10
12
|
nack: {
|
|
11
13
|
type: "invalidSandboxMessage",
|
|
14
|
+
...(requestId !== undefined ? { requestId } : {}),
|
|
12
15
|
reason: nackReasonForInvalidSandboxMessage(incomingType),
|
|
13
16
|
},
|
|
14
17
|
};
|
|
@@ -40,3 +40,5 @@ export declare const notionParentSchema: v.VariantSchema<"type", [v.ObjectSchema
|
|
|
40
40
|
* is exposed, including when a readable child identifies the parent as a data source.
|
|
41
41
|
*/
|
|
42
42
|
export type NotionParent = v.InferOutput<typeof notionParentSchema>;
|
|
43
|
+
/** A parent reference constructed from application records with plain string IDs. */
|
|
44
|
+
export type BridgeParent = v.InferInput<typeof notionParentSchema>;
|
package/dist/protocol/index.d.ts
CHANGED
|
@@ -19,7 +19,7 @@ export type { ResizeMessage } from "./context/messages/resize.js";
|
|
|
19
19
|
export { resizeMessageSchema } from "./context/messages/resize.js";
|
|
20
20
|
export type { ThemeChangedMessage } from "./context/messages/themeChanged.js";
|
|
21
21
|
export { themeChangedMessageSchema } from "./context/messages/themeChanged.js";
|
|
22
|
-
export type { DataSourceParent, NotionParent, PageParent, } from "./context/parent.js";
|
|
22
|
+
export type { BridgeParent, DataSourceParent, NotionParent, PageParent, } from "./context/parent.js";
|
|
23
23
|
export { dataSourceParentSchema, notionParentSchema, pageParentSchema, } from "./context/parent.js";
|
|
24
24
|
export type { NotionTheme } from "./context/theme.js";
|
|
25
25
|
export { notionThemeSchema } from "./context/theme.js";
|
|
@@ -140,11 +140,12 @@ export type { CustomBlockListUsersErrorCode, CustomBlockListUsersErrorInfo, List
|
|
|
140
140
|
export { customBlockListUsersErrorCodeSchema, customBlockListUsersErrorInfoSchema, listUsersMessageSchema, listUsersResultMessageSchema, } from "./users/messages/listUsers.js";
|
|
141
141
|
export type { NotionUserId } from "./users/userId.js";
|
|
142
142
|
export { notionUserIdSchema } from "./users/userId.js";
|
|
143
|
-
export type { CustomBlockCapabilityErrorCode, CustomBlockErrorCode, CustomBlockErrorInfo, } from "./utils/errors.js";
|
|
143
|
+
export type { CustomBlockCapabilityErrorCode, CustomBlockErrorCode, CustomBlockErrorInfo, CustomBlockRequestErrorCode, } from "./utils/errors.js";
|
|
144
144
|
export { CAPABILITY_NOT_GRANTED_ERROR_CODE, customBlockErrorInfoSchema, } from "./utils/errors.js";
|
|
145
145
|
export type { NotionAgentId, NotionBlockId, NotionDataSourceId, NotionPageId, NotionSpaceId, } from "./utils/ids.js";
|
|
146
146
|
export { notionAgentIdSchema, notionBlockIdSchema, notionDataSourceIdSchema, notionPageIdSchema, notionSpaceIdSchema, } from "./utils/ids.js";
|
|
147
147
|
export { isLocalBlockServerUrl } from "./utils/isLocalBlockServerUrl.js";
|
|
148
148
|
export { LATEST_BRIDGE_PROTOCOL_VERSION, TEXT_FALLBACK_PROPERTY_PROTOCOL_VERSION, UNIFIED_PAGE_PROTOCOL_VERSION, } from "./utils/protocolVersion.js";
|
|
149
|
+
export { readRequestId } from "./utils/readRequestId.js";
|
|
149
150
|
export type { NotionRecordPointer } from "./utils/recordPointer.js";
|
|
150
151
|
export { notionRecordPointerSchema } from "./utils/recordPointer.js";
|
package/dist/protocol/index.js
CHANGED
|
@@ -70,4 +70,5 @@ export { CAPABILITY_NOT_GRANTED_ERROR_CODE, customBlockErrorInfoSchema, } from "
|
|
|
70
70
|
export { notionAgentIdSchema, notionBlockIdSchema, notionDataSourceIdSchema, notionPageIdSchema, notionSpaceIdSchema, } from "./utils/ids.js";
|
|
71
71
|
export { isLocalBlockServerUrl } from "./utils/isLocalBlockServerUrl.js";
|
|
72
72
|
export { LATEST_BRIDGE_PROTOCOL_VERSION, TEXT_FALLBACK_PROPERTY_PROTOCOL_VERSION, UNIFIED_PAGE_PROTOCOL_VERSION, } from "./utils/protocolVersion.js";
|
|
73
|
+
export { readRequestId } from "./utils/readRequestId.js";
|
|
73
74
|
export { notionRecordPointerSchema } from "./utils/recordPointer.js";
|
|
@@ -541,6 +541,7 @@ export declare const hostToSandboxMessageSchema: v.VariantSchema<"type", [v.Vari
|
|
|
541
541
|
}, undefined>;
|
|
542
542
|
}, undefined>], undefined>, v.ObjectSchema<{
|
|
543
543
|
readonly type: v.LiteralSchema<"invalidSandboxMessage", undefined>;
|
|
544
|
+
readonly requestId: v.OptionalSchema<v.StringSchema<undefined>, undefined>;
|
|
544
545
|
readonly reason: v.StringSchema<undefined>;
|
|
545
546
|
}, undefined>, v.VariantSchema<"status", [v.ObjectSchema<{
|
|
546
547
|
readonly type: v.LiteralSchema<"queryDataSourceResult", undefined>;
|
|
@@ -2293,6 +2294,7 @@ export declare const hostToSandboxMessageWithProtocol3To5CompatibilitySchema: v.
|
|
|
2293
2294
|
}, undefined>;
|
|
2294
2295
|
}, undefined>], undefined>, v.ObjectSchema<{
|
|
2295
2296
|
readonly type: v.LiteralSchema<"invalidSandboxMessage", undefined>;
|
|
2297
|
+
readonly requestId: v.OptionalSchema<v.StringSchema<undefined>, undefined>;
|
|
2296
2298
|
readonly reason: v.StringSchema<undefined>;
|
|
2297
2299
|
}, undefined>, v.VariantSchema<"status", [v.ObjectSchema<{
|
|
2298
2300
|
readonly type: v.LiteralSchema<"queryDataSourceResult", undefined>;
|
|
@@ -6,6 +6,8 @@ import * as v from "valibot";
|
|
|
6
6
|
*/
|
|
7
7
|
export declare const invalidHostMessageSchema: v.ObjectSchema<{
|
|
8
8
|
readonly type: v.LiteralSchema<"invalidHostMessage", undefined>;
|
|
9
|
+
/** Identifies the rejected request or response, when readable. */
|
|
10
|
+
readonly requestId: v.OptionalSchema<v.StringSchema<undefined>, undefined>;
|
|
9
11
|
/**
|
|
10
12
|
* A human-readable string intended for sandbox-side logging. It has no structured contract.
|
|
11
13
|
*/
|
|
@@ -6,6 +6,8 @@ import * as v from "valibot";
|
|
|
6
6
|
*/
|
|
7
7
|
export const invalidHostMessageSchema = v.object({
|
|
8
8
|
type: v.literal("invalidHostMessage"),
|
|
9
|
+
/** Identifies the rejected request or response, when readable. */
|
|
10
|
+
requestId: v.optional(v.string()),
|
|
9
11
|
/**
|
|
10
12
|
* A human-readable string intended for sandbox-side logging. It has no structured contract.
|
|
11
13
|
*/
|
|
@@ -6,6 +6,8 @@ import * as v from "valibot";
|
|
|
6
6
|
*/
|
|
7
7
|
export declare const invalidSandboxMessageSchema: v.ObjectSchema<{
|
|
8
8
|
readonly type: v.LiteralSchema<"invalidSandboxMessage", undefined>;
|
|
9
|
+
/** Identifies the rejected request or response, when readable. */
|
|
10
|
+
readonly requestId: v.OptionalSchema<v.StringSchema<undefined>, undefined>;
|
|
9
11
|
/**
|
|
10
12
|
* A human-readable string intended for sandbox-side logging. It has no structured contract.
|
|
11
13
|
*/
|
|
@@ -6,6 +6,8 @@ import * as v from "valibot";
|
|
|
6
6
|
*/
|
|
7
7
|
export const invalidSandboxMessageSchema = v.object({
|
|
8
8
|
type: v.literal("invalidSandboxMessage"),
|
|
9
|
+
/** Identifies the rejected request or response, when readable. */
|
|
10
|
+
requestId: v.optional(v.string()),
|
|
9
11
|
/**
|
|
10
12
|
* A human-readable string intended for sandbox-side logging. It has no structured contract.
|
|
11
13
|
*/
|
|
@@ -1318,6 +1318,7 @@ export declare const sandboxToHostMessageSchema: v.VariantSchema<"type", [v.Vari
|
|
|
1318
1318
|
readonly height: v.SchemaWithPipe<readonly [v.NumberSchema<undefined>, v.FiniteAction<number, undefined>, v.MinValueAction<number, 0, undefined>]>;
|
|
1319
1319
|
}, undefined>, v.ObjectSchema<{
|
|
1320
1320
|
readonly type: v.LiteralSchema<"invalidHostMessage", undefined>;
|
|
1321
|
+
readonly requestId: v.OptionalSchema<v.StringSchema<undefined>, undefined>;
|
|
1321
1322
|
readonly reason: v.StringSchema<undefined>;
|
|
1322
1323
|
}, undefined>], undefined>;
|
|
1323
1324
|
export type SandboxToHostMessage = v.InferOutput<typeof sandboxToHostMessageSchema>;
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import * as v from "valibot";
|
|
2
|
-
import type { CustomBlockErrorCode, CustomBlockErrorInfo } from "../utils/errors.js";
|
|
2
|
+
import type { CustomBlockErrorCode, CustomBlockErrorInfo, CustomBlockRequestErrorCode } from "../utils/errors.js";
|
|
3
3
|
export declare const customBlockOpenExternalUrlErrorCodeSchema: v.StringSchema<undefined>;
|
|
4
|
-
export type CustomBlockOpenExternalUrlErrorCode = CustomBlockErrorCode<"user_decline" | "pending_navigation" | "invalid_url">;
|
|
4
|
+
export type CustomBlockOpenExternalUrlErrorCode = CustomBlockErrorCode<CustomBlockRequestErrorCode | "user_decline" | "pending_navigation" | "invalid_url">;
|
|
5
5
|
export type CustomBlockOpenExternalUrlErrorInfo = CustomBlockErrorInfo<CustomBlockOpenExternalUrlErrorCode>;
|
|
6
6
|
export declare const customBlockOpenExternalUrlErrorInfoSchema: v.ObjectSchema<{
|
|
7
7
|
readonly code: v.StringSchema<undefined>;
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import * as v from "valibot";
|
|
2
|
-
import type { CustomBlockCapabilityErrorCode, CustomBlockErrorCode, CustomBlockErrorInfo } from "../../utils/errors.js";
|
|
2
|
+
import type { CustomBlockCapabilityErrorCode, CustomBlockErrorCode, CustomBlockErrorInfo, CustomBlockRequestErrorCode } from "../../utils/errors.js";
|
|
3
3
|
export declare const customBlockCreatePageErrorCodeSchema: v.StringSchema<undefined>;
|
|
4
|
-
export type CustomBlockCreatePageErrorCode = CustomBlockErrorCode<"create_page_failed" | "invalid_page_parent" | "page_unavailable" | "data_source_access_failed" | "unknown_data_source_key" | "unmapped_data_source" | "data_source_inaccessible" | "unmapped_property" | "property_id_mismatch" | "duplicate_property" | "invalid_property_value" | CustomBlockCapabilityErrorCode>;
|
|
4
|
+
export type CustomBlockCreatePageErrorCode = CustomBlockErrorCode<CustomBlockRequestErrorCode | "create_page_failed" | "invalid_page_parent" | "page_unavailable" | "data_source_access_failed" | "unknown_data_source_key" | "unmapped_data_source" | "data_source_inaccessible" | "unmapped_property" | "property_id_mismatch" | "duplicate_property" | "invalid_property_value" | CustomBlockCapabilityErrorCode>;
|
|
5
5
|
export type CustomBlockCreatePageErrorInfo = CustomBlockErrorInfo<CustomBlockCreatePageErrorCode>;
|
|
6
6
|
export declare const customBlockCreatePageErrorInfoSchema: v.ObjectSchema<{
|
|
7
7
|
readonly code: v.StringSchema<undefined>;
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import * as v from "valibot";
|
|
2
|
-
import type { CustomBlockCapabilityErrorCode, CustomBlockErrorCode, CustomBlockErrorInfo } from "../../utils/errors.js";
|
|
2
|
+
import type { CustomBlockCapabilityErrorCode, CustomBlockErrorCode, CustomBlockErrorInfo, CustomBlockRequestErrorCode } from "../../utils/errors.js";
|
|
3
3
|
export declare const customBlockGetPageErrorCodeSchema: v.StringSchema<undefined>;
|
|
4
|
-
export type CustomBlockGetPageErrorCode = CustomBlockErrorCode<"get_page_failed" | "page_unavailable" | CustomBlockCapabilityErrorCode>;
|
|
4
|
+
export type CustomBlockGetPageErrorCode = CustomBlockErrorCode<CustomBlockRequestErrorCode | "get_page_failed" | "page_unavailable" | CustomBlockCapabilityErrorCode>;
|
|
5
5
|
export type CustomBlockGetPageErrorInfo = CustomBlockErrorInfo<CustomBlockGetPageErrorCode>;
|
|
6
6
|
export declare const customBlockGetPageErrorInfoSchema: v.ObjectSchema<{
|
|
7
7
|
readonly code: v.StringSchema<undefined>;
|
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
import * as v from "valibot";
|
|
2
|
-
import type { CustomBlockCapabilityErrorCode, CustomBlockErrorCode, CustomBlockErrorInfo } from "../../utils/errors.js";
|
|
2
|
+
import type { CustomBlockCapabilityErrorCode, CustomBlockErrorCode, CustomBlockErrorInfo, CustomBlockRequestErrorCode } from "../../utils/errors.js";
|
|
3
3
|
export declare const openPageModeSchema: v.PicklistSchema<["side_peek", "center_peek"], undefined>;
|
|
4
4
|
export type OpenPageMode = v.InferOutput<typeof openPageModeSchema>;
|
|
5
5
|
export declare const customBlockOpenPageErrorCodeSchema: v.StringSchema<undefined>;
|
|
6
|
-
export type CustomBlockOpenPageErrorCode = CustomBlockErrorCode<"open_page_failed" | "page_unavailable" | "navigation_unavailable" | CustomBlockCapabilityErrorCode>;
|
|
6
|
+
export type CustomBlockOpenPageErrorCode = CustomBlockErrorCode<CustomBlockRequestErrorCode | "open_page_failed" | "page_unavailable" | "navigation_unavailable" | CustomBlockCapabilityErrorCode>;
|
|
7
7
|
export type CustomBlockOpenPageErrorInfo = CustomBlockErrorInfo<CustomBlockOpenPageErrorCode>;
|
|
8
8
|
export declare const customBlockOpenPageErrorInfoSchema: v.ObjectSchema<{
|
|
9
9
|
readonly code: v.StringSchema<undefined>;
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import * as v from "valibot";
|
|
2
|
-
import type { CustomBlockCapabilityErrorCode, CustomBlockErrorCode, CustomBlockErrorInfo } from "../../utils/errors.js";
|
|
2
|
+
import type { CustomBlockCapabilityErrorCode, CustomBlockErrorCode, CustomBlockErrorInfo, CustomBlockRequestErrorCode } from "../../utils/errors.js";
|
|
3
3
|
export declare const customBlockUpdatePageErrorCodeSchema: v.StringSchema<undefined>;
|
|
4
|
-
export type CustomBlockUpdatePageErrorCode = CustomBlockErrorCode<"update_page_failed" | "invalid_page_update" | "page_unavailable" | "data_source_access_failed" | "unmapped_property" | "property_id_mismatch" | "duplicate_property" | "invalid_property_value" | CustomBlockCapabilityErrorCode>;
|
|
4
|
+
export type CustomBlockUpdatePageErrorCode = CustomBlockErrorCode<CustomBlockRequestErrorCode | "update_page_failed" | "previous_write_incomplete" | "invalid_page_update" | "page_unavailable" | "data_source_access_failed" | "unmapped_property" | "property_id_mismatch" | "duplicate_property" | "invalid_property_value" | CustomBlockCapabilityErrorCode>;
|
|
5
5
|
export type CustomBlockUpdatePageErrorInfo = CustomBlockErrorInfo<CustomBlockUpdatePageErrorCode>;
|
|
6
6
|
export declare const customBlockUpdatePageErrorInfoSchema: v.ObjectSchema<{
|
|
7
7
|
readonly code: v.StringSchema<undefined>;
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import * as v from "valibot";
|
|
2
|
-
import type { CustomBlockCapabilityErrorCode, CustomBlockErrorCode, CustomBlockErrorInfo } from "../../utils/errors.js";
|
|
2
|
+
import type { CustomBlockCapabilityErrorCode, CustomBlockErrorCode, CustomBlockErrorInfo, CustomBlockRequestErrorCode } from "../../utils/errors.js";
|
|
3
3
|
export declare const customBlockGetUserErrorCodeSchema: v.StringSchema<undefined>;
|
|
4
|
-
export type CustomBlockGetUserErrorCode = CustomBlockErrorCode<"get_user_failed" | CustomBlockCapabilityErrorCode>;
|
|
4
|
+
export type CustomBlockGetUserErrorCode = CustomBlockErrorCode<CustomBlockRequestErrorCode | "get_user_failed" | CustomBlockCapabilityErrorCode>;
|
|
5
5
|
export type CustomBlockGetUserErrorInfo = CustomBlockErrorInfo<CustomBlockGetUserErrorCode>;
|
|
6
6
|
export declare const customBlockGetUserErrorInfoSchema: v.ObjectSchema<{
|
|
7
7
|
readonly code: v.StringSchema<undefined>;
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import * as v from "valibot";
|
|
2
|
-
import type { CustomBlockCapabilityErrorCode, CustomBlockErrorCode, CustomBlockErrorInfo } from "../../utils/errors.js";
|
|
2
|
+
import type { CustomBlockCapabilityErrorCode, CustomBlockErrorCode, CustomBlockErrorInfo, CustomBlockRequestErrorCode } from "../../utils/errors.js";
|
|
3
3
|
export declare const customBlockListUsersErrorCodeSchema: v.StringSchema<undefined>;
|
|
4
|
-
export type CustomBlockListUsersErrorCode = CustomBlockErrorCode<"list_users_failed" | CustomBlockCapabilityErrorCode>;
|
|
4
|
+
export type CustomBlockListUsersErrorCode = CustomBlockErrorCode<CustomBlockRequestErrorCode | "list_users_failed" | CustomBlockCapabilityErrorCode>;
|
|
5
5
|
export type CustomBlockListUsersErrorInfo = CustomBlockErrorInfo<CustomBlockListUsersErrorCode>;
|
|
6
6
|
export declare const customBlockListUsersErrorInfoSchema: v.ObjectSchema<{
|
|
7
7
|
readonly code: v.StringSchema<undefined>;
|
|
@@ -16,3 +16,5 @@ export declare const customBlockErrorInfoSchema: v.ObjectSchema<{
|
|
|
16
16
|
readonly message: v.StringSchema<undefined>;
|
|
17
17
|
readonly isRetryable: v.BooleanSchema<undefined>;
|
|
18
18
|
}, undefined>;
|
|
19
|
+
/** Failures shared by one-shot requests. */
|
|
20
|
+
export type CustomBlockRequestErrorCode = CustomBlockErrorCode<"request_timeout" | "request_send_failed" | "request_disposed" | "invalid_host_message" | "invalid_sandbox_message" | "unsupported_operation">;
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import * as v from "valibot";
|
|
2
|
+
const requestIdentitySchema = v.object({ requestId: v.string() });
|
|
3
|
+
/** Reads correlation without accepting the rest of an invalid message. */
|
|
4
|
+
export function readRequestId(data) {
|
|
5
|
+
const result = v.safeParse(requestIdentitySchema, data);
|
|
6
|
+
return result.success ? result.output.requestId : undefined;
|
|
7
|
+
}
|
package/docs/bridge/changelog.md
CHANGED
|
@@ -41,6 +41,13 @@ from `connect`.
|
|
|
41
41
|
|
|
42
42
|
## Changes within a declared version
|
|
43
43
|
|
|
44
|
+
### Protocol 8: correlated request rejections
|
|
45
|
+
|
|
46
|
+
Bridge NACKs (`invalidHostMessage` and `invalidSandboxMessage`) gain an optional string `requestId`.
|
|
47
|
+
Updated SDKs complete the matching request immediately when a rejection can be correlated. Older
|
|
48
|
+
readers ignore the additional field; updated readers continue to accept NACKs without an ID.
|
|
49
|
+
Uncorrelated requests use the SDK's 60-second timeout. This additive change retains protocol 8.
|
|
50
|
+
|
|
44
51
|
### Protocol 5: unavailable containing-page context
|
|
45
52
|
|
|
46
53
|
On October 2, 2026, SDK 0.2.17 added `{ type: "unavailable" }` to containing-page context while
|
package/docs/bridge/protocol.md
CHANGED
|
@@ -62,7 +62,9 @@ a different origin from its embedding page.
|
|
|
62
62
|
- `queryDataSource` is a long-lived subscription; requests and every update use its stable
|
|
63
63
|
`subscriptionId`.
|
|
64
64
|
- The initialization lifecycle uses `initializationId`, not `requestId` or `subscriptionId`.
|
|
65
|
-
- One-way messages, such as `resize
|
|
65
|
+
- One-way messages, such as `resize`, have no correlation ID.
|
|
66
|
+
- Bridge NACKs include the rejected message's `requestId` when it is a string. The ID identifies the
|
|
67
|
+
original request, including when the rejected message is its response.
|
|
66
68
|
|
|
67
69
|
Hosts key query state by `subscriptionId`, replace state when a request reuses one, and suppress
|
|
68
70
|
stale asynchronous results.
|
|
@@ -82,6 +84,22 @@ On parse failure, the host replies with `invalidSandboxMessage` and the sandbox
|
|
|
82
84
|
`invalidHostMessage`, except for the handshake cases below. These replies are negative
|
|
83
85
|
acknowledgments (NACKs). Receivers do not NACK another NACK.
|
|
84
86
|
|
|
87
|
+
A sandbox request with a `requestId` expects a terminal result or correlated rejection. On parse
|
|
88
|
+
failure, read `requestId` separately from the invalid payload. The host includes a readable string
|
|
89
|
+
ID in `invalidSandboxMessage`, even for an unknown request type. The SDK completes the matching
|
|
90
|
+
request with `invalid_sandbox_message`. When the SDK rejects a host response, it completes the
|
|
91
|
+
matching request locally with `invalid_host_message` and includes the ID in `invalidHostMessage`.
|
|
92
|
+
Both errors have `isRetryable: false`.
|
|
93
|
+
|
|
94
|
+
One-shot SDK requests time out after 60 seconds. Missing, unreadable, or unknown IDs do not fail
|
|
95
|
+
unrelated requests. NACK IDs are optional: older readers ignore them, and newer readers accept
|
|
96
|
+
legacy NACKs without IDs. Those requests retain the timeout fallback.
|
|
97
|
+
|
|
98
|
+
Request completion clears its timer, removes the pending entry, and ignores duplicate or late
|
|
99
|
+
results. Disposing the SDK completes pending calls locally with `request_disposed` and clears their
|
|
100
|
+
timers. The SDK does not retry or cancel host work. A timed-out write may still complete; check its
|
|
101
|
+
resulting state before repeating it. Data source subscriptions use a separate lifecycle.
|
|
102
|
+
|
|
85
103
|
Malformed sandbox messages do not change the host's initialization state or timeout, except as
|
|
86
104
|
follows:
|
|
87
105
|
|
package/docs/handlers.md
CHANGED
|
@@ -11,9 +11,8 @@ hosts must provide their own permissions, data access, and persistence.
|
|
|
11
11
|
|
|
12
12
|
## Handler contracts
|
|
13
13
|
|
|
14
|
-
`queryDataSource` is required. Other handlers are optional.
|
|
15
|
-
|
|
16
|
-
carry `{ code, message, isRetryable }`, with open string codes.
|
|
14
|
+
`queryDataSource` is required. Other handlers are optional. A handler returns a result synchronously
|
|
15
|
+
or as a promise. Errors carry `{ code, message, isRetryable }`, with open string codes.
|
|
17
16
|
|
|
18
17
|
### Return bridge data
|
|
19
18
|
|
|
@@ -28,6 +27,10 @@ Query filters and sorts are validated against the actual bound database schema b
|
|
|
28
27
|
`queryDataSource` runs. See the [wire reference](bridge/protocol.md#data-sources) for
|
|
29
28
|
query semantics.
|
|
30
29
|
|
|
30
|
+
For one-shot requests, a missing handler returns `unsupported_operation`. A handler that throws,
|
|
31
|
+
rejects, or returns a malformed result produces `unknown_error`. Exception details go to `onLog`;
|
|
32
|
+
the sandbox receives a generic error. Specific errors returned by handlers pass through unchanged.
|
|
33
|
+
|
|
31
34
|
## Connect a data source
|
|
32
35
|
|
|
33
36
|
Connect an embedded block to an in-memory Tasks data source with one numeric Estimate property. This
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import type { customBlockPageSchema } from "@notionhq/custom-blocks-protocol/context/containingPage.js"
|
|
2
2
|
import type { NotionContrastMode } from "@notionhq/custom-blocks-protocol/context/contrast.js"
|
|
3
|
-
import type {
|
|
3
|
+
import type { BridgeParent } from "@notionhq/custom-blocks-protocol/context/parent.js"
|
|
4
4
|
import type { NotionTheme } from "@notionhq/custom-blocks-protocol/context/theme.js"
|
|
5
5
|
import { bridgeDataSourceBindingsSchema } from "@notionhq/custom-blocks-protocol/dataSources/bridgeDataSourceBindings.js"
|
|
6
6
|
import type { NotionCollectionSchema } from "@notionhq/custom-blocks-protocol/dataSources/collectionSchema.js"
|
|
@@ -129,7 +129,7 @@ export type CustomBlockHostHandle = {
|
|
|
129
129
|
stop: () => void
|
|
130
130
|
setTheme: (theme: NotionTheme) => void
|
|
131
131
|
setContrastMode: (contrastMode: NotionContrastMode) => void
|
|
132
|
-
setParent: (parent:
|
|
132
|
+
setParent: (parent: BridgeParent) => void
|
|
133
133
|
setPage: (page: InferInput<typeof customBlockPageSchema>) => void
|
|
134
134
|
/**
|
|
135
135
|
* Reports synchronous local acceptance, not sandbox delivery or initialization success.
|
|
@@ -148,6 +148,8 @@ export type CustomBlockHostHandle = {
|
|
|
148
148
|
*/
|
|
149
149
|
type OneShotRequest = Extract<SandboxToHostMessage, { requestId: string }>
|
|
150
150
|
|
|
151
|
+
type RequestError = { status: "error"; error: CustomBlockErrorInfo }
|
|
152
|
+
|
|
151
153
|
export function createCustomBlockHost(
|
|
152
154
|
options: CustomBlockHostOptions,
|
|
153
155
|
): CustomBlockHostHandle {
|
|
@@ -247,22 +249,39 @@ export function createCustomBlockHost(
|
|
|
247
249
|
* Invokes a one-shot handler and posts its result with the request's ID.
|
|
248
250
|
* Each result type is named `<request type>Result` by the bridge protocol.
|
|
249
251
|
*/
|
|
250
|
-
async function
|
|
252
|
+
async function handleRequest<
|
|
251
253
|
Request extends OneShotRequest,
|
|
252
254
|
Response extends object,
|
|
253
255
|
>(
|
|
254
256
|
message: Request,
|
|
255
257
|
handler: ((message: Request) => Response | Promise<Response>) | undefined,
|
|
256
258
|
) {
|
|
257
|
-
|
|
258
|
-
|
|
259
|
+
try {
|
|
260
|
+
const response =
|
|
261
|
+
handler === undefined
|
|
262
|
+
? unsupportedOperation(message.type)
|
|
263
|
+
: await handler(message)
|
|
264
|
+
sendInitializedMessage({
|
|
265
|
+
...response,
|
|
266
|
+
type: `${message.type}Result`,
|
|
267
|
+
requestId: message.requestId,
|
|
268
|
+
})
|
|
269
|
+
} catch (error) {
|
|
270
|
+
if (initializationController.status !== "initialized") {
|
|
271
|
+
return
|
|
272
|
+
}
|
|
273
|
+
emit("warn", error)
|
|
274
|
+
sendInitializedMessage({
|
|
275
|
+
type: `${message.type}Result`,
|
|
276
|
+
requestId: message.requestId,
|
|
277
|
+
status: "error",
|
|
278
|
+
error: {
|
|
279
|
+
code: "unknown_error",
|
|
280
|
+
message: `The host could not complete ${message.type}.`,
|
|
281
|
+
isRetryable: false,
|
|
282
|
+
},
|
|
283
|
+
})
|
|
259
284
|
}
|
|
260
|
-
const response = await handler(message)
|
|
261
|
-
sendInitializedMessage({
|
|
262
|
-
type: `${message.type}Result` as const,
|
|
263
|
-
requestId: message.requestId,
|
|
264
|
-
...response,
|
|
265
|
-
})
|
|
266
285
|
}
|
|
267
286
|
|
|
268
287
|
function postQueryDataSourceResult(args: {
|
|
@@ -338,10 +357,12 @@ export function createCustomBlockHost(
|
|
|
338
357
|
}
|
|
339
358
|
|
|
340
359
|
async function handleOpenExternalUrl(message: OpenExternalUrlMessage) {
|
|
341
|
-
if (
|
|
342
|
-
|
|
343
|
-
|
|
344
|
-
|
|
360
|
+
if (navigationAbortController.signal.aborted) {
|
|
361
|
+
return
|
|
362
|
+
}
|
|
363
|
+
const handler = handlers.openExternalUrl
|
|
364
|
+
if (handler === undefined) {
|
|
365
|
+
await handleRequest(message, undefined)
|
|
345
366
|
return
|
|
346
367
|
}
|
|
347
368
|
if (pendingOpenExternalUrlRequestId === message.requestId) {
|
|
@@ -380,25 +401,12 @@ export function createCustomBlockHost(
|
|
|
380
401
|
|
|
381
402
|
pendingOpenExternalUrlRequestId = message.requestId
|
|
382
403
|
try {
|
|
383
|
-
|
|
384
|
-
|
|
385
|
-
|
|
386
|
-
signal: navigationAbortController.signal,
|
|
387
|
-
|
|
404
|
+
await handleRequest(message, () =>
|
|
405
|
+
handler(
|
|
406
|
+
{ ...message, url },
|
|
407
|
+
{ signal: navigationAbortController.signal },
|
|
408
|
+
),
|
|
388
409
|
)
|
|
389
|
-
if (navigationAbortController.signal.aborted) {
|
|
390
|
-
return
|
|
391
|
-
}
|
|
392
|
-
const result: OpenExternalUrlResultMessage = {
|
|
393
|
-
type: "openExternalUrlResult",
|
|
394
|
-
requestId: message.requestId,
|
|
395
|
-
...response,
|
|
396
|
-
}
|
|
397
|
-
sendInitializedMessage(result)
|
|
398
|
-
} catch (error) {
|
|
399
|
-
if (!navigationAbortController.signal.aborted) {
|
|
400
|
-
throw error
|
|
401
|
-
}
|
|
402
410
|
} finally {
|
|
403
411
|
if (pendingOpenExternalUrlRequestId === message.requestId) {
|
|
404
412
|
pendingOpenExternalUrlRequestId = undefined
|
|
@@ -603,12 +611,12 @@ export function createCustomBlockHost(
|
|
|
603
611
|
onUnsubscribeDataSourceQuery: message =>
|
|
604
612
|
querySubscriptions.unsubscribe(message.subscriptionId),
|
|
605
613
|
onOpenExternalUrl: handleOpenExternalUrl,
|
|
606
|
-
onCreatePage: message =>
|
|
607
|
-
onGetPage: message =>
|
|
608
|
-
onOpenPage: message =>
|
|
609
|
-
onGetUser: message =>
|
|
610
|
-
onListUsers: message =>
|
|
611
|
-
onUpdatePage: message =>
|
|
614
|
+
onCreatePage: message => handleRequest(message, handlers.createPage),
|
|
615
|
+
onGetPage: message => handleRequest(message, handlers.getPage),
|
|
616
|
+
onOpenPage: message => handleRequest(message, handlers.openPage),
|
|
617
|
+
onGetUser: message => handleRequest(message, handlers.getUser),
|
|
618
|
+
onListUsers: message => handleRequest(message, handlers.listUsers),
|
|
619
|
+
onUpdatePage: message => handleRequest(message, handlers.updatePage),
|
|
612
620
|
onResize: message => handlers.resize?.(message),
|
|
613
621
|
})
|
|
614
622
|
|
|
@@ -793,6 +801,17 @@ function getBindingError(
|
|
|
793
801
|
return undefined
|
|
794
802
|
}
|
|
795
803
|
|
|
804
|
+
function unsupportedOperation(type: string): RequestError {
|
|
805
|
+
return {
|
|
806
|
+
status: "error",
|
|
807
|
+
error: {
|
|
808
|
+
code: "unsupported_operation",
|
|
809
|
+
message: `The host does not support ${type}.`,
|
|
810
|
+
isRetryable: false,
|
|
811
|
+
},
|
|
812
|
+
}
|
|
813
|
+
}
|
|
814
|
+
|
|
796
815
|
function getQueryValidationError(
|
|
797
816
|
message: QueryDataSourceMessage,
|
|
798
817
|
collectionSchema: NotionCollectionSchema | undefined,
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { readIncomingType } from "@notionhq/custom-blocks-protocol/messages/incomingType.js"
|
|
2
2
|
import type { InvalidSandboxMessage } from "@notionhq/custom-blocks-protocol/messages/invalidSandboxMessage.js"
|
|
3
|
+
import { readRequestId } from "@notionhq/custom-blocks-protocol/utils/readRequestId.js"
|
|
3
4
|
|
|
4
5
|
export type InvalidSandboxMessageResponse = {
|
|
5
6
|
incomingType: string | undefined
|
|
@@ -16,10 +17,12 @@ export function getInvalidSandboxMessageResponse(
|
|
|
16
17
|
) {
|
|
17
18
|
return { incomingType }
|
|
18
19
|
}
|
|
20
|
+
const requestId = readRequestId(data)
|
|
19
21
|
return {
|
|
20
22
|
incomingType,
|
|
21
23
|
nack: {
|
|
22
24
|
type: "invalidSandboxMessage",
|
|
25
|
+
...(requestId !== undefined ? { requestId } : {}),
|
|
23
26
|
reason: nackReasonForInvalidSandboxMessage(incomingType),
|
|
24
27
|
},
|
|
25
28
|
}
|