UNPKG

@mikemajara/notion-cms

Version:

A TypeScript library for using Notion as a headless CMS

18 lines (15 loc) 28.4 kB
'use strict';var chunkT46FQGVA_js=require('./chunk-T46FQGVA.js'),client=require('@notionhq/client');var T=class{constructor(){this.config={enabled:false,level:"info"};}configure(e){this.config={...this.config,...e};}normalizeLevel(e){return e&&["error","warn","info","debug"].includes(e)?e:"info"}shouldLog(e){if(!this.config.enabled)return false;let t=["error","warn","info","debug"],r=t.indexOf(this.normalizeLevel(this.config.level));return t.indexOf(e)<=r}log(...e){this.shouldLog("info")&&console.log("[NotionCMS Debug]:",...e);}query(e,t){this.shouldLog("debug")&&console.log(` [NotionCMS Query]:`,{databaseId:e,filter:t.filter,sorts:t.sorts,pageSize:t.page_size,startCursor:t.start_cursor,timestamp:new Date().toISOString()});}error(e,t){this.shouldLog("error")&&console.error("[NotionCMS Error]:",{message:e.message,code:e.code,context:t,timestamp:new Date().toISOString()});}},p=new T;var k=class{async processFileUrl(e,t){return e}},x=class{constructor(e){this.config=e;}async processFileUrl(e,t){if(!this.config?.storage?.type)return e;try{let r=M(e),s=O(t),n=`${r}${s}`,a=await this.createStorage();if(await a.exists(n))if(this.config?.cache?.ttl&&this.config.storage.type==="local"){let c=await import('fs/promises'),u=`${this.config.storage.path||"./public/assets/notion-files"}/${n}`,y=await c.stat(u);if(Date.now()-y.mtime.getTime()>this.config.cache.ttl)await a.delete(n);else return a.getPublicUrl(n)}else return a.getPublicUrl(n);if(this.config?.cache?.maxSize&&this.config.storage.type==="local"){let c=this.config.storage.path||"./public/assets/notion-files",{calculateDirSize:d}=await import('./file-utils-42FAMQFG.js');await d(c)>this.config.cache.maxSize&&await this.cleanupCache(c);}let{downloadFile:o}=await import('./file-utils-42FAMQFG.js'),l=await o(e);return await a.store(n,l),a.getPublicUrl(n)}catch(r){return console.warn(`Failed to cache file: ${t} from ${e}`,{fileName:t,url:e,error:r instanceof Error?r.message:String(r),stack:r instanceof Error?r.stack:void 0}),e}}generatePublicUrl(e,t){return e.startsWith("./public")?e.replace("./public","")+"/"+t:e.startsWith("public")?"/"+e.substring(6)+"/"+t:`/${t}`}async createStorage(){if(this.config?.storage?.type==="s3-compatible")try{let{S3Storage:e}=await import('./s3-storage-47VTK7YA.js');return new e({endpoint:this.config.storage.endpoint||"",bucket:this.config.storage.bucket||"",accessKey:this.config.storage.accessKey,secretKey:this.config.storage.secretKey,region:this.config.storage.region})}catch(e){console.warn("S3 storage failed, falling back to local storage:",e);let{LocalStorage:t}=await import('./s3-storage-47VTK7YA.js'),r="./public/assets/notion-files";return new t(r)}else {let{LocalStorage:e}=await import('./s3-storage-47VTK7YA.js'),t=this.config?.storage?.path||"./public/assets/notion-files";return new e(t)}}async cleanupCache(e){if(this.config?.cache?.ttl)try{let{cleanupOldFiles:t}=await import('./file-utils-42FAMQFG.js');await t(e,this.config.cache.ttl);}catch(t){console.warn(`Failed to cleanup cache in ${e}:`,t);}}},_=class{constructor(e){let t=e.files;switch(t?.strategy){case "cache":this.strategy=new x(t);break;case "direct":default:this.strategy=new k;break}}isCacheEnabled(){return this.strategy instanceof x}async processFileUrl(e,t){return this.strategy.processFileUrl(e,t)}async processFileInfoArray(e){return Promise.all(e.map(async t=>{let r=await this.processFileUrl(t.url,t.name);return {...t,url:r}}))}extractFileUrl(e){return e.type==="external"?e.external.url:e.type==="file"?e.file.url:""}createFileInfo(e){return {name:e.name,url:this.extractFileUrl(e),type:e.type,...e.type==="file"&&{expiry_time:e.file.expiry_time}}}};function M(i){let e=i.match(/([a-f0-9-]{36})/g);if(e&&e.length>=2)return e[1].replace(/-/g,"");if(e&&e.length===1)return e[0].replace(/-/g,"");let t=0;for(let r=0;r<i.length;r++){let s=i.charCodeAt(r);t=(t<<5)-t+s,t=t&t;}return Math.abs(t).toString(16)}function O(i){let e=i.match(/\.([a-zA-Z0-9]+)(?:\?|$)/);return e?`.${e[1]}`:""}var m=class{constructor(e,t){this.client=e;this.fileManager=t;}query(e,t){return t?new h(this.client,e,t,this.fileManager):new h(this.client,e,{},this.fileManager)}async getDatabase(e,t={}){try{p.query(e,{database_id:e,filter:t.filter,sorts:t.sorts,page_size:t.pageSize,start_cursor:t.startCursor});let r=await this.client.databases.query({database_id:e,filter:t.filter,sorts:t.sorts,page_size:t.pageSize,start_cursor:t.startCursor});p.log(`Query returned ${r.results.length} results`);let s=r.results;return {results:await this.processNotionRecords(s),nextCursor:r.next_cursor,hasMore:r.has_more}}catch(r){throw p.error(r,{databaseId:e,options:t}),r}}async getRecord(e){let t=await this.client.pages.retrieve({page_id:e});return await this.processNotionRecord(t)}async getAllDatabaseRecords(e,t={}){let r=[],s=true,n=null;for(;s;){let a=await this.getDatabase(e,{...t,startCursor:n||void 0});r.push(...a.results),s=a.hasMore,n=a.nextCursor;}return r}createFilter(e,t,r){console.warn("createFilter() is deprecated. Use the new type-safe filter method: queryBuilder.filter(property, operator, value)");let s={property:e};switch(t){case "equals":s.equals=r;break;case "contains":s.contains=r;break;case "startsWith":s.starts_with=r;break;case "endsWith":s.ends_with=r;break;case "greaterThan":s.greater_than=r;break;case "lessThan":s.less_than=r;break;case "greaterThanOrEqualTo":s.greater_than_or_equal_to=r;break;case "lessThanOrEqualTo":s.less_than_or_equal_to=r;break;case "isEmpty":s.is_empty=true;break;case "isNotEmpty":s.is_not_empty=true;break;default:throw new Error(`Unknown filter type: ${t}`)}return s}async getPropertyValue(e){switch(e.type){case "unique_id":return e.unique_id.number;case "title":return e.title?.[0]?.plain_text??"";case "rich_text":return e.rich_text?.[0]?.plain_text??"";case "number":return e.number;case "select":return e.select?.name??null;case "multi_select":return e.multi_select.map(r=>r.name);case "date":let t=e;return t.date?new Date(t.date.start):null;case "people":{let r=e;return Array.isArray(r.people)?r.people.map(s=>s.name||""):[]}case "files":{let s=e.files.map(a=>a.type==="external"?{name:a.name,url:a.external.url}:a.type==="file"?{name:a.name,url:a.file.url}:{name:a.name,url:""});return await Promise.all(s.map(async a=>{let o=await this.fileManager.processFileUrl(a.url,a.name);return {...a,url:o}}))}case "checkbox":return e.checkbox;case "url":return e.url;case "email":return e.email;case "phone_number":return e.phone_number;case "formula":return e.formula;case "relation":{let r=e;return Array.isArray(r.relation)?r.relation.map(s=>s.id):[]}case "rollup":return e.rollup;case "created_time":return e.created_time;case "created_by":{let r=e.created_by;return {id:r.id,name:r.name,avatar_url:r.avatar_url}}case "last_edited_time":return e.last_edited_time;case "last_edited_by":{let r=e.last_edited_by;return {id:r.id,name:r.name,avatar_url:r.avatar_url}}default:return null}}async getPropertyValueAdvanced(e){switch(e.type){case "title":{let t=e;return Array.isArray(t.title)?t.title.map(r=>({content:r.plain_text,annotations:r.annotations,href:r.href,...r.type==="text"&&{link:r.text.link}})):[]}case "rich_text":{let t=e;return Array.isArray(t.rich_text)?t.rich_text.map(r=>({content:r.plain_text,annotations:r.annotations,href:r.href,...r.type==="text"&&{link:r.text.link}})):[]}case "number":return e.number;case "select":{let t=e.select;return t?{id:t.id,name:t.name,color:t.color}:null}case "multi_select":return e.multi_select.map(r=>({id:r.id,name:r.name,color:r.color}));case "date":{let t=e;return t.date?{start:t.date.start,end:t.date.end,time_zone:t.date.time_zone,parsedStart:t.date.start?new Date(t.date.start):null,parsedEnd:t.date.end?new Date(t.date.end):null}:null}case "people":{let t=e;return Array.isArray(t.people)?t.people.map(r=>({id:r.id,name:r.name,avatar_url:r.avatar_url,object:r.object,type:r.type,...r.type==="person"&&r.person&&{email:r.person.email}})):[]}case "files":{let r=e.files.map(n=>n.type==="external"?{name:n.name,type:n.type,external:{url:n.external.url}}:n.type==="file"?{name:n.name,type:n.type,file:{url:n.file.url,expiry_time:n.file.expiry_time}}:{name:n.name,type:n.type});return await Promise.all(r.map(async n=>{let a=n.type==="external"?n.external?.url:n.file?.url;if(a){let o=await this.fileManager.processFileUrl(a,n.name);n.type==="external"&&n.external?n.external.url=o:n.type==="file"&&n.file&&(n.file.url=o);}return n}))}case "checkbox":return e.checkbox;case "url":return e.url;case "email":return e.email;case "phone_number":return e.phone_number;case "formula":{let t=e.formula;return {type:t.type,value:t.type==="string"?t.string:t.type==="number"?t.number:t.type==="boolean"?t.boolean:t.type==="date"?t.date:null}}case "relation":{let t=e;return Array.isArray(t.relation)?t.relation.map(r=>({id:r.id})):[]}case "rollup":{let t=e.rollup;return {type:t.type,function:t.function,...t.type==="array"&&{array:t.array},...t.type==="number"&&{number:t.number},...t.type==="date"&&{date:t.date}}}case "created_time":return {timestamp:e.created_time,date:new Date(e.created_time)};case "created_by":{let t=e.created_by;return {id:t.id,name:t.name,avatar_url:t.avatar_url,object:t.object,type:t.type,...t.type==="person"&&t.person&&{email:t.person.email}}}case "last_edited_time":return {timestamp:e.last_edited_time,date:new Date(e.last_edited_time)};case "last_edited_by":{let t=e.last_edited_by;return {id:t.id,name:t.name,avatar_url:t.avatar_url,object:t.object,type:t.type,...t.type==="person"&&t.person&&{email:t.person.email}}}case "status":{let t=e.status;return t?{id:t.id,name:t.name,color:t.color}:null}case "unique_id":{let t=e.unique_id;return t?{prefix:t.prefix,number:t.number}:null}default:return null}}async processNotionRecord(e){let t={id:e.id},r={id:e.id};for(let[n,a]of Object.entries(e.properties))t[n]=await this.getPropertyValue(a),r[n]=await this.getPropertyValueAdvanced(a);return {id:e.id,...t,advanced:{id:e.id,...r},raw:{id:e.id,properties:e.properties}}}async processNotionRecords(e){return Promise.all(e.map(t=>this.processNotionRecord(t)))}};var w={title:["equals","does_not_equal","contains","does_not_contain","starts_with","ends_with","is_empty","is_not_empty"],rich_text:["equals","does_not_equal","contains","does_not_contain","starts_with","ends_with","is_empty","is_not_empty"],url:["equals","does_not_equal","contains","does_not_contain","starts_with","ends_with","is_empty","is_not_empty"],email:["equals","does_not_equal","contains","does_not_contain","starts_with","ends_with","is_empty","is_not_empty"],phone_number:["equals","does_not_equal","contains","does_not_contain","starts_with","ends_with","is_empty","is_not_empty"],number:["equals","does_not_equal","greater_than","less_than","greater_than_or_equal_to","less_than_or_equal_to","is_empty","is_not_empty"],select:["equals","does_not_equal","is_empty","is_not_empty"],multi_select:["contains","does_not_contain","is_empty","is_not_empty"],status:["equals","does_not_equal","is_empty","is_not_empty"],date:["equals","before","after","on_or_before","on_or_after","is_empty","is_not_empty"],created_time:["equals","before","after","on_or_before","on_or_after"],last_edited_time:["equals","before","after","on_or_before","on_or_after"],checkbox:["equals"],people:["contains","does_not_contain","is_empty","is_not_empty"],relation:["contains","does_not_contain","is_empty","is_not_empty"],created_by:["contains","does_not_contain"],last_edited_by:["contains","does_not_contain"],files:["is_empty","is_not_empty"],formula:["equals","does_not_equal","contains","does_not_contain","greater_than","less_than","greater_than_or_equal_to","less_than_or_equal_to","is_empty","is_not_empty"],rollup:["equals","does_not_equal","contains","does_not_contain","greater_than","less_than","greater_than_or_equal_to","less_than_or_equal_to","is_empty","is_not_empty"],unique_id:["equals","does_not_equal","greater_than","less_than","greater_than_or_equal_to","less_than_or_equal_to"],verification:["equals","before","after","on_or_before","on_or_after"],unknown:["equals","does_not_equal","is_empty","is_not_empty"]},h=class{constructor(e,t,r={},s){this.filterConditions=[];this.logicalOperator="and";this.nestedFilters=[];this.sortOptions=[];this.pageLimit=100;this.singleMode=null;this.client=e,this.databaseId=t,this.fieldTypes=r,this.fileManager=s,this.databaseService=new m(e,s||new _({}));}filter(e,t,r){if(!this.isValidOperatorForField(e,t))throw new Error(`Invalid operator "${t}" for field "${e}" of type "${this.getFieldTypeForFilter(e)}"`);let s=this.getFieldTypeForFilter(e),n=this.mapFieldTypeToNotionProperty(s);return this.filterConditions.push({property:e,operator:t,value:this.prepareFilterValue(s,t,r),propertyType:n}),this}mapFieldTypeToNotionProperty(e){if(!e)return "rich_text";switch(e){case "title":return "title";case "rich_text":return "rich_text";case "number":return "number";case "select":return "select";case "multi_select":return "multi_select";case "date":case "created_time":case "last_edited_time":return "date";case "checkbox":return "checkbox";case "people":case "created_by":case "last_edited_by":return "people";case "files":return "files";case "url":return "url";case "email":return "email";case "phone_number":return "phone_number";case "relation":return "relation";case "formula":return "formula";case "rollup":return "rollup";case "status":return "status";case "unique_id":return "unique_id";default:return "rich_text"}}prepareFilterValue(e,t,r){return t==="is_empty"||t==="is_not_empty"?true:e==="date"||e==="created_time"||e==="last_edited_time"?r instanceof Date?r.toISOString():r:e==="multi_select"&&(t==="contains"||t==="does_not_contain")&&Array.isArray(r)?r[0]||"":r}sort(e,t="ascending"){if(!this.isValidSortField(e))throw new Error(`Invalid sort property "${e}". Property not found in database schema. Available fields: ${Object.keys(this.fieldTypes).join(", ")}`);if(t!=="ascending"&&t!=="descending")throw new Error(`Invalid sort direction "${t}". Must be "ascending" or "descending".`);return p.log(`Adding sort: ${e} ${t}`),this.sortOptions.push({property:e,direction:t}),this}limit(e){return this.pageLimit=e,this}startAfter(e){return this.startCursor=e,this}single(){return this.singleMode="required",this.pageLimit=2,this}maybeSingle(){return this.singleMode="optional",this.pageLimit=1,this}then(e,t){return this.execute().then(e,t)}async execute(){let{results:e}=await this.paginate(this.pageLimit);if(this.singleMode==="required"){if(e.length===0)throw new Error("No records found matching the query");if(e.length>1)throw new Error("Multiple records found when expecting exactly one");return e[0]}return this.singleMode==="optional"?e.length>0?e[0]:null:e}async paginate(e=100){let t=this.buildFilter();try{p.query(this.databaseId,{database_id:this.databaseId,filter:t||void 0,sorts:this.sortOptions,page_size:e,start_cursor:this.startCursor});let r=await this.client.databases.query({database_id:this.databaseId,filter:t||void 0,sorts:this.sortOptions&&this.sortOptions.length>0?this.sortOptions:void 0,page_size:e,start_cursor:this.startCursor});p.log(`Query returned ${r.results.length} results`);let s=r.results;p.log("[QueryBuilder] FileManager present:",!!this.fileManager),p.log("[QueryBuilder] Cache enabled:",this.fileManager?.isCacheEnabled()),p.log(`[QueryBuilder] Using unified processing with ${s.length} pages`);let n=await this.databaseService.processNotionRecords(s);return p.log(`[QueryBuilder] Processed ${n.length} records with unified processing`),{results:n,hasMore:r.has_more,nextCursor:r.next_cursor}}catch(r){throw p.error(r,{databaseId:this.databaseId,filter:t,sorts:this.sortOptions,pageSize:e,startCursor:this.startCursor}),r}}async all(){let e=[],t=true,r=null;for(;t;){r&&this.startAfter(r);let s=await this.paginate(100);e=[...e,...s.results],t=s.hasMore,r=s.nextCursor;}return e}buildFilter(){let e=[];if(this.filterConditions.forEach(t=>{let{property:r,operator:s,value:n,propertyType:a}=t,o={property:r};if(!a)throw new Error(`Property type not determined for property: ${String(r)}`);let l=this.mapToNotionOperator(s);o[a]={[l]:n},e.push(o);}),e.push(...this.nestedFilters),e.length!==0)return e.length===1?e[0]:{[this.logicalOperator]:e}}mapToNotionOperator(e){switch(e){case "equals":return "equals";case "does_not_equal":return "does_not_equal";case "contains":return "contains";case "does_not_contain":return "does_not_contain";case "starts_with":return "starts_with";case "ends_with":return "ends_with";case "greater_than":return "greater_than";case "less_than":return "less_than";case "greater_than_or_equal_to":return "greater_than_or_equal_to";case "less_than_or_equal_to":return "less_than_or_equal_to";case "before":return "before";case "after":return "after";case "on_or_before":return "on_or_before";case "on_or_after":return "on_or_after";case "is_empty":return "is_empty";case "is_not_empty":return "is_not_empty";default:return e}}getFieldTypeForFilter(e){return this.fieldTypes[e]?.type}isValidOperatorForField(e,t){let r=this.getFieldTypeForFilter(e);return !r||!(r in w)?false:w[r].includes(t)}isValidValueForField(e,t){this.getFieldTypeForFilter(e);return true}isValidSortField(e){return this.getFieldTypeForFilter(e)!==void 0}};var v="./public/assets/notion-files",R={files:{strategy:"direct",storage:{type:"local",path:v,endpoint:"",bucket:"",accessKey:"",secretKey:"",region:""},cache:{ttl:864e5,maxSize:104857600}},debug:{enabled:false,level:"info"}};function P(i){if(!i)return R;let e=R.files,t=e.storage,r=e.cache,s=R.debug;return {files:{strategy:i.files?.strategy??e.strategy,storage:{type:i.files?.storage?.type??t.type,path:i.files?.storage?.path??t.path,endpoint:i.files?.storage?.endpoint??t.endpoint,bucket:i.files?.storage?.bucket??t.bucket,accessKey:i.files?.storage?.accessKey??t.accessKey,secretKey:i.files?.storage?.secretKey??t.secretKey,region:i.files?.storage?.region??t.region},cache:{ttl:i.files?.cache?.ttl??r.ttl,maxSize:i.files?.cache?.maxSize??r.maxSize}},debug:{enabled:i.debug?.enabled??s.enabled,level:i.debug?.level??s.level}}}var g=class{blocksToMarkdown(e){if(!e||!Array.isArray(e))return "";let t={type:null,level:0,numbering:[],bulletStyles:["-","*","+","-"]};return this.processBlocksGroup(e,t)}blocksToHtml(e){return !e||!Array.isArray(e)?"":e.map(r=>this.blockToHtml(r)).join("")}processBlocksGroup(e,t){if(!e||e.length===0)return "";let r=[],s=0;for(;s<e.length;){let n=e[s];if(this.isListItem(n.type)){let a=this.extractListGroup(e,s),o=this.processListGroup(a.blocks,t);r.push(o),s=a.nextIndex;}else {let a=this.blockToMarkdown(n,t);a.trim()&&r.push(a),s++;}}return r.join(` `)}isListItem(e){return e==="bulleted_list_item"||e==="numbered_list_item"}extractListGroup(e,t){let s=e[t].type,n=[],a=t;for(;a<e.length&&e[a].type===s;)n.push(e[a]),a++;return {blocks:n,nextIndex:a}}processListGroup(e,t){if(e.length===0)return "";let s=e[0].type==="bulleted_list_item"?"bullet":"numbered",n={type:s,level:t.level,numbering:[...t.numbering],bulletStyles:t.bulletStyles};s==="numbered"&&n.numbering.length<=n.level&&(n.numbering[n.level]=1);let a=[];return e.forEach(o=>{let l=this.blockToMarkdown(o,n);l.trim()&&a.push(l),s==="numbered"&&n.numbering.length>n.level&&n.numbering[n.level]++;}),a.join(` `)}blockToMarkdown(e,t){let{type:r,content:s,children:n}=e,a=" ".repeat(t.level),o="";switch(r){case "paragraph":o=`${a}${s.text}`;break;case "heading_1":o=`${a}# ${s.text}`;break;case "heading_2":o=`${a}## ${s.text}`;break;case "heading_3":o=`${a}### ${s.text}`;break;case "bulleted_list_item":let l=t.bulletStyles[t.level%t.bulletStyles.length];o=`${a}${l} ${s.text}`;break;case "numbered_list_item":let c=t.numbering[t.level]||1;o=`${a}${c}. ${s.text}`;break;case "to_do":let d=s.checked?"[x]":"[ ]";o=`${a}- ${d} ${s.text}`;break;case "toggle":if(o=`${a}<details> ${a}<summary>${s.text}</summary> `,n&&n.length>0){let y={...t,level:t.level+1};o+=this.processBlocksGroup(n,y);}o+=` ${a}</details>`;break;case "code":o=`${a}\`\`\`${s.language||""} ${s.text} ${a}\`\`\``;break;case "quote":o=`${a}> ${s.text}`;break;case "divider":o=`${a}---`;break;case "image":let u=s.caption?` "${s.caption}"`:"";o=`${a}![Image${u}](${s.url})`;break;case "bookmark":case "embed":case "link_preview":o=`${a}[${s.caption||s.url}](${s.url})`;break;case "callout":o=`${a}> **${s.icon?.emoji||""}** ${s.text}`;break;case "table":o=this.tableToMarkdown(e,a);break;case "table_row":o="";break;default:s&&s.text?o=`${a}${s.text}`:o=`${a}<!-- Unsupported block type: ${r} -->`;}if(n&&n.length>0&&r!=="toggle")if(this.isListItem(r)){let l={...t,level:t.level+1},c=this.processBlocksGroup(n,l);c.trim()&&(o+=` `+c);}else {let l={...t,level:t.level+1},c=this.processBlocksGroup(n,l);c.trim()&&(o+=` `+c);}return o}tableToMarkdown(e,t){let{content:r,children:s}=e;if(!s||s.length===0)return `${t}<!-- Empty table -->`;let n=s,a=[];return n.forEach((o,l)=>{let c=o.content.cells.map(u=>u.plainText||""),d=`${t}| ${c.join(" | ")} |`;if(a.push(d),l===0){let u=`${t}|${c.map(()=>" --- ").join("|")}|`;a.push(u);}}),a.join(` `)}blockToHtml(e,t=0){let{type:r,content:s,children:n}=e,a="";switch(r){case "paragraph":a=`<p>${s.text}</p>`;break;case "heading_1":a=`<h1>${s.text}</h1>`;break;case "heading_2":a=`<h2>${s.text}</h2>`;break;case "heading_3":a=`<h3>${s.text}</h3>`;break;case "bulleted_list_item":a=`<li>${s.text}</li>`,t===0&&(a=`<ul>${a}</ul>`);break;case "numbered_list_item":a=`<li>${s.text}</li>`,t===0&&(a=`<ol>${a}</ol>`);break;case "to_do":a=`<div class="to-do"><input type="checkbox"${s.checked?" checked":""} disabled /><span>${s.text}</span></div>`;break;case "toggle":a=`<details> <summary>${s.text}</summary> ${n&&n.length>0?n.map(d=>this.blockToHtml(d,t+1)).join(""):""} </details>`;break;case "code":a=`<pre><code class="language-${s.language||"plaintext"}">${s.text}</code></pre>`;break;case "quote":a=`<blockquote>${s.text}</blockquote>`;break;case "divider":a="<hr />";break;case "image":let l=s.caption?`<figcaption>${s.caption}</figcaption>`:"";a=`<figure><img src="${s.url}" alt="${s.caption||"Image"}" />${l}</figure>`;break;case "bookmark":case "embed":case "link_preview":a=`<a href="${s.url}" target="_blank" rel="noopener noreferrer">${s.caption||s.url}</a>`;break;case "callout":a=`<div class="callout">${s.icon?.emoji?`<span class="icon">${s.icon.emoji}</span>`:""}<div class="callout-content">${s.text}</div></div>`;break;case "table":a=this.tableToHtml(e);break;case "table_row":a="";break;default:s&&s.text?a=`<div>${s.text}</div>`:a=`<!-- Unsupported block type: ${r} -->`;}return n&&n.length>0&&r!=="toggle"&&(r==="bulleted_list_item"&&t===0?a=`<ul>${a}${n.map(o=>this.blockToHtml(o,t+1)).join("")}</ul>`:r==="numbered_list_item"&&t===0?a=`<ol>${a}${n.map(o=>this.blockToHtml(o,t+1)).join("")}</ol>`:a+=n.map(o=>this.blockToHtml(o,t+1)).join("")),a}tableToHtml(e){let{content:t,children:r}=e;if(!r||r.length===0)return "<!-- Empty table -->";let s=r,n="<table>";return s.forEach((a,o)=>{let l=o===0&&t.hasColumnHeader,c=l?"th":"td",u=`<tr>${a.content.cells.map(y=>`<${c}>${y.plainText||""}</${c}>`).join("")}</tr>`;l?(n+=`<thead>${u}</thead>`,s.length>1&&(n+="<tbody>")):n+=u;}),t.hasColumnHeader&&s.length>1&&(n+="</tbody>"),n+="</table>",n}extractRichText(e=[]){return !e||!Array.isArray(e)?"":e.map(t=>t.plain_text||"").join("")}};var b=class{constructor(e){this.fileManager=e;}async simplifyBlockAsync(e){let{id:t,type:r,has_children:s}=e,n=await this.extractBlockContentAsync(e);return {id:t,type:r,content:n,hasChildren:s}}async extractBlockContentAsync(e){let{type:t}=e,r=e[t];switch(t){case "paragraph":case "heading_1":case "heading_2":case "heading_3":case "bulleted_list_item":case "numbered_list_item":case "toggle":case "quote":return {text:this.extractRichText(r.rich_text),richText:r.rich_text};case "code":return {text:this.extractRichText(r.rich_text),language:r.language};case "image":case "file":case "pdf":case "video":case "audio":let n=r.type==="external"?r.external.url:r.file.url;try{n=await this.fileManager.processFileUrl(n,`content-block-${e.id}`);}catch(a){console.warn(`Failed to process content block file: ${n}`,a);}return {caption:r.caption?this.extractRichText(r.caption):"",url:n};case "bookmark":case "embed":case "link_preview":return {url:r.url,caption:r.caption?this.extractRichText(r.caption):""};case "divider":case "equation":case "table_of_contents":return {};case "to_do":return {text:this.extractRichText(r.rich_text),checked:r.checked};case "callout":return {text:this.extractRichText(r.rich_text),icon:r.icon};case "table":return {tableWidth:r.table_width,hasColumnHeader:r.has_column_header,hasRowHeader:r.has_row_header};case "table_row":return {cells:r.cells.map(a=>({plainText:this.extractRichText(a),richText:a}))};case "column_list":case "column":return {};default:return r||{}}}simplifyBlock(e){let{id:t,type:r,has_children:s}=e,n=this.extractBlockContent(e);return {id:t,type:r,content:n,hasChildren:s}}extractBlockContent(e){let{type:t}=e,r=e[t];switch(t){case "paragraph":case "heading_1":case "heading_2":case "heading_3":case "bulleted_list_item":case "numbered_list_item":case "toggle":case "quote":return {text:this.extractRichText(r.rich_text),richText:r.rich_text};case "code":return {text:this.extractRichText(r.rich_text),language:r.language};case "image":case "file":case "pdf":case "video":case "audio":let s=r.type;return {caption:r.caption?this.extractRichText(r.caption):"",url:s==="external"?r.external.url:r.file.url};case "bookmark":case "embed":case "link_preview":return {url:r.url,caption:r.caption?this.extractRichText(r.caption):""};case "divider":case "equation":case "table_of_contents":return {};case "to_do":return {text:this.extractRichText(r.rich_text),checked:r.checked};case "callout":return {text:this.extractRichText(r.rich_text),icon:r.icon};case "table":return {tableWidth:r.table_width,hasColumnHeader:r.has_column_header,hasRowHeader:r.has_row_header};case "table_row":return {cells:r.cells.map(n=>({plainText:this.extractRichText(n),richText:n}))};case "column_list":case "column":return {};default:return r||{}}}extractRichText(e=[]){return !e||!Array.isArray(e)?"":e.map(t=>t.plain_text||"").join("")}};var f=class{constructor(e,t){this.client=e;this.blockProcessor=t;}async getPageContent(e,t=true){let r=await this.getBlocks(e);if(t)for(let s of r)s.hasChildren&&(s.children=await this.getPageContent(s.id,true));return r}async getBlocks(e){let t=[],r=true,s;for(;r;){let n=await this.client.blocks.children.list({block_id:e,start_cursor:s}),a=n.results,o=await Promise.all(a.map(l=>this.blockProcessor.simplifyBlockAsync(l)));t=[...t,...o],r=n.has_more,s=n.next_cursor||void 0;}return t}};var F=class{constructor(e,t){this.client=new client.Client({auth:e}),this.config=P(t),p.configure(this.config.debug),this.fileManager=new _(this.config),this.contentConverter=new g,this.blockProcessor=new b(this.fileManager),this.pageContentService=new f(this.client,this.blockProcessor),this.databaseService=new m(this.client,this.fileManager);}blocksToMarkdown(e){return this.contentConverter.blocksToMarkdown(e)}blocksToHtml(e){return this.contentConverter.blocksToHtml(e)}query(e,t){return this.databaseService.query(e,t)}async getRecord(e){return this.databaseService.getRecord(e)}async getPageContent(e,t=true){return this.pageContentService.getPageContent(e,t)}};Object.defineProperty(exports,"advancedNotionRecord",{enumerable:true,get:function(){return chunkT46FQGVA_js.f}});Object.defineProperty(exports,"advancedNotionRecords",{enumerable:true,get:function(){return chunkT46FQGVA_js.g}});Object.defineProperty(exports,"generateMultipleDatabaseTypes",{enumerable:true,get:function(){return chunkT46FQGVA_js.h}});Object.defineProperty(exports,"generateTypes",{enumerable:true,get:function(){return chunkT46FQGVA_js.a}});Object.defineProperty(exports,"processNotionRecord",{enumerable:true,get:function(){return chunkT46FQGVA_js.b}});Object.defineProperty(exports,"processNotionRecords",{enumerable:true,get:function(){return chunkT46FQGVA_js.c}});Object.defineProperty(exports,"simplifyNotionRecord",{enumerable:true,get:function(){return chunkT46FQGVA_js.d}});Object.defineProperty(exports,"simplifyNotionRecords",{enumerable:true,get:function(){return chunkT46FQGVA_js.e}});exports.BlockProcessor=b;exports.ContentConverter=g;exports.DatabaseService=m;exports.NotionCMS=F;exports.OPERATOR_MAP=w;exports.PageContentService=f;exports.QueryBuilder=h;