@zeno-cms/sdk 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/angular/provider.ts","../src/angular/signals.ts"],"names":["ZENO_CLIENT","InjectionToken","provideZeno","options","makeEnvironmentProviders","ZenoCMS","injectZeno","inject","useAsyncQuery","fetcher","data","signal","error","loading","execute","result","err","useEntries","collectionSlug","params","zeno","useEntry","entryId","useCollections","useCollection","slug","useAssets","useAssetUrl","assetId","useProject","useLocales"],"mappings":"uHAKO,IAAMA,CAAAA,CAAc,IAAIC,cAAAA,CAAwB,SAAS,EAkBzD,SAASC,CAAAA,CAAYC,CAAAA,CAAuB,EAAC,CAAyB,CAC3E,OAAOC,wBAAAA,CAAyB,CAC9B,CACE,OAAA,CAASJ,CAAAA,CACT,UAAA,CAAY,IAAM,IAAIK,CAAAA,CAAQ,CAC5B,OAAQF,CAAAA,CAAQ,MAAA,CAChB,aAAA,CAAeA,CAAAA,CAAQ,aACzB,CAAC,CACH,CACF,CAAC,CACH,CAcO,SAASG,CAAAA,EAAsB,CACpC,OAAOC,MAAAA,CAAOP,CAAW,CAC3B,CC/BA,SAASQ,CAAAA,CACPC,EACgB,CAChB,IAAMC,CAAAA,CAAOC,MAAAA,CAAiB,IAAI,CAAA,CAC5BC,CAAAA,CAAQD,MAAAA,CAAsB,IAAI,CAAA,CAClCE,CAAAA,CAAUF,MAAAA,CAAO,IAAI,CAAA,CAErBG,CAAAA,CAAU,SAAY,CAC1BD,CAAAA,CAAQ,GAAA,CAAI,IAAI,CAAA,CAChBD,CAAAA,CAAM,GAAA,CAAI,IAAI,CAAA,CACd,GAAI,CACF,IAAMG,CAAAA,CAAS,MAAMN,CAAAA,EAAQ,CAC7BC,CAAAA,CAAK,GAAA,CAAIK,EAAO,IAAI,CAAA,CACpBH,CAAAA,CAAM,GAAA,CAAIG,CAAAA,CAAO,KAAK,EACxB,CAAA,M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,CACnD,CAGO,SAASQ,CAAAA,CAAYC,CAAAA,CAAwC,CAClE,IAAMR,CAAAA,CAAOd,CAAAA,EAAW,CACxB,OAAOE,CAAAA,CAAc,IAAMY,CAAAA,CAAK,WAAA,CAAYQ,CAAO,CAAC,CACtD,CAGO,SAASC,CAAAA,EAAmC,CACjD,IAAMT,CAAAA,CAAOd,CAAAA,EAAW,CACxB,OAAOE,CAAAA,CAAc,IAAMY,CAAAA,CAAK,UAAA,EAAY,CAC9C,CAGO,SAASU,CAAAA,EAAoC,CAClD,IAAMV,CAAAA,CAAOd,CAAAA,EAAW,CACxB,OAAOE,CAAAA,CAAc,IAAMY,CAAAA,CAAK,UAAA,EAAY,CAC9C","file":"angular.mjs","sourcesContent":["import { InjectionToken, inject, makeEnvironmentProviders, type EnvironmentProviders } from '@angular/core';\r\nimport { ZenoCMS } from '../client';\r\nimport type { ZenoOptions } from './types';\r\n\r\n/** Injection token for the ZenoCMS client */\r\nexport const ZENO_CLIENT = new InjectionToken<ZenoCMS>('ZenoCMS');\r\n\r\n/**\r\n * Provide the Zeno CMS client at the application level.\r\n * Use in your app config or root module providers.\r\n *\r\n * @example\r\n * ```ts\r\n * // app.config.ts\r\n * import { provideZeno } from '@zeno/sdk/angular'\r\n *\r\n * export const appConfig = {\r\n * providers: [\r\n * provideZeno({ apiKey: environment.zenoApiKey })\r\n * ]\r\n * }\r\n * ```\r\n */\r\nexport function provideZeno(options: ZenoOptions = {}): EnvironmentProviders {\r\n return makeEnvironmentProviders([\r\n {\r\n provide: ZENO_CLIENT,\r\n useFactory: () => new ZenoCMS({\r\n apiKey: options.apiKey,\r\n defaultLocale: options.defaultLocale,\r\n }),\r\n },\r\n ]);\r\n}\r\n\r\n/**\r\n * Inject the ZenoCMS client instance.\r\n * Requires `provideZeno()` in your app providers.\r\n *\r\n * @example\r\n * ```ts\r\n * import { injectZeno } from '@zeno/sdk/angular'\r\n *\r\n * const zeno = injectZeno()\r\n * await zeno.sendEmail({ ... })\r\n * ```\r\n */\r\nexport function injectZeno(): ZenoCMS {\r\n return inject(ZENO_CLIENT);\r\n}\r\n","import { signal, type Signal } from '@angular/core';\r\nimport { injectZeno } from './provider';\r\nimport type { QueryResult } from './types';\r\nimport type {\r\n Entry,\r\n Collection,\r\n Asset,\r\n AssetUrl,\r\n Project,\r\n Locale,\r\n PaginationParams,\r\n FilterParams,\r\n} from '../types';\r\n\r\n/**\r\n * Internal helper: wraps an async SDK call with Angular signals.\r\n * Auto-fetches on creation and exposes a refresh function.\r\n */\r\nfunction useAsyncQuery<T>(\r\n fetcher: () => Promise<{ data: T | null; error: string | null }>\r\n): QueryResult<T> {\r\n const data = signal<T | null>(null);\r\n const error = signal<string | null>(null);\r\n const loading = signal(true);\r\n\r\n const execute = async () => {\r\n loading.set(true);\r\n error.set(null);\r\n try {\r\n const result = await fetcher();\r\n data.set(result.data);\r\n error.set(result.error);\r\n } catch (err) {\r\n error.set(err instanceof Error ? err.message : String(err));\r\n data.set(null);\r\n } finally {\r\n loading.set(false);\r\n }\r\n };\r\n\r\n // Auto-fetch immediately\r\n execute();\r\n\r\n return {\r\n data: data.asReadonly(),\r\n error: error.asReadonly(),\r\n loading: loading.asReadonly(),\r\n refresh: execute,\r\n };\r\n}\r\n\r\n/** Fetch entries, optionally filtered by collection slug */\r\nexport function useEntries(\r\n collectionSlug?: string,\r\n params?: PaginationParams & FilterParams\r\n): QueryResult<Entry[]> {\r\n const zeno = injectZeno();\r\n return useAsyncQuery(() => zeno.getEntries(collectionSlug, params));\r\n}\r\n\r\n/** Fetch a single entry by ID */\r\nexport function useEntry(\r\n entryId: string,\r\n params?: { locale?: string; fallback_locale?: string }\r\n): QueryResult<Entry> {\r\n const zeno = injectZeno();\r\n return useAsyncQuery(() => zeno.getEntry(entryId, params));\r\n}\r\n\r\n/** Fetch all collections */\r\nexport function useCollections(\r\n params?: PaginationParams\r\n): QueryResult<Collection[]> {\r\n const zeno = injectZeno();\r\n return useAsyncQuery(() => zeno.getCollections(params));\r\n}\r\n\r\n/** Fetch a single collection by slug */\r\nexport function useCollection(slug: string): QueryResult<Collection> {\r\n const zeno = injectZeno();\r\n return useAsyncQuery(() => zeno.getCollection(slug));\r\n}\r\n\r\n/** Fetch assets */\r\nexport function useAssets(\r\n params?: PaginationParams & { mimeType?: string }\r\n): QueryResult<Asset[]> {\r\n const zeno = injectZeno();\r\n return useAsyncQuery(() => zeno.getAssets(params));\r\n}\r\n\r\n/** Get a signed download URL for an asset */\r\nexport function useAssetUrl(assetId: string): QueryResult<AssetUrl> {\r\n const zeno = injectZeno();\r\n return useAsyncQuery(() => zeno.getAssetUrl(assetId));\r\n}\r\n\r\n/** Fetch project information */\r\nexport function useProject(): QueryResult<Project> {\r\n const zeno = injectZeno();\r\n return useAsyncQuery(() => zeno.getProject());\r\n}\r\n\r\n/** Fetch available locales */\r\nexport function useLocales(): QueryResult<Locale[]> {\r\n const zeno = injectZeno();\r\n return useAsyncQuery(() => zeno.getLocales());\r\n}\r\n"]}
@@ -0,0 +1,8 @@
1
+ import {createClient}from'@supabase/supabase-js';var w={endpoint:"https://kvpowojjhuprhxdyzmml.supabase.co",publicKey:"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6Imt2cG93b2pqaHVwcmh4ZHl6bW1sIiwicm9sZSI6ImFub24iLCJpYXQiOjE3NTI3ODEwNzAsImV4cCI6MjA2ODM1NzA3MH0.cCPzDNdfTb3WBtYL79GBlw4hfypl4tjnqu7XfEvdKBg"};function o(b,a=null,t){let e=null;return a&&(typeof a=="string"?e=a:a instanceof Error?e=a.message:typeof a=="object"&&a!==null&&"message"in a&&(e=String(a.message))),{data:b,error:e,meta:{...t,timestamp:new Date().toISOString()}}}var L=class{constructor(a={}){this.projectId=null;this.isValidated=false;this.resolvedDefaultLocale=null;let t=a.apiKey||this.getEnvApiKey();if(!t)throw new Error("Missing API key. Provide it via config.apiKey or set an environment variable: ZENO_API_KEY, VITE_ZENO_API_KEY, NEXT_PUBLIC_ZENO_API_KEY, or PUBLIC_ZENO_API_KEY.");let e=this.parseApiKey(t);this.apiKey=t,this.projectSlug=e.projectSlug,this.apiToken=e.token,this.configDefaultLocale=a.defaultLocale,this.supabase=createClient(w.endpoint,w.publicKey,{auth:{persistSession:false,autoRefreshToken:false}});}getEnvApiKey(){let a=["ZENO_API_KEY","NEXT_PUBLIC_ZENO_API_KEY","VITE_ZENO_API_KEY","PUBLIC_ZENO_API_KEY"],t=["ZENO_API_KEY","VITE_ZENO_API_KEY","PUBLIC_ZENO_API_KEY","NEXT_PUBLIC_ZENO_API_KEY"];if(typeof process<"u"&&process.env){for(let e of a)if(process.env[e])return process.env[e]}try{let e=import.meta?.env;if(e){for(let s of t)if(e[s])return e[s]}}catch{}}parseApiKey(a){if(!a.startsWith("zeno_"))throw new Error("Invalid API key format. Expected: zeno_<projectSlug>_<token>");let t=a.slice(5),e=t.indexOf("_");if(e===-1)throw new Error("Invalid API key format. Expected: zeno_<projectSlug>_<token>");let s=t.slice(0,e),r=t.slice(e+1);if(!s||!r)throw new Error("Invalid API key format. Expected: zeno_<projectSlug>_<token>");return {projectSlug:s,token:r}}async getDefaultLocale(){if(this.configDefaultLocale)return this.configDefaultLocale;if(this.resolvedDefaultLocale)return this.resolvedDefaultLocale;try{let a=await this.resolveProjectId(),{data:t}=await this.supabase.from("project_locales").select("locale_code").eq("project_id",a).eq("is_default",!0).single();if(t?.locale_code)return this.resolvedDefaultLocale=t.locale_code,t.locale_code}catch{}return this.resolvedDefaultLocale="en","en"}async resolveProjectId(){if(this.projectId&&this.isValidated)return this.projectId;let{data:a,error:t}=await this.supabase.rpc("validate_sdk_api_key",{p_project_slug:this.projectSlug,p_token:this.apiToken});if(t)throw new Error("API key validation failed: "+t.message);let e=a?.[0];if(!e||!e.is_valid)throw new Error(e?.error_message||"Invalid API key or project not found");return this.projectId=e.project_id,this.isValidated=true,e.project_id}async getProject(){try{let a=await this.resolveProjectId(),{data:t,error:e}=await this.supabase.from("projects").select("id, name, description, slug, status, created_at, updated_at").eq("id",a).single();return o(t,e)}catch(a){return o(null,a)}}async getCollections(a={}){try{let t=await this.resolveProjectId(),{page:e=1,limit:s=50,sortBy:r="created_at",sortOrder:f="desc"}=a,g=(e-1)*s,{count:c}=await this.supabase.from("collections").select("*",{count:"exact",head:!0}).eq("project_id",t),{data:i,error:d}=await this.supabase.from("collections").select("id, name, slug, description, fields, created_at, updated_at").eq("project_id",t).order(r,{ascending:f==="asc"}).range(g,g+s-1),h=i?.map(l=>({...l,fields:typeof l.fields=="string"?JSON.parse(l.fields):l.fields}));return o(h,d,{total:c||0,page:e,limit:s,totalPages:Math.ceil((c||0)/s)})}catch(t){return o(null,t)}}async getCollection(a){try{let t=await this.resolveProjectId(),{data:e,error:s}=await this.supabase.from("collections").select("id, name, slug, description, fields, created_at, updated_at").eq("project_id",t).eq("slug",a).single(),r=e?{...e,fields:typeof e.fields=="string"?JSON.parse(e.fields):e.fields}:null;return o(r,s)}catch(t){return o(null,t)}}async getEntries(a,t={}){try{let e=await this.resolveProjectId(),{page:s=1,limit:r=50,sortBy:f="created_at",sortOrder:g="desc",status:c,search:i,locale:d,fallback_locale:h,dateFrom:l,dateTo:m,dateField:u}=t,P=h||await this.getDefaultLocale(),k=(s-1)*r,p=this.supabase.from("entries").select(`
2
+ id, data, status, collection_id, project_id, created_at, updated_at,
3
+ collections ( id, name, slug )
4
+ `).eq("project_id",e);if(a){let{data:n}=await this.supabase.from("collections").select("id").eq("project_id",e).eq("slug",a).single();if(!n)return o(null,"Collection not found");p=p.eq("collection_id",n.id);}c&&(p=p.eq("status",c)),i&&(p=p.textSearch("data",i)),l&&(p=u?p.gte(`data->${u}`,l):p.gte("created_at",l)),m&&(p=u?p.lte(`data->${u}`,m):p.lte("created_at",m));let _=this.supabase.from("entries").select("*",{count:"exact",head:!0}).eq("project_id",e);if(a){let{data:n}=await this.supabase.from("collections").select("id").eq("project_id",e).eq("slug",a).single();n&&(_=_.eq("collection_id",n.id));}c&&(_=_.eq("status",c)),i&&(_=_.textSearch("data",i)),l&&(_=u?_.gte(`data->${u}`,l):_.gte("created_at",l)),m&&(_=u?_.lte(`data->${u}`,m):_.lte("created_at",m));let{count:A}=await _,{data:N,error:q}=await p.order(f,{ascending:g==="asc"}).range(k,k+r-1);if(q)throw q;let E=(N??[]).map(n=>({...n,collections:Array.isArray(n.collections)?n.collections[0]:n.collections})),Z=E,K=!1;if(d&&E.length>0)try{let n=E.map(j=>j.id),v=await this.supabase.rpc("get_localized_entries_batch",{entry_uuids:n,locale:d,fallback_locale:P});if(v.data&&v.data.length>0){let j=new Map;for(let y of v.data)j.set(y.entry_id,{data:y.data,locale_code:y.locale_code,is_fallback:y.is_fallback});Z=E.map(y=>{let I=j.get(y.id);return I?(I.is_fallback&&(K=!0),{...y,data:I.data,locale_code:I.locale_code}):y});}}catch{}let{data:O}=await this.supabase.from("project_locales").select("locale_code").eq("project_id",e).eq("is_active",!0);return o(Z,null,{total:A||0,page:s,limit:r,totalPages:Math.ceil((A||0)/r),locale:d||P,fallback_used:K,available_locales:O?.map(n=>n.locale_code)||[]})}catch(e){return o(null,e)}}async getEntry(a,t={}){try{let e=await this.resolveProjectId(),{locale:s,fallback_locale:r}=t,f=r||await this.getDefaultLocale(),{data:g,error:c}=await this.supabase.from("entries").select(`
5
+ id, data, status, collection_id, project_id, created_at, updated_at,
6
+ collections ( id, name, slug, fields )
7
+ `).eq("project_id",e).eq("id",a).single();if(c)throw c;let i=g,d=i?{...i,collections:Array.isArray(i.collections)?i.collections[0]:i.collections}:null,h=d,l=!1;if(s&&d)try{let u=await this.supabase.rpc("get_localized_entry",{entry_uuid:a,locale:s,fallback_locale:f});if(u.data?.[0]){let P=u.data[0];P.locale_code!==s&&(l=!0),h={...d,data:P.data,locale_code:P.locale_code};}}catch{}let{data:m}=await this.supabase.from("project_locales").select("locale_code").eq("project_id",e).eq("is_active",!0);return o(h,null,{locale:s||f,fallback_used:l,available_locales:m?.map(u=>u.locale_code)||[]})}catch(e){return o(null,e)}}async getAssets(a={}){try{let t=await this.resolveProjectId(),{page:e=1,limit:s=50,sortBy:r="created_at",sortOrder:f="desc",mimeType:g}=a,c=(e-1)*s,i=this.supabase.from("assets").select("id, filename, original_filename, mime_type, size_bytes, metadata, created_at").eq("project_id",t);g&&(i=i.like("mime_type",`${g}%`));let d=this.supabase.from("assets").select("*",{count:"exact",head:!0}).eq("project_id",t);g&&(d=d.like("mime_type",`${g}%`));let{count:h}=await d,{data:l,error:m}=await i.order(r,{ascending:f==="asc"}).range(c,c+s-1);return o(l,m,{total:h||0,page:e,limit:s,totalPages:Math.ceil((h||0)/s)})}catch(t){return o(null,t)}}async getAssetUrl(a){try{let t=await this.resolveProjectId(),{data:e,error:s}=await this.supabase.from("assets").select("storage_path").eq("project_id",t).eq("id",a).single();if(s||!e)return o(null,"Asset not found");let{data:r,error:f}=await this.supabase.storage.from("assets").createSignedUrl(e.storage_path,3600);return f?o(null,f):o({downloadUrl:r.signedUrl,expiresIn:3600})}catch(t){return o(null,t)}}async sendEmail(a){try{let t=await fetch(`${w.endpoint}/functions/v1/api/email/send`,{method:"POST",headers:{Authorization:`Bearer ${this.apiKey}`,"X-API-Key":this.apiKey,"Content-Type":"application/json"},body:JSON.stringify(a)}),e=await t.json();return t.ok?o(e.data):o(null,e.error||"Email sending failed")}catch(t){return o(null,t)}}async getLocales(){try{let a=await this.resolveProjectId(),{data:t,error:e}=await this.supabase.from("project_locales").select("locale_code, locale_name, locale_native_name, is_default").eq("project_id",a).eq("is_active",!0).order("is_default",{ascending:!1}).order("locale_name",{ascending:!0});if(e)throw e;let s=t?.map(r=>({code:r.locale_code,name:r.locale_name,native_name:r.locale_native_name,is_default:r.is_default}))||[];return o(s)}catch(a){return o(null,a)}}async health(){return o({status:"healthy",version:"1.0.0"})}};export{L as a};//# sourceMappingURL=chunk-4ROHQDX7.mjs.map
8
+ //# sourceMappingURL=chunk-4ROHQDX7.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/client.ts"],"names":["ZENO_INTERNAL","createResponse","data","error","meta","errorMessage","ZenoCMS","config","apiKey","parsed","createClient","processEnvKeys","importMetaKeys","key","metaEnv","withoutPrefix","separatorIndex","projectSlug","token","projectId","result","params","page","limit","sortBy","sortOrder","offset","count","processedData","c","slug","collectionSlug","status","search","locale","fallback_locale","dateFrom","dateTo","dateField","effectiveFallback","query","collection","countQuery","normalized","row","fallbackUsed","entryIds","e","localeMap","loc","entry","localized","availableLocales","l","entryId","mimeType","assetId","asset","assetError","urlData","urlError","emailParams","response"],"mappings":"iDAiBA,IAAMA,CAAAA,CAAgB,CACpB,SAAU,0CAAA,CACV,SAAA,CAAW,kNACb,CAAA,CAEA,SAASC,CAAAA,CACPC,CAAAA,CACAC,EAAiB,IAAA,CACjBC,CAAAA,CACiB,CACjB,IAAIC,CAAAA,CAA8B,IAAA,CAClC,OAAIF,IACE,OAAOA,CAAAA,EAAU,SAAUE,CAAAA,CAAeF,CAAAA,CACrCA,aAAiB,KAAA,CAAOE,CAAAA,CAAeF,CAAAA,CAAM,OAAA,CAC7C,OAAOA,CAAAA,EAAU,QAAA,EAAYA,IAAU,IAAA,EAAQ,SAAA,GAAaA,IACnEE,CAAAA,CAAe,MAAA,CAAQF,CAAAA,CAA+B,OAAO,IAI1D,CACL,IAAA,CAAAD,EACA,KAAA,CAAOG,CAAAA,CACP,KAAM,CACJ,GAAGD,CAAAA,CACH,SAAA,CAAW,IAAI,IAAA,EAAK,CAAE,aACxB,CACF,CACF,CAEO,IAAME,CAAAA,CAAN,KAAc,CAUnB,WAAA,CAAYC,CAAAA,CAAqB,EAAC,CAAG,CALrC,KAAQ,SAAA,CAA2B,IAAA,CACnC,KAAQ,WAAA,CAAuB,KAAA,CAE/B,KAAQ,qBAAA,CAAuC,IAAA,CAI7C,IAAMC,CAAAA,CAASD,CAAAA,CAAO,QAAU,IAAA,CAAK,YAAA,EAAa,CAElD,GAAI,CAACC,CAAAA,CACH,MAAM,IAAI,KAA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xC,KAAA,CAAM,aAAA,CAAe,CAAE,SAAA,CAAW,CAAA,CAAK,CAAC,EAE3C,GAAIhB,CAAAA,CAAO,MAAMA,CAAAA,CAEjB,IAAMyB,CAAAA,CAAgB1B,CAAAA,EAAM,GAAA,CAAKmD,CAAAA,GAAO,CACtC,IAAA,CAAMA,CAAAA,CAAE,WAAA,CACR,IAAA,CAAMA,CAAAA,CAAE,WAAA,CACR,YAAaA,CAAAA,CAAE,kBAAA,CACf,UAAA,CAAYA,CAAAA,CAAE,UAChB,CAAA,CAAE,CAAA,EAAK,EAAC,CAER,OAAOpD,CAAAA,CAAyB2B,CAAa,CAC/C,CAAA,MAASzB,CAAAA,CAAO,CACd,OAAOF,CAAAA,CAAyB,IAAA,CAAME,CAAK,CAC7C,CACF,CAGA,MAAM,MAAA,EAA8C,CAClD,OAAOF,CAAAA,CAA6B,CAClC,MAAA,CAAQ,SAAA,CACR,OAAA,CAAS,OACX,CAAC,CACH,CACF","file":"chunk-4ROHQDX7.mjs","sourcesContent":["import { createClient, type SupabaseClient } from '@supabase/supabase-js';\r\nimport type {\r\n ZenoConfig,\r\n ZenoResponse,\r\n PaginationParams,\r\n FilterParams,\r\n EmailParams,\r\n Collection,\r\n Entry,\r\n Asset,\r\n AssetUrl,\r\n Locale,\r\n Project,\r\n HealthStatus,\r\n} from './types';\r\n\r\n// Internal configuration - injected at build time from environment variables\r\nconst ZENO_INTERNAL = {\r\n endpoint: process.env.ZENO_ENDPOINT!,\r\n publicKey: process.env.ZENO_PUBLIC_KEY!,\r\n};\r\n\r\nfunction createResponse<T>(\r\n data: T | null,\r\n error: unknown = null,\r\n meta?: Omit<NonNullable<ZenoResponse<T>['meta']>, 'timestamp'>\r\n): ZenoResponse<T> {\r\n let errorMessage: string | null = null;\r\n if (error) {\r\n if (typeof error === 'string') errorMessage = error;\r\n else if (error instanceof Error) errorMessage = error.message;\r\n else if (typeof error === 'object' && error !== null && 'message' in error) {\r\n errorMessage = String((error as { message: unknown }).message);\r\n }\r\n }\r\n\r\n return {\r\n data,\r\n error: errorMessage,\r\n meta: {\r\n ...meta,\r\n timestamp: new Date().toISOString(),\r\n },\r\n };\r\n}\r\n\r\nexport class ZenoCMS {\r\n private supabase: SupabaseClient;\r\n private apiKey: string;\r\n private projectSlug: string;\r\n private apiToken: string;\r\n private projectId: string | null = null;\r\n private isValidated: boolean = false;\r\n private configDefaultLocale: string | undefined;\r\n private resolvedDefaultLocale: string | null = null;\r\n\r\n constructor(config: ZenoConfig = {}) {\r\n // Resolve API key: explicit config > environment variable\r\n const apiKey = config.apiKey || this.getEnvApiKey();\r\n\r\n if (!apiKey) {\r\n throw new Error(\r\n 'Missing API key. Provide it via config.apiKey or set an environment variable: ' +\r\n 'ZENO_API_KEY, VITE_ZENO_API_KEY, NEXT_PUBLIC_ZENO_API_KEY, or PUBLIC_ZENO_API_KEY.'\r\n );\r\n }\r\n\r\n // Parse and validate API key format: zeno_<projectSlug>_<token>\r\n const parsed = this.parseApiKey(apiKey);\r\n this.apiKey = apiKey;\r\n this.projectSlug = parsed.projectSlug;\r\n this.apiToken = parsed.token;\r\n this.configDefaultLocale = config.defaultLocale;\r\n\r\n this.supabase = createClient(ZENO_INTERNAL.endpoint, ZENO_INTERNAL.publicKey, {\r\n auth: {\r\n persistSession: false,\r\n autoRefreshToken: false,\r\n },\r\n });\r\n }\r\n\r\n /**\r\n * Reads the API key from environment variables.\r\n * Checks multiple naming conventions so each framework only needs one .env variable:\r\n * ZENO_API_KEY — Node.js / server-side\r\n * NEXT_PUBLIC_ZENO_API_KEY — Next.js client\r\n * VITE_ZENO_API_KEY — Vite (React, Vue, Svelte)\r\n * PUBLIC_ZENO_API_KEY — Astro client\r\n */\r\n private getEnvApiKey(): string | undefined {\r\n const processEnvKeys = [\r\n 'ZENO_API_KEY',\r\n 'NEXT_PUBLIC_ZENO_API_KEY',\r\n 'VITE_ZENO_API_KEY',\r\n 'PUBLIC_ZENO_API_KEY',\r\n ];\r\n\r\n const importMetaKeys = [\r\n 'ZENO_API_KEY',\r\n 'VITE_ZENO_API_KEY',\r\n 'PUBLIC_ZENO_API_KEY',\r\n 'NEXT_PUBLIC_ZENO_API_KEY',\r\n ];\r\n\r\n // Node.js / Next.js (process.env)\r\n if (typeof process !== 'undefined' && process.env) {\r\n for (const key of processEnvKeys) {\r\n if (process.env[key]) return process.env[key];\r\n }\r\n }\r\n\r\n // Vite / Astro / SvelteKit (import.meta.env)\r\n try {\r\n // @ts-expect-error - import.meta.env may not exist in all environments\r\n const metaEnv = import.meta?.env;\r\n if (metaEnv) {\r\n for (const key of importMetaKeys) {\r\n if (metaEnv[key]) return metaEnv[key];\r\n }\r\n }\r\n } catch {\r\n // import.meta not available\r\n }\r\n\r\n return undefined;\r\n }\r\n\r\n /**\r\n * Parse and validate the API key format.\r\n * Expected format: zeno_<projectSlug>_<token>\r\n */\r\n private parseApiKey(apiKey: string): { projectSlug: string; token: string } {\r\n if (!apiKey.startsWith('zeno_')) {\r\n throw new Error('Invalid API key format. Expected: zeno_<projectSlug>_<token>');\r\n }\r\n\r\n const withoutPrefix = apiKey.slice(5); // Remove 'zeno_'\r\n const separatorIndex = withoutPrefix.indexOf('_');\r\n\r\n if (separatorIndex === -1) {\r\n throw new Error('Invalid API key format. Expected: zeno_<projectSlug>_<token>');\r\n }\r\n\r\n const projectSlug = withoutPrefix.slice(0, separatorIndex);\r\n const token = withoutPrefix.slice(separatorIndex + 1);\r\n\r\n if (!projectSlug || !token) {\r\n throw new Error('Invalid API key format. Expected: zeno_<projectSlug>_<token>');\r\n }\r\n\r\n return { projectSlug, token };\r\n }\r\n\r\n /**\r\n * Returns the fallback locale to use.\r\n * Priority: config.defaultLocale > project's default locale from DB > 'en'.\r\n */\r\n private async getDefaultLocale(): Promise<string> {\r\n if (this.configDefaultLocale) return this.configDefaultLocale;\r\n if (this.resolvedDefaultLocale) return this.resolvedDefaultLocale;\r\n\r\n try {\r\n const projectId = await this.resolveProjectId();\r\n const { data } = await this.supabase\r\n .from('project_locales')\r\n .select('locale_code')\r\n .eq('project_id', projectId)\r\n .eq('is_default', true)\r\n .single();\r\n\r\n if (data?.locale_code) {\r\n this.resolvedDefaultLocale = data.locale_code;\r\n return data.locale_code;\r\n }\r\n } catch {\r\n // Fall through to 'en'\r\n }\r\n\r\n this.resolvedDefaultLocale = 'en';\r\n return 'en';\r\n }\r\n\r\n /**\r\n * Resolves and validates the project ID using the API key.\r\n * Validates the token server-side for security.\r\n */\r\n private async resolveProjectId(): Promise<string> {\r\n // Return cached project ID if already validated\r\n if (this.projectId && this.isValidated) return this.projectId;\r\n\r\n // Call server-side validation function\r\n const { data, error } = await this.supabase.rpc('validate_sdk_api_key', {\r\n p_project_slug: this.projectSlug,\r\n p_token: this.apiToken,\r\n });\r\n\r\n if (error) {\r\n throw new Error('API key validation failed: ' + error.message);\r\n }\r\n\r\n // The RPC returns a single row with project_id, is_valid, error_message\r\n const result = data?.[0];\r\n\r\n if (!result || !result.is_valid) {\r\n throw new Error(result?.error_message || 'Invalid API key or project not found');\r\n }\r\n\r\n this.projectId = result.project_id;\r\n this.isValidated = true;\r\n return result.project_id;\r\n }\r\n\r\n /** Get project information */\r\n async getProject(): Promise<ZenoResponse<Project>> {\r\n try {\r\n const projectId = await this.resolveProjectId();\r\n\r\n const { data, error } = await this.supabase\r\n .from('projects')\r\n .select('id, name, description, slug, status, created_at, updated_at')\r\n .eq('id', projectId)\r\n .single();\r\n\r\n return createResponse(data, error);\r\n } catch (error) {\r\n return createResponse<Project>(null, error);\r\n }\r\n }\r\n\r\n /** Get all collections for the project */\r\n async getCollections(params: PaginationParams = {}): Promise<ZenoResponse<Collection[]>> {\r\n try {\r\n const projectId = await this.resolveProjectId();\r\n const { page = 1, limit = 50, sortBy = 'created_at', sortOrder = 'desc' } = params;\r\n const offset = (page - 1) * limit;\r\n\r\n const { count } = await this.supabase\r\n .from('collections')\r\n .select('*', { count: 'exact', head: true })\r\n .eq('project_id', projectId);\r\n\r\n const { data, error } = await this.supabase\r\n .from('collections')\r\n .select('id, name, slug, description, fields, created_at, updated_at')\r\n .eq('project_id', projectId)\r\n .order(sortBy, { ascending: sortOrder === 'asc' })\r\n .range(offset, offset + limit - 1);\r\n\r\n const processedData = data?.map((c) => ({\r\n ...c,\r\n fields: typeof c.fields === 'string' ? JSON.parse(c.fields) : c.fields,\r\n }));\r\n\r\n return createResponse(processedData as Collection[] | null, error, {\r\n total: count || 0,\r\n page,\r\n limit,\r\n totalPages: Math.ceil((count || 0) / limit),\r\n });\r\n } catch (error) {\r\n return createResponse<Collection[]>(null, error);\r\n }\r\n }\r\n\r\n /** Get a single collection by slug */\r\n async getCollection(slug: string): Promise<ZenoResponse<Collection>> {\r\n try {\r\n const projectId = await this.resolveProjectId();\r\n\r\n const { data, error } = await this.supabase\r\n .from('collections')\r\n .select('id, name, slug, description, fields, created_at, updated_at')\r\n .eq('project_id', projectId)\r\n .eq('slug', slug)\r\n .single();\r\n\r\n const processedData = data\r\n ? { ...data, fields: typeof data.fields === 'string' ? JSON.parse(data.fields) : data.fields }\r\n : null;\r\n\r\n return createResponse(processedData as Collection | null, error);\r\n } catch (error) {\r\n return createResponse<Collection>(null, error);\r\n }\r\n }\r\n\r\n /** Get entries, optionally filtered by collection slug */\r\n async getEntries(\r\n collectionSlug?: string,\r\n params: PaginationParams & FilterParams = {}\r\n ): Promise<ZenoResponse<Entry[]>> {\r\n try {\r\n const projectId = await this.resolveProjectId();\r\n const {\r\n page = 1,\r\n limit = 50,\r\n sortBy = 'created_at',\r\n sortOrder = 'desc',\r\n status,\r\n search,\r\n locale,\r\n fallback_locale,\r\n dateFrom,\r\n dateTo,\r\n dateField,\r\n } = params;\r\n const effectiveFallback = fallback_locale || await this.getDefaultLocale();\r\n const offset = (page - 1) * limit;\r\n\r\n let query = this.supabase\r\n .from('entries')\r\n .select(`\r\n id, data, status, collection_id, project_id, created_at, updated_at,\r\n collections ( id, name, slug )\r\n `)\r\n .eq('project_id', projectId);\r\n\r\n // Filter by collection\r\n if (collectionSlug) {\r\n const { data: collection } = await this.supabase\r\n .from('collections')\r\n .select('id')\r\n .eq('project_id', projectId)\r\n .eq('slug', collectionSlug)\r\n .single();\r\n\r\n if (!collection) {\r\n return createResponse<Entry[]>(null, 'Collection not found');\r\n }\r\n query = query.eq('collection_id', collection.id);\r\n }\r\n\r\n if (status) query = query.eq('status', status);\r\n if (search) query = query.textSearch('data', search);\r\n\r\n // Date filtering: use dateField inside data if specified, otherwise use created_at\r\n if (dateFrom) {\r\n query = dateField\r\n ? query.gte(`data->${dateField}`, dateFrom)\r\n : query.gte('created_at', dateFrom);\r\n }\r\n if (dateTo) {\r\n query = dateField\r\n ? query.lte(`data->${dateField}`, dateTo)\r\n : query.lte('created_at', dateTo);\r\n }\r\n\r\n // Count query\r\n let countQuery = this.supabase\r\n .from('entries')\r\n .select('*', { count: 'exact', head: true })\r\n .eq('project_id', projectId);\r\n\r\n if (collectionSlug) {\r\n const { data: collection } = await this.supabase\r\n .from('collections')\r\n .select('id')\r\n .eq('project_id', projectId)\r\n .eq('slug', collectionSlug)\r\n .single();\r\n\r\n if (collection) countQuery = countQuery.eq('collection_id', collection.id);\r\n }\r\n if (status) countQuery = countQuery.eq('status', status);\r\n if (search) countQuery = countQuery.textSearch('data', search);\r\n\r\n // Date filtering for count query\r\n if (dateFrom) {\r\n countQuery = dateField\r\n ? countQuery.gte(`data->${dateField}`, dateFrom)\r\n : countQuery.gte('created_at', dateFrom);\r\n }\r\n if (dateTo) {\r\n countQuery = dateField\r\n ? countQuery.lte(`data->${dateField}`, dateTo)\r\n : countQuery.lte('created_at', dateTo);\r\n }\r\n\r\n const { count } = await countQuery;\r\n\r\n const { data, error } = await query\r\n .order(sortBy, { ascending: sortOrder === 'asc' })\r\n .range(offset, offset + limit - 1);\r\n\r\n if (error) throw error;\r\n\r\n // Normalize Supabase join (returns array for relations) and apply localization\r\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\r\n const rows = (data as any[]) ?? [];\r\n const normalized = rows.map((row) => ({\r\n ...row,\r\n collections: Array.isArray(row.collections) ? row.collections[0] : row.collections,\r\n }));\r\n\r\n let processedData = normalized;\r\n let fallbackUsed = false;\r\n\r\n if (locale && normalized.length > 0) {\r\n try {\r\n // Use batch function to avoid N+1 queries\r\n const entryIds = normalized.map((e) => e.id);\r\n const result = await this.supabase.rpc('get_localized_entries_batch', {\r\n entry_uuids: entryIds,\r\n locale,\r\n fallback_locale: effectiveFallback,\r\n });\r\n\r\n if (result.data && result.data.length > 0) {\r\n // Create a map for quick lookup\r\n const localeMap = new Map<string, { data: Record<string, unknown>; locale_code: string; is_fallback: boolean }>();\r\n for (const loc of result.data) {\r\n localeMap.set(loc.entry_id, {\r\n data: loc.data,\r\n locale_code: loc.locale_code,\r\n is_fallback: loc.is_fallback,\r\n });\r\n }\r\n\r\n // Merge localized data with entries\r\n processedData = normalized.map((entry) => {\r\n const localized = localeMap.get(entry.id);\r\n if (localized) {\r\n if (localized.is_fallback) fallbackUsed = true;\r\n return { ...entry, data: localized.data, locale_code: localized.locale_code };\r\n }\r\n return entry;\r\n });\r\n }\r\n } catch {\r\n // Fallback to base data if batch function fails\r\n }\r\n }\r\n\r\n // Available locales\r\n const { data: availableLocales } = await this.supabase\r\n .from('project_locales')\r\n .select('locale_code')\r\n .eq('project_id', projectId)\r\n .eq('is_active', true);\r\n\r\n return createResponse(processedData as Entry[] | null, null, {\r\n total: count || 0,\r\n page,\r\n limit,\r\n totalPages: Math.ceil((count || 0) / limit),\r\n locale: locale || effectiveFallback,\r\n fallback_used: fallbackUsed,\r\n available_locales: availableLocales?.map((l) => l.locale_code) || [],\r\n });\r\n } catch (error) {\r\n return createResponse<Entry[]>(null, error);\r\n }\r\n }\r\n\r\n /** Get a single entry by ID */\r\n async getEntry(\r\n entryId: string,\r\n params: { locale?: string; fallback_locale?: string } = {}\r\n ): Promise<ZenoResponse<Entry>> {\r\n try {\r\n const projectId = await this.resolveProjectId();\r\n const { locale, fallback_locale } = params;\r\n const effectiveFallback = fallback_locale || await this.getDefaultLocale();\r\n\r\n const { data, error } = await this.supabase\r\n .from('entries')\r\n .select(`\r\n id, data, status, collection_id, project_id, created_at, updated_at,\r\n collections ( id, name, slug, fields )\r\n `)\r\n .eq('project_id', projectId)\r\n .eq('id', entryId)\r\n .single();\r\n\r\n if (error) throw error;\r\n\r\n // Normalize Supabase join (returns array for relations)\r\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\r\n const row = data as any;\r\n const normalized = row ? {\r\n ...row,\r\n collections: Array.isArray(row.collections) ? row.collections[0] : row.collections,\r\n } : null;\r\n\r\n let processedData = normalized;\r\n let fallbackUsed = false;\r\n\r\n if (locale && normalized) {\r\n try {\r\n const result = await this.supabase.rpc('get_localized_entry', {\r\n entry_uuid: entryId,\r\n locale,\r\n fallback_locale: effectiveFallback,\r\n });\r\n\r\n if (result.data?.[0]) {\r\n const localized = result.data[0];\r\n if (localized.locale_code !== locale) fallbackUsed = true;\r\n processedData = { ...normalized, data: localized.data, locale_code: localized.locale_code };\r\n }\r\n } catch {\r\n // Fallback to base data\r\n }\r\n }\r\n\r\n const { data: availableLocales } = await this.supabase\r\n .from('project_locales')\r\n .select('locale_code')\r\n .eq('project_id', projectId)\r\n .eq('is_active', true);\r\n\r\n return createResponse(processedData as Entry | null, null, {\r\n locale: locale || effectiveFallback,\r\n fallback_used: fallbackUsed,\r\n available_locales: availableLocales?.map((l) => l.locale_code) || [],\r\n });\r\n } catch (error) {\r\n return createResponse<Entry>(null, error);\r\n }\r\n }\r\n\r\n /** Get assets for the project */\r\n async getAssets(\r\n params: PaginationParams & { mimeType?: string } = {}\r\n ): Promise<ZenoResponse<Asset[]>> {\r\n try {\r\n const projectId = await this.resolveProjectId();\r\n const { page = 1, limit = 50, sortBy = 'created_at', sortOrder = 'desc', mimeType } = params;\r\n const offset = (page - 1) * limit;\r\n\r\n let query = this.supabase\r\n .from('assets')\r\n .select('id, filename, original_filename, mime_type, size_bytes, metadata, created_at')\r\n .eq('project_id', projectId);\r\n\r\n if (mimeType) query = query.like('mime_type', `${mimeType}%`);\r\n\r\n let countQuery = this.supabase\r\n .from('assets')\r\n .select('*', { count: 'exact', head: true })\r\n .eq('project_id', projectId);\r\n\r\n if (mimeType) countQuery = countQuery.like('mime_type', `${mimeType}%`);\r\n\r\n const { count } = await countQuery;\r\n\r\n const { data, error } = await query\r\n .order(sortBy, { ascending: sortOrder === 'asc' })\r\n .range(offset, offset + limit - 1);\r\n\r\n return createResponse(data as Asset[] | null, error, {\r\n total: count || 0,\r\n page,\r\n limit,\r\n totalPages: Math.ceil((count || 0) / limit),\r\n });\r\n } catch (error) {\r\n return createResponse<Asset[]>(null, error);\r\n }\r\n }\r\n\r\n /** Get a signed download URL for an asset */\r\n async getAssetUrl(assetId: string): Promise<ZenoResponse<AssetUrl>> {\r\n try {\r\n const projectId = await this.resolveProjectId();\r\n\r\n const { data: asset, error: assetError } = await this.supabase\r\n .from('assets')\r\n .select('storage_path')\r\n .eq('project_id', projectId)\r\n .eq('id', assetId)\r\n .single();\r\n\r\n if (assetError || !asset) {\r\n return createResponse<AssetUrl>(null, 'Asset not found');\r\n }\r\n\r\n const { data: urlData, error: urlError } = await this.supabase\r\n .storage\r\n .from('assets')\r\n .createSignedUrl(asset.storage_path, 3600);\r\n\r\n if (urlError) {\r\n return createResponse<AssetUrl>(null, urlError);\r\n }\r\n\r\n return createResponse<AssetUrl>({\r\n downloadUrl: urlData.signedUrl,\r\n expiresIn: 3600,\r\n });\r\n } catch (error) {\r\n return createResponse<AssetUrl>(null, error);\r\n }\r\n }\r\n\r\n /** Send an email via the Zeno edge function */\r\n async sendEmail(emailParams: EmailParams): Promise<ZenoResponse<{ messageId: string }>> {\r\n try {\r\n const response = await fetch(`${ZENO_INTERNAL.endpoint}/functions/v1/api/email/send`, {\r\n method: 'POST',\r\n headers: {\r\n 'Authorization': `Bearer ${this.apiKey}`,\r\n 'X-API-Key': this.apiKey,\r\n 'Content-Type': 'application/json',\r\n },\r\n body: JSON.stringify(emailParams),\r\n });\r\n\r\n const result = await response.json();\r\n\r\n if (!response.ok) {\r\n return createResponse<{ messageId: string }>(null, result.error || 'Email sending failed');\r\n }\r\n\r\n return createResponse(result.data);\r\n } catch (error) {\r\n return createResponse<{ messageId: string }>(null, error);\r\n }\r\n }\r\n\r\n /** Get available locales for the project */\r\n async getLocales(): Promise<ZenoResponse<Locale[]>> {\r\n try {\r\n const projectId = await this.resolveProjectId();\r\n\r\n const { data, error } = await this.supabase\r\n .from('project_locales')\r\n .select('locale_code, locale_name, locale_native_name, is_default')\r\n .eq('project_id', projectId)\r\n .eq('is_active', true)\r\n .order('is_default', { ascending: false })\r\n .order('locale_name', { ascending: true });\r\n\r\n if (error) throw error;\r\n\r\n const processedData = data?.map((l) => ({\r\n code: l.locale_code,\r\n name: l.locale_name,\r\n native_name: l.locale_native_name,\r\n is_default: l.is_default,\r\n })) || [];\r\n\r\n return createResponse<Locale[]>(processedData);\r\n } catch (error) {\r\n return createResponse<Locale[]>(null, error);\r\n }\r\n }\r\n\r\n /** Health check */\r\n async health(): Promise<ZenoResponse<HealthStatus>> {\r\n return createResponse<HealthStatus>({\r\n status: 'healthy',\r\n version: '1.0.0',\r\n });\r\n }\r\n}\r\n"]}
@@ -0,0 +1,206 @@
1
+ /** Configuration for initializing the Zeno CMS SDK */
2
+ interface ZenoConfig {
3
+ /**
4
+ * Zeno CMS API key.
5
+ * Format: zeno_<projectSlug>_<token>
6
+ * Generate this key from the Zeno CMS dashboard in Project Settings > API Keys.
7
+ *
8
+ * If not provided, the SDK will automatically read from the ZENO_API_KEY environment variable.
9
+ */
10
+ apiKey?: string;
11
+ /** Default fallback locale for localized content (e.g. 'en', 'it'). If not set, the project's default locale is used automatically. */
12
+ defaultLocale?: string;
13
+ }
14
+ /** Standard API response wrapper */
15
+ interface ZenoResponse<T> {
16
+ data: T | null;
17
+ error: string | null;
18
+ meta?: {
19
+ total?: number;
20
+ page?: number;
21
+ limit?: number;
22
+ totalPages?: number;
23
+ timestamp: string;
24
+ locale?: string;
25
+ fallback_used?: boolean;
26
+ available_locales?: string[];
27
+ };
28
+ }
29
+ /** Pagination parameters */
30
+ interface PaginationParams {
31
+ page?: number;
32
+ limit?: number;
33
+ sortBy?: string;
34
+ sortOrder?: 'asc' | 'desc';
35
+ }
36
+ /** Filter parameters for entries */
37
+ interface FilterParams {
38
+ status?: string;
39
+ search?: string;
40
+ locale?: string;
41
+ fallback_locale?: string;
42
+ /** Filter entries from this date (ISO string). Filters on created_at by default, or on data.{dateField} if dateField is specified. */
43
+ dateFrom?: string;
44
+ /** Filter entries up to this date (ISO string). Filters on created_at by default, or on data.{dateField} if dateField is specified. */
45
+ dateTo?: string;
46
+ /** Field name inside data to use for date filtering (e.g. 'publishedAt', 'date'). If not specified, filters on created_at. */
47
+ dateField?: string;
48
+ }
49
+ /** Email send parameters */
50
+ interface EmailParams {
51
+ to: string;
52
+ toName?: string;
53
+ subject: string;
54
+ message: string;
55
+ htmlMessage?: string;
56
+ fromName?: string;
57
+ replyTo?: string;
58
+ formName?: string;
59
+ formData?: Record<string, unknown>;
60
+ sourceUrl?: string;
61
+ }
62
+ /** Collection field definition */
63
+ interface Field {
64
+ id: string;
65
+ name: string;
66
+ label: string;
67
+ type: string;
68
+ required?: boolean;
69
+ localized?: boolean;
70
+ validation?: Record<string, unknown>;
71
+ options?: Array<{
72
+ label: string;
73
+ value: string;
74
+ }>;
75
+ targetCollection?: string;
76
+ subFields?: Field[];
77
+ [key: string]: unknown;
78
+ }
79
+ /** Collection definition */
80
+ interface Collection {
81
+ id: string;
82
+ name: string;
83
+ slug: string;
84
+ description: string | null;
85
+ fields: Field[];
86
+ created_at: string;
87
+ updated_at: string;
88
+ }
89
+ /** Content entry */
90
+ interface Entry {
91
+ id: string;
92
+ data: Record<string, unknown>;
93
+ status: string;
94
+ collection_id: string;
95
+ project_id: string;
96
+ created_at: string;
97
+ updated_at: string;
98
+ collections?: {
99
+ id: string;
100
+ name: string;
101
+ slug: string;
102
+ };
103
+ locale_code?: string;
104
+ }
105
+ /** Asset/file metadata */
106
+ interface Asset {
107
+ id: string;
108
+ filename: string;
109
+ original_filename: string;
110
+ mime_type: string;
111
+ size_bytes: number;
112
+ metadata: Record<string, unknown> | null;
113
+ created_at: string;
114
+ }
115
+ /** Asset signed URL result */
116
+ interface AssetUrl {
117
+ downloadUrl: string;
118
+ expiresIn: number;
119
+ }
120
+ /** Project locale */
121
+ interface Locale {
122
+ code: string;
123
+ name: string;
124
+ native_name: string;
125
+ is_default: boolean;
126
+ }
127
+ /** Project information */
128
+ interface Project {
129
+ id: string;
130
+ name: string;
131
+ description: string | null;
132
+ slug: string;
133
+ status: string;
134
+ created_at: string;
135
+ updated_at: string;
136
+ }
137
+ /** Health check result */
138
+ interface HealthStatus {
139
+ status: string;
140
+ version: string;
141
+ }
142
+
143
+ declare class ZenoCMS {
144
+ private supabase;
145
+ private apiKey;
146
+ private projectSlug;
147
+ private apiToken;
148
+ private projectId;
149
+ private isValidated;
150
+ private configDefaultLocale;
151
+ private resolvedDefaultLocale;
152
+ constructor(config?: ZenoConfig);
153
+ /**
154
+ * Reads the API key from environment variables.
155
+ * Checks multiple naming conventions so each framework only needs one .env variable:
156
+ * ZENO_API_KEY — Node.js / server-side
157
+ * NEXT_PUBLIC_ZENO_API_KEY — Next.js client
158
+ * VITE_ZENO_API_KEY — Vite (React, Vue, Svelte)
159
+ * PUBLIC_ZENO_API_KEY — Astro client
160
+ */
161
+ private getEnvApiKey;
162
+ /**
163
+ * Parse and validate the API key format.
164
+ * Expected format: zeno_<projectSlug>_<token>
165
+ */
166
+ private parseApiKey;
167
+ /**
168
+ * Returns the fallback locale to use.
169
+ * Priority: config.defaultLocale > project's default locale from DB > 'en'.
170
+ */
171
+ private getDefaultLocale;
172
+ /**
173
+ * Resolves and validates the project ID using the API key.
174
+ * Validates the token server-side for security.
175
+ */
176
+ private resolveProjectId;
177
+ /** Get project information */
178
+ getProject(): Promise<ZenoResponse<Project>>;
179
+ /** Get all collections for the project */
180
+ getCollections(params?: PaginationParams): Promise<ZenoResponse<Collection[]>>;
181
+ /** Get a single collection by slug */
182
+ getCollection(slug: string): Promise<ZenoResponse<Collection>>;
183
+ /** Get entries, optionally filtered by collection slug */
184
+ getEntries(collectionSlug?: string, params?: PaginationParams & FilterParams): Promise<ZenoResponse<Entry[]>>;
185
+ /** Get a single entry by ID */
186
+ getEntry(entryId: string, params?: {
187
+ locale?: string;
188
+ fallback_locale?: string;
189
+ }): Promise<ZenoResponse<Entry>>;
190
+ /** Get assets for the project */
191
+ getAssets(params?: PaginationParams & {
192
+ mimeType?: string;
193
+ }): Promise<ZenoResponse<Asset[]>>;
194
+ /** Get a signed download URL for an asset */
195
+ getAssetUrl(assetId: string): Promise<ZenoResponse<AssetUrl>>;
196
+ /** Send an email via the Zeno edge function */
197
+ sendEmail(emailParams: EmailParams): Promise<ZenoResponse<{
198
+ messageId: string;
199
+ }>>;
200
+ /** Get available locales for the project */
201
+ getLocales(): Promise<ZenoResponse<Locale[]>>;
202
+ /** Health check */
203
+ health(): Promise<ZenoResponse<HealthStatus>>;
204
+ }
205
+
206
+ export { type Asset, type AssetUrl, type Collection, type EmailParams, type Entry, type Field, type FilterParams, type HealthStatus, type Locale, type PaginationParams, type Project, ZenoCMS, type ZenoConfig, type ZenoResponse };
@@ -0,0 +1,206 @@
1
+ /** Configuration for initializing the Zeno CMS SDK */
2
+ interface ZenoConfig {
3
+ /**
4
+ * Zeno CMS API key.
5
+ * Format: zeno_<projectSlug>_<token>
6
+ * Generate this key from the Zeno CMS dashboard in Project Settings > API Keys.
7
+ *
8
+ * If not provided, the SDK will automatically read from the ZENO_API_KEY environment variable.
9
+ */
10
+ apiKey?: string;
11
+ /** Default fallback locale for localized content (e.g. 'en', 'it'). If not set, the project's default locale is used automatically. */
12
+ defaultLocale?: string;
13
+ }
14
+ /** Standard API response wrapper */
15
+ interface ZenoResponse<T> {
16
+ data: T | null;
17
+ error: string | null;
18
+ meta?: {
19
+ total?: number;
20
+ page?: number;
21
+ limit?: number;
22
+ totalPages?: number;
23
+ timestamp: string;
24
+ locale?: string;
25
+ fallback_used?: boolean;
26
+ available_locales?: string[];
27
+ };
28
+ }
29
+ /** Pagination parameters */
30
+ interface PaginationParams {
31
+ page?: number;
32
+ limit?: number;
33
+ sortBy?: string;
34
+ sortOrder?: 'asc' | 'desc';
35
+ }
36
+ /** Filter parameters for entries */
37
+ interface FilterParams {
38
+ status?: string;
39
+ search?: string;
40
+ locale?: string;
41
+ fallback_locale?: string;
42
+ /** Filter entries from this date (ISO string). Filters on created_at by default, or on data.{dateField} if dateField is specified. */
43
+ dateFrom?: string;
44
+ /** Filter entries up to this date (ISO string). Filters on created_at by default, or on data.{dateField} if dateField is specified. */
45
+ dateTo?: string;
46
+ /** Field name inside data to use for date filtering (e.g. 'publishedAt', 'date'). If not specified, filters on created_at. */
47
+ dateField?: string;
48
+ }
49
+ /** Email send parameters */
50
+ interface EmailParams {
51
+ to: string;
52
+ toName?: string;
53
+ subject: string;
54
+ message: string;
55
+ htmlMessage?: string;
56
+ fromName?: string;
57
+ replyTo?: string;
58
+ formName?: string;
59
+ formData?: Record<string, unknown>;
60
+ sourceUrl?: string;
61
+ }
62
+ /** Collection field definition */
63
+ interface Field {
64
+ id: string;
65
+ name: string;
66
+ label: string;
67
+ type: string;
68
+ required?: boolean;
69
+ localized?: boolean;
70
+ validation?: Record<string, unknown>;
71
+ options?: Array<{
72
+ label: string;
73
+ value: string;
74
+ }>;
75
+ targetCollection?: string;
76
+ subFields?: Field[];
77
+ [key: string]: unknown;
78
+ }
79
+ /** Collection definition */
80
+ interface Collection {
81
+ id: string;
82
+ name: string;
83
+ slug: string;
84
+ description: string | null;
85
+ fields: Field[];
86
+ created_at: string;
87
+ updated_at: string;
88
+ }
89
+ /** Content entry */
90
+ interface Entry {
91
+ id: string;
92
+ data: Record<string, unknown>;
93
+ status: string;
94
+ collection_id: string;
95
+ project_id: string;
96
+ created_at: string;
97
+ updated_at: string;
98
+ collections?: {
99
+ id: string;
100
+ name: string;
101
+ slug: string;
102
+ };
103
+ locale_code?: string;
104
+ }
105
+ /** Asset/file metadata */
106
+ interface Asset {
107
+ id: string;
108
+ filename: string;
109
+ original_filename: string;
110
+ mime_type: string;
111
+ size_bytes: number;
112
+ metadata: Record<string, unknown> | null;
113
+ created_at: string;
114
+ }
115
+ /** Asset signed URL result */
116
+ interface AssetUrl {
117
+ downloadUrl: string;
118
+ expiresIn: number;
119
+ }
120
+ /** Project locale */
121
+ interface Locale {
122
+ code: string;
123
+ name: string;
124
+ native_name: string;
125
+ is_default: boolean;
126
+ }
127
+ /** Project information */
128
+ interface Project {
129
+ id: string;
130
+ name: string;
131
+ description: string | null;
132
+ slug: string;
133
+ status: string;
134
+ created_at: string;
135
+ updated_at: string;
136
+ }
137
+ /** Health check result */
138
+ interface HealthStatus {
139
+ status: string;
140
+ version: string;
141
+ }
142
+
143
+ declare class ZenoCMS {
144
+ private supabase;
145
+ private apiKey;
146
+ private projectSlug;
147
+ private apiToken;
148
+ private projectId;
149
+ private isValidated;
150
+ private configDefaultLocale;
151
+ private resolvedDefaultLocale;
152
+ constructor(config?: ZenoConfig);
153
+ /**
154
+ * Reads the API key from environment variables.
155
+ * Checks multiple naming conventions so each framework only needs one .env variable:
156
+ * ZENO_API_KEY — Node.js / server-side
157
+ * NEXT_PUBLIC_ZENO_API_KEY — Next.js client
158
+ * VITE_ZENO_API_KEY — Vite (React, Vue, Svelte)
159
+ * PUBLIC_ZENO_API_KEY — Astro client
160
+ */
161
+ private getEnvApiKey;
162
+ /**
163
+ * Parse and validate the API key format.
164
+ * Expected format: zeno_<projectSlug>_<token>
165
+ */
166
+ private parseApiKey;
167
+ /**
168
+ * Returns the fallback locale to use.
169
+ * Priority: config.defaultLocale > project's default locale from DB > 'en'.
170
+ */
171
+ private getDefaultLocale;
172
+ /**
173
+ * Resolves and validates the project ID using the API key.
174
+ * Validates the token server-side for security.
175
+ */
176
+ private resolveProjectId;
177
+ /** Get project information */
178
+ getProject(): Promise<ZenoResponse<Project>>;
179
+ /** Get all collections for the project */
180
+ getCollections(params?: PaginationParams): Promise<ZenoResponse<Collection[]>>;
181
+ /** Get a single collection by slug */
182
+ getCollection(slug: string): Promise<ZenoResponse<Collection>>;
183
+ /** Get entries, optionally filtered by collection slug */
184
+ getEntries(collectionSlug?: string, params?: PaginationParams & FilterParams): Promise<ZenoResponse<Entry[]>>;
185
+ /** Get a single entry by ID */
186
+ getEntry(entryId: string, params?: {
187
+ locale?: string;
188
+ fallback_locale?: string;
189
+ }): Promise<ZenoResponse<Entry>>;
190
+ /** Get assets for the project */
191
+ getAssets(params?: PaginationParams & {
192
+ mimeType?: string;
193
+ }): Promise<ZenoResponse<Asset[]>>;
194
+ /** Get a signed download URL for an asset */
195
+ getAssetUrl(assetId: string): Promise<ZenoResponse<AssetUrl>>;
196
+ /** Send an email via the Zeno edge function */
197
+ sendEmail(emailParams: EmailParams): Promise<ZenoResponse<{
198
+ messageId: string;
199
+ }>>;
200
+ /** Get available locales for the project */
201
+ getLocales(): Promise<ZenoResponse<Locale[]>>;
202
+ /** Health check */
203
+ health(): Promise<ZenoResponse<HealthStatus>>;
204
+ }
205
+
206
+ export { type Asset, type AssetUrl, type Collection, type EmailParams, type Entry, type Field, type FilterParams, type HealthStatus, type Locale, type PaginationParams, type Project, ZenoCMS, type ZenoConfig, type ZenoResponse };
package/dist/index.js ADDED
@@ -0,0 +1,8 @@
1
+ 'use strict';var supabaseJs=require('@supabase/supabase-js');var w={endpoint:"https://kvpowojjhuprhxdyzmml.supabase.co",publicKey:"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6Imt2cG93b2pqaHVwcmh4ZHl6bW1sIiwicm9sZSI6ImFub24iLCJpYXQiOjE3NTI3ODEwNzAsImV4cCI6MjA2ODM1NzA3MH0.cCPzDNdfTb3WBtYL79GBlw4hfypl4tjnqu7XfEvdKBg"};function o(A,a=null,t){let e=null;return a&&(typeof a=="string"?e=a:a instanceof Error?e=a.message:typeof a=="object"&&a!==null&&"message"in a&&(e=String(a.message))),{data:A,error:e,meta:{...t,timestamp:new Date().toISOString()}}}var b=class{constructor(a={}){this.projectId=null;this.isValidated=false;this.resolvedDefaultLocale=null;let t=a.apiKey||this.getEnvApiKey();if(!t)throw new Error("Missing API key. Provide it via config.apiKey or set an environment variable: ZENO_API_KEY, VITE_ZENO_API_KEY, NEXT_PUBLIC_ZENO_API_KEY, or PUBLIC_ZENO_API_KEY.");let e=this.parseApiKey(t);this.apiKey=t,this.projectSlug=e.projectSlug,this.apiToken=e.token,this.configDefaultLocale=a.defaultLocale,this.supabase=supabaseJs.createClient(w.endpoint,w.publicKey,{auth:{persistSession:false,autoRefreshToken:false}});}getEnvApiKey(){let a=["ZENO_API_KEY","NEXT_PUBLIC_ZENO_API_KEY","VITE_ZENO_API_KEY","PUBLIC_ZENO_API_KEY"],t=["ZENO_API_KEY","VITE_ZENO_API_KEY","PUBLIC_ZENO_API_KEY","NEXT_PUBLIC_ZENO_API_KEY"];if(typeof process<"u"&&process.env){for(let e of a)if(process.env[e])return process.env[e]}try{let e=undefined;if(e){for(let s of t)if(e[s])return e[s]}}catch{}}parseApiKey(a){if(!a.startsWith("zeno_"))throw new Error("Invalid API key format. Expected: zeno_<projectSlug>_<token>");let t=a.slice(5),e=t.indexOf("_");if(e===-1)throw new Error("Invalid API key format. Expected: zeno_<projectSlug>_<token>");let s=t.slice(0,e),r=t.slice(e+1);if(!s||!r)throw new Error("Invalid API key format. Expected: zeno_<projectSlug>_<token>");return {projectSlug:s,token:r}}async getDefaultLocale(){if(this.configDefaultLocale)return this.configDefaultLocale;if(this.resolvedDefaultLocale)return this.resolvedDefaultLocale;try{let a=await this.resolveProjectId(),{data:t}=await this.supabase.from("project_locales").select("locale_code").eq("project_id",a).eq("is_default",!0).single();if(t?.locale_code)return this.resolvedDefaultLocale=t.locale_code,t.locale_code}catch{}return this.resolvedDefaultLocale="en","en"}async resolveProjectId(){if(this.projectId&&this.isValidated)return this.projectId;let{data:a,error:t}=await this.supabase.rpc("validate_sdk_api_key",{p_project_slug:this.projectSlug,p_token:this.apiToken});if(t)throw new Error("API key validation failed: "+t.message);let e=a?.[0];if(!e||!e.is_valid)throw new Error(e?.error_message||"Invalid API key or project not found");return this.projectId=e.project_id,this.isValidated=true,e.project_id}async getProject(){try{let a=await this.resolveProjectId(),{data:t,error:e}=await this.supabase.from("projects").select("id, name, description, slug, status, created_at, updated_at").eq("id",a).single();return o(t,e)}catch(a){return o(null,a)}}async getCollections(a={}){try{let t=await this.resolveProjectId(),{page:e=1,limit:s=50,sortBy:r="created_at",sortOrder:_="desc"}=a,g=(e-1)*s,{count:c}=await this.supabase.from("collections").select("*",{count:"exact",head:!0}).eq("project_id",t),{data:i,error:d}=await this.supabase.from("collections").select("id, name, slug, description, fields, created_at, updated_at").eq("project_id",t).order(r,{ascending:_==="asc"}).range(g,g+s-1),h=i?.map(l=>({...l,fields:typeof l.fields=="string"?JSON.parse(l.fields):l.fields}));return o(h,d,{total:c||0,page:e,limit:s,totalPages:Math.ceil((c||0)/s)})}catch(t){return o(null,t)}}async getCollection(a){try{let t=await this.resolveProjectId(),{data:e,error:s}=await this.supabase.from("collections").select("id, name, slug, description, fields, created_at, updated_at").eq("project_id",t).eq("slug",a).single(),r=e?{...e,fields:typeof e.fields=="string"?JSON.parse(e.fields):e.fields}:null;return o(r,s)}catch(t){return o(null,t)}}async getEntries(a,t={}){try{let e=await this.resolveProjectId(),{page:s=1,limit:r=50,sortBy:_="created_at",sortOrder:g="desc",status:c,search:i,locale:d,fallback_locale:h,dateFrom:l,dateTo:m,dateField:p}=t,P=h||await this.getDefaultLocale(),k=(s-1)*r,u=this.supabase.from("entries").select(`
2
+ id, data, status, collection_id, project_id, created_at, updated_at,
3
+ collections ( id, name, slug )
4
+ `).eq("project_id",e);if(a){let{data:n}=await this.supabase.from("collections").select("id").eq("project_id",e).eq("slug",a).single();if(!n)return o(null,"Collection not found");u=u.eq("collection_id",n.id);}c&&(u=u.eq("status",c)),i&&(u=u.textSearch("data",i)),l&&(u=p?u.gte(`data->${p}`,l):u.gte("created_at",l)),m&&(u=p?u.lte(`data->${p}`,m):u.lte("created_at",m));let f=this.supabase.from("entries").select("*",{count:"exact",head:!0}).eq("project_id",e);if(a){let{data:n}=await this.supabase.from("collections").select("id").eq("project_id",e).eq("slug",a).single();n&&(f=f.eq("collection_id",n.id));}c&&(f=f.eq("status",c)),i&&(f=f.textSearch("data",i)),l&&(f=p?f.gte(`data->${p}`,l):f.gte("created_at",l)),m&&(f=p?f.lte(`data->${p}`,m):f.lte("created_at",m));let{count:Z}=await f,{data:N,error:q}=await u.order(_,{ascending:g==="asc"}).range(k,k+r-1);if(q)throw q;let E=(N??[]).map(n=>({...n,collections:Array.isArray(n.collections)?n.collections[0]:n.collections})),L=E,K=!1;if(d&&E.length>0)try{let n=E.map(j=>j.id),v=await this.supabase.rpc("get_localized_entries_batch",{entry_uuids:n,locale:d,fallback_locale:P});if(v.data&&v.data.length>0){let j=new Map;for(let y of v.data)j.set(y.entry_id,{data:y.data,locale_code:y.locale_code,is_fallback:y.is_fallback});L=E.map(y=>{let I=j.get(y.id);return I?(I.is_fallback&&(K=!0),{...y,data:I.data,locale_code:I.locale_code}):y});}}catch{}let{data:O}=await this.supabase.from("project_locales").select("locale_code").eq("project_id",e).eq("is_active",!0);return o(L,null,{total:Z||0,page:s,limit:r,totalPages:Math.ceil((Z||0)/r),locale:d||P,fallback_used:K,available_locales:O?.map(n=>n.locale_code)||[]})}catch(e){return o(null,e)}}async getEntry(a,t={}){try{let e=await this.resolveProjectId(),{locale:s,fallback_locale:r}=t,_=r||await this.getDefaultLocale(),{data:g,error:c}=await this.supabase.from("entries").select(`
5
+ id, data, status, collection_id, project_id, created_at, updated_at,
6
+ collections ( id, name, slug, fields )
7
+ `).eq("project_id",e).eq("id",a).single();if(c)throw c;let i=g,d=i?{...i,collections:Array.isArray(i.collections)?i.collections[0]:i.collections}:null,h=d,l=!1;if(s&&d)try{let p=await this.supabase.rpc("get_localized_entry",{entry_uuid:a,locale:s,fallback_locale:_});if(p.data?.[0]){let P=p.data[0];P.locale_code!==s&&(l=!0),h={...d,data:P.data,locale_code:P.locale_code};}}catch{}let{data:m}=await this.supabase.from("project_locales").select("locale_code").eq("project_id",e).eq("is_active",!0);return o(h,null,{locale:s||_,fallback_used:l,available_locales:m?.map(p=>p.locale_code)||[]})}catch(e){return o(null,e)}}async getAssets(a={}){try{let t=await this.resolveProjectId(),{page:e=1,limit:s=50,sortBy:r="created_at",sortOrder:_="desc",mimeType:g}=a,c=(e-1)*s,i=this.supabase.from("assets").select("id, filename, original_filename, mime_type, size_bytes, metadata, created_at").eq("project_id",t);g&&(i=i.like("mime_type",`${g}%`));let d=this.supabase.from("assets").select("*",{count:"exact",head:!0}).eq("project_id",t);g&&(d=d.like("mime_type",`${g}%`));let{count:h}=await d,{data:l,error:m}=await i.order(r,{ascending:_==="asc"}).range(c,c+s-1);return o(l,m,{total:h||0,page:e,limit:s,totalPages:Math.ceil((h||0)/s)})}catch(t){return o(null,t)}}async getAssetUrl(a){try{let t=await this.resolveProjectId(),{data:e,error:s}=await this.supabase.from("assets").select("storage_path").eq("project_id",t).eq("id",a).single();if(s||!e)return o(null,"Asset not found");let{data:r,error:_}=await this.supabase.storage.from("assets").createSignedUrl(e.storage_path,3600);return _?o(null,_):o({downloadUrl:r.signedUrl,expiresIn:3600})}catch(t){return o(null,t)}}async sendEmail(a){try{let t=await fetch(`${w.endpoint}/functions/v1/api/email/send`,{method:"POST",headers:{Authorization:`Bearer ${this.apiKey}`,"X-API-Key":this.apiKey,"Content-Type":"application/json"},body:JSON.stringify(a)}),e=await t.json();return t.ok?o(e.data):o(null,e.error||"Email sending failed")}catch(t){return o(null,t)}}async getLocales(){try{let a=await this.resolveProjectId(),{data:t,error:e}=await this.supabase.from("project_locales").select("locale_code, locale_name, locale_native_name, is_default").eq("project_id",a).eq("is_active",!0).order("is_default",{ascending:!1}).order("locale_name",{ascending:!0});if(e)throw e;let s=t?.map(r=>({code:r.locale_code,name:r.locale_name,native_name:r.locale_native_name,is_default:r.is_default}))||[];return o(s)}catch(a){return o(null,a)}}async health(){return o({status:"healthy",version:"1.0.0"})}};exports.ZenoCMS=b;//# sourceMappingURL=index.js.map
8
+ //# sourceMappingURL=index.js.map