Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[🐛 Bug]: failed to retrieve the Cloudflare request context when using dynamic route for api #687

Open
1 task done
bryandeckers opened this issue Mar 1, 2024 · 13 comments
Labels
bug Something isn't working question Further information is requested

Comments

@bryandeckers
Copy link

bryandeckers commented Mar 1, 2024

next-on-pages environment related information

Unable to run the command since I am on Windows and WSL is failing atm

Description

I am using next-on-pages version 1.9.0 and next version 14.1.0

I am using a dynamic parameter/slug folder before my api folder, when trying to receive the env in a non local environment, I get the error: "failed to retrieve the Cloudflare request context"

Buid log:
2024-03-01T09:25:18.42559Z Cloning repository...
2024-03-01T09:25:19.851277Z From https://github.com/EvenementManager/busma
2024-03-01T09:25:19.85186Z * branch b3b94d517bcca7eb2c2eadc4463423a2e24d8cfa -> FETCH_HEAD
2024-03-01T09:25:19.851996Z
2024-03-01T09:25:19.943334Z HEAD is now at b3b94d5 setupDevplatform only local
2024-03-01T09:25:19.943776Z
2024-03-01T09:25:20.041516Z
2024-03-01T09:25:20.042059Z Using v2 root directory strategy
2024-03-01T09:25:20.070825Z Success: Finished cloning repository files
2024-03-01T09:25:20.755609Z Detected the following tools from environment: npm@9.6.7, nodejs@18.17.1
2024-03-01T09:25:20.756259Z Installing project dependencies: npm clean-install --progress=false
2024-03-01T09:25:24.717666Z npm WARN deprecated rollup-plugin-inject@3.0.2: This package has been deprecated and is no longer maintained. Please use @rollup/plugin-inject.
2024-03-01T09:25:24.751373Z npm WARN deprecated sourcemap-codec@1.4.8: Please use @jridgewell/sourcemap-codec instead
2024-03-01T09:25:28.736904Z npm WARN deprecated debug@4.1.1: Debug versions >=3.2.0 <3.2.7 || >=4 <4.3.1 have a low-severity ReDos regression when used in a Node.js environment. It is recommended you upgrade to 3.2.7 or 4.3.1. (debug-js/debug#797)
2024-03-01T09:25:28.870364Z npm WARN deprecated uuid@3.3.2: Please upgrade to version 7 or higher. Older versions may use Math.random() in certain circumstances, which is known to be problematic. See https://v8.dev/blog/math-random for details.
2024-03-01T09:25:45.474146Z
2024-03-01T09:25:45.474547Z added 814 packages, and audited 815 packages in 24s
2024-03-01T09:25:45.475062Z
2024-03-01T09:25:45.475503Z 156 packages are looking for funding
2024-03-01T09:25:45.475746Z run npm fund for details
2024-03-01T09:25:45.491387Z
2024-03-01T09:25:45.491635Z 7 vulnerabilities (3 low, 4 moderate)
2024-03-01T09:25:45.491829Z
2024-03-01T09:25:45.491985Z To address all issues, run:
2024-03-01T09:25:45.492131Z npm audit fix
2024-03-01T09:25:45.49228Z
2024-03-01T09:25:45.492427Z Run npm audit for details.
2024-03-01T09:25:45.518321Z Executing user command: npx @cloudflare/next-on-pages@1
2024-03-01T09:25:46.749071Z ⚡️ @cloudflare/next-on-pages CLI v.1.9.0
2024-03-01T09:25:47.122829Z ⚡️ Detected Package Manager: npm (9.6.7)
2024-03-01T09:25:47.123108Z ⚡️ Preparing project...
2024-03-01T09:25:47.126558Z ⚡️ Project is ready
2024-03-01T09:25:47.12687Z ⚡️ Building project...
2024-03-01T09:25:48.163271Z ▲ Vercel CLI 33.5.1
2024-03-01T09:25:48.49228Z ▲ Installing dependencies...
2024-03-01T09:25:50.014578Z ▲ up to date in 1s
2024-03-01T09:25:50.014927Z ▲
2024-03-01T09:25:50.015517Z ▲ 156 packages are looking for funding
2024-03-01T09:25:50.015651Z ▲ run npm fund for details
2024-03-01T09:25:50.026645Z ▲ Detected Next.js version: 14.1.0
2024-03-01T09:25:50.032289Z ▲ Detected package-lock.json generated by npm 7+
2024-03-01T09:25:50.032739Z ▲ Running "npm run build"
2024-03-01T09:25:50.424413Z ▲ > adamant@0.1.0 build
2024-03-01T09:25:50.424627Z ▲ > next build
2024-03-01T09:25:51.579172Z ▲ Attention: Next.js now collects completely anonymous telemetry regarding usage.
2024-03-01T09:25:51.579582Z ▲ This information is used to shape Next.js' roadmap and prioritize features.
2024-03-01T09:25:51.579791Z ▲ You can learn more, including how to opt-out if you'd not like to participate in this anonymous program, by visiting the following URL:
2024-03-01T09:25:51.579956Z ▲ https://nextjs.org/telemetry
2024-03-01T09:25:51.70891Z ▲ ▲ Next.js 14.1.0
2024-03-01T09:25:51.709309Z ▲
2024-03-01T09:25:51.781719Z ▲ Creating an optimized production build ...
2024-03-01T09:27:17.458346Z ▲ Compiler edge-server unexpectedly exited with code: null and signal: SIGTERM
2024-03-01T09:27:33.44091Z ▲ ✓ Compiled successfully
2024-03-01T09:27:33.441834Z ▲ Linting and checking validity of types ...
2024-03-01T09:27:43.190397Z ▲ Collecting page data ...
2024-03-01T09:27:44.556083Z ▲ ⚠ Using edge runtime on a page currently disables static generation for that page
2024-03-01T09:27:45.421843Z ▲ /opt/buildhome/repo/.next/server/app/(platform)/[organisationName]/api/customers/route.js:1
2024-03-01T09:27:45.422865Z ▲ (self.webpackChunk_N_E=self.webpackChunk_N_E||[]).push([[8643],{2067:e=>{"use strict";e.exports=require("node:async_hooks")},26195:e=>{"use strict";e.exports=require("node:buffer")},73707:(e,t,r)=>{"use strict";r.r(t),r.d(t,{ComponentMod:()=>P,default:()=>O});var n={};r.r(n),r.d(n,{GET:()=>y,POST:()=>v,runtime:()=>m});var i={};r.r(i),r.d(i,{headerHooks:()=>x,originalPathname:()=>N,patchFetch:()=>E,requestAsyncStorage:()=>S,routeModule:()=>b,serverHooks:()=>,staticGenerationAsyncStorage:()=>w,staticGenerationBailout:()=>C});var s=r(4743),a=r(68381),o=r(42251),l=r(79845),u=r(15469),c=r(91591),d=r(80581),h=r(47630),f=r(25495),p=r(84162),g=r(25511);let m="edge";async function y(e,{params:t}){let{env:r}=(0,u.getRequestContext)(),n=(0,c.t)(r.DB,{schema:h}),i=await (0,p.P)(t.organisationName);if(!i)return;let s=await n.query.customers.findMany({where:(0,f.eq)(h.customers.organisationId,i),with:{address:!0}});return new Response(JSON.stringify(s),{headers:{"Content-Type":"application/json"}})}async function v(e,{params:t}){let{env:r}=(0,u.getRequestContext)(),n=(0,c.t)(r.DB,{schema:h}),i=await e.json();try{let e=await (0,p.P)(t.organisationName);if(!e)return;let r=(0,d.Z)(),s=(0,d.Z)(),a=i.address;await n.insert(h.address).values({...a,id:r});let[o]=await n.insert(h.customers).values({...i,id:s,addressId:r,organisationId:e}).returning();return new Response(JSON.stringify({message:"Klant succesvol aangemaakt",description:"${o.firstName} ${o.lastName}" is aangemaakt,success:!0,data:o}),{headers:{"Content-Type":"application/json"}})}catch(e){return new Response(JSON.stringify({message:"Fout bij het aanmaken van de klant",description:${i.firstName} ${i.lastName}" kon niet worden aangemaakt,success:!1}),{headers:{"Content-Type":"application/json"}})}finally{(0,g.revalidatePath)(/${t.organisationName}/customers)}}let b=new a.AppRouteRouteModule({definition:{kind:o.x.APP_ROUTE,page:"/(platform)/[organisationName]/api/customers/route",pathname:"/[organisationName]/api/customers",filename:"route",bundlePath:"app/(platform)/[organisationName]/api/customers/route"},resolvedPagePath:"/opt/buildhome/repo/app/(platform)/[organisationName]/api/customers/route.ts",nextConfigOutput:"",userland:n}),{requestAsyncStorage:S,staticGenerationAsyncStorage:w,serverHooks:,headerHooks:x,staticGenerationBailout:C}=b,N="/(platform)/[organisationName]/api/customers/route";function E(){return(0,l.XH)({serverHooks:,staticGenerationAsyncStorage:w})}let P=i,O=s.a.wrap(b)},47630:(e,t,r)=>{"use strict";r.r(t),r.d(t,{DocumentItem:()=>en,InvitedUsers:()=>E,InvitedUsersRelations:()=>P,ThemeRelations:()=>v,Themes:()=>y,accounts:()=>h,address:()=>g,addressRelations:()=>m,customerRelations:()=>A,customers:()=>T,documentItemRelations:()=>ei,documentPackage:()=>es,documentPackageRelations:()=>ea,documentRelations:()=>er,documents:()=>et,itemRelations:()=>j,items:()=>$,locationRelations:()=>R,locations:()=>O,organisationPlatformPackageRelations:()=>,organisationPlatformPackages:()=>w,organisationRelations:()=>S,organisations:()=>b,packageItem:()=>M,packageItemRelations:()=>q,packageRelations:()=>D,packages:()=>k,platformPackages:()=>x,priority:()=>eh,projectCategories:()=>U,projectCategoryRelations:()=>B,projectContributor:()=>V,projectContributorRelations:()=>K,projectCustomer:()=>W,projectCustomerRelations:()=>J,projectItem:()=>X,projectItemRelations:()=>Y,projectLocationRelations:()=>G,projectLocations:()=>z,projectPackage:()=>Z,projectPackageRelations:()=>ee,projectRelations:()=>H,projects:()=>F,roles:()=>l,rolesRelations:()=>u,sessions:()=>f,statuses:()=>ed,supplierRelations:()=>L,suppliers:()=>I,taskRelations:()=>ec,tasks:()=>eu,templates:()=>Q,userOrganisationRelations:()=>N,userOrganisations:()=>C,userTask:()=>eo,userTaskRelations:()=>el,users:()=>c,usersRelations:()=>d,verificationTokens:()=>p});var n=r(38695),i=r(36372),s=r(19313),a=r(59678),o=r(87415);let l=(0,n.Px)("role",{id:(0,i.fL)("id").notNull().primaryKey(),name:(0,i.fL)("name").notNull().unique(),description:(0,i.fL)("description"),permission:(0,i.fL)("permission").notNull()}),u=(0,o.lE)(l,({one:e})=>({users:e(c)})),c=(0,n.Px)("user",{id:(0,i.fL)("id").notNull().primaryKey(),name:(0,i.fL)("name").notNull(),email:(0,i.fL)("email").notNull(),emailVerified:(0,s._L)("emailVerified",{mode:"timestamp_ms"}),image:(0,i.fL)("image"),roleId:(0,i.fL)("roleId").references(()=>l.id,{onDelete:"restrict"}),lastOnline:(0,s._L)("lastOnline",{mode:"timestamp_ms"})}),d=(0,o.lE)(c,({many:e})=>({roles:e(l),userOrganisations:e(C)})),h=(0,n.Px)("account",{userId:(0,i.fL)("userId").notNull().references(()=>c.id,{onDelete:"cascade"}),type:(0,i.fL)("type").$type().notNull(),provider:(0,i.fL)("provider").notNull(),providerAccountId:(0,i.fL)("providerAccountId").notNull(),refresh_token:(0,i.fL)("refresh_token"),access_token:(0,i.fL)("access_token"),expires_at:(0,s._L)("expires_at"),token_type:(0,i.fL)("token_type"),scope:(0,i.fL)("scope"),id_token:(0,i.fL)("id_token"),session_state:(0,i.fL)("session_state")},e=>({compoundKey:(0,a.CK)({columns:[e.provider,e.providerAccountId]})})),f=(0,n.Px)("session",{sessionToken:(0,i.fL)("sessionToken").notNull().primaryKey(),userId:(0,i.fL)("userId").notNull().references(()=>c.id,{onDelete:"cascade"}),expires:(0,s._L)("expires",{mode:"timestamp_ms"}).notNull()}),p=(0,n.Px)("verificationToken",{identifier:(0,i.fL)("identifier").notNull(),token:(0,i.fL)("token").notNull(),expires:(0,s._L)("expires",{mode:"timestamp_ms"}).notNull()},e=>({compoundKey:(0,a.CK)({columns:[e.identifier,e.token]})})),g=(0,n.Px)("address",{id:(0,i.fL)("id").notNull().primaryKey(),country:(0,i.fL)("country").notNull(),city:(0,i.fL)("city").notNull(),zipcode:(0,i.fL)("zipcode").notNull(),street:(0,i.fL)("street").notNull(),houseNumber:(0,i.fL)("houseNumber").notNull(),optional:(0,i.fL)("optional")}),m=(0,o.lE)(g,({one:e})=>({organisations:e(b),locations:e(O),customers:e(T),suppliers:e(I)})),y=(0,n.Px)("theme",{id:(0,i.fL)("id").notNull().primaryKey(),name:(0,i.fL)("name").notNull().unique(),primaryColor:(0,i.fL)("primaryColor").notNull(),secondaryColor:(0,i.fL)("secondaryColor").notNull(),backgroundColor:(0,i.fL)("backgroundColor").notNull(),textColor:(0,i.fL)("textColor").notNull()}),v=(0,o.lE)(y,({many:e})=>({organisations:e(b)})),b=(0,n.Px)("organisation",{id:(0,i.fL)("id").notNull().primaryKey(),name:(0,i.fL)("name").notNull().unique(),logo:(0,i.fL)("logo"),vatNbr:(0,i.fL)("vatNbr").unique(),phone:(0,i.fL)("phone"),email:(0,i.fL)("email"),addressId:(0,i.fL)("addressId").references(()=>g.id,{onDelete:"cascade"}),themeId:(0,i.fL)("themeId").references(()=>y.id,{onDelete:"restrict"}),isDeleted:(0,s._L)("isDeleted").notNull().default(0)}),S=(0,o.lE)(b,({many:e,one:t})=>({userOrganisations:e(C),customers:e(T),platformPackage:t(w,{fields:[b.id],references:[w.organisationId]}),items:e($),documents:e(et),projects:e(F),invitedUsers:e(E),theme:t(y,{fields:[b.themeId],references:[y.id]})})),w=(0,n.Px)("organisationPackage",{id:(0,i.fL)("id").notNull().primaryKey(),organisationId:(0,i.fL)("organisationId").notNull().references(()=>b.id,{onDelete:"cascade"}),platformPackageId:(0,i.fL)("platformPackageId").notNull().references(()=>x.id,{onDelete:"cascade"}),startDate:(0,i.fL)("startDate").notNull(),endDate:(0,i.fL)("endDate").notNull(),maxUsers:(0,s._L)("maxUsers").notNull().default(0),paid:(0,s.L)("paid").notNull().default(0)}),=(0,o.lE)(w,({one:e})=>({platformPackage:e(x,{fields:[w.platformPackageId],references:[x.id]}),organisations:e(b,{fields:[w.organisationId],references:[b.id]})})),x=(0,n.Px)("platformPackage",{id:(0,i.fL)("id").notNull().primaryKey(),name:(0,i.fL)("name").notNull().unique(),description:(0,i.fL)("description"),price:(0,s._L)("price").notNull(),maxUsers:(0,s._L)("maxUsers").notNull().default(0)}),C=(0,n.Px)("userOrganisation",{userOrganisationId:(0,i.fL)("userOrganisationId").notNull().primaryKey(),userId:(0,i.fL)("userId").notNull().references(()=>c.id,{onDelete:"cascade"}),organisationId:(0,i.fL)("organisationId").notNull().references(()=>b.id,{onDelete:"cascade"})}),N=(0,o.lE)(C,({one:e})=>({users:e(c,{relationName:"users",fields:[C.userId],references:[c.id]}),organisations:e(b,{relationName:"organisations",fields:[C.organisationId],references:[b.id]})})),E=(0,n.Px)("invitedUser",{id:(0,i.fL)("id").notNull().primaryKey(),email:(0,i.fL)("email").notNull(),userId:(0,i.fL)("organisationId").references(()=>c.id,{onDelete:"cascade"}),organisationId:(0,i.fL)("organisationId").notNull().references(()=>b.id,{onDelete:"cascade"}),invitedBy:(0,i.fL)("invitedBy").notNull().references(()=>c.id,{onDelete:"cascade"}),accepted:(0,s._L)("accepted").notNull().default(0),declined:(0,s._L)("declined").notNull().default(0),sent:(0,s._L)("sent").notNull().default(0)}),P=(0,o.lE)(E,({one:e})=>({organisation:e(b,{fields:[E.organisationId],references:[b.id]}),user:e(c,{fields:[E.userId],references:[c.id]}),invitedBy:e(c,{fields:[E.invitedBy],references:[c.id]})})),O=(0,n.Px)("location",{id:(0,i.fL)("id").notNull().primaryKey(),name:(0,i.fL)("name").notNull().unique(),image:(0,i.fL)("image"),description:(0,i.fL)("description"),internal:(0,s._L)("internal").notNull().default(0),maxCapacity:(0,s._L)("maxCapacity").notNull().default(0),addressId:(0,i.fL)("addressId").notNull().references(()=>g.id,{onDelete:"cascade"}),organisationId:(0,i.fL)("organisationId").notNull().references(()=>b.id,{onDelete:"restrict"}),isDeleted:(0,s._L)("isDeleted").notNull().default(0)}),R=(0,o.lE)(O,({one:e})=>({address:e(g,{fields:[O.addressId],references:[g.id]}),organisation:e(b,{fields:[O.organisationId],references:[b.id]})})),T=(0,n.Px)("customer",{id:(0,i.fL)("id").notNull().primaryKey(),firstName:(0,i.fL)("firstName").notNull(),lastName:(0,i.fL)("lastName").notNull(),email:(0,i.fL)("email").notNull(),phone:(0,i.fL)("phone").notNull(),vatNbr:(0,i.fL)("vatNbr").unique(),addressId:(0,i.fL)("addressId").notNull().references(()=>g.id,{onDelete:"cascade"}),organisationId:(0,i.fL)("organisationId").notNull().references(()=>b.id,{onDelete:"restrict"}),isDeleted:(0,s._L)("isDeleted").notNull().default(0)}),A=(0,o.lE)(T,({one:e})=>({address:e(g,{fields:[T.addressId],references:[g.id]}),organisation:e(b,{fields:[T.organisationId],references:[b.id]})})),I=(0,n.Px)("supplier",{id:(0,i.fL)("id").notNull().primaryKey(),name:(0,i.fL)("name").notNull().unique(),description:(0,i.fL)("description"),logo:(0,i.fL)("logo"),vatNbr:(0,i.fL)("vatNbr").unique(),phone:(0,i.fL)("phone").notNull(),email:(0,i.fL)("email").notNull(),addressId:(0,i.fL)("addressId").notNull().references(()=>g.id,{onDelete:"cascade"}),userId:(0,i.fL)("userId").notNull().references(()=>c.id,{onDelete:"cascade"}),organisationId:(0,i.fL)("organisationId").notNull().references(()=>b.id,{onDelete:"restrict"}),isDeleted:(0,s._L)("isDeleted").notNull().default(0)}),L=(0,o.lE)(I,({one:e})=>({address:e(g,{fields:[I.addressId],references:[g.id]}),users:e(c,{fields:[I.userId],references:[c.id]}),organisation:e(b,{fields:[I.organisationId],references:[b.id]})})),$=(0,n.Px)("item",{id:(0,i.fL)("id").notNull().primaryKey(),name:(0,i.fL)("name").notNull().unique(),price:(0,s._L)("price").notNull(),supplierId:(0,i.fL)("supplierId").notNull().references(()=>I.id,{onDelete:"cascade"}),startDate:(0,s._L)("startDate").notNull(),saved:(0,s._L)("isDeleted").notNull().default(0),isDeleted:(0,s._L)("isDeleted").notNull().default(0)}),j=(0,o.lE)($,({one:e})=&gt;({supplier:e(I,{fields:[$.supplierId],references:[I.id]})})),k=(0,n.Px)("package",{id:(0,i.fL)("id").notNull().primaryKey(),name:(0,i.fL)("name").notNull().unique(),totalPrice:(0,s._L)("totalPrice").notNull(),organisationId:(0,i.fL)("organisationId").notNull().references(()=>b.id,{onDelete:"restrict"}),startDate:(0,s._L)("startDate").notNull(),isDeleted:(0,s._L)("isDeleted").notNull().default(0)}),D=(0,o.lE)(k,({one:e})=>({organisation:e(b,{fields:[k.organisationId],references:[b.id]})})),M=(0,n.Px)("packageItem",{packageItemId:(0,i.fL)("packageItemId").notNull().primaryKey(),packageId:(0,i.fL)("packageId").notNull().references(()=>k.id,{onDelete:"restrict"}),itemId:(0,i.fL)("itemId").notNull().references(()=>$.id,{onDelete:"restrict"})}),q=(0,o.lE)(M,({one:e})=>({item:e($,{fields:[M.itemId],references:[$.id]}),package:e(k,{fields:[M.packageId],references:[k.id]})})),Q=(0,n.Px)("template",{id:(0,i.fL)("id").notNull().primaryKey(),file:(0,i.fL)("file").notNull()}),U=(0,n.Px)("projectCategory",{id:(0,i.fL)("id").notNull().primaryKey(),name:(0,i.fL)("name").notNull().unique()}),B=(0,o.lE)(U,({one:e})=>({projects:e(F)})),F=(0,n.Px)("project",{id:(0,i.fL)("id").notNull().primaryKey(),name:(0,i.fL)("name").notNull().unique(),description:(0,i.fL)("description"),projectCategoryId:(0,i.fL)("projectCategoryId").notNull().references(()=>U.id,{onDelete:"cascade"}),createdAt:(0,s._L)("createdAt").notNull(),updatedAt:(0,s._L)("updatedAt").notNull(),organisationId:(0,i.fL)("organisationId").notNull().references(()=>b.id,{onDelete:"restrict"}),isDeleted:(0,s._L)("isDeleted").notNull().default(0)}),H=(0,o.lE)(F,({one:e,many:t})=>({projectCategory:e(U,{fields:[F.projectCategoryId],references:[U.id]}),organisation:e(b,{fields:[F.organisationId],references:[b.id]}),projectContributors:t(V),projectLocations:t(z),projectCustomers:t(W),projectItems:t(X),projectPackages:t(Z),documents:t(et),tasks:t(eu)})),V=(0,n.Px)("projectContributor",{projectContributorId:(0,i.fL)("projectContributorId").notNull().primaryKey(),projectId:(0,i.fL)("projectId").notNull().references(()=>F.id,{onDelete:"cascade"}),userId:(0,i.fL)("userId").notNull().references(()=>c.id,{onDelete:"cascade"})}),K=(0,o.lE)(V,({one:e})=>({project:e(F,{fields:[V.projectId],references:[F.id]}),user:e(c,{fields:[V.userId],references:[c.id]})})),z=(0,n.Px)("projectLocation",{id:(0,i.fL)("id").notNull().primaryKey(),date:(0,i.fL)("date").notNull(),startHour:(0,i.fL)("startHour").notNull(),endHour:(0,i.fL)("endHour").notNull(),projectId:(0,i.fL)("projectId").notNull().references(()=>F.id,{onDelete:"cascade"}),locationId:(0,i.fL)("locationId").notNull().references(()=>O.id,{onDelete:"restrict"})}),G=(0,o.lE)(z,({one:e})=>({project:e(F,{fields:[z.projectId],references:[F.id]}),location:e(O,{fields:[z.locationId],references:[O.id]})})),W=(0,n.Px)("projectCustomer",{projectCustomerId:(0,i.fL)("projectCustomerId").notNull().primaryKey(),projectId:(0,i.fL)("projectId").notNull().references(()=>F.id,{onDelete:"cascade"}),customerId:(0,i.fL)("customerId").notNull().references(()=>T.id,{onDelete:"restrict"})}),J=(0,o.lE)(W,({one:e})=>({project:e(F,{fields:[W.projectId],references:[F.id]}),customer:e(T,{fields:[W.customerId],references:[T.id]})})),X=(0,n.Px)("projectItem",{projectItemId:(0,i.fL)("projectItemId").notNull().primaryKey(),itemId:(0,i.fL)("itemId").notNull().references(()=>$.id,{onDelete:"restrict"}),projectId:(0,i.fL)("projectId").notNull().references(()=>F.id,{onDelete:"cascade"})}),Y=(0,o.lE)(X,({one:e})=>({item:e($,{fields:[X.itemId],references:[$.id]}),project:e(F,{fields:[X.projectId],references:[F.id]})})),Z=(0,n.Px)("projectPackage",{projectPackageId:(0,i.fL)("projectPackageId").notNull().primaryKey(),packageId:(0,i.fL)("packageId").notNull().references(()=>k.id,{onDelete:"restrict"}),projectId:(0,i.fL)("projectId").notNull().references(()=>F.id,{onDelete:"cascade"})}),ee=(0,o.lE)(Z,({one:e})=>({package:e(k,{fields:[Z.packageId],references:[k.id]}),project:e(F,{fields:[Z.projectId],references:[F.id]})})),et=(0,n.Px)("document",{id:(0,i.fL)("id").notNull().primaryKey(),name:(0,i.fL)("name").notNull().unique(),documentNumber:(0,i.fL)("documentNumber").notNull().unique(),startDate:(0,s._L)("startDate").notNull(),endDate:(0,s._L)("endDate").notNull(),sent:(0,s._L)("sent").notNull().default(0),paid:(0,s._L)("paid").notNull().default(0),accepted:(0,s._L)("accepted").notNull().default(0),type:(0,i.fL)("type").notNull(),templateId:(0,i.fL)("templateId").notNull().references(()=>Q.id,{onDelete:"restrict"}),projectId:(0,i.fL)("projectId").notNull().references(()=>F.id,{onDelete:"cascade"}),isDeleted:(0,s._L)("isDeleted").notNull().default(0)}),er=(0,o.lE)(et,({one:e,many:t})=>({template:e(Q,{fields:[et.templateId],references:[Q.id]}),project:e(F,{fields:[et.projectId],references:[F.id]}),documentItems:t(en)})),en=(0,n.Px)("documentItem",{documentItemId:(0,i.fL)("documentItemId").notNull().primaryKey(),documentId:(0,i.fL)("documentId").notNull().references(()=>et.id,{onDelete:"cascade"}),itemId:(0,i.fL)("itemId").notNull().references(()=>$.id,{onDelete:"restrict"})}),ei=(0,o.lE)(en,({one:e})=>({document:e(et,{fields:[en.documentId],references:[et.id]}),item:e($,{fields:[en.itemId],references:[$.id]})})),es=(0,n.Px)("documentPackage",{documentPackageId:(0,i.fL)("documentPackageId").notNull().primaryKey(),documentId:(0,i.fL)("documentId").notNull().references(()=>et.id,{onDelete:"cascade"}),packageId:(0,i.fL)("packageId").notNull().references(()=>k.id,{onDelete:"restrict"})}),ea=(0,o.lE)(es,({one:e})=>({document:e(et,{fields:[es.documentId],references:[et.id]}),package:e(k,{fields:[es.packageId],references:[k.id]})})),eo=(0,n.Px)("userTask",{userTaskId:(0,i.fL)("userTaskId").notNull().primaryKey(),userId:(0,i.fL)("userId").notNull().references(()=>c.id,{onDelete:"cascade"}),taskId:(0,i.fL)("taskId").notNull().references(()=>eu.id,{onDelete:"cascade"})}),el=(0,o.lE)(eo,({one:e})=>({user:e(c,{fields:[eo.userId],references:[c.id]}),task:e(eu,{fields:[eo.taskId],references:[eu.id]})})),eu=(0,n.Px)("task",{id:(0,i.fL)("id").notNull().primaryKey(),title:(0,i.fL)("title").notNull(),description:(0,i.fL)("description"),deadline:(0,s._L)("endDate").notNull(),statusId:(0,i.fL)("statusId").notNull().references(()=>ed.id,{onDelete:"cascade"}),priorityId:(0,i.fL)("priorityId").notNull().references(()=>eh.id,{onDelete:"cascade"}),projectId:(0,i.fL)("projectId").notNull().references(()=>F.id,{onDelete:"cascade"}),isDeleted:(0,s._L)("isDeleted").notNull().default(0)}),ec=(0,o.lE)(eu,({one:e})=>({status:e(ed,{fields:[eu.statusId],references:[ed.id]}),priority:e(eh,{fields:[eu.priorityId],references:[eh.id]}),project:e(F,{fields:[eu.projectId],references:[F.id]})})),ed=(0,n.Px)("status",{id:(0,i.fL)("id").notNull().primaryKey(),name:(0,i.fL)("name").notNull().unique(),color:(0,i.fL)("description"),priority:(0,s._L)("priority").notNull().default(0)}),eh=(0,n.Px)("priority",{id:(0,i.fL)("id").notNull().primaryKey(),name:(0,i.fL)("name").notNull().unique(),color:(0,i.fL)("description"),priority:(0,s._L)("priority").notNull().default(0)})},84162:(e,t,r)=>{"use strict";r.d(t,{P:()=>u});var n=r(15469),i=r(91591),s=r(47630),a=r(25495);let{env:o}=(0,n.getRequestContext)(),l=(0,i.t)(o.DB,{schema:s}),u=async e=>{let t=await l.query.organisations.findFirst({where:(0,a.eq)(s.organisations.name,e),columns:{id:!0}});if(t)return t.id}},15469:(e,t,r)=>{"use strict";var n=Object.defineProperty,i=Object.getOwnPropertyDescriptor,s=Object.getOwnPropertyNames,a=Object.prototype.hasOwnProperty,o={};((e,t)=>{for(var r in t)n(e,r,{get:t[r],enumerable:!0})})(o,{getOptionalRequestContext:()=>u,getRequestContext:()=>c}),e.exports=((e,t,r,o)=>{if(t&&"object"==typeof t||"function"==typeof t)for(let r of s(t))a.call(e,r)||void 0===r||n(e,r,{get:()=>t[r],enumerable:!(o=i(t,r))||o.enumerable});return e})(n({},"__esModule",{value:!0}),o),r(96557);var l=Symbol.for("cloudflare-request-context");function u(){return globalThis[l]}function c(){let e=u();if(!e)throw Error("Error: failed to retrieve the Cloudflare request context");return e}},25511:(e,t,r)=>{"use strict";let n={unstable_cache:r(31696).A,revalidateTag:r(58007).O,revalidatePath:r(42517).t,unstable_noStore:r(14369).P};e.exports=n,t.unstable_cache=n.unstable_cache,t.revalidatePath=n.revalidatePath,t.revalidateTag=n.revalidateTag,t.unstable_noStore=n.unstable_noStore},19462:e=>{"use strict";var t=Object.defineProperty,r=Object.getOwnPropertyDescriptor,n=Object.getOwnPropertyNames,i=Object.prototype.hasOwnProperty,s={};function a(e){var t;let r=["path"in e&&e.path&&Path=${e.path},"expires"in e&&(e.expires||0===e.expires)&&Expires=${("number"==typeof e.expires?new Date(e.expires):e.expires).toUTCString()},"maxAge"in e&&"number"==typeof e.maxAge&&Max-Age=${e.maxAge},"domain"in e&&e.domain&&Domain=${e.domain},"secure"in e&&e.secure&&"Secure","httpOnly"in e&&e.httpOnly&&"HttpOnly","sameSite"in e&&e.sameSite&&SameSite=${e.sameSite},"priority"in e&&e.priority&&Priority=${e.priority}].filter(Boolean);return${e.name}=${encodeURIComponent(null!=(t=e.value)?t:"")}; ${r.join("; ")}}function o(e){let t=new Map;for(let r of e.split(/; /)){if(!r)continue;let e=r.indexOf("=");if(-1===e){t.set(r,"true");continue}let[n,i]=[r.slice(0,e),r.slice(e+1)];try{t.set(n,decodeURIComponent(null!=i?i:"true"))}catch{}}return t}function l(e){var t,r;if(!e)return;let[[n,i],...s]=o(e),{domain:a,expires:l,httponly:d,maxage:h,path:f,samesite:p,secure:g,priority:m}=Object.fromEntries(s.map(([e,t])=>[e.toLowerCase(),t]));return function(e){let t={};for(let r in e)e[r]&&(t[r]=e[r]);return t}({name:n,value:decodeURIComponent(i),domain:a,...l&&{expires:new Date(l)},...d&&{httpOnly:!0},..."string"==typeof h&&{maxAge:Number(h)},path:f,...p&&{sameSite:u.includes(t=(t=p).toLowerCase())?t:void 0},...g&&{secure:!0},...m&&{priority:c.includes(r=(r=m).toLowerCase())?r:void 0}})}((e,r)=>{for(var n in r)t(e,n,{get:r[n],enumerable:!0})})(s,{RequestCookies:()=>d,ResponseCookies:()=>h,parseCookie:()=>o,parseSetCookie:()=>l,stringifyCookie:()=>a}),e.exports=((e,s,a,o)=>{if(s&&"object"==typeof s||"function"==typeof s)for(let a of n(s))i.call(e,a)||void 0===a||t(e,a,{get:()=>s[a],enumerable:!(o=r(s,a))||o.enumerable});return e})(t({},"__esModule",{value:!0}),s);var u=["strict","lax","none"],c=["low","medium","high"],d=class{constructor(e){this._parsed=new Map,this._headers=e;let t=e.get("cookie");if(t)for(let[e,r]of o(t))this._parsed.set(e,{name:e,value:r})}Symbol.iterator{return this._parsedSymbol.iterator}get size(){return this._parsed.size}get(...e){let t="string"==typeof e[0]?e[0]:e[0].name;return this._parsed.get(t)}getAll(...e){var t;let r=Array.from(this._parsed);if(!e.length)return r.map(([e,t])=>t);let n="string"==typeof e[0]?e[0]:null==(t=e[0])?void 0:t.name;return r.filter(([e])=>e===n).map(([e,t])=>t)}has(e){return this._parsed.has(e)}set(...e){let[t,r]=1===e.length?[e[0].name,e[0].value]:e,n=this._parsed;return n.set(t,{name:t,value:r}),this._headers.set("cookie",Array.from(n).map(([e,t])=>a(t)).join("; ")),this}delete(e){let t=this._parsed,r=Array.isArray(e)?e.map(e=>t.delete(e)):t.delete(e);return this._headers.set("cookie",Array.from(t).map(([e,t])=>a(t)).join("; ")),r}clear(){return this.delete(Array.from(this._parsed.keys())),this}Symbol.for("edge-runtime.inspect.custom"){returnRequestCookies ${JSON.stringify(Object.fromEntries(this._parsed))}}toString(){return[...this._parsed.values()].map(e=>${e.name}=${encodeURIComponent(e.value)}).join("; ")}},h=class{constructor(e){var t,r,n;this._parsed=new Map,this._headers=e;let i=null!=(n=null!=(r=null==(t=e.getSetCookie)?void 0:t.call(e))?r:e.get("set-cookie"))?n:[];for(let e of Array.isArray(i)?i:function(e){if(!e)return[];var t,r,n,i,s,a=[],o=0;function l(){for(;o<e.length&&/\s/.test(e.charAt(o));)o+=1;return o<e.length}for(;o<e.length;){for(t=o,s=!1;l();)if(","===(r=e.charAt(o))){for(n=o,o+=1,l(),i=o;o<e.length&&"="!==(r=e.charAt(o))&&";"!==r&&","!==r;)o+=1;o<e.length&&"="===e.charAt(o)?(s=!0,o=i,a.push(e.substring(t,n)),t=o):o=n+1}else o+=1;(!s||o>=e.length)&&a.push(e.substring(t,e.length))}return a}(i)){let t=l(e);t&&this._parsed.set(t.name,t)}}get(...e){let t="string"==typeof e[0]?e[0]:e[0].name;return this._parsed.get(t)}getAll(...e){var t;let r=Array.from(this._parsed.values());if(!e.length)return r;let n="string"==typeof e[0]?e[0]:null==(t=e[0])?void 0:t.name;return r.filter(e=>e.name===n)}has(e){return this._parsed.has(e)}set(...e){let[t,r,n]=1===e.length?[e[0].name,e[0].value,e[0]]:e,i=this._parsed;return i.set(t,function(e={name:"",value:""}){return"number"==typeof e.expires&&(e.expires=new Date(e.expires)),e.maxAge&&(e.expires=new Date(Date.now()+1e3e.maxAge)),(null===e.path||void 0===e.path)&&(e.path="/"),e}({name:t,value:r,...n})),function(e,t){for(let[,r]of(t.delete("set-cookie"),e)){let e=a(r);t.append("set-cookie",e)}}(i,this._headers),this}delete(...e){let[t,r,n]="string"==typeof e[0]?[e[0]]:[e[0].name,e[0].path,e[0].domain];return this.set({name:t,path:r,domain:n,value:"",expires:new Date(0)})}Symbol.for("edge-runtime.inspect.custom"){returnResponseCookies ${JSON.stringify(Object.fromEntries(this._parsed))}}toString(){return[...this._parsed.values()].map(a).join("; ")}}},92075:(e,t,r)=>{"use strict";(()=>{var t={491:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ContextAPI=void 0;let n=r(223),i=r(172),s=r(930),a="context",o=new n.NoopContextManager;class l{constructor(){}static getInstance(){return this._instance||(this._instance=new l),this._instance}setGlobalContextManager(e){return(0,i.registerGlobal)(a,e,s.DiagAPI.instance())}active(){return this._getContextManager().active()}with(e,t,r,...n){return this._getContextManager().with(e,t,r,...n)}bind(e,t){return this._getContextManager().bind(e,t)}_getContextManager(){return(0,i.getGlobal)(a)||o}disable(){this._getContextManager().disable(),(0,i.unregisterGlobal)(a,s.DiagAPI.instance())}}t.ContextAPI=l},930:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DiagAPI=void 0;let n=r(56),i=r(912),s=r(957),a=r(172);class o{constructor(){function e(e){return function(...t){let r=(0,a.getGlobal)("diag");if(r)return re}}let t=this;t.setLogger=(e,r={logLevel:s.DiagLogLevel.INFO})=>{var n,o,l;if(e===t){let e=Error("Cannot use diag as the logger for itself. Please use a DiagLogger implementation like ConsoleDiagLogger or a custom implementation");return t.error(null!==(n=e.stack)&&void 0!==n?n:e.message),!1}"number"==typeof r&&(r={logLevel:r});let u=(0,a.getGlobal)("diag"),c=(0,i.createLogLevelDiagLogger)(null!==(o=r.logLevel)&&void 0!==o?o:s.DiagLogLevel.INFO,e);if(u&&!r.suppressOverrideMessage){let e=null!==(l=Error().stack)&&void 0!==l?l:"";u.warn(Current logger will be overwritten from ${e}),c.warn(Current logger will overwrite one already registered from ${e})}return(0,a.registerGlobal)("diag",c,t,!0)},t.disable=()=>{(0,a.unregisterGlobal)("diag",t)},t.createComponentLogger=e=>new n.DiagComponentLogger(e),t.verbose=e("verbose"),t.debug=e("debug"),t.info=e("info"),t.warn=e("warn"),t.error=e("error")}static instance(){return this._instance||(this._instance=new o),this._instance}}t.DiagAPI=o},653:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.MetricsAPI=void 0;let n=r(660),i=r(172),s=r(930),a="metrics";class o{constructor(){}static getInstance(){return this._instance||(this._instance=new o),this._instance}setGlobalMeterProvider(e){return(0,i.registerGlobal)(a,e,s.DiagAPI.instance())}getMeterProvider(){return(0,i.getGlobal)(a)||n.NOOP_METER_PROVIDER}getMeter(e,t,r){return this.getMeterProvider().getMeter(e,t,r)}disable(){(0,i.unregisterGlobal)(a,s.DiagAPI.instance())}}t.MetricsAPI=o},181:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.PropagationAPI=void 0;let n=r(172),i=r(874),s=r(194),a=r(277),o=r(369),l=r(930),u="propagation",c=new i.NoopTextMapPropagator;class d{constructor(){this.createBaggage=o.createBaggage,this.getBaggage=a.getBaggage,this.getActiveBaggage=a.getActiveBaggage,this.setBaggage=a.setBaggage,this.deleteBaggage=a.deleteBaggage}static getInstance(){return this._instance||(this._instance=new d),this._instance}setGlobalPropagator(e){return(0,n.registerGlobal)(u,e,l.DiagAPI.instance())}inject(e,t,r=s.defaultTextMapSetter){return this._getGlobalPropagator().inject(e,t,r)}extract(e,t,r=s.defaultTextMapGetter){return this._getGlobalPropagator().extract(e,t,r)}fields(){return this._getGlobalPropagator().fields()}disable(){(0,n.unregisterGlobal)(u,l.DiagAPI.instance())}_getGlobalPropagator(){return(0,n.getGlobal)(u)||c}}t.PropagationAPI=d},997:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.TraceAPI=void 0;let n=r(172),i=r(846),s=r(139),a=r(607),o=r(930),l="trace";class u{constructor(){this._proxyTracerProvider=new i.ProxyTracerProvider,this.wrapSpanContext=s.wrapSpanContext,this.isSpanContextValid=s.isSpanContextValid,this.deleteSpan=a.deleteSpan,this.getSpan=a.getSpan,this.getActiveSpan=a.getActiveSpan,this.getSpanContext=a.getSpanContext,this.setSpan=a.setSpan,this.setSpanContext=a.setSpanContext}static getInstance(){return this._instance||(this._instance=new u),this._instance}setGlobalTracerProvider(e){let t=(0,n.registerGlobal)(l,this._proxyTracerProvider,o.DiagAPI.instance());return t&&this._proxyTracerProvider.setDelegate(e),t}getTracerProvider(){return(0,n.getGlobal)(l)||this._proxyTracerProvider}getTracer(e,t){return this.getTracerProvider().getTracer(e,t)}disable(){(0,n.unregisterGlobal)(l,o.DiagAPI.instance()),this._proxyTracerProvider=new i.ProxyTracerProvider}}t.TraceAPI=u},277:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.deleteBaggage=t.setBaggage=t.getActiveBaggage=t.getBaggage=void 0;let n=r(491),i=(0,r(780).createContextKey)("OpenTelemetry Baggage Key");function s(e){return e.getValue(i)||void 0}t.getBaggage=s,t.getActiveBaggage=function(){return s(n.ContextAPI.getInstance().active())},t.setBaggage=function(e,t){return e.setValue(i,t)},t.deleteBaggage=function(e){return e.deleteValue(i)}},993:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.BaggageImpl=void 0;class r{constructor(e){this._entries=e?new Map(e):new Map}getEntry(e){let t=this._entries.get(e);if(t)return Object.assign({},t)}getAllEntries(){return Array.from(this._entries.entries()).map(([e,t])=>[e,t])}setEntry(e,t){let n=new r(this._entries);return n._entries.set(e,t),n}removeEntry(e){let t=new r(this._entries);return t._entries.delete(e),t}removeEntries(...e){let t=new r(this._entries);for(let r of e)t._entries.delete(r);return t}clear(){return new r}}t.BaggageImpl=r},830:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.baggageEntryMetadataSymbol=void 0,t.baggageEntryMetadataSymbol=Symbol("BaggageEntryMetadata")},369:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.baggageEntryMetadataFromString=t.createBaggage=void 0;let n=r(930),i=r(993),s=r(830),a=n.DiagAPI.instance();t.createBaggage=function(e={}){return new i.BaggageImpl(new Map(Object.entries(e)))},t.baggageEntryMetadataFromString=function(e){return"string"!=typeof e&&(a.error(Cannot create baggage metadata from unknown type: ${typeof e}),e=""),{TYPE:s.baggageEntryMetadataSymbol,toString:()=>e}}},67:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.context=void 0;let n=r(491);t.context=n.ContextAPI.getInstance()},223:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.NoopContextManager=void 0;let n=r(780);class i{active(){return n.ROOT_CONTEXT}with(e,t,r,...n){return t.call(r,...n)}bind(e,t){return t}enable(){return this}disable(){return this}}t.NoopContextManager=i},780:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ROOT_CONTEXT=t.createContextKey=void 0,t.createContextKey=function(e){return Symbol.for(e)};class r{constructor(e){let t=this;t._currentContext=e?new Map(e):new Map,t.getValue=e=>t._currentContext.get(e),t.setValue=(e,n)=>{let i=new r(t._currentContext);return i._currentContext.set(e,n),i},t.deleteValue=e=>{let n=new r(t._currentContext);return n._currentContext.delete(e),n}}}t.ROOT_CONTEXT=new r},506:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.diag=void 0;let n=r(930);t.diag=n.DiagAPI.instance()},56:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DiagComponentLogger=void 0;let n=r(172);class i{constructor(e){this._namespace=e.namespace||"DiagComponentLogger"}debug(...e){return s("debug",this._namespace,e)}error(...e){return s("error",this._namespace,e)}info(...e){return s("info",this._namespace,e)}warn(...e){return s("warn",this._namespace,e)}verbose(...e){return s("verbose",this._namespace,e)}}function s(e,t,r){let i=(0,n.getGlobal)("diag");if(i)return r.unshift(t),ie}t.DiagComponentLogger=i},972:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DiagConsoleLogger=void 0;let r=[{n:"error",c:"error"},{n:"warn",c:"warn"},{n:"info",c:"info"},{n:"debug",c:"debug"},{n:"verbose",c:"trace"}];class n{constructor(){for(let e=0;e<r.length;e++)this[r[e].n]=function(e){return function(...t){if(console){let r=console[e];if("function"!=typeof r&&(r=console.log),"function"==typeof r)return r.apply(console,t)}}}(r[e].c)}}t.DiagConsoleLogger=n},912:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.createLogLevelDiagLogger=void 0;let n=r(957);t.createLogLevelDiagLogger=function(e,t){function r(r,n){let i=t[r];return"function"==typeof i&&e>=n?i.bind(t):function(){}}return e<n.DiagLogLevel.NONE?e=n.DiagLogLevel.NONE:e>n.DiagLogLevel.ALL&&(e=n.DiagLogLevel.ALL),t=t||{},{error:r("error",n.DiagLogLevel.ERROR),warn:r("warn",n.DiagLogLevel.WARN),info:r("info",n.DiagLogLevel.INFO),debug:r("debug",n.DiagLogLevel.DEBUG),verbose:r("verbose",n.DiagLogLevel.VERBOSE)}}},957:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DiagLogLevel=void 0,function(e){e[e.NONE=0]="NONE",e[e.ERROR=30]="ERROR",e[e.WARN=50]="WARN",e[e.INFO=60]="INFO",e[e.DEBUG=70]="DEBUG",e[e.VERBOSE=80]="VERBOSE",e[e.ALL=9999]="ALL"}(t.DiagLogLevel||(t.DiagLogLevel={}))},172:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.unregisterGlobal=t.getGlobal=t.registerGlobal=void 0;let n=r(200),i=r(521),s=r(130),a=i.VERSION.split(".")[0],o=Symbol.for(opentelemetry.js.api.${a}),l=n._globalThis;t.registerGlobal=function(e,t,r,n=!1){var s;let a=l[o]=null!==(s=l[o])&&void 0!==s?s:{version:i.VERSION};if(!n&&a[e]){let t=Error(@opentelemetry/api: Attempted duplicate registration of API: ${e});return r.error(t.stack||t.message),!1}if(a.version!==i.VERSION){let t=Error(@opentelemetry/api: Registration of version v${a.version} for ${e} does not match previously registered API v${i.VERSION});return r.error(t.stack||t.message),!1}return a[e]=t,r.debug(@opentelemetry/api: Registered a global for ${e} v${i.VERSION}.),!0},t.getGlobal=function(e){var t,r;let n=null===(t=l[o])||void 0===t?void 0:t.version;if(n&&(0,s.isCompatible)(n))return null===(r=l[o])||void 0===r?void 0:r[e]},t.unregisterGlobal=function(e,t){t.debug(@opentelemetry/api: Unregistering a global for ${e} v${i.VERSION}.);let r=l[o];r&&delete r[e]}},130:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.isCompatible=t._makeCompatibilityCheck=void 0;let n=r(521),i=/^(\d+).(\d+).(\d+)(-(.+))?$/;function s(e){let t=new Set([e]),r=new Set,n=e.match(i);if(!n)return()=>!1;let s={major:+n[1],minor:+n[2],patch:+n[3],prerelease:n[4]};if(null!=s.prerelease)return function(t){return t===e};function a(e){return r.add(e),!1}return function(e){if(t.has(e))return!0;if(r.has(e))return!1;let n=e.match(i);if(!n)return a(e);let o={major:+n[1],minor:+n[2],patch:+n[3],prerelease:n[4]};return null!=o.prerelease||s.major!==o.major?a(e):0===s.major?s.minor===o.minor&&s.patch<=o.patch?(t.add(e),!0):a(e):s.minor<=o.minor?(t.add(e),!0):a(e)}}t._makeCompatibilityCheck=s,t.isCompatible=s(n.VERSION)},886:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.metrics=void 0;let n=r(653);t.metrics=n.MetricsAPI.getInstance()},901:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ValueType=void 0,function(e){e[e.INT=0]="INT",e[e.DOUBLE=1]="DOUBLE"}(t.ValueType||(t.ValueType={}))},102:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.createNoopMeter=t.NOOP_OBSERVABLE_UP_DOWN_COUNTER_METRIC=t.NOOP_OBSERVABLE_GAUGE_METRIC=t.NOOP_OBSERVABLE_COUNTER_METRIC=t.NOOP_UP_DOWN_COUNTER_METRIC=t.NOOP_HISTOGRAM_METRIC=t.NOOP_COUNTER_METRIC=t.NOOP_METER=t.NoopObservableUpDownCounterMetric=t.NoopObservableGaugeMetric=t.NoopObservableCounterMetric=t.NoopObservableMetric=t.NoopHistogramMetric=t.NoopUpDownCounterMetric=t.NoopCounterMetric=t.NoopMetric=t.NoopMeter=void 0;class r{constructor(){}createHistogram(e,r){return t.NOOP_HISTOGRAM_METRIC}createCounter(e,r){return t.NOOP_COUNTER_METRIC}createUpDownCounter(e,r){return t.NOOP_UP_DOWN_COUNTER_METRIC}createObservableGauge(e,r){return t.NOOP_OBSERVABLE_GAUGE_METRIC}createObservableCounter(e,r){return t.NOOP_OBSERVABLE_COUNTER_METRIC}createObservableUpDownCounter(e,r){return t.NOOP_OBSERVABLE_UP_DOWN_COUNTER_METRIC}addBatchObservableCallback(e,t){}removeBatchObservableCallback(e){}}t.NoopMeter=r;class n{}t.NoopMetric=n;class i extends n{add(e,t){}}t.NoopCounterMetric=i;class s extends n{add(e,t){}}t.NoopUpDownCounterMetric=s;class a extends n{record(e,t){}}t.NoopHistogramMetric=a;class o{addCallback(e){}removeCallback(e){}}t.NoopObservableMetric=o;class l extends o{}t.NoopObservableCounterMetric=l;class u extends o{}t.NoopObservableGaugeMetric=u;class c extends o{}t.NoopObservableUpDownCounterMetric=c,t.NOOP_METER=new r,t.NOOP_COUNTER_METRIC=new i,t.NOOP_HISTOGRAM_METRIC=new a,t.NOOP_UP_DOWN_COUNTER_METRIC=new s,t.NOOP_OBSERVABLE_COUNTER_METRIC=new l,t.NOOP_OBSERVABLE_GAUGE_METRIC=new u,t.NOOP_OBSERVABLE_UP_DOWN_COUNTER_METRIC=new c,t.createNoopMeter=function(){return t.NOOP_METER}},660:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.NOOP_METER_PROVIDER=t.NoopMeterProvider=void 0;let n=r(102);class i{getMeter(e,t,r){return n.NOOP_METER}}t.NoopMeterProvider=i,t.NOOP_METER_PROVIDER=new i},200:function(e,t,r){var n=this&&this.__createBinding||(Object.create?function(e,t,r,n){void 0===n&&(n=r),Object.defineProperty(e,n,{enumerable:!0,get:function(){return t[r]}})}:function(e,t,r,n){void 0===n&&(n=r),e[n]=t[r]}),i=this&&this.__exportStar||function(e,t){for(var r in e)"default"===r||Object.prototype.hasOwnProperty.call(t,r)||n(t,e,r)};Object.defineProperty(t,"__esModule",{value:!0}),i(r(46),t)},651:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t._globalThis=void 0,t._globalThis="object"==typeof globalThis?globalThis:r.g},46:function(e,t,r){var n=this&&this.__createBinding||(Object.create?function(e,t,r,n){void 0===n&&(n=r),Object.defineProperty(e,n,{enumerable:!0,get:function(){return t[r]}})}:function(e,t,r,n){void 0===n&&(n=r),e[n]=t[r]}),i=this&&this.__exportStar||function(e,t){for(var r in e)"default"===r||Object.prototype.hasOwnProperty.call(t,r)||n(t,e,r)};Object.defineProperty(t,"__esModule",{value:!0}),i(r(651),t)},939:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.propagation=void 0;let n=r(181);t.propagation=n.PropagationAPI.getInstance()},874:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.NoopTextMapPropagator=void 0;class r{inject(e,t){}extract(e,t){return e}fields(){return[]}}t.NoopTextMapPropagator=r},194:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.defaultTextMapSetter=t.defaultTextMapGetter=void 0,t.defaultTextMapGetter={get(e,t){if(null!=e)return e[t]},keys:e=>null==e?[]:Object.keys(e)},t.defaultTextMapSetter={set(e,t,r){null!=e&&(e[t]=r)}}},845:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.trace=void 0;let n=r(997);t.trace=n.TraceAPI.getInstance()},403:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.NonRecordingSpan=void 0;let n=r(476);class i{constructor(e=n.INVALID_SPAN_CONTEXT){this._spanContext=e}spanContext(){return this._spanContext}setAttribute(e,t){return this}setAttributes(e){return this}addEvent(e,t){return this}setStatus(e){return this}updateName(e){return this}end(e){}isRecording(){return!1}recordException(e,t){}}t.NonRecordingSpan=i},614:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.NoopTracer=void 0;let n=r(491),i=r(607),s=r(403),a=r(139),o=n.ContextAPI.getInstance();class l{startSpan(e,t,r=o.active()){if(null==t?void 0:t.root)return new s.NonRecordingSpan;let n=r&&(0,i.getSpanContext)(r);return"object"==typeof n&&"string"==typeof n.spanId&&"string"==typeof n.traceId&&"number"==typeof n.traceFlags&&(0,a.isSpanContextValid)(n)?new s.NonRecordingSpan(n):new s.NonRecordingSpan}startActiveSpan(e,t,r,n){let s,a,l;if(arguments.length<2)return;2==arguments.length?l=t:3==arguments.length?(s=t,l=r):(s=t,a=r,l=n);let u=null!=a?a:o.active(),c=this.startSpan(e,s,u),d=(0,i.setSpan)(u,c);return o.with(d,l,void 0,c)}}t.NoopTracer=l},124:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.NoopTracerProvider=void 0;let n=r(614);class i{getTracer(e,t,r){return new n.NoopTracer}}t.NoopTracerProvider=i},125:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ProxyTracer=void 0;let n=new(r(614)).NoopTracer;class i{constructor(e,t,r,n){this._provider=e,this.name=t,this.version=r,this.options=n}startSpan(e,t,r){return this._getTracer().startSpan(e,t,r)}startActiveSpan(e,t,r,n){let i=this._getTracer();return Reflect.apply(i.startActiveSpan,i,arguments)}_getTracer(){if(this._delegate)return this._delegate;let e=this._provider.getDelegateTracer(this.name,this.version,this.options);return e?(this._delegate=e,this._delegate):n}}t.ProxyTracer=i},846:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ProxyTracerProvider=void 0;let n=r(125),i=new(r(124)).NoopTracerProvider;class s{getTracer(e,t,r){var i;return null!==(i=this.getDelegateTracer(e,t,r))&&void 0!==i?i:new n.ProxyTracer(this,e,t,r)}getDelegate(){var e;return null!==(e=this._delegate)&&void 0!==e?e:i}setDelegate(e){this._delegate=e}getDelegateTracer(e,t,r){var n;return null===(n=this._delegate)||void 0===n?void 0:n.getTracer(e,t,r)}}t.ProxyTracerProvider=s},996:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.SamplingDecision=void 0,function(e){e[e.NOT_RECORD=0]="NOT_RECORD",e[e.RECORD=1]="RECORD",e[e.RECORD_AND_SAMPLED=2]="RECORD_AND_SAMPLED"}(t.SamplingDecision||(t.SamplingDecision={}))},607:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.getSpanContext=t.setSpanContext=t.deleteSpan=t.setSpan=t.getActiveSpan=t.getSpan=void 0;let n=r(780),i=r(403),s=r(491),a=(0,n.createContextKey)("OpenTelemetry Context Key SPAN");function o(e){return e.getValue(a)||void 0}function l(e,t){return e.setValue(a,t)}t.getSpan=o,t.getActiveSpan=function(){return o(s.ContextAPI.getInstance().active())},t.setSpan=l,t.deleteSpan=function(e){return e.deleteValue(a)},t.setSpanContext=function(e,t){return l(e,new i.NonRecordingSpan(t))},t.getSpanContext=function(e){var t;return null===(t=o(e))||void 0===t?void 0:t.spanContext()}},325:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.TraceStateImpl=void 0;let n=r(564);class i{constructor(e){this._internalState=new Map,e&&this._parse(e)}set(e,t){let r=this._clone();return r._internalState.has(e)&&r._internalState.delete(e),r._internalState.set(e,t),r}unset(e){let t=this._clone();return t._internalState.delete(e),t}get(e){return this._internalState.get(e)}serialize(){return this._keys().reduce((e,t)=>(e.push(t+"="+this.get(t)),e),[]).join(",")}_parse(e){!(e.length>512)&&(this._internalState=e.split(",").reverse().reduce((e,t)=>{let r=t.trim(),i=r.indexOf("=");if(-1!==i){let s=r.slice(0,i),a=r.slice(i+1,t.length);(0,n.validateKey)(s)&&(0,n.validateValue)(a)&&e.set(s,a)}return e},new Map),this._internalState.size>32&&(this._internalState=new Map(Array.from(this._internalState.entries()).reverse().slice(0,32))))}_keys(){return Array.from(this._internalState.keys()).reverse()}_clone(){let e=new i;return e._internalState=new Map(this._internalState),e}}t.TraceStateImpl=i},564:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.validateValue=t.validateKey=void 0;let r="[_0-9a-z-/]",n=[a-z]${r}{0,255},i=[a-z0-9]${r}{0,240}@[a-z]${r}{0,13},s=RegExp(^(?:${n}|${i})$),a=/^[ -]{0,255}[!-]$/,o=/,|=/;t.validateKey=function(e){return s.test(e)},t.validateValue=function(e){return a.test(e)&&!o.test(e)}},98:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.createTraceState=void 0;let n=r(325);t.createTraceState=function(e){return new n.TraceStateImpl(e)}},476:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.INVALID_SPAN_CONTEXT=t.INVALID_TRACEID=t.INVALID_SPANID=void 0;let n=r(475);t.INVALID_SPANID="0000000000000000",t.INVALID_TRACEID="00000000000000000000000000000000",t.INVALID_SPAN_CONTEXT={traceId:t.INVALID_TRACEID,spanId:t.INVALID_SPANID,traceFlags:n.TraceFlags.NONE}},357:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.SpanKind=void 0,function(e){e[e.INTERNAL=0]="INTERNAL",e[e.SERVER=1]="SERVER",e[e.CLIENT=2]="CLIENT",e[e.PRODUCER=3]="PRODUCER",e[e.CONSUMER=4]="CONSUMER"}(t.SpanKind||(t.SpanKind={}))},139:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.wrapSpanContext=t.isSpanContextValid=t.isValidSpanId=t.isValidTraceId=void 0;let n=r(476),i=r(403),s=/^([0-9a-f]{32})$/i,a=/^[0-9a-f]{16}$/i;function o(e){return s.test(e)&&e!==n.INVALID_TRACEID}function l(e){return a.test(e)&&e!==n.INVALID_SPANID}t.isValidTraceId=o,t.isValidSpanId=l,t.isSpanContextValid=function(e){return o(e.traceId)&&l(e.spanId)},t.wrapSpanContext=function(e){return new i.NonRecordingSpan(e)}},847:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.SpanStatusCode=void 0,function(e){e[e.UNSET=0]="UNSET",e[e.OK=1]="OK",e[e.ERROR=2]="ERROR"}(t.SpanStatusCode||(t.SpanStatusCode={}))},475:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.TraceFlags=void 0,function(e){e[e.NONE=0]="NONE",e[e.SAMPLED=1]="SAMPLED"}(t.TraceFlags||(t.TraceFlags={}))},521:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.VERSION=void 0,t.VERSION="1.6.0"}},n={};function i(e){var r=n[e];if(void 0!==r)return r.exports;var s=n[e]={exports:{}},a=!0;try{t[e].call(s.exports,s,s.exports,i),a=!1}finally{a&&delete n[e]}return s.exports}i.ab="//";var s={};(()=>{Object.defineProperty(s,"__esModule",{value:!0}),s.trace=s.propagation=s.metrics=s.diag=s.context=s.INVALID_SPAN_CONTEXT=s.INVALID_TRACEID=s.INVALID_SPANID=s.isValidSpanId=s.isValidTraceId=s.isSpanContextValid=s.createTraceState=s.TraceFlags=s.SpanStatusCode=s.SpanKind=s.SamplingDecision=s.ProxyTracerProvider=s.ProxyTracer=s.defaultTextMapSetter=s.defaultTextMapGetter=s.ValueType=s.createNoopMeter=s.DiagLogLevel=s.DiagConsoleLogger=s.ROOT_CONTEXT=s.createContextKey=s.baggageEntryMetadataFromString=void 0;var e=i(369);Object.defineProperty(s,"baggageEntryMetadataFromString",{enumerable:!0,get:function(){return e.baggageEntryMetadataFromString}});var t=i(780);Object.defineProperty(s,"createContextKey",{enumerable:!0,get:function(){return t.createContextKey}}),Object.defineProperty(s,"ROOT_CONTEXT",{enumerable:!0,get:function(){return t.ROOT_CONTEXT}});var r=i(972);Object.defineProperty(s,"DiagConsoleLogger",{enumerable:!0,get:function(){return r.DiagConsoleLogger}});var n=i(957);Object.defineProperty(s,"DiagLogLevel",{enumerable:!0,get:function(){return n.DiagLogLevel}});var a=i(102);Object.defineProperty(s,"createNoopMeter",{enumerable:!0,get:function(){return a.createNoopMeter}});var o=i(901);Object.defineProperty(s,"ValueType",{enumerable:!0,get:function(){return o.ValueType}});var l=i(194);Object.defineProperty(s,"defaultTextMapGetter",{enumerable:!0,get:function(){return l.defaultTextMapGetter}}),Object.defineProperty(s,"defaultTextMapSetter",{enumerable:!0,get:function(){return l.defaultTextMapSetter}});var u=i(125);Object.defineProperty(s,"ProxyTracer",{enumerable:!0,get:function(){return u.ProxyTracer}});var c=i(846);Object.defineProperty(s,"ProxyTracerProvider",{enumerable:!0,get:function(){return c.ProxyTracerProvider}});var d=i(996);Object.defineProperty(s,"SamplingDecision",{enumerable:!0,get:function(){return d.SamplingDecision}});var h=i(357);Object.defineProperty(s,"SpanKind",{enumerable:!0,get:function(){return h.SpanKind}});var f=i(847);Object.defineProperty(s,"SpanStatusCode",{enumerable:!0,get:function(){return f.SpanStatusCode}});var p=i(475);Object.defineProperty(s,"TraceFlags",{enumerable:!0,get:function(){return p.TraceFlags}});var g=i(98);Object.defineProperty(s,"createTraceState",{enumerable:!0,get:function(){return g.createTraceState}});var m=i(139);Object.defineProperty(s,"isSpanContextValid",{enumerable:!0,get:function(){return m.isSpanContextValid}}),Object.defineProperty(s,"isValidTraceId",{enumerable:!0,get:function(){return m.isValidTraceId}}),Object.defineProperty(s,"isValidSpanId",{enumerable:!0,get:function(){return m.isValidSpanId}});var y=i(476);Object.defineProperty(s,"INVALID_SPANID",{enumerable:!0,get:function(){return y.INVALID_SPANID}}),Object.defineProperty(s,"INVALID_TRACEID",{enumerable:!0,get:function(){return y.INVALID_TRACEID}}),Object.defineProperty(s,"INVALID_SPAN_CONTEXT",{enumerable:!0,get:function(){return y.INVALID_SPAN_CONTEXT}});let v=i(67);Object.defineProperty(s,"context",{enumerable:!0,get:function(){return v.context}});let b=i(506);Object.defineProperty(s,"diag",{enumerable:!0,get:function(){return b.diag}});let S=i(886);Object.defineProperty(s,"metrics",{enumerable:!0,get:function(){return S.metrics}});let w=i(939);Object.defineProperty(s,"propagation",{enumerable:!0,get:function(){return w.propagation}});let _=i(845);Object.defineProperty(s,"trace",{enumerable:!0,get:function(){return .trace}}),s.default={context:v.context,diag:b.diag,metrics:S.metrics,propagation:w.propagation,trace:.trace}})(),e.exports=s})()},59577:e=>{"use strict";(()=>{"undefined"!=typeof nccwpck_require&&(nccwpck_require.ab="//");var t={};(()=>{/!
2024-03-01T09:27:45.423745Z ▲
2024-03-01T09:27:45.423949Z ▲
2024-03-01T09:27:45.424106Z ▲ Error: Error: failed to retrieve the Cloudflare request context
2024-03-01T09:27:45.424271Z ▲ at c (/opt/buildhome/repo/.next/server/app/(platform)/[organisationName]/api/customers/route.js:1:19380)
2024-03-01T09:27:45.424426Z ▲ at 84162 (/opt/buildhome/repo/.next/server/app/(platform)/[organisationName]/api/customers/route.js:1:18594)
2024-03-01T09:27:45.424585Z ▲ at webpack_require (/opt/buildhome/repo/.next/server/edge-runtime-webpack.js:25:42)
2024-03-01T09:27:45.424747Z ▲ at 73707 (/opt/buildhome/repo/.next/server/app/(platform)/[organisationName]/api/customers/route.js:1:635)
2024-03-01T09:27:45.424889Z ▲ at webpack_require (/opt/buildhome/repo/.next/server/edge-runtime-webpack.js:25:42)
2024-03-01T09:27:45.425039Z ▲ at /opt/buildhome/repo/.next/server/app/(platform)/[organisationName]/api/customers/route.js:30:4970
2024-03-01T09:27:45.425248Z ▲ at webpackJsonpCallback (/opt/buildhome/repo/.next/server/edge-runtime-webpack.js:208:39)
2024-03-01T09:27:45.425398Z ▲ at /opt/buildhome/repo/.next/server/app/(platform)/[organisationName]/api/customers/route.js:1:51
2024-03-01T09:27:45.425532Z ▲ at Script.runInContext (node:vm:135:12)
2024-03-01T09:27:45.425671Z ▲ at runInContext (node:vm:283:6)
2024-03-01T09:27:45.425831Z ▲ > Build error occurred
2024-03-01T09:27:45.429335Z ▲ Error: Failed to collect page data for /[organisationName]/api/customers
2024-03-01T09:27:45.429799Z ▲ at /opt/buildhome/repo/node_modules/next/dist/build/utils.js:1258:15
2024-03-01T09:27:45.429981Z ▲ at process.processTicksAndRejections (node:internal/process/task_queues:95:5) {
2024-03-01T09:27:45.430108Z ▲ type: 'Error'
2024-03-01T09:27:45.431413Z ▲ }
2024-03-01T09:27:45.520795Z ▲ Error: Command "npm run build" exited with 1
2024-03-01T09:27:45.65477Z
2024-03-01T09:27:45.655118Z ⚡️ The Vercel build (npx vercel build) command failed. For more details see the Vercel logs above.
2024-03-01T09:27:45.655319Z ⚡️ If you need help solving the issue, refer to the Vercel or Next.js documentation or their repositories.
2024-03-01T09:27:45.655462Z
2024-03-01T09:27:45.67291Z Failed: Error while executing user command. Exited with error code: 1
2024-03-01T09:27:45.683688Z Failed: build command exited with code: 1
2024-03-01T09:27:46.664887Z Failed: error occurred while running build command

My folder structure:
image

Reproduction

No response

Pages Deployment Method

Pages CI (GitHub/GitLab integration)

Pages Deployment ID

No response

Additional Information

No response

Would you like to help?

  • Would you like to help fixing this bug?
@bryandeckers bryandeckers added the bug Something isn't working label Mar 1, 2024
@dario-piotrowicz
Copy link
Member

Hi @bryandeckers, thanks for the issue 🙂

Could you confirm if you're using the edge runtime in your component?

Does getRequestContext work when running the app with next dev?

@bryandeckers
Copy link
Author

Hi @bryandeckers, thanks for the issue 🙂

Could you confirm if you're using the edge runtime in your component?

Does getRequestContext work when running the app with next dev?

Yes I am indeed using Edge runtime and yes it works locally when using next dev.

Example of one of my api GET's:
export const runtime = "edge";
import { getRequestContext } from "@cloudflare/next-on-pages";
import { drizzle } from "drizzle-orm/d1";
import { v4 as uuidv4 } from "uuid";
import * as schema from "@/db/schema";
import { eq } from "drizzle-orm";
import { customers, address } from "@/db/schema";
import { Customer } from "@/types/customer";
import { getOrganisationId } from "@/modules/api";
import { InsertAddress } from "@/types/address";
import { revalidatePath } from "next/cache";

export async function GET(
request: Request,
{ params }: { params: { organisationName: string } }
) {
const { env } = getRequestContext();
const db = drizzle(env.DB, { schema });
const orgId = await getOrganisationId(params.organisationName);

if (!orgId) return;

const customersList = await db.query.customers.findMany({
where: eq(customers.organisationId, orgId),
with: {
address: true,
},
});

return new Response(JSON.stringify(customersList), {
headers: { "Content-Type": "application/json" },
});
}

@dario-piotrowicz
Copy link
Member

mh... 🤔

Two more questions 😅

  • could you share the content of your app/(platform)/[organisationName]/api/customers/route.js file? (redacting any private logic/info if need be)
  • are you calling setupDevPlatform only when process.env.NODE_ENV === 'development' as suggested in our readme? (this should not be necessary... I'm just wondering... and actually if you do have that I'd also ask you trying to remove it and see what that does if possible)

Also, using getOptionalRequestContext instead of getRequestContext could be a viable workaround? 🤔

@bryandeckers
Copy link
Author

I'm not able to get the markdown code tag to work but this is my customers/route.ts but all my api routes follow this principle so I would assume the error would be for all files.

Code:
export const runtime = "edge";
import { getRequestContext } from "@cloudflare/next-on-pages";
import { drizzle } from "drizzle-orm/d1";
import { v4 as uuidv4 } from "uuid";
import * as schema from "@/db/schema";
import { eq } from "drizzle-orm";
import { customers, address } from "@/db/schema";
import { Customer } from "@/types/customer";
import { getOrganisationId } from "@/modules/api";
import { InsertAddress } from "@/types/address";
import { revalidatePath } from "next/cache";

export async function GET(
request: Request,
{ params }: { params: { organisationName: string } }
) {
const { env } = getRequestContext();
const db = drizzle(env.DB, { schema });
const orgId = await getOrganisationId(params.organisationName);

if (!orgId) return;

const customersList = await db.query.customers.findMany({
where: eq(customers.organisationId, orgId),
with: {
address: true,
},
});

return new Response(JSON.stringify(customersList), {
headers: { "Content-Type": "application/json" },
});
}

export async function POST(
request: Request,
{ params }: { params: { organisationName: string } }
) {
const { env } = getRequestContext();
const db = drizzle(env.DB, { schema });
const customer: Customer = await request.json();

try {
//get organisation by id
const organisationId = await getOrganisationId(params.organisationName);
if (!organisationId) return;

const addressId = uuidv4();
const id = uuidv4();

const customerAddress: InsertAddress = customer.address;

await db.insert(address).values({
  ...customerAddress,
  id: addressId,
});

const [newCustomer] = await db
  .insert(customers)
  .values({
    ...customer,
    id,
    addressId,
    organisationId,
  })
  .returning();
return new Response(
  JSON.stringify({
    message: "Klant succesvol aangemaakt",
    description: `"${newCustomer.firstName} ${newCustomer.lastName}" is aangemaakt`,
    success: true,
    data: newCustomer,
  }),
  {
    headers: { "Content-Type": "application/json" },
  }
);

} catch (error) {
return new Response(
JSON.stringify({
message: "Fout bij het aanmaken van de klant",
description: ${customer.firstName} ${customer.lastName}" kon niet worden aangemaakt,
success: false,
}),
{
headers: { "Content-Type": "application/json" },
}
);
} finally {
// Revalidate cache
revalidatePath(/${params.organisationName}/customers);
}
}

My next.config.mjs:
// we import the utility from the next-dev submodule
import { setupDevPlatform } from "@cloudflare/next-on-pages/next-dev";

/** @type {import('next').NextConfig} */
const nextConfig = {
images: {
remotePatterns: [
{
protocol: "https",
hostname: "busma.be",
},
],
},
logging: {
fetches: {
fullUrl: true,
},
},
};

export default nextConfig;

// we only need to use the utility during development so we can check NODE_ENV
// (note: this check is recommended but completely optional)
if (process.env.NODE_ENV === 'development') {
// awaiting the call is not necessary but it helps making sure that the setup has succeeded.
// If you cannot use top level awaits you could use the following to avoid an unhandled rejection:
// setupDevPlatform().catch(e => console.error(e));
await setupDevPlatform();
}

Your second comment is what I was trying to just implement to hopefully fix it but got the same result as when I called setupDevPlatform without the development env check.

I am not sure if using getOptionalRequestContext is possible as I need to get the binding in order to interact with it, correct me if I'm wrong.

@dario-piotrowicz
Copy link
Member

I am not sure if using getOptionalRequestContext is possible as I need to get the binding in order to interact with it, correct me if I'm wrong.

It feels like what's going wrong here is that Next is trying to pre-render your route when building the application, so I was suggesting getOptionalRequestContext as a workaround just to get the pre-rendering not to complain.

Something along these lines:

const requestContext = getOptionalRequestContext();

if(!requestContext) {
  // Next.js is trying to wrongly pre-render this, so we need to bail out
  return; // or return whatever no-op response/result that would make sense
}

// your existing logic goes here...

it was just an idea to quickly unblock you

@bryandeckers
Copy link
Author

Maybe a bit of a general question but can I define the following at the top of the file "globally"? Because if not I would have to add that requestContext check for every api route times every get,post,put

const { env } = getRequestContext();
const db = drizzle(env.DB, { schema });

@bryandeckers
Copy link
Author

@dario-piotrowicz still the same error: Error: failed to retrieve the Cloudflare request context
When using the following:

const requestContext = getOptionalRequestContext();

if(!requestContext) {
  // Next.js is trying to wrongly pre-render this, so we need to bail out
  return; // or return whatever no-op response/result that would make sense
}
export const runtime = "edge";
import { getOptionalRequestContext } from "@cloudflare/next-on-pages";
import { drizzle } from "drizzle-orm/d1";
import { v4 as uuidv4 } from "uuid";
import * as schema from "@/db/schema";
import { eq } from "drizzle-orm";
import { customers, address } from "@/db/schema";
import { Customer } from "@/types/customer";
import { getOrganisationId } from "@/modules/api";
import { InsertAddress } from "@/types/address";
import { revalidatePath } from "next/cache";

export async function GET(
  request: Request,
  { params }: { params: { organisationName: string } }
) {

  const requestContext = getOptionalRequestContext();
  if(!requestContext ) {
    return
  }
  const db = drizzle(requestContext.env.DB, { schema });
  const orgId = await getOrganisationId(params.organisationName);

  if (!orgId) return;

  const customersList = await db.query.customers.findMany({
    where: eq(customers.organisationId, orgId),
    with: {
      address: true,
    },
  });

  return new Response(JSON.stringify(customersList), {
    headers: { "Content-Type": "application/json" },
  });
}

export async function POST(
  request: Request,
  { params }: { params: { organisationName: string } }
) {
  const requestContext = getOptionalRequestContext();
  if(!requestContext ) {
    return
  }
  const db = drizzle(requestContext.env.DB, { schema });
  const customer: Customer = await request.json();

  try {
    //get organisation by id
    const organisationId = await getOrganisationId(params.organisationName);
    if (!organisationId) return;

    const addressId = uuidv4();
    const id = uuidv4();

    const customerAddress: InsertAddress = customer.address;

    await db.insert(address).values({
      ...customerAddress,
      id: addressId,
    });

    const [newCustomer] = await db
      .insert(customers)
      .values({
        ...customer,
        id,
        addressId,
        organisationId,
      })
      .returning();
    return new Response(
      JSON.stringify({
        message: "Klant succesvol aangemaakt",
        description: `"${newCustomer.firstName} ${newCustomer.lastName}" is aangemaakt`,
        success: true,
        data: newCustomer,
      }),
      {
        headers: { "Content-Type": "application/json" },
      }
    );
  } catch (error) {
    return new Response(
      JSON.stringify({
        message: "Fout bij het aanmaken van de klant",
        description: `${customer.firstName} ${customer.lastName}" kon niet worden aangemaakt`,
        success: false,
      }),
      {
        headers: { "Content-Type": "application/json" },
      }
    );
  } finally {
    // Revalidate cache
    revalidatePath(`/${params.organisationName}/customers`);
  }
}

@dario-piotrowicz
Copy link
Member

@dario-piotrowicz still the same error: Error: failed to retrieve the Cloudflare request context When using the following:

Sorry for doubting you but the code path in getOptionalRequestContext doesn't include the error at all, so if you were to use only that I think it's not really possible to get the "failed to retrieve the Cloudflare request context" error 😕

export function getOptionalRequestContext<
CfProperties extends Record<string, unknown> = IncomingRequestCfProperties,
Context = ExecutionContext,
>(): undefined | RequestContext<CfProperties, Context> {
const cloudflareRequestContext = (
globalThis as unknown as {
[cloudflareRequestContextSymbol]:
| RequestContext<CfProperties, Context>
| undefined;
}
)[cloudflareRequestContextSymbol];
if (inferRuntime() === 'nodejs') {
// no matter what, we want to throw if either
// `getRequestContext` or `getOptionalRequestContext`
// is run in the Node.js runtime
throw new Error(dedent`
\`getRequestContext\` and \`getOptionalRequestContext\` can only be run
inside the edge runtime, so please make sure to have included
\`export const runtime = 'edge'\` in all the routes using such functions
(regardless of whether they are used directly or indirectly through imports).
`);
}
return cloudflareRequestContext;
}

Are you sure you've avoided getRequestContext in all the code that can run as part of that route (including middlewares for example) and properly built your app?

@dario-piotrowicz
Copy link
Member

@bryandeckers I've tried reproducing the issue but with no luck

I'm afraid that I won't be able to help much unless you can share a minimal reproduction of the issue 😓

Is there any chance you could create one? or somehow share privately your code?


Maybe a bit of a general question but can I define the following at the top of the file "globally"? Because if not I would have to add that requestContext check for every api route times every get,post,put

const { env } = getRequestContext(); const db = drizzle(env.DB, { schema });

Yes, that should be totally fine 🙂

@dario-piotrowicz dario-piotrowicz added the question Further information is requested label Mar 5, 2024
@bryandeckers
Copy link
Author

@bryandeckers I've tried reproducing the issue but with no luck

I'm afraid that I won't be able to help much unless you can share a minimal reproduction of the issue 😓

Is there any chance you could create one? or somehow share privately your code?

Maybe a bit of a general question but can I define the following at the top of the file "globally"? Because if not I would have to add that requestContext check for every api route times every get,post,put
const { env } = getRequestContext(); const db = drizzle(env.DB, { schema });

Yes, that should be totally fine 🙂

I will see if I can ceate a minimal reproduction this weekend, thank you for your answer by the way

@AdamGoodApp
Copy link

I had the same issue and solved it with @dario-piotrowicz recommendation.

import { getOptionalRequestContext } from '@cloudflare/next-on-pages'

export const d1 = getOptionalRequestContext()?.env.DB;
const db = d1 ? drizzle(d1, { schema: { ...users, ...projects, ...userOnProjects } }) : null;

@alienkarma
Copy link

I was struggling a bit trying to resolve the "ERR_PACKAGE_PATH_NOT_EXPORTED" error from "@cloudflare/next-on-pages" package.

But this solution weirdly helped, by creating an extra file referencing it as another variable.

I had the same issue and solved it with @dario-piotrowicz recommendation.

import { getOptionalRequestContext } from '@cloudflare/next-on-pages'

export const d1 = getOptionalRequestContext()?.env.DB;
const db = d1 ? drizzle(d1, { schema: { ...users, ...projects, ...userOnProjects } }) : null;

This is my final code (before it was integrated into my main code)

"use server";

import {
  getRequestContext as grc,
  getOptionalRequestContext as gorc,
} from "@cloudflare/next-on-pages";

export const getRequestContext = grc;
export const getOptionalRequestContext = gorc;

@alienkarma
Copy link

This is unrelated to the issue thread, but wanted to post an alternate solution if nothing else works for some of you.

I created a wrapper function based on Cloudflare's API that you can use to directly read/write to the KV store.

https://www.npmjs.com/package/cloudflare-kv-wrapper

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug Something isn't working question Further information is requested
Projects
None yet
Development

No branches or pull requests

4 participants