@somewhere-cloud/cli 0.38.153 → 0.38.155

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.
Files changed (147) hide show
  1. package/CHANGELOG.md +11 -0
  2. package/dist/docs/adopt.md +39 -0
  3. package/dist/docs/analytics.md +161 -0
  4. package/dist/docs/api-reference.md +339 -0
  5. package/dist/docs/api-surface.md +2067 -0
  6. package/dist/docs/app-mcp.md +162 -0
  7. package/dist/docs/architecture-patterns.md +334 -0
  8. package/dist/docs/auth-client.md +531 -0
  9. package/dist/docs/billing.md +76 -0
  10. package/dist/docs/browser.md +639 -0
  11. package/dist/docs/calendar.md +298 -0
  12. package/dist/docs/changes.md +323 -0
  13. package/dist/docs/cli.md +407 -0
  14. package/dist/docs/common-mistakes.md +199 -0
  15. package/dist/docs/connect-agent.md +72 -0
  16. package/dist/docs/cors.md +114 -0
  17. package/dist/docs/cron.md +167 -0
  18. package/dist/docs/database-engine.md +167 -0
  19. package/dist/docs/declared-data.md +1656 -0
  20. package/dist/docs/declared-files.md +475 -0
  21. package/dist/docs/deploy-intelligence.md +188 -0
  22. package/dist/docs/deploy.md +733 -0
  23. package/dist/docs/design-system.md +273 -0
  24. package/dist/docs/dev-environments.md +496 -0
  25. package/dist/docs/domain-ownership.md +31 -0
  26. package/dist/docs/domains.md +370 -0
  27. package/dist/docs/feedback.md +88 -0
  28. package/dist/docs/file-tools.md +116 -0
  29. package/dist/docs/functions.md +489 -0
  30. package/dist/docs/getting-started.md +238 -0
  31. package/dist/docs/github.md +95 -0
  32. package/dist/docs/google-calendar.md +212 -0
  33. package/dist/docs/groups.md +836 -0
  34. package/dist/docs/guarantees.md +58 -0
  35. package/dist/docs/handled-for-you.md +224 -0
  36. package/dist/docs/inspect.md +171 -0
  37. package/dist/docs/limits.md +68 -0
  38. package/dist/docs/live-data.md +197 -0
  39. package/dist/docs/live.md +92 -0
  40. package/dist/docs/local-dev.md +30 -0
  41. package/dist/docs/migration-supabase.md +58 -0
  42. package/dist/docs/payments.md +1102 -0
  43. package/dist/docs/portability.md +194 -0
  44. package/dist/docs/postgres.md +301 -0
  45. package/dist/docs/pricing-comparison.md +42 -0
  46. package/dist/docs/pricing.md +39 -0
  47. package/dist/docs/project-groups.md +107 -0
  48. package/dist/docs/projects.md +380 -0
  49. package/dist/docs/recipe-ai-agent.md +112 -0
  50. package/dist/docs/recipe-ai-features.md +227 -0
  51. package/dist/docs/recipe-ai-receipts.md +783 -0
  52. package/dist/docs/recipe-background-jobs.md +369 -0
  53. package/dist/docs/recipe-booking.md +348 -0
  54. package/dist/docs/recipe-csv-import.md +390 -0
  55. package/dist/docs/recipe-ecommerce.md +127 -0
  56. package/dist/docs/recipe-email.md +282 -0
  57. package/dist/docs/recipe-escalation.md +133 -0
  58. package/dist/docs/recipe-file-uploads.md +159 -0
  59. package/dist/docs/recipe-import-app.md +110 -0
  60. package/dist/docs/recipe-login.md +457 -0
  61. package/dist/docs/recipe-multi-chat.md +198 -0
  62. package/dist/docs/recipe-paid-api.md +161 -0
  63. package/dist/docs/recipe-pdfs.md +205 -0
  64. package/dist/docs/recipe-push-notifications.md +107 -0
  65. package/dist/docs/recipe-seo.md +200 -0
  66. package/dist/docs/recipe-signed-in-app.md +330 -0
  67. package/dist/docs/render.md +99 -0
  68. package/dist/docs/rooms.md +554 -0
  69. package/dist/docs/sdk.md +287 -0
  70. package/dist/docs/sdks.md +24 -0
  71. package/dist/docs/search.md +199 -0
  72. package/dist/docs/security-model.md +168 -0
  73. package/dist/docs/setup.md +212 -0
  74. package/dist/docs/smoke.md +102 -0
  75. package/dist/docs/speed.md +298 -0
  76. package/dist/docs/sql-compatibility.md +96 -0
  77. package/dist/docs/sw.agent.md +248 -0
  78. package/dist/docs/sw.ai.md +1291 -0
  79. package/dist/docs/sw.auth.md +1811 -0
  80. package/dist/docs/sw.billing.md +171 -0
  81. package/dist/docs/sw.db.md +2128 -0
  82. package/dist/docs/sw.email.md +661 -0
  83. package/dist/docs/sw.endpoint.md +187 -0
  84. package/dist/docs/sw.env.md +303 -0
  85. package/dist/docs/sw.fetch.md +115 -0
  86. package/dist/docs/sw.fs.md +424 -0
  87. package/dist/docs/sw.groups.md +836 -0
  88. package/dist/docs/sw.image.md +69 -0
  89. package/dist/docs/sw.jobs.md +520 -0
  90. package/dist/docs/sw.logs.md +61 -0
  91. package/dist/docs/sw.mail.md +106 -0
  92. package/dist/docs/sw.notifications.md +78 -0
  93. package/dist/docs/sw.push.md +161 -0
  94. package/dist/docs/sw.rateLimit.md +67 -0
  95. package/dist/docs/sw.web.md +128 -0
  96. package/dist/docs/tasks.md +269 -0
  97. package/dist/docs/test.md +220 -0
  98. package/dist/docs/tool-reference-account.md +7 -0
  99. package/dist/docs/tool-reference-ai.md +121 -0
  100. package/dist/docs/tool-reference-analytics.md +37 -0
  101. package/dist/docs/tool-reference-api.md +19 -0
  102. package/dist/docs/tool-reference-artifacts.md +35 -0
  103. package/dist/docs/tool-reference-auth.md +163 -0
  104. package/dist/docs/tool-reference-browser.md +114 -0
  105. package/dist/docs/tool-reference-code.md +26 -0
  106. package/dist/docs/tool-reference-connect.md +21 -0
  107. package/dist/docs/tool-reference-cron.md +48 -0
  108. package/dist/docs/tool-reference-db.md +282 -0
  109. package/dist/docs/tool-reference-domains.md +107 -0
  110. package/dist/docs/tool-reference-email.md +55 -0
  111. package/dist/docs/tool-reference-env.md +19 -0
  112. package/dist/docs/tool-reference-feedback.md +56 -0
  113. package/dist/docs/tool-reference-fs.md +265 -0
  114. package/dist/docs/tool-reference-github.md +57 -0
  115. package/dist/docs/tool-reference-groups.md +85 -0
  116. package/dist/docs/tool-reference-help.md +29 -0
  117. package/dist/docs/tool-reference-jobs.md +39 -0
  118. package/dist/docs/tool-reference-live.md +48 -0
  119. package/dist/docs/tool-reference-logs.md +16 -0
  120. package/dist/docs/tool-reference-payments.md +44 -0
  121. package/dist/docs/tool-reference-project.md +706 -0
  122. package/dist/docs/tool-reference-push.md +78 -0
  123. package/dist/docs/tool-reference-rate-limit.md +18 -0
  124. package/dist/docs/tool-reference-search.md +68 -0
  125. package/dist/docs/tool-reference-security.md +42 -0
  126. package/dist/docs/tool-reference-smoke.md +17 -0
  127. package/dist/docs/tool-reference-stock-photos.md +20 -0
  128. package/dist/docs/tool-reference-tasks.md +73 -0
  129. package/dist/docs/tool-reference-telegram.md +32 -0
  130. package/dist/docs/tool-reference-usage.md +9 -0
  131. package/dist/docs/tool-reference-web.md +71 -0
  132. package/dist/docs/tool-reference-webhooks.md +9 -0
  133. package/dist/docs/troubleshooting.md +411 -0
  134. package/dist/docs/typed-functions.md +94 -0
  135. package/dist/docs/verify-before-deploy.md +67 -0
  136. package/dist/docs/vs-supabase.md +75 -0
  137. package/dist/docs/vs-vercel.md +103 -0
  138. package/dist/lib/bundle.js +303 -221
  139. package/dist/lib/bundle.js.map +3 -3
  140. package/dist/types/lib/test-session.d.ts +8 -0
  141. package/npm-shrinkwrap.json +2 -2
  142. package/package.json +3 -2
  143. package/runtime/DECLARED-DATA-VENDOR.json +5 -5
  144. package/runtime/PLATFORM-SOURCE.json +1 -1
  145. package/runtime/SOURCE-LINT-VENDOR.json +2 -2
  146. package/runtime/declared-data.cjs +37 -19
  147. package/runtime/source-lint.cjs +1 -1
@@ -10,4 +10,4 @@ ${endMarker}`}function scanFileForSecrets(file,source,findings){const findingKey
10
10
  if (!__sw_reMatch(${ROLE_NAME_PATTERN}, roles[i]) || typeof domain !== 'string' || !__sw_reMatch(${EMAIL_DOMAIN_PATTERN}, domain)) return false;
11
11
  }
12
12
  return true;
13
- }`;var EMAIL_DOMAIN=EMAIL_DOMAIN_PATTERN;var GROUP_KEYS=["roles","adminGrantableRoles"];var APP_ROLE_KEYS=["grantableBy","emailDomain","assignedBy"];function readStringList2(r,fail,ctx){const open=r.peek();if(open.kind!=="punct"||open.value!=="[")fail(open.line,`${ctx} must be a list of quoted role names, such as ['viewer'].`);r.next();const out=[];while(!r.tryPunct("]")){const t=r.next();if(t.kind!=="string")fail(t.line,`${ctx} must be a list of quoted role names; found ${t.kind==="eof"?"the end of the file":`"${t.value}"`}. Values must be literal strings.`);out.push(t.value);if(!r.tryPunct(",")){r.expectPunct("]",`closing ${ctx}`);break}}return out}function readGroupRoles(r,fail){r.expectPunct("{","opening schema option groups");const seen=new Set;const out={roles:[],adminGrantableRoles:[]};while(!r.tryPunct("}")){const key=r.readKey("for a groups option");if(!GROUP_KEYS.includes(key.name)){fail(key.line,`groups has an unknown option "${key.name}". Allowed: ${GROUP_KEYS.join(", ")}. owner, admin and member are built in.`)}if(seen.has(key.name))fail(key.line,`groups declares ${key.name} twice.`);seen.add(key.name);r.expectPunct(":",`after groups.${key.name}`);out[key.name]=readStringList2(r,fail,`groups.${key.name}`);if(!r.tryPunct(",")){r.expectPunct("}","closing schema option groups");break}}return out}function readAppRoles(r,fail){r.expectPunct("{","opening schema option appRoles");const out=[];while(!r.tryPunct("}")){const key=r.readKey("for an app role name");if(out.some(role2=>role2.name===key.name))fail(key.line,`app role "${key.name}" is declared twice.`);r.expectPunct(":",`after app role "${key.name}"`);r.expectPunct("{",`opening app role "${key.name}", which takes { grantableBy: [...], emailDomain: '...' }`);const role={name:key.name,grantableBy:[]};const seen=new Set;while(!r.tryPunct("}")){const opt=r.readKey(`for an option of app role "${key.name}"`);if(!APP_ROLE_KEYS.includes(opt.name)){fail(opt.line,`app role "${key.name}" has an unknown option "${opt.name}". Allowed: ${APP_ROLE_KEYS.join(", ")}.`)}if(seen.has(opt.name))fail(opt.line,`app role "${key.name}" declares ${opt.name} twice.`);seen.add(opt.name);r.expectPunct(":",`after appRoles.${key.name}.${opt.name}`);if(opt.name==="assignedBy"){const t=r.next();if(t.kind!=="string"||t.value!=="server")fail(t.line,`appRoles.${key.name}.assignedBy must be 'server'.`);role.assignedBy="server"}else if(opt.name==="emailDomain"){const t=r.next();if(t.kind!=="string")fail(t.line,`appRoles.${key.name}.emailDomain must be one quoted domain, such as 'example.com'.`);if(!EMAIL_DOMAIN.test(t.value)){fail(t.line,`appRoles.${key.name}.emailDomain "${t.value}" must be one lowercase domain such as 'example.com': no "@", no wildcard, no scheme or path. Users whose verified email is at exactly that domain hold the role; subdomains are other domains.`)}role.emailDomain=t.value}else{role.grantableBy=readStringList2(r,fail,`appRoles.${key.name}.grantableBy`)}if(!r.tryPunct(",")){r.expectPunct("}",`closing app role "${key.name}"`);break}}out.push(role);if(!r.tryPunct(",")){r.expectPunct("}","closing schema option appRoles");break}}return out.sort((a,b)=>a.name<b.name?-1:a.name>b.name?1:0)}function validateDeclaredRoles(groups,appRoles){const delegation=Object.create(null);for(const role of appRoles??[])delegation[role.name]=role.grantableBy;return[...emailDomainRoleErrors(appRoles??[]),...roleVocabularyErrors({groupRoles:groups?.roles??[],adminGrantableGroupRoles:groups?.adminGrantableRoles??[],appRoles:(appRoles??[]).map(role=>role.name),appRoleDelegation:delegation})]}function emailDomainRoleErrors(appRoles){const errors=[];const byDomain=new Set(appRoles.filter(role=>role.emailDomain!==void 0).map(role=>role.name));for(const role of appRoles){if(role.assignedBy!==void 0&&role.assignedBy!=="server")errors.push(`appRoles.${role.name}.assignedBy must be 'server'.`);if(role.assignedBy&&role.emailDomain)errors.push(`appRoles.${role.name} cannot combine assignedBy and emailDomain.`);if(role.emailDomain!==void 0&&!EMAIL_DOMAIN.test(role.emailDomain))errors.push(`appRoles.${role.name}.emailDomain is not one lowercase domain.`);for(const grantor of role.grantableBy){if(appRoles.some(source=>source.name===grantor&&source.assignedBy))errors.push(`appRoles.${role.name}.grantableBy cannot name server-assigned role "${grantor}".`);if(byDomain.has(grantor)){errors.push(`appRoles.${role.name}.grantableBy names "${grantor}", which is held by email domain. A role held by email domain cannot grant other roles; list a role that is granted explicitly.`)}}}return errors}var STALE_JOB_WINDOW_MS=45*60*1e3;var BINDING_OPERATIONS=["read","create","update","delete"];var ROW_OPERATIONS=["read","update","delete"];var MAX_JOB_BINDING_SECONDS=STALE_JOB_WINDOW_MS/1e3;var NAME=/^[a-z][a-z0-9_]{0,63}$/;var BUILT_IN_GROUP_ROLES2=["admin","member","owner"];var lines=new WeakMap;var byName=list=>list.sort((a,b)=>a.name<b.name?-1:a.name>b.name?1:0);function readString(r,fail,ctx){const t=r.next();if(t.kind!=="string")fail(t.line,`${ctx} must be a quoted literal string.`);return t}function readStrings(r,fail,ctx){const open=r.next();if(open.kind!=="punct"||open.value!=="[")fail(open.line,`${ctx} must be a list of quoted literal strings, such as ['read'].`);const out=[];while(!r.tryPunct("]")){const t=r.next();if(t.kind!=="string")fail(t.line,`${ctx} must be a list of quoted literal strings.`);if(out.some(seen=>seen.value===t.value))fail(t.line,`${ctx} lists "${t.value}" twice.`);out.push(t);if(!r.tryPunct(",")){r.expectPunct("]",`closing ${ctx}`);break}}return out}function readOperations(r,fail,ctx,allowed){const list=readStrings(r,fail,ctx);if(list.length===0)fail(r.peek().line,`${ctx} must name at least one operation.`);for(const t of list){if(!allowed.includes(t.value))fail(t.line,`${ctx} has an unknown operation "${t.value}". Allowed: ${allowed.join(", ")}.`)}const ops=BINDING_OPERATIONS.filter(op=>list.some(t=>t.value===op));if(!ops.includes("read")&&(ops.includes("update")||ops.includes("delete"))){fail(list[0].line,`${ctx} allows ${ops.filter(op=>op!=="create").join(" and ")} without read. Update and delete return the existing row, so they also need read; create alone is allowed because it returns only the row it created.`)}return ops}function readNamed(r,fail,option,kind,keys,readField){r.expectPunct("{",`opening schema option ${option}`);const out=[];while(!r.tryPunct("}")){const key=r.readKey(`for a ${kind} name`);if(!NAME.test(key.name))fail(key.line,`${kind} name "${key.name}" must be lowercase letters, digits and underscores, starting with a letter (at most 64).`);if(out.some(entry=>entry.name===key.name))fail(key.line,`${kind} "${key.name}" is declared twice.`);r.expectPunct(":",`after ${kind} "${key.name}"`);r.expectPunct("{",`opening ${kind} "${key.name}"`);const fields={};const fieldLines={"":key.line};const seen=new Set;while(!r.tryPunct("}")){const opt=r.readKey(`for an option of ${kind} "${key.name}"`);if(!keys.includes(opt.name))fail(opt.line,`${kind} "${key.name}" has an unknown option "${opt.name}". Allowed: ${keys.join(", ")}.`);if(seen.has(opt.name))fail(opt.line,`${kind} "${key.name}" declares ${opt.name} twice.`);seen.add(opt.name);r.expectPunct(":",`after ${option}.${key.name}.${opt.name}`);fieldLines[opt.name]=r.peek().line;readField(opt.name,fields,key.name);if(!r.tryPunct(",")){r.expectPunct("}",`closing ${kind} "${key.name}"`);break}}const missing=keys.filter(k=>!seen.has(k));if(missing.length)fail(key.line,`${kind} "${key.name}" is missing ${missing.join(", ")}.`);lines.set(fields,fieldLines);out.push({name:key.name,line:key.line,fields});if(!r.tryPunct(",")){r.expectPunct("}",`closing schema option ${option}`);break}}return out}function readPaymentBindings(r,fail){const entries2=readNamed(r,fail,"payments","payment binding",["table","amount","currency","onPaid"],(key,fields,name)=>{if(key!=="onPaid"){fields[key]=readString(r,fail,`payments.${name}.${key}`).value.toLowerCase();return}r.expectPunct("{",`opening payments.${name}.onPaid, which takes one transition: { status: { from: [...], to: '...' } }`);const column=r.readKey(`for the status column in payments.${name}.onPaid`);r.expectPunct(":",`after payments.${name}.onPaid.${column.name}`);r.expectPunct("{",`opening payments.${name}.onPaid.${column.name}, which takes { from: [...], to: '...' }`);const transition={};while(!r.tryPunct("}")){const opt=r.readKey(`for an option of payments.${name}.onPaid.${column.name}`);if(opt.name!=="from"&&opt.name!=="to")fail(opt.line,`payments.${name}.onPaid.${column.name} has an unknown option "${opt.name}". Allowed: from, to.`);if(transition[opt.name])fail(opt.line,`payments.${name}.onPaid.${column.name} declares ${opt.name} twice.`);r.expectPunct(":",`after ${opt.name}`);if(opt.name==="from")transition.from=readStrings(r,fail,`payments.${name}.onPaid.${column.name}.from`);else transition.to=readString(r,fail,`payments.${name}.onPaid.${column.name}.to`);if(!r.tryPunct(",")){r.expectPunct("}",`closing payments.${name}.onPaid.${column.name}`);break}}if(!transition.from||!transition.to)fail(column.line,`payments.${name}.onPaid.${column.name} needs both from and to.`);r.tryPunct(",");if(!r.tryPunct("}")){const extra=r.peek();fail(extra.line,`payments.${name}.onPaid declares one status transition only; this one has a second entry. Other paid effects run from the signed payment event.`)}const values=[...transition.from,transition.to];for(const t of values){if(t.value.length<1||t.value.length>64||/[\u0000-\u001f]/.test(t.value))fail(t.line,`payments.${name}.onPaid.${column.name} status values must be 1 to 64 characters, without control characters.`)}if(transition.from.length===0)fail(column.line,`payments.${name}.onPaid.${column.name}.from must list at least one unpaid state.`);if(transition.from.some(t=>t.value===transition.to.value))fail(transition.to.line,`payments.${name}.onPaid.${column.name}.to must differ from every from state.`);fields.status={column:column.name.toLowerCase(),from:transition.from.map(t=>t.value).sort(),to:transition.to.value}});return byName(entries2.map(({name,fields})=>{const binding={name,...fields};lines.set(binding,lines.get(fields));return binding}))}function readJobBindings(r,fail){const entries2=readNamed(r,fail,"jobs","job binding",["table","operations","maxDurationSeconds"],(key,fields,name)=>{if(key==="table")fields.table=readString(r,fail,`jobs.${name}.table`).value.toLowerCase();else if(key==="operations")fields.operations=readOperations(r,fail,`jobs.${name}.operations`,ROW_OPERATIONS);else{const t=r.next();if(t.kind!=="number"||!/^[1-9][0-9]{0,9}$/.test(t.value)||Number(t.value)>MAX_JOB_BINDING_SECONDS){fail(t.line,`jobs.${name}.maxDurationSeconds must be a whole number of seconds from 1 to ${MAX_JOB_BINDING_SECONDS}: how long the row grant lasts from the job's scheduled start, retries included.`)}fields.maxDurationSeconds=Number(t.value)}});return byName(entries2.map(({name,fields})=>{const binding={name,...fields};lines.set(binding,lines.get(fields));return binding}))}function readServiceRoles(r,fail){const entries2=readNamed(r,fail,"serviceRoles","service role",["tables"],(_key,fields,name)=>{r.expectPunct("{",`opening serviceRoles.${name}.tables, which takes { table: ['read', ...] }`);const tables=[];const tableLines={};while(!r.tryPunct("}")){const t=r.readKey(`for a table in serviceRoles.${name}.tables`);const table=t.name.toLowerCase();if(tables.some(entry=>entry.table===table))fail(t.line,`serviceRoles.${name}.tables names "${t.name}" twice.`);r.expectPunct(":",`after serviceRoles.${name}.tables.${t.name}`);tables.push({table,operations:readOperations(r,fail,`serviceRoles.${name}.tables.${t.name}`,BINDING_OPERATIONS)});tableLines[table]=t.line;if(!r.tryPunct(",")){r.expectPunct("}",`closing serviceRoles.${name}.tables`);break}}if(tables.length===0)fail(r.peek().line,`serviceRoles.${name}.tables must grant at least one table.`);fields.tables=tables.sort((a,b)=>a.table<b.table?-1:a.table>b.table?1:0);lines.set(fields.tables,tableLines)});return byName(entries2.map(({name,fields})=>{const role={name,tables:fields.tables};lines.set(role,lines.get(fields));return role}))}function validateBindings(input,tableInfo,errors){const at2=(entry,field)=>`line ${lines.get(entry)?.[field]??lines.get(entry)?.[""]??0}: `;const rowTable=(entry,kind)=>{const info=tableInfo(entry.table);if(!info){errors.push(`${at2(entry,"table")}${kind} "${entry.name}" names table "${entry.table}", which is not declared in db/schema.ts.`);return null}if(!info.privateUser)errors.push(`${at2(entry,"table")}${kind} "${entry.name}" names table "${entry.table}", whose scope is not owner(), member(), anyOf(), group(), appRole() or parent(). It binds rows a signed-in user holds; other tables are reached from server functions.`);if(!info.key)errors.push(`${at2(entry,"table")}${kind} "${entry.name}" names table "${entry.table}", which needs exactly one id() key.`);return info};const reachesAllOf=node=>!!node&&(node.kind==="all_of"||node.kind==="parent"&&reachesAllOf(node.policy));for(const p of input.payments??[]){const info=rowTable(p,"payment binding");if(!info)continue;if(info.table.scope.kind==="policy"&&reachesAllOf(info.table.scope.policy)){errors.push(`${at2(p,"table")}payment binding "${p.name}" names table "${p.table}", which uses allOf(); payment bindings on allOf tables are not supported yet; such tables are reached from server functions.`);continue}const column=name=>info.table.columns.find(c=>c.name===name);const checks=[["amount",p.amount,"integer","a required integer() column holding the amount in minor units (cents)"],["currency",p.currency,"text","a required text() column holding the currency code"],["onPaid",p.status.column,"text","a required text() status column"]];for(const[field,name,helper,what]of checks){const c=column(name);if(!c){errors.push(`${at2(p,field)}payment binding "${p.name}" names "${name}", which is not a declared column of "${p.table}".`);continue}if(c.helper!==helper||c.nullable)errors.push(`${at2(p,field)}payment binding "${p.name}": "${p.table}"."${name}" must be ${what}.`);if(info.identity.includes(name))errors.push(`${at2(p,field)}payment binding "${p.name}": "${p.table}"."${name}" is the table's access column; a payment never moves a row.`);const writable=[...info.table.client?.create??[],...info.table.client?.update??[],...info.table.client?.intake?.fields??[]];if(writable.includes(name))errors.push(`${at2(p,field)}payment binding "${p.name}": "${p.table}"."${name}" is browser-writable through client.create, client.update or client.intake, and a payment binding requires it not to be; the server sets prices and the payment sets the status.`)}if(new Set([p.amount,p.currency,p.status.column]).size!==3)errors.push(`${at2(p,"")}payment binding "${p.name}" must name three different columns for amount, currency and status.`);const status=column(p.status.column);if(status&&!(status.hasDefault&&typeof status.default==="string"&&p.status.from.includes(status.default))){errors.push(`${at2(p,"onPaid")}payment binding "${p.name}": "${p.table}"."${p.status.column}" must declare a default that is one of its unpaid from states (${p.status.from.join(", ")}), so a new row starts unpaid.`)}}for(const j of input.jobs??[])rowTable(j,"job binding");const taken=new Set([...BUILT_IN_GROUP_ROLES2,...input.groups?.roles??[],...(input.appRoles??[]).map(role=>role.name)]);for(const s of input.serviceRoles??[]){if(taken.has(s.name))errors.push(`${at2(s,"")}service role "${s.name}" has the name of a group or app role. Service roles are a separate namespace for unattended work, so the name must differ.`);const tableLines=lines.get(s.tables)??{};for(const grant of s.tables){if(!tableInfo(grant.table))errors.push(`line ${tableLines[grant.table]??0}: service role "${s.name}" grants table "${grant.table}", which is not declared in db/schema.ts.`)}}}function readSchemaOptions(reader,fail,fileErrors){const o={};if(!reader.tryPunct(",")||reader.peek().kind==="punct"&&reader.peek().value===")")return o;reader.expectPunct("{","opening schema options");while(!reader.tryPunct("}")){const option=reader.readKey("for a schema option");const after=()=>reader.expectPunct(":",`after schema option "${option.name}"`);if(option.name==="files"&&!o.fileCollections){after();o.fileCollections=readFileCollections(reader,fail,fileErrors)}else if(option.name==="groups"&&!o.groupRoles){after();o.groupRoles=readGroupRoles(reader,fail)}else if(option.name==="appRoles"&&!o.appRoles){after();o.appRoles=readAppRoles(reader,fail)}else if(option.name==="payments"&&!o.payments){after();o.payments=readPaymentBindings(reader,fail)}else if(option.name==="jobs"&&!o.jobs){after();o.jobs=readJobBindings(reader,fail)}else if(option.name==="serviceRoles"&&!o.serviceRoles){after();o.serviceRoles=readServiceRoles(reader,fail)}else if(option.name==="search"&&!o.managedSearch){after();const helper=reader.expectIdent('for schema option "search"');if(helper.value!=="owner")fail(helper.line,"search ownership must be declared with owner().");reader.expectPunct("(","after search: owner");reader.expectPunct(")","closing search: owner()");o.managedSearch={kind:"owner"}}else{fail(option.line,`unknown schema option "${option.name}". The schema-level options are search: owner(), files: { \u2026 }, groups: { \u2026 }, appRoles: { \u2026 }, payments: { \u2026 }, jobs: { \u2026 } and serviceRoles: { \u2026 }, each at most once.`)}if(!reader.tryPunct(",")){reader.expectPunct("}","closing schema options");break}}reader.tryPunct(",");return o}function policyOwner(policy){if(policy.kind==="owner")return policy;if(policy.kind==="any_of")return policy.policies.map(policyOwner).find(value=>value!==null)??null;if(policy.kind==="all_of")return policyOwner(policy.who);return null}function scopeOwner(scope){return scope.kind==="owner"?scope:scope.kind==="policy"?policyOwner(scope.policy):null}function declaredOwnerColumn(scope){return scopeOwner(scope)?.column??null}function declaredScopeIdentityColumns(scope){if(scope.kind==="owner")return[scope.column];if(scope.kind==="member")return[...scope.group];if(scope.kind!=="policy")return[];const collect=policy=>policy.kind==="owner"?[policy.column]:policy.kind==="member"?[...policy.group]:policy.kind==="any_of"?policy.policies.flatMap(collect):policy.kind==="all_of"?[...collect(policy.gate),...collect(policy.who)]:policy.kind==="group"?[policy.column]:policy.kind==="app_role"?[]:[policy.via,...policy.author?[policy.author.column]:[]];return[...new Set(collect(scope.policy))]}function declaredTeamColumns(scope){if(scope.kind!=="policy")return[];const p=scope.policy;if(p.kind==="group")return[p.column];if(p.kind==="any_of")return p.policies.flatMap(x=>x.kind==="group"?[x.column]:[]);if(p.kind==="all_of")return p.gate.kind==="group"?[p.gate.column]:[];return[]}var ROOM_REFEREE_PATH=/^\/api\/[A-Za-z0-9_\-]+(?:\/[A-Za-z0-9_\-.]+)*$/;function readRoomsOption(r,rawName,line){r.expectPunct("{",`opening the rooms option of table "${rawName}", which takes { save?: 'column', referee?: '/api/path' }`);const out={line};while(!r.tryPunct("}")){const opt=r.readKey(`for an option of rooms on table "${rawName}"`);if(opt.name!=="save"&&opt.name!=="referee"){throw new SchemaTsError(`line ${opt.line}: rooms on table "${rawName}" has an unknown option "${opt.name}". Allowed: save, referee.`)}if(out[opt.name])throw new SchemaTsError(`line ${opt.line}: rooms on table "${rawName}" declares ${opt.name} twice.`);r.expectPunct(":",`after rooms.${opt.name}`);const t=r.next();if(t.kind!=="string")throw new SchemaTsError(`line ${t.line}: rooms.${opt.name} on table "${rawName}" must be a quoted literal string.`);out[opt.name]={value:t.value,line:t.line};if(!r.tryPunct(",")){r.expectPunct("}",`closing the rooms option of table "${rawName}"`);break}}return out}function validateRoomsOption(input,rawName,nameLine,columns,scope,client,relations){if(columns.filter(c=>c.helper==="id").length!==1){throw new SchemaTsError(`line ${input.line}: table "${rawName}" declares rooms, which need exactly one id() column: a room is attached to one row by its id.`)}const out={};if(input.save){const name=input.save.value.toLowerCase();const column=columns.find(c=>c.name===name);if(!column)throw new SchemaTsError(`line ${input.save.line}: rooms.save on table "${rawName}" names "${input.save.value}", which is not one of its declared columns.`);if(column.helper!=="json")throw new SchemaTsError(`line ${input.save.line}: rooms.save on table "${rawName}" names "${name}", which must be a json() column: the room saves its whole state there.`);if(declaredScopeIdentityColumns(scope).includes(name)||declaredOwnerColumn(scope)===name){throw new SchemaTsError(`line ${input.save.line}: rooms.save on table "${rawName}" names "${name}", which the table's access rule reads; the room's state can never decide who may see the row.`)}if(relations.some(rel=>rel.kind==="belongsTo"&&rel.fk===name)){throw new SchemaTsError(`line ${input.save.line}: rooms.save on table "${rawName}" names "${name}", which is a relation key.`)}const writable=[...client?.create??[],...client?.update??[],...client?.intake?.fields??[]];if(writable.includes(name)){throw new SchemaTsError(`line ${input.save.line}: rooms.save on table "${rawName}" names "${name}", which is browser-writable through client.create, client.update or client.intake. The room is the only writer of its save column; remove it from those lists.`)}out.save=name}if(input.referee){const path=input.referee.value;if(!ROOM_REFEREE_PATH.test(path)||path.length>200||path.split("/").some(part=>part==="."||part==="..")){throw new SchemaTsError(`line ${input.referee.line}: rooms.referee on table "${rawName}" must be the path of one of the app's own functions, such as '/api/game-room'.`)}out.referee=path}void nameLine;return out}var COLUMN_HELPERS=new Set(["id","text","number","integer","bigint","boolean","timestamp","json","blob"]);var SCOPE_HELPERS=new Set(["owner","shared","serverOnly","member","anyOf","allOf","parent","group","appRole","appOwner"]);var TABLE_MARKER_HELPERS=new Set(["removedTable","exported"]);var SCHEMA_CALLABLE=new Set([...COLUMN_HELPERS,...SCOPE_HELPERS,...TABLE_MARKER_HELPERS,"schema","table","grant","removed","hasMany","belongsTo","files"]);var SAFE_IDENT=/^[a-zA-Z_][a-zA-Z0-9_]*$/;var RESERVED_PREFIXES=["app_","sqlite_","d1_","__sw_"];var ROW_HINT_FIELDS=["can","mine"];var MAX_TABLES=100;var MAX_COLUMNS=100;var MAX_INDEXES=40;var MAX_INDEX_COLUMNS=8;var MAX_NAME_LENGTH=64;var MAX_SOURCE_BYTES=256*1024;var DEFAULT_OWNER_COLUMN="user_id";var MEMBER_OPERATIONS=["read","create","update","delete"];var SchemaTsError=class extends Error{};function tokenize(source){const tokens=[];let i=0;let line=1;const n=source.length;while(i<n){const ch=source[i];if(ch==="\n"){line++;i++;continue}if(ch===" "||ch===" "||ch==="\r"){i++;continue}if(ch==="/"&&source[i+1]==="/"){while(i<n&&source[i]!=="\n")i++;continue}if(ch==="/"&&source[i+1]==="*"){i+=2;while(i<n&&!(source[i]==="*"&&source[i+1]==="/")){if(source[i]==="\n")line++;i++}i+=2;continue}if(ch==="`"){throw new SchemaTsError(`line ${line}: template literals are not allowed in db/schema.ts; strings are plain 'single-quoted' strings.`)}if(ch==="'"||ch==='"'){const startLine=line;let value="";i++;let closed=false;while(i<n){const c=source[i];if(c==="\\"){const next=source[i+1];if(next==="'"||next==='"'||next==="\\"){value+=next;i+=2;continue}throw new SchemaTsError(`line ${line}: unsupported escape "\\${next??""}" in a string \u2014 db/schema.ts strings allow only \\', \\" and \\\\.`)}if(c==="\n"){throw new SchemaTsError(`line ${startLine}: unterminated string.`)}if(c===ch){closed=true;i++;break}value+=c;i++}if(!closed)throw new SchemaTsError(`line ${startLine}: unterminated string.`);tokens.push({kind:"string",value,line:startLine});continue}if(/[0-9]/.test(ch)||ch==="-"&&/[0-9]/.test(source[i+1]??"")){let j=i+(ch==="-"?1:0);while(j<n&&/[0-9]/.test(source[j]))j++;if(source[j]==="."){j++;while(j<n&&/[0-9]/.test(source[j]))j++}const text=source.slice(i,j);const num=Number(text);if(!Number.isFinite(num))throw new SchemaTsError(`line ${line}: invalid number "${text}".`);tokens.push({kind:"number",value:text,line});i=j;continue}if(/[A-Za-z_$]/.test(ch)){let j=i;while(j<n&&/[A-Za-z0-9_$]/.test(source[j]))j++;tokens.push({kind:"ident",value:source.slice(i,j),line});i=j;continue}if("(){}[]:,;.=".includes(ch)){tokens.push({kind:"punct",value:ch,line});i++;continue}throw new SchemaTsError(`line ${line}: unexpected character "${ch}". db/schema.ts holds only the schema declaration \u2014 no expressions, operators, or type annotations.`)}tokens.push({kind:"eof",value:"",line});return tokens}var Reader=class{constructor(tokens,options={}){this.tokens=tokens;this.bareIdIsText=table=>!options.legacyIntegerIdDefault&&!options.integerKeyTables?.has(table.toLowerCase())}pos=0;bareIdIsText;peek(){return this.tokens[this.pos]}next(){return this.tokens[this.pos++]}fail(msg){throw new SchemaTsError(`line ${this.peek().line}: ${msg}`)}expectPunct(p,context){const t=this.next();if(t.kind!=="punct"||t.value!==p){throw new SchemaTsError(`line ${t.line}: expected "${p}" ${context}, found ${describeToken(t)}.`)}}tryPunct(p){const t=this.peek();if(t.kind==="punct"&&t.value===p){this.pos++;return true}return false}expectIdent(context){const t=this.next();if(t.kind!=="ident"){throw new SchemaTsError(`line ${t.line}: expected a name ${context}, found ${describeToken(t)}.`)}return t}readKey(context){const t=this.next();if(t.kind==="ident"||t.kind==="string")return{name:t.value,line:t.line};throw new SchemaTsError(`line ${t.line}: expected a name ${context}, found ${describeToken(t)}.`)}readLiteral(context){const t=this.next();if(t.kind==="string")return t.value;if(t.kind==="number")return Number(t.value);if(t.kind==="ident"&&t.value==="true")return true;if(t.kind==="ident"&&t.value==="false")return false;if(t.kind==="ident"&&t.value==="null")return null;throw new SchemaTsError(`line ${t.line}: expected a literal value (string, number, true/false, or null) ${context}, found ${describeToken(t)}. Computed values are not allowed \u2014 the declaration must be readable without running it.`)}readLiteralObject(context){this.expectPunct("{",context);const out=new Map;while(!this.tryPunct("}")){const key=this.readKey(`for an option key ${context}`);this.expectPunct(":",`after "${key.name}" ${context}`);const value=this.readLiteral(`for "${key.name}" ${context}`);if(out.has(key.name))throw new SchemaTsError(`line ${key.line}: option "${key.name}" appears twice ${context}.`);out.set(key.name,{value,line:key.line});if(!this.tryPunct(",")){this.expectPunct("}",context);break}}return out}atEof(){return this.peek().kind==="eof"}};function describeToken(t){if(t.kind==="eof")return"the end of the file";if(t.kind==="string")return`the string '${t.value.slice(0,40)}'`;return`"${t.value}"`}function readClientPermissions(r){r.expectPunct("{","opening client permissions");const out=Object.create(null);while(!r.tryPunct("}")){const key=r.readKey("for a client permission");if(Object.prototype.hasOwnProperty.call(out,key.name))r.fail(`client declares "${key.name}" twice.`);r.expectPunct(":",`after client permission "${key.name}"`);if(key.name==="publicRead"&&r.peek().kind==="punct"&&r.peek().value==="{"){r.expectPunct("{","opening client.publicRead");const whereKey=r.readKey("in client.publicRead");if(whereKey.name!=="where")r.fail("client.publicRead only accepts a where object.");r.expectPunct(":","after client.publicRead.where");out[key.name]={where:Object.fromEntries([...r.readLiteralObject("for client.publicRead.where")].map(([name,item])=>[name,item.value]))};r.tryPunct(",");r.expectPunct("}","closing client.publicRead")}else if(r.tryPunct("[")){const fields=[];while(!r.tryPunct("]")){fields.push(r.readLiteral(`in client.${key.name}`));if(!r.tryPunct(",")){r.expectPunct("]",`closing client.${key.name}`);break}}out[key.name]=fields}else{out[key.name]=["links","intake","target","where"].includes(key.name)&&r.peek().kind==="punct"&&r.peek().value==="{"?readClientPermissions(r):r.readLiteral(`for client.${key.name}`)}if(!r.tryPunct(",")){r.expectPunct("}","closing client permissions");break}}return out}function skipImport(r){r.next();r.expectPunct("{",'after "import"');while(!r.tryPunct("}")){r.expectIdent("inside the import list");if(!r.tryPunct(",")){r.expectPunct("}","closing the import list");break}}const from=r.expectIdent("after the import list");if(from.value!=="from")throw new SchemaTsError(`line ${from.line}: expected "from" after the import list.`);const src=r.next();if(src.kind!=="string")throw new SchemaTsError(`line ${src.line}: expected a module name string after "from".`);r.tryPunct(";")}function checkDeclaredName(kind,raw,line){if(raw.length>MAX_NAME_LENGTH){throw new SchemaTsError(`line ${line}: ${kind} name "${raw.slice(0,40)}\u2026" is longer than ${MAX_NAME_LENGTH} characters.`)}if(!SAFE_IDENT.test(raw)){throw new SchemaTsError(`line ${line}: ${kind} name "${raw}" is invalid. A name is letters, digits, and underscores, starting with a letter or underscore.`)}const name=raw.toLowerCase();if(name.startsWith("_")||RESERVED_PREFIXES.some(p=>name.startsWith(p))){throw new SchemaTsError(`line ${line}: ${kind} name "${raw}" uses a reserved platform prefix and cannot be declared: names starting with "app_" or "_" belong to the platform.`)}if(kind==="Column"&&ROW_HINT_FIELDS.includes(name)){throw new SchemaTsError(`line ${line}: column name "${raw}" is reserved for row hints: a read with { can: true } returns can and mine on every row, so a column cannot take either name.`)}return name}function readColumn(r,tableName,rawName,line){const helperTok=r.expectIdent(`for column "${tableName}"."${rawName}"`);const helper=helperTok.value;if(helper==="removed"){r.expectPunct("(",'after "removed"');r.expectPunct(")",`closing removed() on "${tableName}"."${rawName}" \u2014 the removal marker takes no options`);return{kind:"removed",name:checkDeclaredName("Column",rawName,line)}}if(TABLE_MARKER_HELPERS.has(helper)){throw new SchemaTsError(`line ${helperTok.line}: "${tableName}"."${rawName}" uses ${helper}(), which marks a whole table, not a column. Removing columns from the live database is not supported yet, so "${rawName}" stays declared with its column type.`)}if(!COLUMN_HELPERS.has(helper)){throw new SchemaTsError(`line ${helperTok.line}: unknown column type "${helper}" on "${tableName}"."${rawName}". Column types are id, text, number, integer, bigint, boolean, timestamp, json, and blob.`)}r.expectPunct("(",`after "${helper}"`);let opts=new Map;if(!r.tryPunct(")")){opts=r.readLiteralObject(`in ${helper}() options for "${tableName}"."${rawName}"`);r.tryPunct(",");r.expectPunct(")",`closing ${helper}()`)}const name=checkDeclaredName("Column",rawName,line);const col={name,helper,uuid:helper==="id"&&r.bareIdIsText(tableName),nullable:false,hasDefault:false,default:null,autoNow:false,unique:false,references:null,onDelete:"restrict",renamedFrom:null};const allowed=helper==="id"?new Set(["uuid"]):new Set(["nullable","default","unique","references","onDelete","renamedFrom"]);for(const[key,{value,line:optLine}]of opts){if(!allowed.has(key)){throw new SchemaTsError(`line ${optLine}: ${helper}() on "${tableName}"."${rawName}" has an unknown option "${key}". Allowed: ${[...allowed].join(", ")}.`)}switch(key){case"uuid":if(typeof value!=="boolean")throw new SchemaTsError(`line ${optLine}: "uuid" must be true or false.`);col.uuid=value;break;case"nullable":if(typeof value!=="boolean")throw new SchemaTsError(`line ${optLine}: "nullable" must be true or false.`);col.nullable=value;break;case"unique":if(typeof value!=="boolean")throw new SchemaTsError(`line ${optLine}: "unique" must be true or false.`);col.unique=value;break;case"default":{const t=col.helper;if(t==="timestamp"&&value==="now"){col.autoNow=true;break}const okType=value===null||t==="boolean"&&typeof value==="boolean"||(t==="number"||t==="integer")&&typeof value==="number"||(t==="text"||t==="timestamp"||t==="json"||t==="bigint")&&typeof value==="string";if(!okType){throw new SchemaTsError(`line ${optLine}: the default for "${tableName}"."${rawName}" (${t}) must be ${t==="boolean"?"true or false":t==="number"||t==="integer"?"a number":t==="bigint"?"a whole number written as a string, like '9007199254740993'":t==="blob"?"omitted \u2014 blob columns cannot declare a default":"a string"} or null.`)}if(t==="integer"&&typeof value==="number"&&!Number.isSafeInteger(value)){throw new SchemaTsError(Number.isInteger(value)?`line ${optLine}: the default for integer column "${tableName}"."${rawName}" is outside JavaScript's exact whole-number range (\xB19007199254740991); a bigint() column takes such a default written as a string.`:`line ${optLine}: the default for integer column "${tableName}"."${rawName}" must be a whole number.`)}if(t==="bigint"&&typeof value==="string"&&!isCanonicalBigintText(value)){throw new SchemaTsError(`line ${optLine}: the default for bigint column "${tableName}"."${rawName}" must be a whole number between -9223372036854775808 and 9223372036854775807, written as a string with no sign other than a leading minus and no leading zeros.`)}col.hasDefault=true;col.default=value;break}case"references":if(typeof value!=="string"||!SAFE_IDENT.test(value)){throw new SchemaTsError(`line ${optLine}: "references" must be the name of a table declared in this file.`)}col.references=value.toLowerCase();break;case"onDelete":if(value!=="cascade"&&value!=="restrict"){throw new SchemaTsError(`line ${optLine}: "onDelete" must be 'cascade' or 'restrict'.`)}col.onDelete=value;break;case"renamedFrom":if(typeof value!=="string"||!SAFE_IDENT.test(value)||value.length>MAX_NAME_LENGTH){throw new SchemaTsError(`line ${optLine}: "renamedFrom" on "${tableName}"."${rawName}" must be the previous column name.`)}col.renamedFrom=value.toLowerCase();break}}if(col.renamedFrom===col.name){throw new SchemaTsError(`line ${line}: "${tableName}"."${rawName}" declares renamedFrom: '${col.renamedFrom}' \u2014 that is its own name. A rename needs the OLD name there.`)}if(col.onDelete==="cascade"&&!col.references){throw new SchemaTsError(`line ${line}: "onDelete" on "${tableName}"."${rawName}" needs "references" on the same column.`)}if(col.hasDefault&&col.default===null){if(!col.nullable){throw new SchemaTsError(`line ${line}: "${tableName}"."${rawName}" is required but declares { default: null } \u2014 a required column can never hold null. It is accepted with a non-null default or { nullable: true }.`)}col.hasDefault=false}return{kind:"column",column:col}}function readColumnOrColumnList(r,ctx){if(r.tryPunct("[")){const out=[];while(!r.tryPunct("]")){const t2=r.next();if(t2.kind!=="string"){throw new SchemaTsError(`line ${t2.line}: ${ctx} must be quoted column names.`)}out.push(t2.value.toLowerCase());if(!r.tryPunct(",")){r.expectPunct("]",`closing ${ctx}`);break}}return out}const t=r.next();if(t.kind!=="string"){throw new SchemaTsError(`line ${t.line}: ${ctx} must be a quoted column name, or a list of them for a composite key.`)}return[t.value.toLowerCase()]}function readSingleColumn(r,ctx){const t=r.next();if(t.kind!=="string"){throw new SchemaTsError(`line ${t.line}: ${ctx} must be a single quoted column name.`)}return t.value.toLowerCase()}function validateMemberColumns(names,optionLabel,tableName,line){const seen=new Set;for(const name of names){if(!SAFE_IDENT.test(name)||name.length>MAX_NAME_LENGTH){throw new SchemaTsError(`line ${line}: member(${optionLabel}) on table "${tableName}" names an invalid column "${name}".`)}if(seen.has(name)){throw new SchemaTsError(`line ${line}: member(${optionLabel}) on table "${tableName}" lists "${name}" twice.`)}seen.add(name)}}function readMemberOperations(r,tableName){r.expectPunct("[",`for member({ operations }) on table "${tableName}"`);const seen=new Set;while(!r.tryPunct("]")){const token=r.next();if(token.kind!=="string"||!MEMBER_OPERATIONS.includes(token.value)){throw new SchemaTsError(`line ${token.line}: member({ operations }) on table "${tableName}" only accepts 'read', 'create', 'update', and 'delete'.`)}seen.add(token.value);if(!r.tryPunct(",")){r.expectPunct("]",`closing member({ operations }) on table "${tableName}"`);break}}const normalized=MEMBER_OPERATIONS.filter(operation=>seen.has(operation));return normalized.length===MEMBER_OPERATIONS.length?void 0:normalized}function readMemberScope(r,tableName,scopeLine){r.expectPunct("{",`in member() options for table "${tableName}" \u2014 member() needs { group, membership, member_user, member_group }`);let group=null;let membership=null;let memberUser=null;let memberGroup=null;let operations,operationsSeen=false;let selector;let read;while(!r.tryPunct("}")){const key=r.readKey(`for a member() option of table "${tableName}"`);r.expectPunct(":",`after "${key.name}" in member() for table "${tableName}"`);if(key.name==="group"){group=readColumnOrColumnList(r,`member({ group }) on table "${tableName}"`)}else if(key.name==="membership"){membership=readSingleColumn(r,`member({ membership }) on table "${tableName}"`)}else if(key.name==="member_user"){memberUser=readSingleColumn(r,`member({ member_user }) on table "${tableName}"`)}else if(key.name==="member_group"){memberGroup=readColumnOrColumnList(r,`member({ member_group }) on table "${tableName}"`)}else if(key.name==="operations"){if(operationsSeen)throw new SchemaTsError(`line ${key.line}: member() on table "${tableName}" declares operations more than once.`);operationsSeen=true;operations=readMemberOperations(r,tableName)}else if(key.name==="where"){if(selector)throw new SchemaTsError("member() declares where more than once.");r.expectPunct("{","opening member where");const column=r.readKey("member where column").name;validateMemberColumns([column],"where",tableName,key.line);r.expectPunct(":","after member where column");let value;if(r.tryPunct("[")){const list=[];while(!r.tryPunct("]")){list.push(r.readLiteral("member where value"));if(!r.tryPunct(",")){r.expectPunct("]","closing member where list");break}}value=list}else value=r.readLiteral("member where literal");const values=typeof value==="string"?[value]:value;if(!Array.isArray(values)||!values.length||values.some(v=>typeof v!=="string"))throw new SchemaTsError("member where needs one text column and a nonempty string literal or list.");r.tryPunct(",");r.expectPunct("}","member where accepts exactly one column");selector={column,values:[...new Set(values)].sort()}}else if(key.name==="read"){if(read)throw new SchemaTsError(`line ${key.line}: member() on table "${tableName}" declares read more than once.`);read=readBranchReadColumns(r,`member({ read }) on table "${tableName}"`)}else{throw new SchemaTsError(`line ${key.line}: member() on table "${tableName}" has an unknown option "${key.name}". Allowed: group, membership, member_user, member_group, operations, read.`)}if(!r.tryPunct(",")){r.expectPunct("}",`closing member() options for table "${tableName}"`);break}}const missing=[];if(!group)missing.push("group");if(!membership)missing.push("membership");if(!memberUser)missing.push("member_user");if(!memberGroup)missing.push("member_group");if(missing.length>0||!group||!membership||!memberUser||!memberGroup){throw new SchemaTsError(`line ${scopeLine}: member() on table "${tableName}" is missing ${missing.join(", ")}. It needs member({ group, membership, member_user, member_group }) \u2014 group and member_group name the group-key columns on this table and on the membership table.`)}validateMemberColumns(group,"group",tableName,scopeLine);validateMemberColumns([membership],"membership",tableName,scopeLine);validateMemberColumns([memberUser],"member_user",tableName,scopeLine);validateMemberColumns(memberGroup,"member_group",tableName,scopeLine);if(group.length>MAX_INDEX_COLUMNS){throw new SchemaTsError(`line ${scopeLine}: member({ group }) on table "${tableName}" lists ${group.length} columns (max ${MAX_INDEX_COLUMNS}).`)}if(group.length!==memberGroup.length){throw new SchemaTsError(`line ${scopeLine}: member() on table "${tableName}" has a ${group.length}-column group but a ${memberGroup.length}-column member_group. The group key must have the same number of columns on both sides.`)}const node={kind:"member",group,membership,memberUser,memberGroup,...selector?{restriction:{...selector,operations:operations??[...MEMBER_OPERATIONS]}}:{},...operations!==void 0?{operations}:{},...read?{read}:{}};if(operationsSeen)explicitMemberOperations.add(node);return node}var explicitMemberOperations=new WeakSet;function readPolicyOwner(r,tableName,line){r.expectPunct("(",'after "owner"');let column=DEFAULT_OWNER_COLUMN;let read;if(!r.tryPunct(")")){r.expectPunct("{",`in owner() inside anyOf() for table "${tableName}"`);const seen=new Set;while(!r.tryPunct("}")){const key=r.readKey(`for an owner() option inside anyOf() for table "${tableName}"`);if(seen.has(key.name))throw new SchemaTsError(`line ${key.line}: option "${key.name}" appears twice in owner() inside anyOf() for table "${tableName}".`);seen.add(key.name);r.expectPunct(":",`after "${key.name}" in owner() inside anyOf() for table "${tableName}"`);if(key.name==="column"){const value=r.readLiteral(`for "column" in owner() inside anyOf() for table "${tableName}"`);if(typeof value!=="string"||!SAFE_IDENT.test(value)||value.length>MAX_NAME_LENGTH){throw new SchemaTsError(`line ${key.line}: owner({ column }) on table "${tableName}" must be a valid column name.`)}column=value.toLowerCase()}else if(key.name==="read"){read=readBranchReadColumns(r,`owner({ read }) on table "${tableName}"`)}else{throw new SchemaTsError(`line ${key.line}: owner() inside anyOf() only allows column and read. Visitor ownership is not part of policy scope.`)}if(!r.tryPunct(",")){r.expectPunct("}",`closing owner() options inside anyOf() for table "${tableName}"`);break}}r.tryPunct(",");r.expectPunct(")","closing owner()")}return{kind:"owner",column,...read?{read}:{}}}function readBranchReadColumns(r,ctx){const open=r.next();if(open.kind!=="punct"||open.value!=="[")throw new SchemaTsError(`line ${open.line}: ${ctx} must be a list of quoted column names, such as ['id', 'subject'].`);const out=[];while(!r.tryPunct("]")){const t=r.next();if(t.kind!=="string"||!SAFE_IDENT.test(t.value)||t.value.length>MAX_NAME_LENGTH)throw new SchemaTsError(`line ${t.line}: ${ctx} must be a list of quoted column names; values must be literal strings.`);const name=t.value.toLowerCase();if(out.includes(name))throw new SchemaTsError(`line ${t.line}: ${ctx} lists "${t.value}" twice.`);out.push(name);if(!r.tryPunct(",")){r.expectPunct("]",`closing ${ctx}`);break}}if(out.length===0)throw new SchemaTsError(`line ${open.line}: ${ctx} must name at least one column; leave read out for every column.`);return out}function refuseBranchRead(node,line,tableName,where){if(node.read)throw new SchemaTsError(`line ${line}: read on ${where} of table "${tableName}" is accepted only on the branches of the table's own anyOf(); it names the columns that branch may read.`)}function readPolicyMember(r,tableName,line){r.expectPunct("(",'after "member"');const scope=readMemberScope(r,tableName,line);r.tryPunct(",");r.expectPunct(")","closing member()");if(scope.kind!=="member")throw new SchemaTsError(`line ${line}: invalid member() policy.`);return scope}var ANY_OF_FORMS="anyOf() accepts exactly one owner() and one member(), grant(), group() or appRole().";function readAnyOfBranch(r,tableName,which){const tok=r.expectIdent(`for the ${which} policy in anyOf() on table "${tableName}"`);const failAt=(at2,message)=>{throw new SchemaTsError(`line ${at2}: ${message}`)};if(tok.value==="owner")return readPolicyOwner(r,tableName,tok.line);if(tok.value==="member")return readPolicyMember(r,tableName,tok.line);if(tok.value==="grant")return readGrantScope(r,tableName,tok.line,failAt);if(tok.value==="group")return readGroupScope(r,tableName,tok.line,failAt);if(tok.value==="appRole")return readAppRoleScope(r,tableName,tok.line,failAt);if(tok.value==="appOwner")return readAppOwnerScope(r,tableName,tok.line,failAt);throw new SchemaTsError(`line ${tok.line}: ${ANY_OF_FORMS}`)}function readAnyOfScope(r,tableName,line){r.expectPunct("(",'after "anyOf"');const firstPolicy=readAnyOfBranch(r,tableName,"first");r.expectPunct(",",`between the two policies in anyOf() on table "${tableName}"`);let secondPolicy=readAnyOfBranch(r,tableName,"second");if(r.tryPunct(",")&&!(r.peek().kind==="punct"&&r.peek().value===")")){const third=readAnyOfBranch(r,tableName,"second");if(secondPolicy.kind!=="member"||third.kind!=="member"||firstPolicy.kind!=="owner")throw new SchemaTsError("Three-branch anyOf accepts owner and two same-relation member branches only.");const a=secondPolicy,b=third;if(JSON.stringify([a.group,a.membership,a.memberUser,a.memberGroup])!==JSON.stringify([b.group,b.membership,b.memberUser,b.memberGroup]))throw new SchemaTsError("Two member branches over different membership relations are not supported.");if(!!a.restriction===!!b.restriction)throw new SchemaTsError("Two member branches need exactly one restricted branch; more than one restricted branch is not supported.");if(a.read||b.read)throw new SchemaTsError("Two member branches cannot declare separate read projections.");const restricted=a.restriction?a:b,ordinary=a.restriction?b:a;const ordinaryOps=ordinary.operations??[...MEMBER_OPERATIONS];if(!ordinaryOps.includes("read")&&(ordinaryOps.includes("update")||ordinaryOps.includes("delete")))throw new SchemaTsError("An unrestricted member update/delete branch must independently include unrestricted read.");const combined=MEMBER_OPERATIONS.filter(op=>ordinaryOps.includes(op)||(restricted.operations??MEMBER_OPERATIONS).includes(op));const narrow=restricted.restriction;secondPolicy={...a,operations:combined,restriction:{...narrow,operations:narrow.operations.filter(op=>!ordinaryOps.includes(op))}};r.tryPunct(",")}r.expectPunct(")","closing anyOf()");const owners=[firstPolicy,secondPolicy].filter(p=>p.kind==="owner");if(owners.length!==1)throw new SchemaTsError(`line ${line}: ${ANY_OF_FORMS}`);const owner=owners[0];const other=firstPolicy.kind==="owner"?secondPolicy:firstPolicy;if(other.kind==="member"&&other.ownerGrant&&owner.column!==DEFAULT_OWNER_COLUMN)throw new SchemaTsError(`line ${line}: grant() requires owner() with managed user_id.`);const otherRead=other;const reads=[owner.read??null,otherRead.read??null];delete owner.read;delete otherRead.read;return{kind:"policy",policy:{kind:"any_of",policies:[owner,other],...reads[0]||reads[1]?{reads}:{}}}}var ALL_OF_FORMS="allOf() takes a gate \u2014 member(), group() or appRole() \u2014 and then owner() or anyOf(owner(), ...).";var ALL_OF_EXPLICIT="allOf needs explicit operations";function readAllOfScope(r,tableName,line){r.expectPunct("(",'after "allOf"');const failAt=(at2,message)=>{throw new SchemaTsError(`line ${at2}: ${message}`)};const gateTok=r.expectIdent(`for the gate in allOf() on table "${tableName}"`);let gate;if(gateTok.value==="member")gate=readPolicyMember(r,tableName,gateTok.line);else if(gateTok.value==="group")gate=readGroupScope(r,tableName,gateTok.line,failAt);else if(gateTok.value==="appRole")gate=readAppRoleScope(r,tableName,gateTok.line,failAt);else if(gateTok.value==="appOwner")gate=readAppOwnerScope(r,tableName,gateTok.line,failAt);else throw new SchemaTsError(`line ${gateTok.line}: ${ALL_OF_FORMS}`);r.expectPunct(",",`between the gate and who in allOf() on table "${tableName}"`);const whoTok=r.expectIdent(`for who in allOf() on table "${tableName}"`);let who;if(whoTok.value==="owner")who=readPolicyOwner(r,tableName,whoTok.line);else if(whoTok.value==="anyOf"){const scope=readAnyOfScope(r,tableName,whoTok.line);if(scope.kind!=="policy")throw new SchemaTsError(`line ${whoTok.line}: ${ALL_OF_FORMS}`);who=scope.policy}else throw new SchemaTsError(`line ${whoTok.line}: ${ALL_OF_FORMS}`);r.tryPunct(",");r.expectPunct(")","closing allOf()");refuseBranchRead(gate,line,tableName,"the gate of allOf()");refuseBranchRead(who,line,tableName,"who in allOf()");if(who.kind==="any_of"&&who.reads)throw new SchemaTsError(`line ${line}: read on a branch of anyOf() inside allOf() on table "${tableName}" is not accepted; per-branch columns belong on the table's own anyOf().`);const x=who.kind==="any_of"?who.policies[1]:null;if(x?.kind==="member"&&x.ownerGrant)throw new SchemaTsError(`line ${line}: grant() belongs in anyOf(owner(), grant()), not allOf().`);for(const node of[gate,...x?[x]:[]]){if(node.kind!=="member")continue;if(!explicitMemberOperations.has(node)){throw new SchemaTsError(`line ${line}: ${ALL_OF_EXPLICIT}: member() inside allOf() on table "${tableName}" must list its operations, such as operations: ['read', 'create', 'update', 'delete'].`)}if(node.operations===void 0)node.operations=[...MEMBER_OPERATIONS]}if(x){const sameMember=x.kind==="member"&&gate.kind==="member"&&x.membership===gate.membership&&x.memberUser===gate.memberUser&&x.group.length===gate.group.length&&x.group.every((column,i)=>column===gate.group[i])&&x.memberGroup.length===gate.memberGroup.length&&x.memberGroup.every((column,i)=>column===gate.memberGroup[i]);const sameGroup=x.kind==="group"&&gate.kind==="group"&&x.column===gate.column;if(x.kind!=="app_role"&&!sameMember&&!sameGroup){throw new SchemaTsError(`line ${line}: allOf() on table "${tableName}": the second branch of who must be appRole() or the gate's own membership \u2014 the same group() column, or the same member() relation, keys and member user.`)}}return{kind:"policy",policy:{kind:"all_of",gate,who}}}function readParentScope(r,tableName,line){r.expectPunct("(",'after "parent"');const where=`parent() options for table "${tableName}"`;r.expectPunct("{",`in ${where}`);let via=null;let authorColumn=null;const actions={};const seen=new Set;while(!r.tryPunct("}")){const key=r.readKey(`for an option key in ${where}`);if(seen.has(key.name))throw new SchemaTsError(`line ${key.line}: option "${key.name}" appears twice in ${where}.`);seen.add(key.name);r.expectPunct(":",`after "${key.name}" in ${where}`);if(key.name==="via"||key.name==="author"){const t=r.next();if(t.kind!=="string"||!SAFE_IDENT.test(t.value)||t.value.length>MAX_NAME_LENGTH){throw new SchemaTsError(key.name==="via"?`line ${t.line}: parent({ via }) on table "${tableName}" must name a valid declared foreign-key column.`:`line ${t.line}: parent({ author }) on table "${tableName}" must name a declared nullable text() column the platform stamps with the row's creator.`)}if(key.name==="via")via={value:t.value.toLowerCase(),line:t.line};else authorColumn={value:t.value.toLowerCase(),line:t.line}}else if(key.name==="update"||key.name==="delete"){const open=r.next();if(open.kind!=="punct"||open.value!=="[")throw new SchemaTsError(`line ${open.line}: parent({ ${key.name} }) on table "${tableName}" lists who may ${key.name} a row: 'author' and/or 'parent', such as ['author', 'parent'].`);const list=[];while(!r.tryPunct("]")){const t=r.next();if(t.kind!=="string"||t.value!=="author"&&t.value!=="parent")throw new SchemaTsError(`line ${t.line}: parent({ ${key.name} }) on table "${tableName}" accepts 'author' (the row's author) and 'parent' (whoever may ${key.name} the parent row).`);if(list.includes(t.value))throw new SchemaTsError(`line ${t.line}: parent({ ${key.name} }) on table "${tableName}" lists '${t.value}' twice.`);list.push(t.value);if(!r.tryPunct(",")){r.expectPunct("]",`closing parent({ ${key.name} })`);break}}if(list.length===0)throw new SchemaTsError(`line ${open.line}: parent({ ${key.name} }) on table "${tableName}" is empty, so nobody could ${key.name} a row. List 'author' and/or 'parent', or leave it out for today's rule ('parent').`);actions[key.name]=["author","parent"].filter(a=>list.includes(a))}else{throw new SchemaTsError(`line ${key.line}: parent() on table "${tableName}" has an unknown option "${key.name}". Allowed: via, author, update, delete.`)}if(!r.tryPunct(",")){r.expectPunct("}",`closing ${where}`);break}}r.tryPunct(",");r.expectPunct(")","closing parent()");if(!via)throw new SchemaTsError(`line ${line}: parent() on table "${tableName}" needs { via: 'foreign_key' }.`);const usesAuthor=[actions.update,actions.delete].some(list=>list?.includes("author"));if(usesAuthor&&!authorColumn)throw new SchemaTsError(`line ${line}: parent() on table "${tableName}" lets 'author' act but declares no author column; add author: 'author_id' (a nullable text() column the platform stamps).`);if(!authorColumn&&(actions.update||actions.delete))throw new SchemaTsError(`line ${line}: parent() on table "${tableName}" lists update or delete without an author column; without author, every operation already follows the parent.`);const author=authorColumn?{column:authorColumn.value,...actions.update?{update:actions.update}:{},...actions.delete?{delete:actions.delete}:{}}:void 0;const sentinel={kind:"parent",via:via.value,table:"",parentKey:"",policy:{kind:"owner",column:""},...author?{author}:{}};rememberParentLine(sentinel,line);return{kind:"policy",policy:sentinel}}function readRelations(r,tableName){r.expectPunct("{",`for "relations" of table "${tableName}"`);const out=[];const seen=new Set;while(!r.tryPunct("}")){const key=r.readKey(`for a relation name of table "${tableName}"`);if(!SAFE_IDENT.test(key.name)||key.name.length>MAX_NAME_LENGTH){throw new SchemaTsError(`line ${key.line}: relation name "${key.name}" on table "${tableName}" is invalid. A name is letters, digits, and underscores, starting with a letter or underscore.`)}const name=key.name.toLowerCase();if(seen.has(name))throw new SchemaTsError(`line ${key.line}: relation "${key.name}" on table "${tableName}" is declared twice.`);seen.add(name);r.expectPunct(":",`after relation "${key.name}" on table "${tableName}"`);const callee=r.expectIdent(`for relation "${key.name}" on table "${tableName}"`);if(callee.value!=="hasMany"&&callee.value!=="belongsTo"){throw new SchemaTsError(`line ${callee.line}: relation "${key.name}" on table "${tableName}" uses "${callee.value}()", which is not supported. Relations are hasMany('child_table', 'foreign_key') and belongsTo('parent_table', 'foreign_key').`)}const kind=callee.value;const side=kind==="hasMany"?"child":"parent";r.expectPunct("(",`after "${kind}"`);const relatedTok=r.next();if(relatedTok.kind!=="string")throw new SchemaTsError(`line ${relatedTok.line}: ${kind}() for relation "${key.name}" on table "${tableName}" needs the ${side} table name as a quoted string first.`);r.expectPunct(",",`after the ${side} table in ${kind}() for relation "${key.name}" on table "${tableName}" \u2014 ${kind}('${side}_table', 'foreign_key')`);const fkTok=r.next();if(fkTok.kind!=="string")throw new SchemaTsError(`line ${fkTok.line}: ${kind}() for relation "${key.name}" on table "${tableName}" needs the foreign-key column as a quoted string second.`);r.tryPunct(",");r.expectPunct(")",`closing ${kind}() for relation "${key.name}" on table "${tableName}"`);const relatedTable=relatedTok.value.toLowerCase();const fk=fkTok.value.toLowerCase();if(!SAFE_IDENT.test(relatedTable)||relatedTable.length>MAX_NAME_LENGTH){throw new SchemaTsError(`line ${relatedTok.line}: ${kind}() ${side} table "${relatedTok.value}" for relation "${key.name}" on table "${tableName}" is not a valid table name.`)}if(!SAFE_IDENT.test(fk)||fk.length>MAX_NAME_LENGTH){throw new SchemaTsError(`line ${fkTok.line}: ${kind}() foreign key "${fkTok.value}" for relation "${key.name}" on table "${tableName}" is not a valid column name.`)}out.push({name,kind,table:relatedTable,fk,parentKey:""});if(!r.tryPunct(",")){r.expectPunct("}",`closing "relations" of table "${tableName}"`);break}}out.sort((a,b)=>a.name<b.name?-1:a.name>b.name?1:0);return out}function readScope(r,tableName){const tok=r.expectIdent(`for the scope of table "${tableName}"`);if(!SCOPE_HELPERS.has(tok.value)){throw new SchemaTsError(`line ${tok.line}: unknown scope "${tok.value}" on table "${tableName}". Table scopes are owner(), group(), appRole(), appOwner(), member(), anyOf(), allOf(), parent(), shared(), and serverOnly().`)}if(tok.value==="anyOf")return readAnyOfScope(r,tableName,tok.line);if(tok.value==="allOf")return readAllOfScope(r,tableName,tok.line);if(tok.value==="parent")return readParentScope(r,tableName,tok.line);const failAt=(line,message)=>{throw new SchemaTsError(`line ${line}: ${message}`)};if(tok.value==="group"||tok.value==="appRole"||tok.value==="appOwner"){const policy=tok.value==="group"?readGroupScope(r,tableName,tok.line,failAt):tok.value==="appOwner"?readAppOwnerScope(r,tableName,tok.line,failAt):readAppRoleScope(r,tableName,tok.line,failAt);refuseBranchRead(policy,tok.line,tableName,`the ${tok.value}() scope`);return{kind:"policy",policy}}if(tok.value==="member"){r.expectPunct("(",'after "member"');const scope=readMemberScope(r,tableName,tok.line);r.tryPunct(",");r.expectPunct(")","closing member()");if(scope.kind==="member")refuseBranchRead(scope,tok.line,tableName,"the member() scope");return scope}r.expectPunct("(",`after "${tok.value}"`);let opts=new Map;if(!r.tryPunct(")")){opts=r.readLiteralObject(`in ${tok.value}() options for table "${tableName}"`);r.tryPunct(",");r.expectPunct(")",`closing ${tok.value}()`)}if(tok.value==="owner"){let column=DEFAULT_OWNER_COLUMN;let visitors=false;for(const[key,{value,line}]of opts){if(key==="visitors"){if(typeof value!=="boolean"){throw new SchemaTsError(`line ${line}: owner({ visitors }) on table "${tableName}" must be true or false.`)}visitors=value;continue}if(key!=="column"){throw new SchemaTsError(`line ${line}: owner() on table "${tableName}" has an unknown option "${key}". Allowed: column, visitors.`)}if(typeof value!=="string"||!SAFE_IDENT.test(value)||value.length>MAX_NAME_LENGTH){throw new SchemaTsError(`line ${line}: owner({ column }) on table "${tableName}" must be a valid column name.`)}column=value.toLowerCase()}return{kind:"owner",column,...visitors?{visitors:true}:{}}}if(opts.size>0){throw new SchemaTsError(`line ${tok.line}: ${tok.value}() on table "${tableName}" takes no options.`)}return tok.value==="shared"?{kind:"shared"}:{kind:"server_only"}}function readColumnLists(r,tableName,optionName){const startLine=r.peek().line;r.expectPunct("[",`for "${optionName}" of table "${tableName}"`);const entries2=[];while(!r.tryPunct("]")){const entryLine=r.peek().line;r.expectPunct("[",`for a "${optionName}" entry of table "${tableName}" (it is a list of column lists, e.g. [['a'], ['b', 'c']])`);const entry=[];while(!r.tryPunct("]")){const t=r.next();if(t.kind!=="string"){throw new SchemaTsError(`line ${t.line}: "${optionName}" columns for table "${tableName}" must be quoted column names.`)}const colName=t.value.toLowerCase();if(entry.includes(colName)){throw new SchemaTsError(`line ${t.line}: a "${optionName}" entry on table "${tableName}" lists "${t.value}" twice.`)}entry.push(colName);if(!r.tryPunct(",")){r.expectPunct("]",`closing a "${optionName}" entry of table "${tableName}"`);break}}if(entry.length===0){throw new SchemaTsError(`line ${entryLine}: a "${optionName}" entry on table "${tableName}" is empty.`)}if(entry.length>MAX_INDEX_COLUMNS){throw new SchemaTsError(`line ${entryLine}: a "${optionName}" entry on table "${tableName}" lists ${entry.length} columns (max ${MAX_INDEX_COLUMNS}).`)}entries2.push({columns:entry,line:entryLine});if(!r.tryPunct(",")){r.expectPunct("]",`closing "${optionName}" of table "${tableName}"`);break}}if(entries2.length>MAX_INDEXES){throw new SchemaTsError(`line ${startLine}: table "${tableName}" declares ${entries2.length} "${optionName}" entries (max ${MAX_INDEXES}).`)}return entries2}function readTable(r,rawName,nameLine){const callee=r.expectIdent(`for table "${rawName}"`);if(callee.value==="removed"){throw new SchemaTsError(`line ${callee.line}: table "${rawName}" uses removed(), which marks a single column; a whole table is removed with ${rawName}: removedTable().`)}if(TABLE_MARKER_HELPERS.has(callee.value)){r.expectPunct("(",`after "${callee.value}"`);r.expectPunct(")",`closing ${callee.value}() on table "${rawName}" \u2014 the marker takes no options`);return{kind:callee.value,name:checkDeclaredName("Table",rawName,nameLine)}}if(callee.value!=="table"){throw new SchemaTsError(`line ${callee.line}: expected table(\u2026) for "${rawName}", found "${callee.value}(".`)}const name=checkDeclaredName("Table",rawName,nameLine);r.expectPunct("(",'after "table"');r.expectPunct("{",`opening the columns of table "${rawName}"`);const columns=[];const removedColumns=[];const seen=new Set;while(!r.tryPunct("}")){const key=r.readKey(`for a column of table "${rawName}"`);r.expectPunct(":",`after column "${key.name}"`);const entry=readColumn(r,rawName,key.name,key.line);const entryName=entry.kind==="column"?entry.column.name:entry.name;if(seen.has(entryName)){throw new SchemaTsError(`line ${key.line}: column "${rawName}"."${key.name}" is declared twice (names are case-insensitive).`)}seen.add(entryName);if(entry.kind==="column")columns.push(entry.column);else removedColumns.push(entry.name);if(!r.tryPunct(",")){r.expectPunct("}",`closing the columns of table "${rawName}"`);break}}if(columns.length===0){throw new SchemaTsError(`line ${nameLine}: table "${rawName}" declares no columns${removedColumns.length>0?" (removal markers do not count \u2014 a table needs at least one kept column, or the whole table marked removedTable())":""}.`)}if(columns.length>MAX_COLUMNS){throw new SchemaTsError(`line ${nameLine}: table "${rawName}" declares ${columns.length} columns (max ${MAX_COLUMNS}).`)}const idCols=columns.filter(c=>c.helper==="id");if(idCols.length>1){throw new SchemaTsError(`line ${nameLine}: table "${rawName}" declares ${idCols.length} id() columns \u2014 a table has at most one.`)}let scope=null;let indexEntries=null;let uniqueEntries=null;let relations=[];let relationsDeclared=false;let clientInput;let roomsInput;let columnOptions;if(r.tryPunct(",")){r.expectPunct("{",`opening the options of table "${rawName}"`);while(!r.tryPunct("}")){const key=r.readKey(`for an option of table "${rawName}"`);r.expectPunct(":",`after "${key.name}"`);if(key.name==="scope"){if(scope)throw new SchemaTsError(`line ${key.line}: table "${rawName}" declares "scope" twice.`);scope=readScope(r,rawName);resolveGrantRowKeys(scope,idCols[0]?.name,rawName,key.line,(at2,message)=>{throw new SchemaTsError(`line ${at2}: ${message}`)})}else if(key.name==="indexes"){if(indexEntries)throw new SchemaTsError(`line ${key.line}: table "${rawName}" declares "indexes" twice.`);indexEntries=readColumnLists(r,rawName,"indexes")}else if(key.name==="unique"){if(uniqueEntries)throw new SchemaTsError(`line ${key.line}: table "${rawName}" declares "unique" twice.`);uniqueEntries=readColumnLists(r,rawName,"unique")}else if(key.name==="relations"){if(relationsDeclared)throw new SchemaTsError(`line ${key.line}: table "${rawName}" declares "relations" twice.`);relationsDeclared=true;relations=readRelations(r,rawName)}else if(key.name==="client"){if(clientInput)throw new SchemaTsError(`line ${key.line}: table "${rawName}" declares "client" twice.`);clientInput=readClientPermissions(r)}else if(key.name==="rooms"){if(roomsInput)throw new SchemaTsError(`line ${key.line}: table "${rawName}" declares "rooms" twice.`);roomsInput=readRoomsOption(r,rawName,key.line)}else if(key.name==="columns"){if(columnOptions)throw new SchemaTsError(`line ${key.line}: table "${rawName}" declares "columns" twice.`);columnOptions=readColumnRules(r,rawName,key.line,(at2,message)=>{throw new SchemaTsError(`line ${at2}: ${message}`)})}else{throw new SchemaTsError(`line ${key.line}: table "${rawName}" has an unknown option "${key.name}". Allowed: scope, indexes, unique, relations, client, rooms, columns.`)}if(!r.tryPunct(",")){r.expectPunct("}",`closing the options of table "${rawName}"`);break}}}r.tryPunct(",");r.expectPunct(")",`closing table("${rawName}")`);scope??={kind:"owner",column:DEFAULT_OWNER_COLUMN};const managedOwner=scopeOwner(scope);if(columns.some(column=>column.name===SHARED_AUTHOR_COLUMN||column.renamedFrom===SHARED_AUTHOR_COLUMN)||removedColumns.includes(SHARED_AUTHOR_COLUMN)||managedOwner?.column===SHARED_AUTHOR_COLUMN){throw new SchemaTsError(`line ${nameLine}: "${SHARED_AUTHOR_COLUMN}" is platform-maintained row authorship and cannot be declared, removed, renamed, or used as a custom owner column.`)}if(managedOwner){const clash=columns.find(c=>c.name===managedOwner.column);if(clash){throw new SchemaTsError(`line ${nameLine}: table "${rawName}" declares the column "${managedOwner.column}", but that is its owner column, which the platform creates and manages, so it is not declared among the columns; owner({ column: '\u2026' }) names a different owner column.`)}if(removedColumns.includes(managedOwner.column)){throw new SchemaTsError(`line ${nameLine}: table "${rawName}" marks its owner column "${managedOwner.column}" as removed(). The owner column carries the table's private scope and cannot be removed while owner() is part of that scope.`)}}const declaredNow=new Set(columns.map(c=>c.name));const renameSources=new Set;for(const c of columns){if(!c.renamedFrom)continue;if(declaredNow.has(c.renamedFrom)){throw new SchemaTsError(`line ${nameLine}: "${rawName}"."${c.name}" declares renamedFrom: '${c.renamedFrom}', but "${c.renamedFrom}" is still declared as a column. A rename replaces the old column, so the old declaration is not accepted alongside it.`)}if(managedOwner&&c.renamedFrom===managedOwner.column){throw new SchemaTsError(`line ${nameLine}: "${rawName}"."${c.name}" declares renamedFrom: '${c.renamedFrom}', but that is the table's owner column, which the platform creates and manages \u2014 it cannot be renamed into an ordinary column.`)}if(removedColumns.includes(c.renamedFrom)){throw new SchemaTsError(`line ${nameLine}: "${rawName}"."${c.renamedFrom}" is marked removed() AND named by renamedFrom on "${c.name}" \u2014 it cannot be both removed and renamed.`)}if(renameSources.has(c.renamedFrom)){throw new SchemaTsError(`line ${nameLine}: two columns of "${rawName}" declare renamedFrom: '${c.renamedFrom}' \u2014 a column can only be renamed to one new name.`)}renameSources.add(c.renamedFrom)}const known=new Set(columns.map(c=>c.name));if(managedOwner)known.add(managedOwner.column);const indexes=[];for(const entry of indexEntries??[]){for(const colName of entry.columns){if(!known.has(colName)){throw new SchemaTsError(`line ${entry.line}: index on table "${rawName}" names "${colName}", which is not one of its declared columns.`)}}indexes.push(entry.columns)}const uniques=[];for(const entry of uniqueEntries??[]){for(const colName of entry.columns){if(!known.has(colName)){throw new SchemaTsError(`line ${entry.line}: a "unique" entry on table "${rawName}" names "${colName}", which is not one of its declared columns.`)}}const single=entry.columns.length===1?columns.find(c=>c.name===entry.columns[0]):void 0;if(single){if(single.helper==="id"){throw new SchemaTsError(`line ${entry.line}: the primary key "${single.name}" on table "${rawName}" is already unique, so a one-column "unique" group on it is not accepted.`)}single.unique=true;continue}if(entry.columns.length<2){throw new SchemaTsError(`line ${entry.line}: the "unique" option on table "${rawName}" lists only "${entry.columns[0]}", the owner column the platform manages, and an owner column cannot be unique on its own. For one row per owner, add kind: text({ default: 'profile' }), keep kind out of client writes, omit it from server writes, and declare unique: [['${entry.columns[0]}', 'kind']].`)}uniques.push(entry.columns)}if(scope.kind==="policy"&&scope.policy.kind==="any_of"&&scope.policy.reads){const key=columns.filter(column=>column.helper==="id").length===1?columns.find(column=>column.helper==="id").name:null;const declared=new Set(columns.map(column=>column.name));scope.policy.reads.forEach((list,i)=>{if(!list)return;const branch=scope.policy.kind==="any_of"?scope.policy.policies[i]:null;const label=branch?.kind==="owner"?"owner()":branch?.kind==="member"?branch.ownerGrant?"grant()":"member()":branch?.kind==="group"?"group()":"appRole()";for(const column of list){if(!declared.has(column))throw new SchemaTsError(`line ${nameLine}: table "${rawName}": ${label} read lists "${column}", which is not one of its declared columns.`)}if(key&&!list.includes(key))throw new SchemaTsError(`line ${nameLine}: table "${rawName}": ${label} read must include the id column "${key}", which every reader needs to page and address rows.`);for(const relation of relations){if(relation.kind==="belongsTo"&&!list.includes(relation.fk))throw new SchemaTsError(`line ${nameLine}: table "${rawName}": ${label} read must include "${relation.fk}", the key relation "${relation.name}" joins by; a reader without it would get an empty relation.`)}})}let client;if(clientInput){if(columns.filter(column=>column.helper==="id").length!==1){throw new SchemaTsError(`line ${nameLine}: table "${rawName}": client operations require exactly one id() column.`)}const branch=scope.kind==="policy"&&scope.policy.kind==="any_of"?scope.policy.policies.find(node=>node.kind==="member"||node.kind==="group"):scope.kind==="policy"&&scope.policy.kind==="all_of"&&(scope.policy.gate.kind==="member"||scope.policy.gate.kind==="group")?scope.policy.gate:void 0;const branchGroup=branch?.kind==="member"?branch.group:branch?.kind==="group"?[branch.column]:void 0;const parsed=parseClientPermissions(clientInput,columns,{...scope,...managedOwner?{column:managedOwner.column}:{},...branchGroup?{group:branchGroup}:{}});if(!parsed.ok)throw new SchemaTsError(`line ${nameLine}: table "${rawName}": ${parsed.message}`);const key=columns.find(column=>column.helper==="id").name;if(Array.isArray(parsed.permissions.read)&&!parsed.permissions.read.includes(key)){throw new SchemaTsError(`line ${nameLine}: table "${rawName}": client.read must include primary key "${key}" for stable pagination.`)}client=parsed.permissions}const rooms=roomsInput?validateRoomsOption(roomsInput,rawName,nameLine,columns,scope,client,relations):void 0;if(scope.kind==="policy"&&scope.policy.kind==="parent"&&scope.policy.author){const authorColumn=scope.policy.author.column;const declared=columns.find(c=>c.name===authorColumn);if(!declared||declared.helper!=="text"||!declared.nullable||declared.hasDefault||declared.renamedFrom){throw new SchemaTsError(`line ${nameLine}: parent({ author: '${authorColumn}' }) on table "${rawName}" must name a declared text({ nullable: true }) column without a default or rename: the platform stamps it with the row's creator, and a row without one grants its author nothing.`)}if(authorColumn===scope.policy.via)throw new SchemaTsError(`line ${nameLine}: parent({ author }) on table "${rawName}" cannot be the parent link "${authorColumn}".`);if(client&&((client.create??[]).includes(authorColumn)||(client.update??[]).includes(authorColumn))){throw new SchemaTsError(`line ${nameLine}: table "${rawName}": "${authorColumn}" is the author the platform stamps, so client.create and client.update cannot list it.`)}}const columnRules=columnOptions?.write;const memberOf=columnOptions?.memberOf;if(memberOf){validateColumnMemberOf(memberOf,{tableName:rawName,nameLine,columns,ownerColumn:managedOwner?.column??null,accessColumns:declaredScopeIdentityColumns(scope),roomSave:rooms?.save??null,groupColumns:declaredTeamColumns(scope)},(at2,message)=>{throw new SchemaTsError(`line ${at2}: ${message}`)})}if(columnRules){validateColumnRules(columnRules,{tableName:rawName,nameLine,declaredColumns:new Set(columns.map(c=>c.name)),ownerColumn:managedOwner?.column??null,accessColumns:declaredScopeIdentityColumns(scope),roomSave:rooms?.save??null,serverOnly:scope.kind==="server_only"},(at2,message)=>{throw new SchemaTsError(`line ${at2}: ${message}`)})}return{kind:"table",table:{name,scope,relations,columns,indexes,uniques,removedColumns:[...removedColumns].sort(),...client?{client}:{},...rooms?{rooms}:{},...columnRules?{columnRules}:{},...memberOf?{memberOf}:{}}}}function extractSchemaTs(source,options={}){if(typeof source!=="string"||source.trim().length===0){return{ok:false,errors:["db/schema.ts is empty. It needs at least one table; without the file, the database is unmanaged."]}}if(source.length>MAX_SOURCE_BYTES){return{ok:false,errors:[`db/schema.ts is larger than ${Math.floor(MAX_SOURCE_BYTES/1024)}KB \u2014 that is not a schema declaration.`]}}try{const r=new Reader(resolveSchemaConstants(tokenize(source),SCHEMA_CALLABLE,MAX_SOURCE_BYTES,(line,message)=>{throw new SchemaTsError(`line ${line}: ${message}`)}),options);while(r.peek().kind==="ident"&&r.peek().value==="import")skipImport(r);const exp=r.expectIdent("to start the declaration");if(exp.value!=="export"){throw new SchemaTsError(`line ${exp.line}: db/schema.ts must contain only the schema declaration: optional imports, optional const declarations, then "export default schema({ \u2026 })". Found "${exp.value}".`)}const def=r.expectIdent('after "export"');if(def.value!=="default")throw new SchemaTsError(`line ${def.line}: expected "default" after "export".`);const schemaTok=r.expectIdent('after "export default"');if(schemaTok.value!=="schema"){throw new SchemaTsError(`line ${schemaTok.line}: expected schema({ \u2026 }) after "export default", found "${schemaTok.value}".`)}r.expectPunct("(",'after "schema"');r.expectPunct("{","opening the schema tables");const tables=[];const removedTables=[];const exportedTables=[];const seen=new Set;const reader=r;while(!reader.tryPunct("}")){const key=reader.readKey("for a table name");reader.expectPunct(":",`after table "${key.name}"`);const entry=readTable(reader,key.name,key.line);const entryName=entry.kind==="table"?entry.table.name:entry.name;if(seen.has(entryName)){throw new SchemaTsError(`line ${key.line}: table "${key.name}" is declared twice (names are case-insensitive).`)}seen.add(entryName);if(entry.kind==="table")tables.push(entry.table);else if(entry.kind==="removedTable")removedTables.push(entryName);else exportedTables.push(entryName);if(!reader.tryPunct(",")){reader.expectPunct("}","closing the schema tables");break}}const fileErrors=[];const fail=(line,message)=>{throw new SchemaTsError(`line ${line}: ${message}`)};const{managedSearch,fileCollections,groupRoles,appRoles:declaredAppRoles,payments,jobs,serviceRoles}=readSchemaOptions(reader,fail,fileErrors);const appOwnerErrors=[];for(const role of declaredAppRoles??[]){if(role.name===APP_OWNER_ROLE_NAME)appOwnerErrors.push(`appRoles declares "${APP_OWNER_ROLE_NAME}", which is built in: use appOwner() in a table's scope for the app's owner.`);if(role.grantableBy.includes(APP_OWNER_ROLE_NAME))appOwnerErrors.push(`appRoles.${role.name}.grantableBy names "${APP_OWNER_ROLE_NAME}". The app's owner holds no grant, so it cannot be a grantor; grant from a function that checks user.is_owner instead.`)}const appRoles=!appOwnerErrors.length&&usesAppOwner(tables)?[...declaredAppRoles??[],{name:APP_OWNER_ROLE_NAME,grantableBy:[]}].sort((a,b)=>a.name<b.name?-1:a.name>b.name?1:0):declaredAppRoles;reader.expectPunct(")","closing schema(\u2026)");reader.tryPunct(";");if(!reader.atEof()){reader.fail(`db/schema.ts must end after "export default schema({ \u2026 })" \u2014 found ${describeToken(reader.peek())}. The file holds only the schema declaration.`)}if(tables.length===0&&removedTables.length===0&&exportedTables.length===0&&!managedSearch&&!fileCollections?.length){return{ok:false,errors:["db/schema.ts declares no tables. It needs at least one table; without the file, the database is unmanaged."]}}if(tables.length>MAX_TABLES){return{ok:false,errors:[`db/schema.ts declares ${tables.length} tables (max ${MAX_TABLES}).`]}}const errors=[...appOwnerErrors];const names=new Set(tables.map(t=>t.name));for(const t of tables){for(const c of t.columns){if(c.references&&!names.has(c.references)){const marked=removedTables.includes(c.references)||exportedTables.includes(c.references);errors.push(marked?`Column "${t.name}"."${c.name}" references "${c.references}", which this file marks ${removedTables.includes(c.references)?"removedTable()":"exported()"}. The table can go only once no column references it (the column marked removed(), or without "references").`:`Column "${t.name}"."${c.name}" references "${c.references}", which is not declared in db/schema.ts. Foreign keys can only target tables in the same declaration.`)}}}const keyOf=new Map(tables.map(t=>[t.name,t.columns.find(c=>c.helper==="id")]));for(const t of tables){for(const c of t.columns){const key=c.references?keyOf.get(c.references):void 0;if(!key)continue;const fits=key.uuid?c.helper==="text":c.helper==="integer"||c.helper==="number";if(fits)continue;errors.push(key.uuid?`Column "${t.name}"."${c.name}" references "${c.references}", whose id() is a random text key, but is declared ${c.helper}(). The column type must match the key: text({ references: '${c.references}' }), or an integer key on "${c.references}" with id({ uuid: false }).`:`Column "${t.name}"."${c.name}" references "${c.references}", whose key is an integer (id({ uuid: false })), but is declared ${c.helper}(). The column type must match the key: integer({ references: '${c.references}' }), or a random text key on "${c.references}" with id().`)}}const tableByName=new Map(tables.map(t=>[t.name,t]));const knownColumns=t=>{const s=new Set(t.columns.map(c=>c.name));const owner=scopeOwner(t.scope);if(owner)s.add(owner.column);return s};const privatePolicy=scope=>{if(scope.kind==="owner"&&!scope.visitors)return{kind:"owner",column:scope.column};if(scope.kind==="member")return scope;if(scope.kind==="policy"&&scope.policy.kind!=="parent")return scope.policy;return null};resolveAppRoleScopes(tables,appRoles,errors);resolveColumnRuleRoles(tables,appRoles,groupRoles,errors);resolveGroupsAndParents(tables,tableByName,privatePolicy,groupRoles,errors);validateDeclaredMemberships(tables,tableByName,knownColumns,errors);validateDeclaredRelations(tables,tableByName,knownColumns,table=>removedTables.includes(table)?"removedTable()":exportedTables.includes(table)?"exported()":null,errors);validateRowLinks(tables,tableByName,errors);validateIntake(tables,tableByName,errors);if(fileCollections){errors.push(...fileErrors);validateFileCollections(fileCollections,name=>{const t=tableByName.get(name);return t?{columns:knownColumns(t),clientWrites:tableAllowsClientWrites(t),parentTarget:fileParentTarget(t)}:null},errors)}if(groupRoles||appRoles)errors.push(...validateDeclaredRoles(groupRoles,appRoles));validateBindings({payments,jobs,serviceRoles,groups:groupRoles,appRoles},name=>{const t=tableByName.get(name);return t?{table:t,key:fileParentTarget(t).key,privateUser:fileParentTarget(t).privateUserPolicy,identity:declaredScopeIdentityColumns(t.scope)}:null},errors);if(errors.length>0)return{ok:false,errors};return{ok:true,declaration:{tables,removedTables:removedTables.sort(),exportedTables:exportedTables.sort(),...managedSearch?{search:managedSearch}:{},...fileCollections?{files:fileCollections}:{},...groupRoles?{groups:groupRoles}:{},...appRoles?{appRoles}:{},...payments?{payments}:{},...jobs?{jobs}:{},...serviceRoles?{serviceRoles}:{}}}}catch(err){if(err instanceof SchemaTsError){return{ok:false,errors:[`db/schema.ts could not be read: ${err.message}`]}}throw err}}var MAX_FILE_BYTES=256*1024;var MAX_PAYLOAD_CHARS=8*1024;var COMPARE_WINDOW=96;var MAX_FINDINGS_PER_FILE=20;var MAX_FINDINGS=100;var IDENT2=/^[A-Za-z_$][\w$]*$/;var WRITE=/\.(insert|update)\(\s*(['"`])([A-Za-z_]\w{0,63})\2\s*,\s*/g;var TX=/\.tx\(/g;var STEP=/\{(?=\s*['"]?(?:op|table)['"]?\s*:)/g;var VERIFIED=/\b(?:verifyInvocation|verifyWebhook|constructEvent|verifySignature)\s*\(/;var VERIFIER_NAMES=new Set(["verifyInvocation","verifyWebhook","constructEvent","verifySignature"]);function hasVerifierCall(source){const tokens=tokenizer2(source,{ecmaVersion:"latest",sourceType:"module"});let previous="";let member=false;for(const token of tokens){const kind=token.type.label;if(member&&kind==="(")return true;member=(previous==="."||previous==="?.")&&kind==="name"&&VERIFIER_NAMES.has(source.slice(token.start,token.end));previous=kind}return false}function stripComments(source){let out="";let i=0;while(i<source.length){const ch=source[i];const next=source[i+1];if(ch==='"'||ch==="'"||ch==="`"){let j=i+1;while(j<source.length&&source[j]!==ch&&!(ch!=="`"&&source[j]==="\n"))j+=source[j]==="\\"?2:1;out+=source.slice(i,j+1);i=j+1}else if(ch==="/"&&next==="/"){while(i<source.length&&source[i]!=="\n"){out+=" ";i++}}else if(ch==="/"&&next==="*"){const end=source.indexOf("*/",i+2);const stop=end<0?source.length:end+2;out+=source.slice(i,stop).replace(/[^\n]/g," ");i=stop}else{out+=ch;i++}}return out}function bindings(source){const b={objects:new Set,paths:new Set,forms:new Set,values:new Set,callers:new Set};const input=String.raw`\(?\s*(?:await\s+)?[\w$.]{1,64}\.(json|formData)\(\)`;for(const m of source.matchAll(new RegExp(String.raw`\b(?:const|let|var)\s+([A-Za-z_$][\w$]*)\s*(?::[^=;\n]{0,200})?=\s*${input}`,"g"))){(m[2]==="formData"?b.forms:b.objects).add(m[1])}const destructure=names=>{for(const part of names.split(",")){const name=part.split("=")[0].split(":").pop()?.trim();if(name&&IDENT2.test(name))b.values.add(name.toLowerCase())}};for(const m of source.matchAll(new RegExp(String.raw`\b(?:const|let|var)\s*\{([^{}]{0,2000})\}\s*(?::[^=;\n]{0,200})?=\s*${input}`,"g")))destructure(m[1]);for(const m of source.matchAll(/\b(?:const|let|var)\s*\{([^{}]{0,2000})\}\s*=\s*([A-Za-z_$][\w$]*)\s*[;\n]/g))if(b.objects.has(m[2]))destructure(m[1]);for(const m of source.matchAll(/\b(?:const|let|var)\s+([A-Za-z_$][\w$]*)\s*=\s*[\w$.]{0,64}(?:searchParams|\bparams)\.get\(/g))b.values.add(m[1].toLowerCase());for(const m of source.matchAll(/\b(?:const|let|var)\s+([A-Za-z_$][\w$]*)\s*(?::[^=;\n]{0,200})?=\s*(?:await\s+)?sw\.auth\.\w{1,40}\(/g))b.callers.add(m[1]);for(const m of source.matchAll(/\b(?:const|let|var)\s*\{([^{}]{0,2000})\}\s*=\s*(?:await\s+)?sw\.auth\.\w{1,40}\(/g)){for(const part of m[1].split(",")){const name=part.split("=")[0].split(":").pop()?.trim();if(name&&IDENT2.test(name))b.callers.add(name)}}if(/\bsw\.endpoint\s*\(/.test(source)){for(const m of source.matchAll(/\bhandler\s*(?::\s*)?(?:async\s*)?(?:function\s*)?\(\s*(?:\{([^{}]{0,400})\}|([A-Za-z_$][\w$]*))/g)){if(m[2]){b.paths.add(m[2]+".body");continue}for(const part of m[1].split(",")){const[key,renamed]=part.split("=")[0].split(":").map(x=>x.trim());const local=renamed||key;if(!local||!IDENT2.test(local))continue;if(key==="body")b.objects.add(local);else if(key==="user")b.callers.add(local)}}}return b}function requestObject(expression,b){const v=expression.trim();return b.objects.has(v)||b.paths.has(v)}function serverReceivers(source){const receivers=["sw.db.server"];for(const m of source.matchAll(/\b(?:const|let|var)\s+([A-Za-z_$][\w$]*)\s*=\s*sw\.db\.server\b(?!\.)/g))receivers.push(m[1]);return receivers}function receivedBy(source,dot,receivers){return receivers.some(receiver=>{const start=dot-receiver.length;return start>=0&&source.startsWith(receiver,start)&&!/[\w$.]/.test(source[start-1]??"")})}function objectLiteral(source,index){if(source[index]!=="{")return null;const end=Math.min(source.length,index+MAX_PAYLOAD_CHARS);let depth=0;let quote=null;for(let i=index;i<end;i++){const ch=source[i];if(quote){if(ch==="\\")i++;else if(ch===quote)quote=null;continue}if(ch==='"'||ch==="'"||ch==="`")quote=ch;else if(ch==="{")depth++;else if(ch==="}"&&--depth===0)return source.slice(index,i+1)}return null}function comparedToCaller(source,lower,column,callers){if(callers.size===0)return false;const needle=`.${column.toLowerCase()}`;const callerId=text=>{for(const m of text.matchAll(/([A-Za-z_$][\w$]*)(?:\??\.[A-Za-z_$][\w$]*){0,3}\??\.id\b/g))if(callers.has(m[1]))return true;for(const m of text.matchAll(/([A-Za-z_$][\w$]*)\??\.(?:userId|user_id)\b/g))if(callers.has(m[1]))return true;return false};for(let at2=lower.indexOf(needle);at2>=0;at2=lower.indexOf(needle,at2+1)){const after=at2+needle.length;if(/[\w$]/.test(lower[after]??""))continue;const owner=/([A-Za-z_$][\w$]*)\??$/.exec(source.slice(Math.max(0,at2-64),at2));if(owner&&callers.has(owner[1]))continue;const right=source.slice(after,after+COMPARE_WINDOW);const op=/^\s*[!=]==?\s*/.exec(right);if(op&&callerId(right.slice(op[0].length)))return true;const left=source.slice(Math.max(0,at2-COMPARE_WINDOW),at2);const lop=/[!=]==?\s*[\w$.?]{0,80}$/.exec(left);if(lop&&callerId(left.slice(0,lop.index).slice(-COMPARE_WINDOW)))return true}return false}function lineIndex(source){const starts=[0];for(let i=source.indexOf("\n");i>=0;i=source.indexOf("\n",i+1))starts.push(i+1);return starts}function lineAt2(starts,offset2){let lo=0,hi=starts.length-1;while(lo<hi){const mid=lo+hi+1>>1;if(starts[mid]<=offset2)lo=mid;else hi=mid-1}return lo+1}function requestValue(value,b){const v=value.trim().replace(/^(?:String|Number|BigInt)\(\s*([\s\S]*?)\s*\)$/,"$1").trim();const member=/^([A-Za-z_$][\w$]*(?:\??\.[A-Za-z_$][\w$]*)?)(?:\??\.[A-Za-z_$][\w$]*|\[[^\]]{1,64}\])$/.exec(v);if(member&&(b.objects.has(member[1])||b.paths.has(member[1].replace("?.","."))))return true;const root=/^([A-Za-z_$][\w$]*)(?:\??\.[A-Za-z_$][\w$]*|\[[^\]]{1,64}\])$/.exec(v);if(root&&b.objects.has(root[1]))return true;const form=/^([A-Za-z_$][\w$]*)\.get\(\s*['"`][\w-]{1,64}['"`]\s*\)$/.exec(v);if(form&&b.forms.has(form[1]))return true;return IDENT2.test(v)&&b.values.has(v.toLowerCase())}function entries(payload){const out=[];let depth=0,quote=null,start=1;const push=end=>{const text=payload.slice(start,end);const lead=text.length-text.trimStart().length;const body=text.trim();if(body){const spread=/^\.\.\.\s*([A-Za-z_$][\w$]*)$/.exec(body);const keyed=/^['"]?([A-Za-z_$][\w$]*)['"]?\s*(?::\s*([\s\S]*))?$/.exec(body);if(spread)out.push({key:null,spread:spread[1],value:"",offset:start+lead});else if(keyed)out.push({key:keyed[1],spread:null,value:keyed[2]??keyed[1],offset:start+lead})}start=end+1};for(let i=1;i<payload.length-1;i++){const ch=payload[i];if(quote){if(ch==="\\")i++;else if(ch===quote)quote=null;continue}if(ch==='"'||ch==="'"||ch==="`")quote=ch;else if("{[(".includes(ch))depth++;else if("}])".includes(ch))depth--;else if(ch===","&&depth===0)push(i)}push(payload.length-1);return out}function requestOwnershipFindings(functions,schema){const findings=[];let skippedFiles=0;let truncated=false;for(const[file,raw]of Object.entries(functions)){if(!file.startsWith("api/")||typeof raw!=="string"||!raw.includes("server"))continue;if(raw.length>MAX_FILE_BYTES){skippedFiles++;continue}if(findings.length>=MAX_FINDINGS){truncated=true;break}const source=stripComments(raw);if(VERIFIED.test(source)){if(/\.[jt]sx$/.test(file)||raw.includes("</")){skippedFiles++}else{try{if(hasVerifierCall(raw)){skippedFiles++;continue}}catch{skippedFiles++}}}const b=bindings(source);if(b.objects.size===0&&b.paths.size===0&&b.forms.size===0&&b.values.size===0)continue;const lower=source.toLowerCase();const receivers=serverReceivers(source);const starts=lineIndex(source);const columnsByTable=new Map;const seen=new Set;let fileCount=0;let fileFull=false;const report=(table,columns,offset2)=>{if(fileCount>=MAX_FINDINGS_PER_FILE||findings.length>=MAX_FINDINGS){truncated=true;fileFull=true;return false}const line=lineAt2(starts,offset2);const key=`${line}\0${table}\0${columns.join(",")}`;if(!seen.has(key)){seen.add(key);fileCount++;findings.push({file,line,table,columns})}return true};const ownershipColumns=table=>{const cached=columnsByTable.get(table);if(cached)return cached;const declared=schema.tables.find(t=>t.name===table);let columns=[];if(declared){const owner=declaredOwnerColumn(declared.scope);if(owner)columns=[owner];else if(declared.scope.kind==="server_only"){columns=declared.columns.map(c=>c.name).filter(name=>comparedToCaller(source,lower,name,b.callers))}}columnsByTable.set(table,columns);return columns};const inspect=(table,kind,at2)=>{const columns=ownershipColumns(table);if(columns.length===0)return;const bare=/^([A-Za-z_$][\w$]*(?:\.[A-Za-z_$][\w$]*)?)\s*[,)}]/.exec(source.slice(at2,at2+80));if(bare&&requestObject(bare[1],b)){report(table,columns,at2);return}const payload=objectLiteral(source,at2);if(!payload){if(source[at2]==="{")truncated=true;return}let list=entries(payload);if(kind==="update"){list=list.flatMap(e=>{if(e.key!=="set"&&e.key!=="where")return[e];const valueAt=payload.indexOf(e.value,e.offset);const inner=valueAt<0?null:objectLiteral(payload,valueAt);return inner?entries(inner).map(x=>({...x,offset:valueAt+x.offset})):[]}).filter(e=>e.key!=="op"&&e.key!=="table")}const spreadIndex=list.findIndex(e=>e.spread!==null&&b.objects.has(e.spread));const spreadColumns=[];for(const column of columns){const keyed=list.map((e,index)=>({e,index})).filter(({e})=>e.key?.toLowerCase()===column);const last=keyed[keyed.length-1];if(last&&requestValue(last.e.value,b))report(table,[last.e.key??column],at2+last.e.offset);else if(spreadIndex>=0&&(!last||last.index<spreadIndex))spreadColumns.push(column)}if(spreadColumns.length>0)report(table,spreadColumns,at2+list[spreadIndex].offset)};for(const m of source.matchAll(WRITE)){if(fileFull)break;if(!receivedBy(source,m.index,receivers))continue;inspect(m[3].toLowerCase(),m[1]==="update"?"update":"insert",m.index+m[0].length)}if(!fileFull&&[...source.matchAll(TX)].some(m=>receivedBy(source,m.index,receivers))){for(const m of source.matchAll(STEP)){if(fileFull)break;const step=objectLiteral(source,m.index);if(!step){truncated=true;continue}const fields=entries(step);const field=key=>fields.find(e=>e.key===key);const op=/^['"`](insert|update)['"`]$/.exec(field("op")?.value.trim()??"")?.[1];const table=/^['"`]([A-Za-z_]\w{0,63})['"`]$/.exec(field("table")?.value.trim()??"")?.[1];if(!op||!table)continue;if(op==="update"){inspect(table.toLowerCase(),"update",m.index);continue}const values=field("values");const valueAt=values?step.indexOf(values.value,values.offset):-1;if(valueAt>=0)inspect(table.toLowerCase(),"insert",m.index+valueAt)}}}return{findings,skippedFiles,truncated}}var MAX_FILE_BYTES2=256*1024;var MAX_FINDINGS_PER_FILE2=20;var MAX_FINDINGS2=100;var SEND=/await\s+sw\s*\.\s*email\s*\.\s*send\s*\(/y;var LOOP_HEADER=/(?:^|[^\w$.])(?:for|while)\s*(?:await\s*)?$/;var BLOCK_HEADER=/(?:^|[^\w$.])(?:if|switch|catch|with)\s*$/;function scanFile(source){const offsets=[];const seenLoops=new Set;const stack=[];let lastParen=null;let quote=null;let lastDoClose=-1;const prevNonSpace=i=>{let j=i-1;while(j>=0&&/\s/.test(source[j]))j--;return j};const nextNonSpace=i=>{let j=i;while(j<source.length&&/\s/.test(source[j]))j++;return j};const popLoopStatements=()=>{while(stack.length&&stack[stack.length-1].kind==="loopstmt")stack.pop()};for(let i=0;i<source.length;i++){const ch=source[i];if(quote){if(ch==="\\")i++;else if(ch===quote||ch==="\n"&&quote!=="`")quote=null;continue}const current2=stack[stack.length-1];if(current2?.kind==="loopstmt"){if(ch==="\n"&&current2.started){stack.pop();continue}if(!/\s/.test(ch))current2.started=true}if(ch==='"'||ch==="'"||ch==="`"){quote=ch;continue}if(ch==="/"){const p=prevNonSpace(i);const before=p<0?"":source[p];if(p<0||"(,=:[!&|?{};+-*%~^".includes(before)||/(?:^|[^\w$])(?:return|typeof|case|in|of|await|yield)$/.test(source.slice(Math.max(0,p-7),p+1))){let j=i+1,inClass=false;for(;j<source.length&&source[j]!=="\n";j++){if(source[j]==="\\"){j++;continue}if(source[j]==="[")inClass=true;else if(source[j]==="]")inClass=false;else if(source[j]==="/"&&!inClass)break}i=j;continue}}if(ch==="("){stack.push({kind:"paren",open:i});continue}if(ch===")"){while(stack.length&&stack[stack.length-1].kind==="loopstmt")stack.pop();const top2=stack[stack.length-1];if(top2?.kind==="paren"){stack.pop();lastParen={open:top2.open,close:i};const header=source.slice(Math.max(0,top2.open-24),top2.open);const next=source[nextNonSpace(i+1)];const trailer=/(?:^|[^\w$.])while\s*$/.exec(header);const doTrailer=trailer!==null&&prevNonSpace(top2.open-(header.length-header.lastIndexOf("while")))===lastDoClose;if(LOOP_HEADER.test(header)&&next!=="{"&&next!==";"&&!doTrailer){stack.push({kind:"loopstmt",open:i,depth:stack.length,started:false})}}continue}if(ch==="{"){const p=prevNonSpace(i);let kind="block";if(p>=1&&source[p]===">"&&source[p-1]==="=")kind="function";else if(lastParen&&(lastParen.close===p||lastParen.close<p&&i-lastParen.close<=128&&/^\s*:[^{};=()]*$/.test(source.slice(lastParen.close+1,i)))){const header=source.slice(Math.max(0,lastParen.open-24),lastParen.open);kind=LOOP_HEADER.test(header)?"loop":BLOCK_HEADER.test(header)?"block":"function"}else if(/(?:^|[^\w$.])do\s*$/.test(source.slice(Math.max(0,i-8),i))){stack.push({kind:"loop",open:i,isDo:true});continue}stack.push({kind,open:i});continue}if(ch==="}"){popLoopStatements();let k=stack.length-1;while(k>=0&&stack[k].kind==="paren")k--;const closed=k>=0?stack[k]:void 0;if(closed&&closed.kind==="loop"&&closed.isDo)lastDoClose=i;stack.length=Math.max(0,k);popLoopStatements();continue}if(ch===";"){const top2=stack[stack.length-1];if(top2?.kind==="loopstmt"&&top2.depth===stack.length-1)stack.pop();continue}if(ch!=="a"||/[\w$.]/.test(source[i-1]??""))continue;SEND.lastIndex=i;if(!SEND.test(source))continue;const top=stack[stack.length-1];if(top?.kind==="paren")continue;if(/=>\s*(?:async\s*)?$/.test(source.slice(Math.max(0,i-64),i)))continue;for(let k=stack.length-1;k>=0;k--){const frame=stack[k];if(frame.kind==="function")break;if(frame.kind==="loop"||frame.kind==="loopstmt"){if(!seenLoops.has(frame.open)){seenLoops.add(frame.open);offsets.push(i)}break}}}return offsets}function sequentialEmailFindings(functions){const findings=[];let skippedFiles=0;let truncated=false;for(const[file,raw]of Object.entries(functions)){if(typeof raw!=="string"||!raw.includes("email"))continue;if(raw.length>MAX_FILE_BYTES2){skippedFiles++;continue}const source=stripComments(raw);const offsets=scanFile(source);if(offsets.length===0)continue;const starts=lineIndex(source);for(const[n,offset2]of offsets.entries()){if(n>=MAX_FINDINGS_PER_FILE2||findings.length>=MAX_FINDINGS2){truncated=true;break}findings.push({file,line:lineAt2(starts,offset2)})}}return{findings,skippedFiles,truncated}}var MAX_FILE_BYTES3=256*1024;var MAX_FINDINGS_PER_FILE3=20;var MAX_FINDINGS3=100;var SEARCH_WINDOW=4e3;var CALL=/\blistUsers\s*\(/g;var SEARCH_METHODS="(?:find|filter|some|findIndex|findLast|findLastIndex)";var IDENT3=/^[A-Za-z_$][\w$]*$/;function closeOf(source,open){const pairs={"(":")","[":"]","{":"}"};const stack=[];let quote=null;for(let i=open;i<source.length;i++){const ch=source[i];if(quote){if(ch==="\\")i++;else if(ch===quote)quote=null;continue}if(ch==='"'||ch==="'"||ch==="`"){quote=ch;continue}if(pairs[ch])stack.push(pairs[ch]);else if(ch===")"||ch==="]"||ch==="}"){if(stack.pop()!==ch)return-1;if(stack.length===0)return i+1}}return-1}var escapeRe=s=>s.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");function resultRefs(before){const tail=before.slice(-200);const destructured=/(?:const|let|var)\s*\{([^{}]*)\}\s*=\s*(?:await\s+)?[\w$.?\s]*$/.exec(tail);if(destructured){for(const part of destructured[1].split(",")){const[key,alias]=part.split(":").map(s=>s.trim());if(key==="users")return[escapeRe(alias&&IDENT3.test(alias)?alias:"users")]}return[]}const named=/(?:(?:const|let|var)\s+)?([A-Za-z_$][\w$]*)\s*=\s*(?:await\s+)?[\w$.?\s]*$/.exec(tail);return named?[`${escapeRe(named[1])}\\s*\\??\\.\\s*users`]:[]}function comparesExactEmail(callback){return callback.split(/&&|\|\|/).some(clause=>/\.\s*email\b/.test(clause)&&/(?<![!=<>])={2,3}(?!=)/.test(clause))}function searchesExactEmail(source,from,refs){const window=source.slice(from,from+SEARCH_WINDOW);for(const ref2 of refs){const pattern=new RegExp(`(?:^|[^\\w$.])${ref2}\\s*\\??\\.\\s*${SEARCH_METHODS}\\s*\\(`,"g");for(let m=pattern.exec(window);m;m=pattern.exec(window)){const open=from+m.index+m[0].length-1;const close=closeOf(source,open);if(close>0&&comparesExactEmail(source.slice(open,close)))return true}}return false}function scanFile2(source){const offsets=[];for(let m=CALL.exec(source);m;m=CALL.exec(source)){const open=m.index+m[0].length-1;const close=closeOf(source,open);if(close<0)continue;if(/\bemails\b/.test(source.slice(open,close)))continue;const chained=new RegExp(`^\\s*\\)?\\s*\\??\\.\\s*users\\s*\\??\\.\\s*${SEARCH_METHODS}\\s*\\(`).exec(source.slice(close,close+120));if(chained){const searchOpen=close+chained[0].length-1;const searchClose=closeOf(source,searchOpen);if(searchClose>0&&comparesExactEmail(source.slice(searchOpen,searchClose))){offsets.push(m.index);continue}}const refs=resultRefs(source.slice(0,m.index));if(refs.length&&searchesExactEmail(source,close,refs))offsets.push(m.index)}CALL.lastIndex=0;return offsets}function userEmailScanFindings(functions){const findings=[];let skippedFiles=0;let truncated=false;for(const[file,raw]of Object.entries(functions)){if(typeof raw!=="string"||!raw.includes("listUsers"))continue;if(raw.length>MAX_FILE_BYTES3){skippedFiles++;continue}const source=stripComments(raw);const offsets=scanFile2(source);if(offsets.length===0)continue;const starts=lineIndex(source);for(const[n,offset2]of offsets.entries()){if(n>=MAX_FINDINGS_PER_FILE3||findings.length>=MAX_FINDINGS3){truncated=true;break}findings.push({file,line:lineAt2(starts,offset2)})}}return{findings,skippedFiles,truncated}}var SOURCE_LINT_VERSION="6";async function lintSourceSnapshot(files,functions={}){const entries2=map=>Object.keys(map).sort().map(key=>[key,map[key]]);const sha256=async value=>{const bytes=await crypto.subtle.digest("SHA-256",new TextEncoder().encode(value));return Array.from(new Uint8Array(bytes),byte=>byte.toString(16).padStart(2,"0")).join("")};const schema=files["db/schema.ts"];const[source_sha256,schema_sha256]=await Promise.all([sha256(JSON.stringify([entries2(files),entries2(functions)])),schema===void 0?Promise.resolve(null):sha256(schema)]);return{...lintSource(files,functions),source_sha256,schema_sha256}}function lintSource(files,functions={}){const findings=scanSourceForSecrets(files,functions).map(finding=>({rule:"somewhere/source-secret",severity:"warning",file:finding.file,line:finding.line,message:`${finding.label} in source. The existing deploy secret guard may refuse this source.`,fix:"A credential literal in source is readable by anyone with the source. A project environment variable without a VITE_ or REACT_APP_ prefix, read only inside a server handler, keeps it private.",docs:"https://somewhere.cloud/docs/sw.env.txt"}));const schema=files["db/schema.ts"];let requestOwnership="not-applicable";if(schema!==void 0){const parsed=extractSchemaTs(schema);if(!parsed.ok){requestOwnership="skipped";for(const message of parsed.errors){findings.push({rule:"somewhere/schema-declaration",severity:"warning",file:"db/schema.ts",line:Number(/\bline (\d+):/.exec(message)?.[1]??1),message,fix:"The indicated schema helper, column or access rule is what this declaration accepts. The same schema parser runs during deploy.",docs:"https://somewhere.cloud/docs/declared-data.txt"})}}else{let ownership=[];try{const result=requestOwnershipFindings(functions,parsed.declaration);ownership=result.findings;requestOwnership=result.skippedFiles>0||result.truncated?"partial":"checked"}catch{requestOwnership="skipped"}for(const finding of ownership){findings.push({rule:"somewhere/request-ownership",severity:"warning",file:finding.file,line:finding.line,message:finding.columns.length===1?`${finding.table}.${finding.columns[0]} is set or matched through sw.db.server from request input, so a caller can choose whose row this is. Lint cannot see authorization done elsewhere, so whether this write is authorized is not established.`:`${finding.table} ownership columns ${finding.columns.join(", ")} are set through sw.db.server from the whole request body, so a caller can choose whose row this is. Lint cannot see authorization done elsewhere, so whether this write is authorized is not established.`,fix:`${finding.columns.join(" and ")} set from the signed-in user (sw.auth), or by the user-mode sw.db write which sets ownership itself, cannot be chosen by the caller. A handler that intentionally acts for another user is safe only with a check of the caller's role before this write.`,docs:"https://somewhere.cloud/docs/declared-data.txt"})}}}let sequentialEmail=Object.keys(functions).length===0?"not-applicable":"checked";try{const result=sequentialEmailFindings(functions);if(result.skippedFiles>0||result.truncated)sequentialEmail="partial";for(const finding of result.findings){findings.push({rule:"somewhere/sequential-email",severity:"warning",file:finding.file,line:finding.line,message:"sw.email.send is awaited inside a loop, so each email waits for the previous one to be delivered and the total time grows with the number of recipients. A handler or job that reaches its time limit stops sending the rest without an error.",fix:"Independent emails can be sent a few at a time (for example batches of 5 with Promise.allSettled per batch) or from a job. A sequential loop is needed when order matters or an email depends on an earlier result; one unbounded Promise.all over an arbitrary list has no concurrency limit.",docs:"https://somewhere.cloud/docs/sw.email.txt"})}}catch{sequentialEmail="skipped"}let userEmailLookup=Object.keys(functions).length===0?"not-applicable":"checked";try{const result=userEmailScanFindings(functions);if(result.skippedFiles>0||result.truncated)userEmailLookup="partial";for(const finding of result.findings){findings.push({rule:"somewhere/user-email-scan",severity:"warning",file:finding.file,line:finding.line,message:"sw.auth listUsers is called without emails and its result is then searched for one exact email. That reads whole directory pages to find one user, so it gets slower as the app grows, and a user beyond the pages read is reported as missing.",fix:"sw.auth.server.listUsers({ emails: [email] }) looks the user up directly and returns only that user (users[0], or none). Paging listUsers fits real bulk work such as exports or admin lists.",docs:"https://somewhere.cloud/docs/sw.auth.txt"})}}catch{userEmailLookup="skipped"}for(const finding of apiIndexRouteFindings(functions)){findings.push({rule:"somewhere/index-route",severity:"warning",file:finding.file,line:1,message:finding.warning,fix:"A folder's index file serves the folder's own path. Keep one of the two handlers; a deploy refuses both.",docs:"https://somewhere.cloud/docs/functions.txt"})}findings.sort((a,b)=>a.file.localeCompare(b.file)||a.line-b.line||a.rule.localeCompare(b.rule));return{version:SOURCE_LINT_VERSION,findings,coverage:{schema:schema===void 0?"absent":"checked",request_ownership:requestOwnership,sequential_email:sequentialEmail,user_email_lookup:userEmailLookup,authorization:"not-assessed"}}}
13
+ }`;var EMAIL_DOMAIN=EMAIL_DOMAIN_PATTERN;var GROUP_KEYS=["roles","adminGrantableRoles"];var APP_ROLE_KEYS=["grantableBy","emailDomain","assignedBy"];function readStringList2(r,fail,ctx){const open=r.peek();if(open.kind!=="punct"||open.value!=="[")fail(open.line,`${ctx} must be a list of quoted role names, such as ['viewer'].`);r.next();const out=[];while(!r.tryPunct("]")){const t=r.next();if(t.kind!=="string")fail(t.line,`${ctx} must be a list of quoted role names; found ${t.kind==="eof"?"the end of the file":`"${t.value}"`}. Values must be literal strings.`);out.push(t.value);if(!r.tryPunct(",")){r.expectPunct("]",`closing ${ctx}`);break}}return out}function readGroupRoles(r,fail){r.expectPunct("{","opening schema option groups");const seen=new Set;const out={roles:[],adminGrantableRoles:[]};while(!r.tryPunct("}")){const key=r.readKey("for a groups option");if(!GROUP_KEYS.includes(key.name)){fail(key.line,`groups has an unknown option "${key.name}". Allowed: ${GROUP_KEYS.join(", ")}. owner, admin and member are built in.`)}if(seen.has(key.name))fail(key.line,`groups declares ${key.name} twice.`);seen.add(key.name);r.expectPunct(":",`after groups.${key.name}`);out[key.name]=readStringList2(r,fail,`groups.${key.name}`);if(!r.tryPunct(",")){r.expectPunct("}","closing schema option groups");break}}return out}function readAppRoles(r,fail){r.expectPunct("{","opening schema option appRoles");const out=[];while(!r.tryPunct("}")){const key=r.readKey("for an app role name");if(out.some(role2=>role2.name===key.name))fail(key.line,`app role "${key.name}" is declared twice.`);r.expectPunct(":",`after app role "${key.name}"`);r.expectPunct("{",`opening app role "${key.name}", which takes { grantableBy: [...], emailDomain: '...' }`);const role={name:key.name,grantableBy:[]};const seen=new Set;while(!r.tryPunct("}")){const opt=r.readKey(`for an option of app role "${key.name}"`);if(!APP_ROLE_KEYS.includes(opt.name)){fail(opt.line,`app role "${key.name}" has an unknown option "${opt.name}". Allowed: ${APP_ROLE_KEYS.join(", ")}.`)}if(seen.has(opt.name))fail(opt.line,`app role "${key.name}" declares ${opt.name} twice.`);seen.add(opt.name);r.expectPunct(":",`after appRoles.${key.name}.${opt.name}`);if(opt.name==="assignedBy"){const t=r.next();if(t.kind!=="string"||t.value!=="server")fail(t.line,`appRoles.${key.name}.assignedBy must be 'server'.`);role.assignedBy="server"}else if(opt.name==="emailDomain"){const t=r.next();if(t.kind!=="string")fail(t.line,`appRoles.${key.name}.emailDomain must be one quoted domain, such as 'example.com'.`);if(!EMAIL_DOMAIN.test(t.value)){fail(t.line,`appRoles.${key.name}.emailDomain "${t.value}" must be one lowercase domain such as 'example.com': no "@", no wildcard, no scheme or path. Users whose verified email is at exactly that domain hold the role; subdomains are other domains.`)}role.emailDomain=t.value}else{role.grantableBy=readStringList2(r,fail,`appRoles.${key.name}.grantableBy`)}if(!r.tryPunct(",")){r.expectPunct("}",`closing app role "${key.name}"`);break}}out.push(role);if(!r.tryPunct(",")){r.expectPunct("}","closing schema option appRoles");break}}return out.sort((a,b)=>a.name<b.name?-1:a.name>b.name?1:0)}function validateDeclaredRoles(groups,appRoles){const delegation=Object.create(null);for(const role of appRoles??[])delegation[role.name]=role.grantableBy;return[...emailDomainRoleErrors(appRoles??[]),...roleVocabularyErrors({groupRoles:groups?.roles??[],adminGrantableGroupRoles:groups?.adminGrantableRoles??[],appRoles:(appRoles??[]).map(role=>role.name),appRoleDelegation:delegation})]}function emailDomainRoleErrors(appRoles){const errors=[];const byDomain=new Set(appRoles.filter(role=>role.emailDomain!==void 0).map(role=>role.name));for(const role of appRoles){if(role.assignedBy!==void 0&&role.assignedBy!=="server")errors.push(`appRoles.${role.name}.assignedBy must be 'server'.`);if(role.assignedBy&&role.emailDomain)errors.push(`appRoles.${role.name} cannot combine assignedBy and emailDomain.`);if(role.emailDomain!==void 0&&!EMAIL_DOMAIN.test(role.emailDomain))errors.push(`appRoles.${role.name}.emailDomain is not one lowercase domain.`);for(const grantor of role.grantableBy){if(appRoles.some(source=>source.name===grantor&&source.assignedBy))errors.push(`appRoles.${role.name}.grantableBy cannot name server-assigned role "${grantor}".`);if(byDomain.has(grantor)){errors.push(`appRoles.${role.name}.grantableBy names "${grantor}", which is held by email domain. A role held by email domain cannot grant other roles; list a role that is granted explicitly.`)}}}return errors}var STALE_JOB_WINDOW_MS=45*60*1e3;var BINDING_OPERATIONS=["read","create","update","delete"];var ROW_OPERATIONS=["read","update","delete"];var MAX_JOB_BINDING_SECONDS=STALE_JOB_WINDOW_MS/1e3;var NAME=/^[a-z][a-z0-9_]{0,63}$/;var BUILT_IN_GROUP_ROLES2=["admin","member","owner"];var lines=new WeakMap;var byName=list=>list.sort((a,b)=>a.name<b.name?-1:a.name>b.name?1:0);function readString(r,fail,ctx){const t=r.next();if(t.kind!=="string")fail(t.line,`${ctx} must be a quoted literal string.`);return t}function readStrings(r,fail,ctx){const open=r.next();if(open.kind!=="punct"||open.value!=="[")fail(open.line,`${ctx} must be a list of quoted literal strings, such as ['read'].`);const out=[];while(!r.tryPunct("]")){const t=r.next();if(t.kind!=="string")fail(t.line,`${ctx} must be a list of quoted literal strings.`);if(out.some(seen=>seen.value===t.value))fail(t.line,`${ctx} lists "${t.value}" twice.`);out.push(t);if(!r.tryPunct(",")){r.expectPunct("]",`closing ${ctx}`);break}}return out}function readOperations(r,fail,ctx,allowed){const list=readStrings(r,fail,ctx);if(list.length===0)fail(r.peek().line,`${ctx} must name at least one operation.`);for(const t of list){if(!allowed.includes(t.value))fail(t.line,`${ctx} has an unknown operation "${t.value}". Allowed: ${allowed.join(", ")}.`)}const ops=BINDING_OPERATIONS.filter(op=>list.some(t=>t.value===op));if(!ops.includes("read")&&(ops.includes("update")||ops.includes("delete"))){fail(list[0].line,`${ctx} allows ${ops.filter(op=>op!=="create").join(" and ")} without read. Update and delete return the existing row, so they also need read; create alone is allowed because it returns only the row it created.`)}return ops}function readNamed(r,fail,option,kind,keys,readField){r.expectPunct("{",`opening schema option ${option}`);const out=[];while(!r.tryPunct("}")){const key=r.readKey(`for a ${kind} name`);if(!NAME.test(key.name))fail(key.line,`${kind} name "${key.name}" must be lowercase letters, digits and underscores, starting with a letter (at most 64).`);if(out.some(entry=>entry.name===key.name))fail(key.line,`${kind} "${key.name}" is declared twice.`);r.expectPunct(":",`after ${kind} "${key.name}"`);r.expectPunct("{",`opening ${kind} "${key.name}"`);const fields={};const fieldLines={"":key.line};const seen=new Set;while(!r.tryPunct("}")){const opt=r.readKey(`for an option of ${kind} "${key.name}"`);if(!keys.includes(opt.name))fail(opt.line,`${kind} "${key.name}" has an unknown option "${opt.name}". Allowed: ${keys.join(", ")}.`);if(seen.has(opt.name))fail(opt.line,`${kind} "${key.name}" declares ${opt.name} twice.`);seen.add(opt.name);r.expectPunct(":",`after ${option}.${key.name}.${opt.name}`);fieldLines[opt.name]=r.peek().line;readField(opt.name,fields,key.name);if(!r.tryPunct(",")){r.expectPunct("}",`closing ${kind} "${key.name}"`);break}}const missing=keys.filter(k=>!seen.has(k));if(missing.length)fail(key.line,`${kind} "${key.name}" is missing ${missing.join(", ")}.`);lines.set(fields,fieldLines);out.push({name:key.name,line:key.line,fields});if(!r.tryPunct(",")){r.expectPunct("}",`closing schema option ${option}`);break}}return out}function readPaymentBindings(r,fail){const entries2=readNamed(r,fail,"payments","payment binding",["table","amount","currency","onPaid"],(key,fields,name)=>{if(key!=="onPaid"){fields[key]=readString(r,fail,`payments.${name}.${key}`).value.toLowerCase();return}r.expectPunct("{",`opening payments.${name}.onPaid, which takes one transition: { status: { from: [...], to: '...' } }`);const column=r.readKey(`for the status column in payments.${name}.onPaid`);r.expectPunct(":",`after payments.${name}.onPaid.${column.name}`);r.expectPunct("{",`opening payments.${name}.onPaid.${column.name}, which takes { from: [...], to: '...' }`);const transition={};while(!r.tryPunct("}")){const opt=r.readKey(`for an option of payments.${name}.onPaid.${column.name}`);if(opt.name!=="from"&&opt.name!=="to")fail(opt.line,`payments.${name}.onPaid.${column.name} has an unknown option "${opt.name}". Allowed: from, to.`);if(transition[opt.name])fail(opt.line,`payments.${name}.onPaid.${column.name} declares ${opt.name} twice.`);r.expectPunct(":",`after ${opt.name}`);if(opt.name==="from")transition.from=readStrings(r,fail,`payments.${name}.onPaid.${column.name}.from`);else transition.to=readString(r,fail,`payments.${name}.onPaid.${column.name}.to`);if(!r.tryPunct(",")){r.expectPunct("}",`closing payments.${name}.onPaid.${column.name}`);break}}if(!transition.from||!transition.to)fail(column.line,`payments.${name}.onPaid.${column.name} needs both from and to.`);r.tryPunct(",");if(!r.tryPunct("}")){const extra=r.peek();fail(extra.line,`payments.${name}.onPaid declares one status transition only; this one has a second entry. Other paid effects run from the signed payment event.`)}const values=[...transition.from,transition.to];for(const t of values){if(t.value.length<1||t.value.length>64||/[\u0000-\u001f]/.test(t.value))fail(t.line,`payments.${name}.onPaid.${column.name} status values must be 1 to 64 characters, without control characters.`)}if(transition.from.length===0)fail(column.line,`payments.${name}.onPaid.${column.name}.from must list at least one unpaid state.`);if(transition.from.some(t=>t.value===transition.to.value))fail(transition.to.line,`payments.${name}.onPaid.${column.name}.to must differ from every from state.`);fields.status={column:column.name.toLowerCase(),from:transition.from.map(t=>t.value).sort(),to:transition.to.value}});return byName(entries2.map(({name,fields})=>{const binding={name,...fields};lines.set(binding,lines.get(fields));return binding}))}function readJobBindings(r,fail){const entries2=readNamed(r,fail,"jobs","job binding",["table","operations","maxDurationSeconds"],(key,fields,name)=>{if(key==="table")fields.table=readString(r,fail,`jobs.${name}.table`).value.toLowerCase();else if(key==="operations")fields.operations=readOperations(r,fail,`jobs.${name}.operations`,ROW_OPERATIONS);else{const t=r.next();if(t.kind!=="number"||!/^[1-9][0-9]{0,9}$/.test(t.value)||Number(t.value)>MAX_JOB_BINDING_SECONDS){fail(t.line,`jobs.${name}.maxDurationSeconds must be a whole number of seconds from 1 to ${MAX_JOB_BINDING_SECONDS}: how long the row grant lasts from the job's scheduled start, retries included.`)}fields.maxDurationSeconds=Number(t.value)}});return byName(entries2.map(({name,fields})=>{const binding={name,...fields};lines.set(binding,lines.get(fields));return binding}))}function readServiceRoles(r,fail){const entries2=readNamed(r,fail,"serviceRoles","service role",["tables"],(_key,fields,name)=>{r.expectPunct("{",`opening serviceRoles.${name}.tables, which takes { table: ['read', ...] }`);const tables=[];const tableLines={};while(!r.tryPunct("}")){const t=r.readKey(`for a table in serviceRoles.${name}.tables`);const table=t.name.toLowerCase();if(tables.some(entry=>entry.table===table))fail(t.line,`serviceRoles.${name}.tables names "${t.name}" twice.`);r.expectPunct(":",`after serviceRoles.${name}.tables.${t.name}`);tables.push({table,operations:readOperations(r,fail,`serviceRoles.${name}.tables.${t.name}`,BINDING_OPERATIONS)});tableLines[table]=t.line;if(!r.tryPunct(",")){r.expectPunct("}",`closing serviceRoles.${name}.tables`);break}}if(tables.length===0)fail(r.peek().line,`serviceRoles.${name}.tables must grant at least one table.`);fields.tables=tables.sort((a,b)=>a.table<b.table?-1:a.table>b.table?1:0);lines.set(fields.tables,tableLines)});return byName(entries2.map(({name,fields})=>{const role={name,tables:fields.tables};lines.set(role,lines.get(fields));return role}))}function validateBindings(input,tableInfo,errors){const at2=(entry,field)=>`line ${lines.get(entry)?.[field]??lines.get(entry)?.[""]??0}: `;const rowTable=(entry,kind)=>{const info=tableInfo(entry.table);if(!info){errors.push(`${at2(entry,"table")}${kind} "${entry.name}" names table "${entry.table}", which is not declared in db/schema.ts.`);return null}if(!info.privateUser)errors.push(`${at2(entry,"table")}${kind} "${entry.name}" names table "${entry.table}", whose scope is not owner(), member(), anyOf(), group(), appRole() or parent(). It binds rows a signed-in user holds; other tables are reached from server functions.`);if(!info.key)errors.push(`${at2(entry,"table")}${kind} "${entry.name}" names table "${entry.table}", which needs exactly one id() key.`);return info};const reachesAllOf=node=>!!node&&(node.kind==="all_of"||node.kind==="parent"&&reachesAllOf(node.policy));for(const p of input.payments??[]){const info=rowTable(p,"payment binding");if(!info)continue;if(info.table.scope.kind==="policy"&&reachesAllOf(info.table.scope.policy)){errors.push(`${at2(p,"table")}payment binding "${p.name}" names table "${p.table}", which uses allOf(); payment bindings on allOf tables are not supported yet; such tables are reached from server functions.`);continue}const column=name=>info.table.columns.find(c=>c.name===name);const checks=[["amount",p.amount,"integer","a required integer() column holding the amount in minor units (cents)"],["currency",p.currency,"text","a required text() column holding the currency code"],["onPaid",p.status.column,"text","a required text() status column"]];for(const[field,name,helper,what]of checks){const c=column(name);if(!c){errors.push(`${at2(p,field)}payment binding "${p.name}" names "${name}", which is not a declared column of "${p.table}".`);continue}if(c.helper!==helper||c.nullable)errors.push(`${at2(p,field)}payment binding "${p.name}": "${p.table}"."${name}" must be ${what}.`);if(info.identity.includes(name))errors.push(`${at2(p,field)}payment binding "${p.name}": "${p.table}"."${name}" is the table's access column; a payment never moves a row.`);const writable=[...info.table.client?.create??[],...info.table.client?.update??[],...info.table.client?.intake?.fields??[]];if(writable.includes(name))errors.push(`${at2(p,field)}payment binding "${p.name}": "${p.table}"."${name}" is browser-writable through client.create, client.update or client.intake, and a payment binding requires it not to be; the server sets prices and the payment sets the status.`)}if(new Set([p.amount,p.currency,p.status.column]).size!==3)errors.push(`${at2(p,"")}payment binding "${p.name}" must name three different columns for amount, currency and status.`);const status=column(p.status.column);if(status&&!(status.hasDefault&&typeof status.default==="string"&&p.status.from.includes(status.default))){errors.push(`${at2(p,"onPaid")}payment binding "${p.name}": "${p.table}"."${p.status.column}" must declare a default that is one of its unpaid from states (${p.status.from.join(", ")}), so a new row starts unpaid.`)}}for(const j of input.jobs??[])rowTable(j,"job binding");const taken=new Set([...BUILT_IN_GROUP_ROLES2,...input.groups?.roles??[],...(input.appRoles??[]).map(role=>role.name)]);for(const s of input.serviceRoles??[]){if(taken.has(s.name))errors.push(`${at2(s,"")}service role "${s.name}" has the name of a group or app role. Service roles are a separate namespace for unattended work, so the name must differ.`);const tableLines=lines.get(s.tables)??{};for(const grant of s.tables){if(!tableInfo(grant.table))errors.push(`line ${tableLines[grant.table]??0}: service role "${s.name}" grants table "${grant.table}", which is not declared in db/schema.ts.`)}}}function readSchemaOptions(reader,fail,fileErrors){const o={};if(!reader.tryPunct(",")||reader.peek().kind==="punct"&&reader.peek().value===")")return o;reader.expectPunct("{","opening schema options");while(!reader.tryPunct("}")){const option=reader.readKey("for a schema option");const after=()=>reader.expectPunct(":",`after schema option "${option.name}"`);if(option.name==="files"&&!o.fileCollections){after();o.fileCollections=readFileCollections(reader,fail,fileErrors)}else if(option.name==="groups"&&!o.groupRoles){after();o.groupRoles=readGroupRoles(reader,fail)}else if(option.name==="appRoles"&&!o.appRoles){after();o.appRoles=readAppRoles(reader,fail)}else if(option.name==="payments"&&!o.payments){after();o.payments=readPaymentBindings(reader,fail)}else if(option.name==="jobs"&&!o.jobs){after();o.jobs=readJobBindings(reader,fail)}else if(option.name==="serviceRoles"&&!o.serviceRoles){after();o.serviceRoles=readServiceRoles(reader,fail)}else if(option.name==="search"&&!o.managedSearch){after();const helper=reader.expectIdent('for schema option "search"');if(helper.value!=="owner")fail(helper.line,"search ownership must be declared with owner().");reader.expectPunct("(","after search: owner");reader.expectPunct(")","closing search: owner()");o.managedSearch={kind:"owner"}}else{fail(option.line,`unknown schema option "${option.name}". The schema-level options are search: owner(), files: { \u2026 }, groups: { \u2026 }, appRoles: { \u2026 }, payments: { \u2026 }, jobs: { \u2026 } and serviceRoles: { \u2026 }, each at most once.`)}if(!reader.tryPunct(",")){reader.expectPunct("}","closing schema options");break}}reader.tryPunct(",");return o}function policyOwner(policy){if(policy.kind==="owner")return policy;if(policy.kind==="any_of")return policy.policies.map(policyOwner).find(value=>value!==null)??null;if(policy.kind==="all_of")return policyOwner(policy.who);return null}function scopeOwner(scope){return scope.kind==="owner"?scope:scope.kind==="policy"?policyOwner(scope.policy):null}function declaredOwnerColumn(scope){return scopeOwner(scope)?.column??null}function declaredScopeIdentityColumns(scope){if(scope.kind==="owner")return[scope.column];if(scope.kind==="member")return[...scope.group];if(scope.kind!=="policy")return[];const collect=policy=>policy.kind==="owner"?[policy.column]:policy.kind==="member"?[...policy.group]:policy.kind==="any_of"?policy.policies.flatMap(collect):policy.kind==="all_of"?[...collect(policy.gate),...collect(policy.who)]:policy.kind==="group"?[policy.column]:policy.kind==="app_role"?[]:[policy.via,...policy.author?[policy.author.column]:[]];return[...new Set(collect(scope.policy))]}function declaredTeamColumns(scope){if(scope.kind!=="policy")return[];const p=scope.policy;if(p.kind==="group")return[p.column];if(p.kind==="any_of")return p.policies.flatMap(x=>x.kind==="group"?[x.column]:[]);if(p.kind==="all_of")return p.gate.kind==="group"?[p.gate.column]:[];return[]}var ROOM_REFEREE_PATH=/^\/api\/[A-Za-z0-9_\-]+(?:\/[A-Za-z0-9_\-.]+)*$/;function readRoomsOption(r,rawName,line){r.expectPunct("{",`opening the rooms option of table "${rawName}", which takes { save?: 'column', referee?: '/api/path' }`);const out={line};while(!r.tryPunct("}")){const opt=r.readKey(`for an option of rooms on table "${rawName}"`);if(opt.name!=="save"&&opt.name!=="referee"){throw new SchemaTsError(`line ${opt.line}: rooms on table "${rawName}" has an unknown option "${opt.name}". Allowed: save, referee.`)}if(out[opt.name])throw new SchemaTsError(`line ${opt.line}: rooms on table "${rawName}" declares ${opt.name} twice.`);r.expectPunct(":",`after rooms.${opt.name}`);const t=r.next();if(t.kind!=="string")throw new SchemaTsError(`line ${t.line}: rooms.${opt.name} on table "${rawName}" must be a quoted literal string.`);out[opt.name]={value:t.value,line:t.line};if(!r.tryPunct(",")){r.expectPunct("}",`closing the rooms option of table "${rawName}"`);break}}return out}function validateRoomsOption(input,rawName,nameLine,columns,scope,client,relations){if(columns.filter(c=>c.helper==="id").length!==1){throw new SchemaTsError(`line ${input.line}: table "${rawName}" declares rooms, which need exactly one id() column: a room is attached to one row by its id.`)}const out={};if(input.save){const name=input.save.value.toLowerCase();const column=columns.find(c=>c.name===name);if(!column)throw new SchemaTsError(`line ${input.save.line}: rooms.save on table "${rawName}" names "${input.save.value}", which is not one of its declared columns.`);if(column.helper!=="json")throw new SchemaTsError(`line ${input.save.line}: rooms.save on table "${rawName}" names "${name}", which must be a json() column: the room saves its whole state there.`);if(declaredScopeIdentityColumns(scope).includes(name)||declaredOwnerColumn(scope)===name){throw new SchemaTsError(`line ${input.save.line}: rooms.save on table "${rawName}" names "${name}", which the table's access rule reads; the room's state can never decide who may see the row.`)}if(relations.some(rel=>rel.kind==="belongsTo"&&rel.fk===name)){throw new SchemaTsError(`line ${input.save.line}: rooms.save on table "${rawName}" names "${name}", which is a relation key.`)}const writable=[...client?.create??[],...client?.update??[],...client?.intake?.fields??[]];if(writable.includes(name)){throw new SchemaTsError(`line ${input.save.line}: rooms.save on table "${rawName}" names "${name}", which is browser-writable through client.create, client.update or client.intake. The room is the only writer of its save column; remove it from those lists.`)}out.save=name}if(input.referee){const path=input.referee.value;if(!ROOM_REFEREE_PATH.test(path)||path.length>200||path.split("/").some(part=>part==="."||part==="..")){throw new SchemaTsError(`line ${input.referee.line}: rooms.referee on table "${rawName}" must be the path of one of the app's own functions, such as '/api/game-room'.`)}out.referee=path}void nameLine;return out}var COLUMN_HELPERS=new Set(["id","text","number","integer","bigint","boolean","timestamp","json","blob"]);var SCOPE_HELPERS=new Set(["owner","shared","serverOnly","member","anyOf","allOf","parent","group","appRole","appOwner"]);var TABLE_MARKER_HELPERS=new Set(["removedTable","exported"]);var SCHEMA_CALLABLE=new Set([...COLUMN_HELPERS,...SCOPE_HELPERS,...TABLE_MARKER_HELPERS,"schema","table","grant","removed","hasMany","belongsTo","files"]);var SAFE_IDENT=/^[a-zA-Z_][a-zA-Z0-9_]*$/;var RESERVED_PREFIXES=["app_","sqlite_","d1_","__sw_"];var ROW_HINT_FIELDS=["can","mine"];var MAX_TABLES=100;var MAX_COLUMNS=100;var MAX_INDEXES=40;var MAX_INDEX_COLUMNS=8;var MAX_NAME_LENGTH=64;var MAX_SOURCE_BYTES=256*1024;var DEFAULT_OWNER_COLUMN="user_id";var MEMBER_OPERATIONS=["read","create","update","delete"];var SchemaTsError=class extends Error{};function tokenize(source){const tokens=[];let i=0;let line=1;const n=source.length;while(i<n){const ch=source[i];if(ch==="\n"){line++;i++;continue}if(ch===" "||ch===" "||ch==="\r"){i++;continue}if(ch==="/"&&source[i+1]==="/"){while(i<n&&source[i]!=="\n")i++;continue}if(ch==="/"&&source[i+1]==="*"){i+=2;while(i<n&&!(source[i]==="*"&&source[i+1]==="/")){if(source[i]==="\n")line++;i++}i+=2;continue}if(ch==="`"){throw new SchemaTsError(`line ${line}: template literals are not allowed in db/schema.ts; strings are plain 'single-quoted' strings.`)}if(ch==="'"||ch==='"'){const startLine=line;let value="";i++;let closed=false;while(i<n){const c=source[i];if(c==="\\"){const next=source[i+1];if(next==="'"||next==='"'||next==="\\"){value+=next;i+=2;continue}throw new SchemaTsError(`line ${line}: unsupported escape "\\${next??""}" in a string \u2014 db/schema.ts strings allow only \\', \\" and \\\\.`)}if(c==="\n"){throw new SchemaTsError(`line ${startLine}: unterminated string.`)}if(c===ch){closed=true;i++;break}value+=c;i++}if(!closed)throw new SchemaTsError(`line ${startLine}: unterminated string.`);tokens.push({kind:"string",value,line:startLine});continue}if(/[0-9]/.test(ch)||ch==="-"&&/[0-9]/.test(source[i+1]??"")){let j=i+(ch==="-"?1:0);while(j<n&&/[0-9]/.test(source[j]))j++;if(source[j]==="."){j++;while(j<n&&/[0-9]/.test(source[j]))j++}const text=source.slice(i,j);const num=Number(text);if(!Number.isFinite(num))throw new SchemaTsError(`line ${line}: invalid number "${text}".`);tokens.push({kind:"number",value:text,line});i=j;continue}if(/[A-Za-z_$]/.test(ch)){let j=i;while(j<n&&/[A-Za-z0-9_$]/.test(source[j]))j++;tokens.push({kind:"ident",value:source.slice(i,j),line});i=j;continue}if("(){}[]:,;.=".includes(ch)){tokens.push({kind:"punct",value:ch,line});i++;continue}throw new SchemaTsError(`line ${line}: unexpected character "${ch}". db/schema.ts holds only the schema declaration \u2014 no expressions, operators, or type annotations.`)}tokens.push({kind:"eof",value:"",line});return tokens}var Reader=class{constructor(tokens,options={}){this.tokens=tokens;this.bareIdIsText=table=>!options.legacyIntegerIdDefault&&!options.integerKeyTables?.has(table.toLowerCase())}pos=0;bareIdIsText;peek(){return this.tokens[this.pos]}next(){return this.tokens[this.pos++]}fail(msg){throw new SchemaTsError(`line ${this.peek().line}: ${msg}`)}expectPunct(p,context){const t=this.next();if(t.kind!=="punct"||t.value!==p){throw new SchemaTsError(`line ${t.line}: expected "${p}" ${context}, found ${describeToken(t)}.`)}}tryPunct(p){const t=this.peek();if(t.kind==="punct"&&t.value===p){this.pos++;return true}return false}expectIdent(context){const t=this.next();if(t.kind!=="ident"){throw new SchemaTsError(`line ${t.line}: expected a name ${context}, found ${describeToken(t)}.`)}return t}readKey(context){const t=this.next();if(t.kind==="ident"||t.kind==="string")return{name:t.value,line:t.line};throw new SchemaTsError(`line ${t.line}: expected a name ${context}, found ${describeToken(t)}.`)}readLiteral(context){const t=this.next();if(t.kind==="string")return t.value;if(t.kind==="number")return Number(t.value);if(t.kind==="ident"&&t.value==="true")return true;if(t.kind==="ident"&&t.value==="false")return false;if(t.kind==="ident"&&t.value==="null")return null;throw new SchemaTsError(`line ${t.line}: expected a literal value (string, number, true/false, or null) ${context}, found ${describeToken(t)}. Computed values are not allowed \u2014 the declaration must be readable without running it.`)}readLiteralObject(context){this.expectPunct("{",context);const out=new Map;while(!this.tryPunct("}")){const key=this.readKey(`for an option key ${context}`);this.expectPunct(":",`after "${key.name}" ${context}`);const value=this.readLiteral(`for "${key.name}" ${context}`);if(out.has(key.name))throw new SchemaTsError(`line ${key.line}: option "${key.name}" appears twice ${context}.`);out.set(key.name,{value,line:key.line});if(!this.tryPunct(",")){this.expectPunct("}",context);break}}return out}atEof(){return this.peek().kind==="eof"}};function describeToken(t){if(t.kind==="eof")return"the end of the file";if(t.kind==="string")return`the string '${t.value.slice(0,40)}'`;return`"${t.value}"`}function readClientPermissions(r){r.expectPunct("{","opening client permissions");const out=Object.create(null);while(!r.tryPunct("}")){const key=r.readKey("for a client permission");if(Object.prototype.hasOwnProperty.call(out,key.name))r.fail(`client declares "${key.name}" twice.`);r.expectPunct(":",`after client permission "${key.name}"`);if(key.name==="publicRead"&&r.peek().kind==="punct"&&r.peek().value==="{"){r.expectPunct("{","opening client.publicRead");const whereKey=r.readKey("in client.publicRead");if(whereKey.name!=="where")r.fail("client.publicRead only accepts a where object.");r.expectPunct(":","after client.publicRead.where");out[key.name]={where:Object.fromEntries([...r.readLiteralObject("for client.publicRead.where")].map(([name,item])=>[name,item.value]))};r.tryPunct(",");r.expectPunct("}","closing client.publicRead")}else if(r.tryPunct("[")){const fields=[];while(!r.tryPunct("]")){fields.push(r.readLiteral(`in client.${key.name}`));if(!r.tryPunct(",")){r.expectPunct("]",`closing client.${key.name}`);break}}out[key.name]=fields}else{out[key.name]=["links","intake","target","where"].includes(key.name)&&r.peek().kind==="punct"&&r.peek().value==="{"?readClientPermissions(r):r.readLiteral(`for client.${key.name}`)}if(!r.tryPunct(",")){r.expectPunct("}","closing client permissions");break}}return out}function skipImport(r){r.next();r.expectPunct("{",'after "import"');while(!r.tryPunct("}")){r.expectIdent("inside the import list");if(!r.tryPunct(",")){r.expectPunct("}","closing the import list");break}}const from=r.expectIdent("after the import list");if(from.value!=="from")throw new SchemaTsError(`line ${from.line}: expected "from" after the import list.`);const src=r.next();if(src.kind!=="string")throw new SchemaTsError(`line ${src.line}: expected a module name string after "from".`);r.tryPunct(";")}function checkDeclaredName(kind,raw,line){if(raw.length>MAX_NAME_LENGTH){throw new SchemaTsError(`line ${line}: ${kind} name "${raw.slice(0,40)}\u2026" is longer than ${MAX_NAME_LENGTH} characters.`)}if(!SAFE_IDENT.test(raw)){throw new SchemaTsError(`line ${line}: ${kind} name "${raw}" is invalid. A name is letters, digits, and underscores, starting with a letter or underscore.`)}const name=raw.toLowerCase();if(name.startsWith("_")||RESERVED_PREFIXES.some(p=>name.startsWith(p))){throw new SchemaTsError(`line ${line}: ${kind} name "${raw}" uses a reserved platform prefix and cannot be declared: names starting with "app_" or "_" belong to the platform.`)}if(kind==="Column"&&ROW_HINT_FIELDS.includes(name)){throw new SchemaTsError(`line ${line}: column name "${raw}" is reserved for row hints: a read with { can: true } returns can and mine on every row, so a column cannot take either name.`)}return name}function readColumn(r,tableName,rawName,line){const helperTok=r.expectIdent(`for column "${tableName}"."${rawName}"`);const helper=helperTok.value;if(helper==="removed"){r.expectPunct("(",'after "removed"');r.expectPunct(")",`closing removed() on "${tableName}"."${rawName}" \u2014 the removal marker takes no options`);return{kind:"removed",name:checkDeclaredName("Column",rawName,line)}}if(TABLE_MARKER_HELPERS.has(helper)){throw new SchemaTsError(`line ${helperTok.line}: "${tableName}"."${rawName}" uses ${helper}(), which marks a whole table, not a column. Removing columns from the live database is not supported yet, so "${rawName}" stays declared with its column type.`)}if(!COLUMN_HELPERS.has(helper)){throw new SchemaTsError(`line ${helperTok.line}: unknown column type "${helper}" on "${tableName}"."${rawName}". Column types are id, text, number, integer, bigint, boolean, timestamp, json, and blob.`)}r.expectPunct("(",`after "${helper}"`);let opts=new Map;if(!r.tryPunct(")")){opts=r.readLiteralObject(`in ${helper}() options for "${tableName}"."${rawName}"`);r.tryPunct(",");r.expectPunct(")",`closing ${helper}()`)}const name=checkDeclaredName("Column",rawName,line);const col={name,helper,uuid:helper==="id"&&r.bareIdIsText(tableName),nullable:false,hasDefault:false,default:null,autoNow:false,unique:false,references:null,onDelete:"restrict",renamedFrom:null};const allowed=helper==="id"?new Set(["uuid"]):new Set(["nullable","default","unique","references","onDelete","renamedFrom"]);for(const[key,{value,line:optLine}]of opts){if(!allowed.has(key)){throw new SchemaTsError(`line ${optLine}: ${helper}() on "${tableName}"."${rawName}" has an unknown option "${key}". Allowed: ${[...allowed].join(", ")}.`)}switch(key){case"uuid":if(typeof value!=="boolean")throw new SchemaTsError(`line ${optLine}: "uuid" must be true or false.`);col.uuid=value;break;case"nullable":if(typeof value!=="boolean")throw new SchemaTsError(`line ${optLine}: "nullable" must be true or false.`);col.nullable=value;break;case"unique":if(typeof value!=="boolean")throw new SchemaTsError(`line ${optLine}: "unique" must be true or false.`);col.unique=value;break;case"default":{const t=col.helper;if(t==="timestamp"&&value==="now"){col.autoNow=true;break}const okType=value===null||t==="boolean"&&typeof value==="boolean"||(t==="number"||t==="integer")&&typeof value==="number"||(t==="text"||t==="timestamp"||t==="json"||t==="bigint")&&typeof value==="string";if(!okType){throw new SchemaTsError(`line ${optLine}: the default for "${tableName}"."${rawName}" (${t}) must be ${t==="boolean"?"true or false":t==="number"||t==="integer"?"a number":t==="bigint"?"a whole number written as a string, like '9007199254740993'":t==="blob"?"omitted \u2014 blob columns cannot declare a default":"a string"} or null.`)}if(t==="integer"&&typeof value==="number"&&!Number.isSafeInteger(value)){throw new SchemaTsError(Number.isInteger(value)?`line ${optLine}: the default for integer column "${tableName}"."${rawName}" is outside JavaScript's exact whole-number range (\xB19007199254740991); a bigint() column takes such a default written as a string.`:`line ${optLine}: the default for integer column "${tableName}"."${rawName}" must be a whole number.`)}if(t==="bigint"&&typeof value==="string"&&!isCanonicalBigintText(value)){throw new SchemaTsError(`line ${optLine}: the default for bigint column "${tableName}"."${rawName}" must be a whole number between -9223372036854775808 and 9223372036854775807, written as a string with no sign other than a leading minus and no leading zeros.`)}col.hasDefault=true;col.default=value;break}case"references":if(typeof value!=="string"||!SAFE_IDENT.test(value)){throw new SchemaTsError(`line ${optLine}: "references" must be the name of a table declared in this file.`)}col.references=value.toLowerCase();break;case"onDelete":if(value!=="cascade"&&value!=="restrict"){throw new SchemaTsError(`line ${optLine}: "onDelete" must be 'cascade' or 'restrict'.`)}col.onDelete=value;break;case"renamedFrom":if(typeof value!=="string"||!SAFE_IDENT.test(value)||value.length>MAX_NAME_LENGTH){throw new SchemaTsError(`line ${optLine}: "renamedFrom" on "${tableName}"."${rawName}" must be the previous column name.`)}col.renamedFrom=value.toLowerCase();break}}if(col.renamedFrom===col.name){throw new SchemaTsError(`line ${line}: "${tableName}"."${rawName}" declares renamedFrom: '${col.renamedFrom}' \u2014 that is its own name. A rename needs the OLD name there.`)}if(col.onDelete==="cascade"&&!col.references){throw new SchemaTsError(`line ${line}: "onDelete" on "${tableName}"."${rawName}" needs "references" on the same column.`)}if(col.hasDefault&&col.default===null){if(!col.nullable){throw new SchemaTsError(`line ${line}: "${tableName}"."${rawName}" is required but declares { default: null } \u2014 a required column can never hold null. It is accepted with a non-null default or { nullable: true }.`)}col.hasDefault=false}return{kind:"column",column:col}}function readColumnOrColumnList(r,ctx){if(r.tryPunct("[")){const out=[];while(!r.tryPunct("]")){const t2=r.next();if(t2.kind!=="string"){throw new SchemaTsError(`line ${t2.line}: ${ctx} must be quoted column names.`)}out.push(t2.value.toLowerCase());if(!r.tryPunct(",")){r.expectPunct("]",`closing ${ctx}`);break}}return out}const t=r.next();if(t.kind!=="string"){throw new SchemaTsError(`line ${t.line}: ${ctx} must be a quoted column name, or a list of them for a composite key.`)}return[t.value.toLowerCase()]}function readSingleColumn(r,ctx){const t=r.next();if(t.kind!=="string"){throw new SchemaTsError(`line ${t.line}: ${ctx} must be a single quoted column name.`)}return t.value.toLowerCase()}function validateMemberColumns(names,optionLabel,tableName,line){const seen=new Set;for(const name of names){if(!SAFE_IDENT.test(name)||name.length>MAX_NAME_LENGTH){throw new SchemaTsError(`line ${line}: member(${optionLabel}) on table "${tableName}" names an invalid column "${name}".`)}if(seen.has(name)){throw new SchemaTsError(`line ${line}: member(${optionLabel}) on table "${tableName}" lists "${name}" twice.`)}seen.add(name)}}function readMemberOperations(r,tableName){r.expectPunct("[",`for member({ operations }) on table "${tableName}"`);const seen=new Set;while(!r.tryPunct("]")){const token=r.next();if(token.kind!=="string"||!MEMBER_OPERATIONS.includes(token.value)){throw new SchemaTsError(`line ${token.line}: member({ operations }) on table "${tableName}" only accepts 'read', 'create', 'update', and 'delete'.`)}seen.add(token.value);if(!r.tryPunct(",")){r.expectPunct("]",`closing member({ operations }) on table "${tableName}"`);break}}const normalized=MEMBER_OPERATIONS.filter(operation=>seen.has(operation));return normalized.length===MEMBER_OPERATIONS.length?void 0:normalized}function readMemberScope(r,tableName,scopeLine,context){r.expectPunct("{",`in member() options for table "${tableName}" \u2014 member() needs { group, membership, member_user, member_group }`);let group=null;let membership=null;let memberUser=null;let memberGroup=null;let operations,operationsSeen=false;let selector;let selectorOption;let read;while(!r.tryPunct("}")){const key=r.readKey(`for a member() option of table "${tableName}"`);r.expectPunct(":",`after "${key.name}" in member() for table "${tableName}"`);if(key.name==="group"){group=readColumnOrColumnList(r,`member({ group }) on table "${tableName}"`)}else if(key.name==="membership"){membership=readSingleColumn(r,`member({ membership }) on table "${tableName}"`)}else if(key.name==="member_user"){memberUser=readSingleColumn(r,`member({ member_user }) on table "${tableName}"`)}else if(key.name==="member_group"){memberGroup=readColumnOrColumnList(r,`member({ member_group }) on table "${tableName}"`)}else if(key.name==="operations"){if(operationsSeen)throw new SchemaTsError(`line ${key.line}: member() on table "${tableName}" declares operations more than once.`);operationsSeen=true;operations=readMemberOperations(r,tableName)}else if(key.name==="where"||key.name==="deleteWhere"){const option=key.name;if(option==="deleteWhere"&&context!=="standalone"){throw new SchemaTsError(`line ${key.line}: deleteWhere on table "${tableName}" requires a standalone member() scope.`)}if(selectorOption&&selectorOption!==option){throw new SchemaTsError(`line ${key.line}: member() on table "${tableName}" accepts either where or deleteWhere.`)}if(selectorOption)throw new SchemaTsError(`member() declares ${option} more than once.`);selectorOption=option;r.expectPunct("{",`opening member ${option}`);const column=r.readKey(`member ${option} column`).name;validateMemberColumns([column],option,tableName,key.line);r.expectPunct(":",`after member ${option} column`);let value;if(r.tryPunct("[")){const list=[];while(!r.tryPunct("]")){list.push(r.readLiteral(`member ${option} value`));if(!r.tryPunct(",")){r.expectPunct("]",`closing member ${option} list`);break}}value=list}else value=r.readLiteral(`member ${option} literal`);const values=typeof value==="string"?[value]:value;if(!Array.isArray(values)||!values.length||values.some(v=>typeof v!=="string"))throw new SchemaTsError(`member ${option} needs one text column and a nonempty string literal or list.`);r.tryPunct(",");r.expectPunct("}",`member ${option} accepts exactly one column`);selector={column,values:[...new Set(values)].sort()}}else if(key.name==="read"){if(read)throw new SchemaTsError(`line ${key.line}: member() on table "${tableName}" declares read more than once.`);read=readBranchReadColumns(r,`member({ read }) on table "${tableName}"`)}else{throw new SchemaTsError(`line ${key.line}: member() on table "${tableName}" has an unknown option "${key.name}". Allowed: group, membership, member_user, member_group, operations, where, read${context==="standalone"?", deleteWhere":""}.`)}if(!r.tryPunct(",")){r.expectPunct("}",`closing member() options for table "${tableName}"`);break}}const missing=[];if(!group)missing.push("group");if(!membership)missing.push("membership");if(!memberUser)missing.push("member_user");if(!memberGroup)missing.push("member_group");if(missing.length>0||!group||!membership||!memberUser||!memberGroup){throw new SchemaTsError(`line ${scopeLine}: member() on table "${tableName}" is missing ${missing.join(", ")}. It needs member({ group, membership, member_user, member_group }) \u2014 group and member_group name the group-key columns on this table and on the membership table.`)}validateMemberColumns(group,"group",tableName,scopeLine);validateMemberColumns([membership],"membership",tableName,scopeLine);validateMemberColumns([memberUser],"member_user",tableName,scopeLine);validateMemberColumns(memberGroup,"member_group",tableName,scopeLine);if(group.length>MAX_INDEX_COLUMNS){throw new SchemaTsError(`line ${scopeLine}: member({ group }) on table "${tableName}" lists ${group.length} columns (max ${MAX_INDEX_COLUMNS}).`)}if(group.length!==memberGroup.length){throw new SchemaTsError(`line ${scopeLine}: member() on table "${tableName}" has a ${group.length}-column group but a ${memberGroup.length}-column member_group. The group key must have the same number of columns on both sides.`)}if(selectorOption==="deleteWhere"&&operations&&!operations.includes("delete")){throw new SchemaTsError(`line ${scopeLine}: member() on table "${tableName}" uses deleteWhere, so operations must include 'delete'.`)}const restrictedOperations=selectorOption==="deleteWhere"?["delete"]:operations??[...MEMBER_OPERATIONS];const node={kind:"member",group,membership,memberUser,memberGroup,...selector?{restriction:{...selector,operations:restrictedOperations}}:{},...operations!==void 0?{operations}:{},...read?{read}:{}};if(operationsSeen)explicitMemberOperations.add(node);return node}var explicitMemberOperations=new WeakSet;function readPolicyOwner(r,tableName,line){r.expectPunct("(",'after "owner"');let column=DEFAULT_OWNER_COLUMN;let read;if(!r.tryPunct(")")){r.expectPunct("{",`in owner() inside anyOf() for table "${tableName}"`);const seen=new Set;while(!r.tryPunct("}")){const key=r.readKey(`for an owner() option inside anyOf() for table "${tableName}"`);if(seen.has(key.name))throw new SchemaTsError(`line ${key.line}: option "${key.name}" appears twice in owner() inside anyOf() for table "${tableName}".`);seen.add(key.name);r.expectPunct(":",`after "${key.name}" in owner() inside anyOf() for table "${tableName}"`);if(key.name==="column"){const value=r.readLiteral(`for "column" in owner() inside anyOf() for table "${tableName}"`);if(typeof value!=="string"||!SAFE_IDENT.test(value)||value.length>MAX_NAME_LENGTH){throw new SchemaTsError(`line ${key.line}: owner({ column }) on table "${tableName}" must be a valid column name.`)}column=value.toLowerCase()}else if(key.name==="read"){read=readBranchReadColumns(r,`owner({ read }) on table "${tableName}"`)}else{throw new SchemaTsError(`line ${key.line}: owner() inside anyOf() only allows column and read. Visitor ownership is not part of policy scope.`)}if(!r.tryPunct(",")){r.expectPunct("}",`closing owner() options inside anyOf() for table "${tableName}"`);break}}r.tryPunct(",");r.expectPunct(")","closing owner()")}return{kind:"owner",column,...read?{read}:{}}}function readBranchReadColumns(r,ctx){const open=r.next();if(open.kind!=="punct"||open.value!=="[")throw new SchemaTsError(`line ${open.line}: ${ctx} must be a list of quoted column names, such as ['id', 'subject'].`);const out=[];while(!r.tryPunct("]")){const t=r.next();if(t.kind!=="string"||!SAFE_IDENT.test(t.value)||t.value.length>MAX_NAME_LENGTH)throw new SchemaTsError(`line ${t.line}: ${ctx} must be a list of quoted column names; values must be literal strings.`);const name=t.value.toLowerCase();if(out.includes(name))throw new SchemaTsError(`line ${t.line}: ${ctx} lists "${t.value}" twice.`);out.push(name);if(!r.tryPunct(",")){r.expectPunct("]",`closing ${ctx}`);break}}if(out.length===0)throw new SchemaTsError(`line ${open.line}: ${ctx} must name at least one column; leave read out for every column.`);return out}function refuseBranchRead(node,line,tableName,where){if(node.read)throw new SchemaTsError(`line ${line}: read on ${where} of table "${tableName}" is accepted only on the branches of the table's own anyOf(); it names the columns that branch may read.`)}function readPolicyMember(r,tableName,line){r.expectPunct("(",'after "member"');const scope=readMemberScope(r,tableName,line,"composed");r.tryPunct(",");r.expectPunct(")","closing member()");if(scope.kind!=="member")throw new SchemaTsError(`line ${line}: invalid member() policy.`);return scope}var ANY_OF_FORMS="anyOf() accepts exactly one owner() and one member(), grant(), group() or appRole().";function readAnyOfBranch(r,tableName,which){const tok=r.expectIdent(`for the ${which} policy in anyOf() on table "${tableName}"`);const failAt=(at2,message)=>{throw new SchemaTsError(`line ${at2}: ${message}`)};if(tok.value==="owner")return readPolicyOwner(r,tableName,tok.line);if(tok.value==="member")return readPolicyMember(r,tableName,tok.line);if(tok.value==="grant")return readGrantScope(r,tableName,tok.line,failAt);if(tok.value==="group")return readGroupScope(r,tableName,tok.line,failAt);if(tok.value==="appRole")return readAppRoleScope(r,tableName,tok.line,failAt);if(tok.value==="appOwner")return readAppOwnerScope(r,tableName,tok.line,failAt);throw new SchemaTsError(`line ${tok.line}: ${ANY_OF_FORMS}`)}function readAnyOfScope(r,tableName,line){r.expectPunct("(",'after "anyOf"');const firstPolicy=readAnyOfBranch(r,tableName,"first");r.expectPunct(",",`between the two policies in anyOf() on table "${tableName}"`);let secondPolicy=readAnyOfBranch(r,tableName,"second");if(r.tryPunct(",")&&!(r.peek().kind==="punct"&&r.peek().value===")")){const third=readAnyOfBranch(r,tableName,"second");if(secondPolicy.kind!=="member"||third.kind!=="member"||firstPolicy.kind!=="owner")throw new SchemaTsError("Three-branch anyOf accepts owner and two same-relation member branches only.");const a=secondPolicy,b=third;if(JSON.stringify([a.group,a.membership,a.memberUser,a.memberGroup])!==JSON.stringify([b.group,b.membership,b.memberUser,b.memberGroup]))throw new SchemaTsError("Two member branches over different membership relations are not supported.");if(!!a.restriction===!!b.restriction)throw new SchemaTsError("Two member branches need exactly one restricted branch; more than one restricted branch is not supported.");if(a.read||b.read)throw new SchemaTsError("Two member branches cannot declare separate read projections.");const restricted=a.restriction?a:b,ordinary=a.restriction?b:a;const ordinaryOps=ordinary.operations??[...MEMBER_OPERATIONS];if(!ordinaryOps.includes("read")&&(ordinaryOps.includes("update")||ordinaryOps.includes("delete")))throw new SchemaTsError("An unrestricted member update/delete branch must independently include unrestricted read.");const combined=MEMBER_OPERATIONS.filter(op=>ordinaryOps.includes(op)||(restricted.operations??MEMBER_OPERATIONS).includes(op));const narrow=restricted.restriction;secondPolicy={...a,operations:combined,restriction:{...narrow,operations:narrow.operations.filter(op=>!ordinaryOps.includes(op))}};r.tryPunct(",")}r.expectPunct(")","closing anyOf()");const owners=[firstPolicy,secondPolicy].filter(p=>p.kind==="owner");if(owners.length!==1)throw new SchemaTsError(`line ${line}: ${ANY_OF_FORMS}`);const owner=owners[0];const other=firstPolicy.kind==="owner"?secondPolicy:firstPolicy;if(other.kind==="member"&&other.ownerGrant&&owner.column!==DEFAULT_OWNER_COLUMN)throw new SchemaTsError(`line ${line}: grant() requires owner() with managed user_id.`);const otherRead=other;const reads=[owner.read??null,otherRead.read??null];delete owner.read;delete otherRead.read;return{kind:"policy",policy:{kind:"any_of",policies:[owner,other],...reads[0]||reads[1]?{reads}:{}}}}var ALL_OF_FORMS="allOf() takes a gate \u2014 member(), group() or appRole() \u2014 and then owner() or anyOf(owner(), ...).";var ALL_OF_EXPLICIT="allOf needs explicit operations";function readAllOfScope(r,tableName,line){r.expectPunct("(",'after "allOf"');const failAt=(at2,message)=>{throw new SchemaTsError(`line ${at2}: ${message}`)};const gateTok=r.expectIdent(`for the gate in allOf() on table "${tableName}"`);let gate;if(gateTok.value==="member")gate=readPolicyMember(r,tableName,gateTok.line);else if(gateTok.value==="group")gate=readGroupScope(r,tableName,gateTok.line,failAt);else if(gateTok.value==="appRole")gate=readAppRoleScope(r,tableName,gateTok.line,failAt);else if(gateTok.value==="appOwner")gate=readAppOwnerScope(r,tableName,gateTok.line,failAt);else throw new SchemaTsError(`line ${gateTok.line}: ${ALL_OF_FORMS}`);r.expectPunct(",",`between the gate and who in allOf() on table "${tableName}"`);const whoTok=r.expectIdent(`for who in allOf() on table "${tableName}"`);let who;if(whoTok.value==="owner")who=readPolicyOwner(r,tableName,whoTok.line);else if(whoTok.value==="anyOf"){const scope=readAnyOfScope(r,tableName,whoTok.line);if(scope.kind!=="policy")throw new SchemaTsError(`line ${whoTok.line}: ${ALL_OF_FORMS}`);who=scope.policy}else throw new SchemaTsError(`line ${whoTok.line}: ${ALL_OF_FORMS}`);r.tryPunct(",");r.expectPunct(")","closing allOf()");refuseBranchRead(gate,line,tableName,"the gate of allOf()");refuseBranchRead(who,line,tableName,"who in allOf()");if(who.kind==="any_of"&&who.reads)throw new SchemaTsError(`line ${line}: read on a branch of anyOf() inside allOf() on table "${tableName}" is not accepted; per-branch columns belong on the table's own anyOf().`);const x=who.kind==="any_of"?who.policies[1]:null;if(x?.kind==="member"&&x.ownerGrant)throw new SchemaTsError(`line ${line}: grant() belongs in anyOf(owner(), grant()), not allOf().`);for(const node of[gate,...x?[x]:[]]){if(node.kind!=="member")continue;if(!explicitMemberOperations.has(node)){throw new SchemaTsError(`line ${line}: ${ALL_OF_EXPLICIT}: member() inside allOf() on table "${tableName}" must list its operations, such as operations: ['read', 'create', 'update', 'delete'].`)}if(node.operations===void 0)node.operations=[...MEMBER_OPERATIONS]}if(x){const sameMember=x.kind==="member"&&gate.kind==="member"&&x.membership===gate.membership&&x.memberUser===gate.memberUser&&x.group.length===gate.group.length&&x.group.every((column,i)=>column===gate.group[i])&&x.memberGroup.length===gate.memberGroup.length&&x.memberGroup.every((column,i)=>column===gate.memberGroup[i]);const sameGroup=x.kind==="group"&&gate.kind==="group"&&x.column===gate.column;if(x.kind!=="app_role"&&!sameMember&&!sameGroup){throw new SchemaTsError(`line ${line}: allOf() on table "${tableName}": the second branch of who must be appRole() or the gate's own membership \u2014 the same group() column, or the same member() relation, keys and member user.`)}}return{kind:"policy",policy:{kind:"all_of",gate,who}}}function readParentScope(r,tableName,line){r.expectPunct("(",'after "parent"');const where=`parent() options for table "${tableName}"`;r.expectPunct("{",`in ${where}`);let via=null;let authorColumn=null;const actions={};const seen=new Set;while(!r.tryPunct("}")){const key=r.readKey(`for an option key in ${where}`);if(seen.has(key.name))throw new SchemaTsError(`line ${key.line}: option "${key.name}" appears twice in ${where}.`);seen.add(key.name);r.expectPunct(":",`after "${key.name}" in ${where}`);if(key.name==="via"||key.name==="author"){const t=r.next();if(t.kind!=="string"||!SAFE_IDENT.test(t.value)||t.value.length>MAX_NAME_LENGTH){throw new SchemaTsError(key.name==="via"?`line ${t.line}: parent({ via }) on table "${tableName}" must name a valid declared foreign-key column.`:`line ${t.line}: parent({ author }) on table "${tableName}" must name a declared nullable text() column the platform stamps with the row's creator.`)}if(key.name==="via")via={value:t.value.toLowerCase(),line:t.line};else authorColumn={value:t.value.toLowerCase(),line:t.line}}else if(key.name==="update"||key.name==="delete"){const open=r.next();if(open.kind!=="punct"||open.value!=="[")throw new SchemaTsError(`line ${open.line}: parent({ ${key.name} }) on table "${tableName}" lists who may ${key.name} a row: 'author' and/or 'parent', such as ['author', 'parent'].`);const list=[];while(!r.tryPunct("]")){const t=r.next();if(t.kind!=="string"||t.value!=="author"&&t.value!=="parent")throw new SchemaTsError(`line ${t.line}: parent({ ${key.name} }) on table "${tableName}" accepts 'author' (the row's author) and 'parent' (whoever may ${key.name} the parent row).`);if(list.includes(t.value))throw new SchemaTsError(`line ${t.line}: parent({ ${key.name} }) on table "${tableName}" lists '${t.value}' twice.`);list.push(t.value);if(!r.tryPunct(",")){r.expectPunct("]",`closing parent({ ${key.name} })`);break}}if(list.length===0)throw new SchemaTsError(`line ${open.line}: parent({ ${key.name} }) on table "${tableName}" is empty, so nobody could ${key.name} a row. List 'author' and/or 'parent', or leave it out for today's rule ('parent').`);actions[key.name]=["author","parent"].filter(a=>list.includes(a))}else{throw new SchemaTsError(`line ${key.line}: parent() on table "${tableName}" has an unknown option "${key.name}". Allowed: via, author, update, delete.`)}if(!r.tryPunct(",")){r.expectPunct("}",`closing ${where}`);break}}r.tryPunct(",");r.expectPunct(")","closing parent()");if(!via)throw new SchemaTsError(`line ${line}: parent() on table "${tableName}" needs { via: 'foreign_key' }.`);const usesAuthor=[actions.update,actions.delete].some(list=>list?.includes("author"));if(usesAuthor&&!authorColumn)throw new SchemaTsError(`line ${line}: parent() on table "${tableName}" lets 'author' act but declares no author column; add author: 'author_id' (a nullable text() column the platform stamps).`);if(!authorColumn&&(actions.update||actions.delete))throw new SchemaTsError(`line ${line}: parent() on table "${tableName}" lists update or delete without an author column; without author, every operation already follows the parent.`);const author=authorColumn?{column:authorColumn.value,...actions.update?{update:actions.update}:{},...actions.delete?{delete:actions.delete}:{}}:void 0;const sentinel={kind:"parent",via:via.value,table:"",parentKey:"",policy:{kind:"owner",column:""},...author?{author}:{}};rememberParentLine(sentinel,line);return{kind:"policy",policy:sentinel}}function readRelations(r,tableName){r.expectPunct("{",`for "relations" of table "${tableName}"`);const out=[];const seen=new Set;while(!r.tryPunct("}")){const key=r.readKey(`for a relation name of table "${tableName}"`);if(!SAFE_IDENT.test(key.name)||key.name.length>MAX_NAME_LENGTH){throw new SchemaTsError(`line ${key.line}: relation name "${key.name}" on table "${tableName}" is invalid. A name is letters, digits, and underscores, starting with a letter or underscore.`)}const name=key.name.toLowerCase();if(seen.has(name))throw new SchemaTsError(`line ${key.line}: relation "${key.name}" on table "${tableName}" is declared twice.`);seen.add(name);r.expectPunct(":",`after relation "${key.name}" on table "${tableName}"`);const callee=r.expectIdent(`for relation "${key.name}" on table "${tableName}"`);if(callee.value!=="hasMany"&&callee.value!=="belongsTo"){throw new SchemaTsError(`line ${callee.line}: relation "${key.name}" on table "${tableName}" uses "${callee.value}()", which is not supported. Relations are hasMany('child_table', 'foreign_key') and belongsTo('parent_table', 'foreign_key').`)}const kind=callee.value;const side=kind==="hasMany"?"child":"parent";r.expectPunct("(",`after "${kind}"`);const relatedTok=r.next();if(relatedTok.kind!=="string")throw new SchemaTsError(`line ${relatedTok.line}: ${kind}() for relation "${key.name}" on table "${tableName}" needs the ${side} table name as a quoted string first.`);r.expectPunct(",",`after the ${side} table in ${kind}() for relation "${key.name}" on table "${tableName}" \u2014 ${kind}('${side}_table', 'foreign_key')`);const fkTok=r.next();if(fkTok.kind!=="string")throw new SchemaTsError(`line ${fkTok.line}: ${kind}() for relation "${key.name}" on table "${tableName}" needs the foreign-key column as a quoted string second.`);r.tryPunct(",");r.expectPunct(")",`closing ${kind}() for relation "${key.name}" on table "${tableName}"`);const relatedTable=relatedTok.value.toLowerCase();const fk=fkTok.value.toLowerCase();if(!SAFE_IDENT.test(relatedTable)||relatedTable.length>MAX_NAME_LENGTH){throw new SchemaTsError(`line ${relatedTok.line}: ${kind}() ${side} table "${relatedTok.value}" for relation "${key.name}" on table "${tableName}" is not a valid table name.`)}if(!SAFE_IDENT.test(fk)||fk.length>MAX_NAME_LENGTH){throw new SchemaTsError(`line ${fkTok.line}: ${kind}() foreign key "${fkTok.value}" for relation "${key.name}" on table "${tableName}" is not a valid column name.`)}out.push({name,kind,table:relatedTable,fk,parentKey:""});if(!r.tryPunct(",")){r.expectPunct("}",`closing "relations" of table "${tableName}"`);break}}out.sort((a,b)=>a.name<b.name?-1:a.name>b.name?1:0);return out}function readScope(r,tableName){const tok=r.expectIdent(`for the scope of table "${tableName}"`);if(!SCOPE_HELPERS.has(tok.value)){throw new SchemaTsError(`line ${tok.line}: unknown scope "${tok.value}" on table "${tableName}". Table scopes are owner(), group(), appRole(), appOwner(), member(), anyOf(), allOf(), parent(), shared(), and serverOnly().`)}if(tok.value==="anyOf")return readAnyOfScope(r,tableName,tok.line);if(tok.value==="allOf")return readAllOfScope(r,tableName,tok.line);if(tok.value==="parent")return readParentScope(r,tableName,tok.line);const failAt=(line,message)=>{throw new SchemaTsError(`line ${line}: ${message}`)};if(tok.value==="group"||tok.value==="appRole"||tok.value==="appOwner"){const policy=tok.value==="group"?readGroupScope(r,tableName,tok.line,failAt):tok.value==="appOwner"?readAppOwnerScope(r,tableName,tok.line,failAt):readAppRoleScope(r,tableName,tok.line,failAt);refuseBranchRead(policy,tok.line,tableName,`the ${tok.value}() scope`);return{kind:"policy",policy}}if(tok.value==="member"){r.expectPunct("(",'after "member"');const scope=readMemberScope(r,tableName,tok.line,"standalone");r.tryPunct(",");r.expectPunct(")","closing member()");if(scope.kind==="member")refuseBranchRead(scope,tok.line,tableName,"the member() scope");return scope}r.expectPunct("(",`after "${tok.value}"`);let opts=new Map;if(!r.tryPunct(")")){opts=r.readLiteralObject(`in ${tok.value}() options for table "${tableName}"`);r.tryPunct(",");r.expectPunct(")",`closing ${tok.value}()`)}if(tok.value==="owner"){let column=DEFAULT_OWNER_COLUMN;let visitors=false;for(const[key,{value,line}]of opts){if(key==="visitors"){if(typeof value!=="boolean"){throw new SchemaTsError(`line ${line}: owner({ visitors }) on table "${tableName}" must be true or false.`)}visitors=value;continue}if(key!=="column"){throw new SchemaTsError(`line ${line}: owner() on table "${tableName}" has an unknown option "${key}". Allowed: column, visitors.`)}if(typeof value!=="string"||!SAFE_IDENT.test(value)||value.length>MAX_NAME_LENGTH){throw new SchemaTsError(`line ${line}: owner({ column }) on table "${tableName}" must be a valid column name.`)}column=value.toLowerCase()}return{kind:"owner",column,...visitors?{visitors:true}:{}}}if(opts.size>0){throw new SchemaTsError(`line ${tok.line}: ${tok.value}() on table "${tableName}" takes no options.`)}return tok.value==="shared"?{kind:"shared"}:{kind:"server_only"}}function readColumnLists(r,tableName,optionName){const startLine=r.peek().line;r.expectPunct("[",`for "${optionName}" of table "${tableName}"`);const entries2=[];while(!r.tryPunct("]")){const entryLine=r.peek().line;r.expectPunct("[",`for a "${optionName}" entry of table "${tableName}" (it is a list of column lists, e.g. [['a'], ['b', 'c']])`);const entry=[];while(!r.tryPunct("]")){const t=r.next();if(t.kind!=="string"){throw new SchemaTsError(`line ${t.line}: "${optionName}" columns for table "${tableName}" must be quoted column names.`)}const colName=t.value.toLowerCase();if(entry.includes(colName)){throw new SchemaTsError(`line ${t.line}: a "${optionName}" entry on table "${tableName}" lists "${t.value}" twice.`)}entry.push(colName);if(!r.tryPunct(",")){r.expectPunct("]",`closing a "${optionName}" entry of table "${tableName}"`);break}}if(entry.length===0){throw new SchemaTsError(`line ${entryLine}: a "${optionName}" entry on table "${tableName}" is empty.`)}if(entry.length>MAX_INDEX_COLUMNS){throw new SchemaTsError(`line ${entryLine}: a "${optionName}" entry on table "${tableName}" lists ${entry.length} columns (max ${MAX_INDEX_COLUMNS}).`)}entries2.push({columns:entry,line:entryLine});if(!r.tryPunct(",")){r.expectPunct("]",`closing "${optionName}" of table "${tableName}"`);break}}if(entries2.length>MAX_INDEXES){throw new SchemaTsError(`line ${startLine}: table "${tableName}" declares ${entries2.length} "${optionName}" entries (max ${MAX_INDEXES}).`)}return entries2}function readTable(r,rawName,nameLine){const callee=r.expectIdent(`for table "${rawName}"`);if(callee.value==="removed"){throw new SchemaTsError(`line ${callee.line}: table "${rawName}" uses removed(), which marks a single column; a whole table is removed with ${rawName}: removedTable().`)}if(TABLE_MARKER_HELPERS.has(callee.value)){r.expectPunct("(",`after "${callee.value}"`);r.expectPunct(")",`closing ${callee.value}() on table "${rawName}" \u2014 the marker takes no options`);return{kind:callee.value,name:checkDeclaredName("Table",rawName,nameLine)}}if(callee.value!=="table"){throw new SchemaTsError(`line ${callee.line}: expected table(\u2026) for "${rawName}", found "${callee.value}(".`)}const name=checkDeclaredName("Table",rawName,nameLine);r.expectPunct("(",'after "table"');r.expectPunct("{",`opening the columns of table "${rawName}"`);const columns=[];const removedColumns=[];const seen=new Set;while(!r.tryPunct("}")){const key=r.readKey(`for a column of table "${rawName}"`);r.expectPunct(":",`after column "${key.name}"`);const entry=readColumn(r,rawName,key.name,key.line);const entryName=entry.kind==="column"?entry.column.name:entry.name;if(seen.has(entryName)){throw new SchemaTsError(`line ${key.line}: column "${rawName}"."${key.name}" is declared twice (names are case-insensitive).`)}seen.add(entryName);if(entry.kind==="column")columns.push(entry.column);else removedColumns.push(entry.name);if(!r.tryPunct(",")){r.expectPunct("}",`closing the columns of table "${rawName}"`);break}}if(columns.length===0){throw new SchemaTsError(`line ${nameLine}: table "${rawName}" declares no columns${removedColumns.length>0?" (removal markers do not count \u2014 a table needs at least one kept column, or the whole table marked removedTable())":""}.`)}if(columns.length>MAX_COLUMNS){throw new SchemaTsError(`line ${nameLine}: table "${rawName}" declares ${columns.length} columns (max ${MAX_COLUMNS}).`)}const idCols=columns.filter(c=>c.helper==="id");if(idCols.length>1){throw new SchemaTsError(`line ${nameLine}: table "${rawName}" declares ${idCols.length} id() columns \u2014 a table has at most one.`)}let scope=null;let indexEntries=null;let uniqueEntries=null;let relations=[];let relationsDeclared=false;let clientInput;let roomsInput;let columnOptions;if(r.tryPunct(",")){r.expectPunct("{",`opening the options of table "${rawName}"`);while(!r.tryPunct("}")){const key=r.readKey(`for an option of table "${rawName}"`);r.expectPunct(":",`after "${key.name}"`);if(key.name==="scope"){if(scope)throw new SchemaTsError(`line ${key.line}: table "${rawName}" declares "scope" twice.`);scope=readScope(r,rawName);resolveGrantRowKeys(scope,idCols[0]?.name,rawName,key.line,(at2,message)=>{throw new SchemaTsError(`line ${at2}: ${message}`)})}else if(key.name==="indexes"){if(indexEntries)throw new SchemaTsError(`line ${key.line}: table "${rawName}" declares "indexes" twice.`);indexEntries=readColumnLists(r,rawName,"indexes")}else if(key.name==="unique"){if(uniqueEntries)throw new SchemaTsError(`line ${key.line}: table "${rawName}" declares "unique" twice.`);uniqueEntries=readColumnLists(r,rawName,"unique")}else if(key.name==="relations"){if(relationsDeclared)throw new SchemaTsError(`line ${key.line}: table "${rawName}" declares "relations" twice.`);relationsDeclared=true;relations=readRelations(r,rawName)}else if(key.name==="client"){if(clientInput)throw new SchemaTsError(`line ${key.line}: table "${rawName}" declares "client" twice.`);clientInput=readClientPermissions(r)}else if(key.name==="rooms"){if(roomsInput)throw new SchemaTsError(`line ${key.line}: table "${rawName}" declares "rooms" twice.`);roomsInput=readRoomsOption(r,rawName,key.line)}else if(key.name==="columns"){if(columnOptions)throw new SchemaTsError(`line ${key.line}: table "${rawName}" declares "columns" twice.`);columnOptions=readColumnRules(r,rawName,key.line,(at2,message)=>{throw new SchemaTsError(`line ${at2}: ${message}`)})}else{throw new SchemaTsError(`line ${key.line}: table "${rawName}" has an unknown option "${key.name}". Allowed: scope, indexes, unique, relations, client, rooms, columns.`)}if(!r.tryPunct(",")){r.expectPunct("}",`closing the options of table "${rawName}"`);break}}}r.tryPunct(",");r.expectPunct(")",`closing table("${rawName}")`);scope??={kind:"owner",column:DEFAULT_OWNER_COLUMN};const managedOwner=scopeOwner(scope);if(columns.some(column=>column.name===SHARED_AUTHOR_COLUMN||column.renamedFrom===SHARED_AUTHOR_COLUMN)||removedColumns.includes(SHARED_AUTHOR_COLUMN)||managedOwner?.column===SHARED_AUTHOR_COLUMN){throw new SchemaTsError(`line ${nameLine}: "${SHARED_AUTHOR_COLUMN}" is platform-maintained row authorship and cannot be declared, removed, renamed, or used as a custom owner column.`)}if(managedOwner){const clash=columns.find(c=>c.name===managedOwner.column);if(clash){throw new SchemaTsError(`line ${nameLine}: table "${rawName}" declares the column "${managedOwner.column}", but that is its owner column, which the platform creates and manages, so it is not declared among the columns; owner({ column: '\u2026' }) names a different owner column.`)}if(removedColumns.includes(managedOwner.column)){throw new SchemaTsError(`line ${nameLine}: table "${rawName}" marks its owner column "${managedOwner.column}" as removed(). The owner column carries the table's private scope and cannot be removed while owner() is part of that scope.`)}}const declaredNow=new Set(columns.map(c=>c.name));const renameSources=new Set;for(const c of columns){if(!c.renamedFrom)continue;if(declaredNow.has(c.renamedFrom)){throw new SchemaTsError(`line ${nameLine}: "${rawName}"."${c.name}" declares renamedFrom: '${c.renamedFrom}', but "${c.renamedFrom}" is still declared as a column. A rename replaces the old column, so the old declaration is not accepted alongside it.`)}if(managedOwner&&c.renamedFrom===managedOwner.column){throw new SchemaTsError(`line ${nameLine}: "${rawName}"."${c.name}" declares renamedFrom: '${c.renamedFrom}', but that is the table's owner column, which the platform creates and manages \u2014 it cannot be renamed into an ordinary column.`)}if(removedColumns.includes(c.renamedFrom)){throw new SchemaTsError(`line ${nameLine}: "${rawName}"."${c.renamedFrom}" is marked removed() AND named by renamedFrom on "${c.name}" \u2014 it cannot be both removed and renamed.`)}if(renameSources.has(c.renamedFrom)){throw new SchemaTsError(`line ${nameLine}: two columns of "${rawName}" declare renamedFrom: '${c.renamedFrom}' \u2014 a column can only be renamed to one new name.`)}renameSources.add(c.renamedFrom)}const known=new Set(columns.map(c=>c.name));if(managedOwner)known.add(managedOwner.column);const indexes=[];for(const entry of indexEntries??[]){for(const colName of entry.columns){if(!known.has(colName)){throw new SchemaTsError(`line ${entry.line}: index on table "${rawName}" names "${colName}", which is not one of its declared columns.`)}}indexes.push(entry.columns)}const uniques=[];for(const entry of uniqueEntries??[]){for(const colName of entry.columns){if(!known.has(colName)){throw new SchemaTsError(`line ${entry.line}: a "unique" entry on table "${rawName}" names "${colName}", which is not one of its declared columns.`)}}const single=entry.columns.length===1?columns.find(c=>c.name===entry.columns[0]):void 0;if(single){if(single.helper==="id"){throw new SchemaTsError(`line ${entry.line}: the primary key "${single.name}" on table "${rawName}" is already unique, so a one-column "unique" group on it is not accepted.`)}single.unique=true;continue}if(entry.columns.length<2){throw new SchemaTsError(`line ${entry.line}: the "unique" option on table "${rawName}" lists only "${entry.columns[0]}", the owner column the platform manages, and an owner column cannot be unique on its own. For one row per owner, add kind: text({ default: 'profile' }), keep kind out of client writes, omit it from server writes, and declare unique: [['${entry.columns[0]}', 'kind']].`)}uniques.push(entry.columns)}if(scope.kind==="policy"&&scope.policy.kind==="any_of"&&scope.policy.reads){const key=columns.filter(column=>column.helper==="id").length===1?columns.find(column=>column.helper==="id").name:null;const declared=new Set(columns.map(column=>column.name));scope.policy.reads.forEach((list,i)=>{if(!list)return;const branch=scope.policy.kind==="any_of"?scope.policy.policies[i]:null;const label=branch?.kind==="owner"?"owner()":branch?.kind==="member"?branch.ownerGrant?"grant()":"member()":branch?.kind==="group"?"group()":"appRole()";for(const column of list){if(!declared.has(column))throw new SchemaTsError(`line ${nameLine}: table "${rawName}": ${label} read lists "${column}", which is not one of its declared columns.`)}if(key&&!list.includes(key))throw new SchemaTsError(`line ${nameLine}: table "${rawName}": ${label} read must include the id column "${key}", which every reader needs to page and address rows.`);for(const relation of relations){if(relation.kind==="belongsTo"&&!list.includes(relation.fk))throw new SchemaTsError(`line ${nameLine}: table "${rawName}": ${label} read must include "${relation.fk}", the key relation "${relation.name}" joins by; a reader without it would get an empty relation.`)}})}let client;if(clientInput){if(columns.filter(column=>column.helper==="id").length!==1){throw new SchemaTsError(`line ${nameLine}: table "${rawName}": client operations require exactly one id() column.`)}const branch=scope.kind==="policy"&&scope.policy.kind==="any_of"?scope.policy.policies.find(node=>node.kind==="member"||node.kind==="group"):scope.kind==="policy"&&scope.policy.kind==="all_of"&&(scope.policy.gate.kind==="member"||scope.policy.gate.kind==="group")?scope.policy.gate:void 0;const branchGroup=branch?.kind==="member"?branch.group:branch?.kind==="group"?[branch.column]:void 0;const parsed=parseClientPermissions(clientInput,columns,{...scope,...managedOwner?{column:managedOwner.column}:{},...branchGroup?{group:branchGroup}:{}});if(!parsed.ok)throw new SchemaTsError(`line ${nameLine}: table "${rawName}": ${parsed.message}`);const key=columns.find(column=>column.helper==="id").name;if(Array.isArray(parsed.permissions.read)&&!parsed.permissions.read.includes(key)){throw new SchemaTsError(`line ${nameLine}: table "${rawName}": client.read must include primary key "${key}" for stable pagination.`)}client=parsed.permissions}const rooms=roomsInput?validateRoomsOption(roomsInput,rawName,nameLine,columns,scope,client,relations):void 0;if(scope.kind==="policy"&&scope.policy.kind==="parent"&&scope.policy.author){const authorColumn=scope.policy.author.column;const declared=columns.find(c=>c.name===authorColumn);if(!declared||declared.helper!=="text"||!declared.nullable||declared.hasDefault||declared.renamedFrom){throw new SchemaTsError(`line ${nameLine}: parent({ author: '${authorColumn}' }) on table "${rawName}" must name a declared text({ nullable: true }) column without a default or rename: the platform stamps it with the row's creator, and a row without one grants its author nothing.`)}if(authorColumn===scope.policy.via)throw new SchemaTsError(`line ${nameLine}: parent({ author }) on table "${rawName}" cannot be the parent link "${authorColumn}".`);if(client&&((client.create??[]).includes(authorColumn)||(client.update??[]).includes(authorColumn))){throw new SchemaTsError(`line ${nameLine}: table "${rawName}": "${authorColumn}" is the author the platform stamps, so client.create and client.update cannot list it.`)}}const columnRules=columnOptions?.write;const memberOf=columnOptions?.memberOf;if(memberOf){validateColumnMemberOf(memberOf,{tableName:rawName,nameLine,columns,ownerColumn:managedOwner?.column??null,accessColumns:declaredScopeIdentityColumns(scope),roomSave:rooms?.save??null,groupColumns:declaredTeamColumns(scope)},(at2,message)=>{throw new SchemaTsError(`line ${at2}: ${message}`)})}if(columnRules){validateColumnRules(columnRules,{tableName:rawName,nameLine,declaredColumns:new Set(columns.map(c=>c.name)),ownerColumn:managedOwner?.column??null,accessColumns:declaredScopeIdentityColumns(scope),roomSave:rooms?.save??null,serverOnly:scope.kind==="server_only"},(at2,message)=>{throw new SchemaTsError(`line ${at2}: ${message}`)})}return{kind:"table",table:{name,scope,relations,columns,indexes,uniques,removedColumns:[...removedColumns].sort(),...client?{client}:{},...rooms?{rooms}:{},...columnRules?{columnRules}:{},...memberOf?{memberOf}:{}}}}function extractSchemaTs(source,options={}){if(typeof source!=="string"||source.trim().length===0){return{ok:false,errors:["db/schema.ts is empty. It needs at least one table; without the file, the database is unmanaged."]}}if(source.length>MAX_SOURCE_BYTES){return{ok:false,errors:[`db/schema.ts is larger than ${Math.floor(MAX_SOURCE_BYTES/1024)}KB \u2014 that is not a schema declaration.`]}}try{const r=new Reader(resolveSchemaConstants(tokenize(source),SCHEMA_CALLABLE,MAX_SOURCE_BYTES,(line,message)=>{throw new SchemaTsError(`line ${line}: ${message}`)}),options);while(r.peek().kind==="ident"&&r.peek().value==="import")skipImport(r);const exp=r.expectIdent("to start the declaration");if(exp.value!=="export"){throw new SchemaTsError(`line ${exp.line}: db/schema.ts must contain only the schema declaration: optional imports, optional const declarations, then "export default schema({ \u2026 })". Found "${exp.value}".`)}const def=r.expectIdent('after "export"');if(def.value!=="default")throw new SchemaTsError(`line ${def.line}: expected "default" after "export".`);const schemaTok=r.expectIdent('after "export default"');if(schemaTok.value!=="schema"){throw new SchemaTsError(`line ${schemaTok.line}: expected schema({ \u2026 }) after "export default", found "${schemaTok.value}".`)}r.expectPunct("(",'after "schema"');r.expectPunct("{","opening the schema tables");const tables=[];const removedTables=[];const exportedTables=[];const seen=new Set;const reader=r;while(!reader.tryPunct("}")){const key=reader.readKey("for a table name");reader.expectPunct(":",`after table "${key.name}"`);const entry=readTable(reader,key.name,key.line);const entryName=entry.kind==="table"?entry.table.name:entry.name;if(seen.has(entryName)){throw new SchemaTsError(`line ${key.line}: table "${key.name}" is declared twice (names are case-insensitive).`)}seen.add(entryName);if(entry.kind==="table")tables.push(entry.table);else if(entry.kind==="removedTable")removedTables.push(entryName);else exportedTables.push(entryName);if(!reader.tryPunct(",")){reader.expectPunct("}","closing the schema tables");break}}const fileErrors=[];const fail=(line,message)=>{throw new SchemaTsError(`line ${line}: ${message}`)};const{managedSearch,fileCollections,groupRoles,appRoles:declaredAppRoles,payments,jobs,serviceRoles}=readSchemaOptions(reader,fail,fileErrors);const appOwnerErrors=[];for(const role of declaredAppRoles??[]){if(role.name===APP_OWNER_ROLE_NAME)appOwnerErrors.push(`appRoles declares "${APP_OWNER_ROLE_NAME}", which is built in: use appOwner() in a table's scope for the app's owner.`);if(role.grantableBy.includes(APP_OWNER_ROLE_NAME))appOwnerErrors.push(`appRoles.${role.name}.grantableBy names "${APP_OWNER_ROLE_NAME}". The app's owner holds no grant, so it cannot be a grantor; grant from a function that checks user.is_owner instead.`)}const appRoles=!appOwnerErrors.length&&usesAppOwner(tables)?[...declaredAppRoles??[],{name:APP_OWNER_ROLE_NAME,grantableBy:[]}].sort((a,b)=>a.name<b.name?-1:a.name>b.name?1:0):declaredAppRoles;reader.expectPunct(")","closing schema(\u2026)");reader.tryPunct(";");if(!reader.atEof()){reader.fail(`db/schema.ts must end after "export default schema({ \u2026 })" \u2014 found ${describeToken(reader.peek())}. The file holds only the schema declaration.`)}if(tables.length===0&&removedTables.length===0&&exportedTables.length===0&&!managedSearch&&!fileCollections?.length){return{ok:false,errors:["db/schema.ts declares no tables. It needs at least one table; without the file, the database is unmanaged."]}}if(tables.length>MAX_TABLES){return{ok:false,errors:[`db/schema.ts declares ${tables.length} tables (max ${MAX_TABLES}).`]}}const errors=[...appOwnerErrors];const names=new Set(tables.map(t=>t.name));for(const t of tables){for(const c of t.columns){if(c.references&&!names.has(c.references)){const marked=removedTables.includes(c.references)||exportedTables.includes(c.references);errors.push(marked?`Column "${t.name}"."${c.name}" references "${c.references}", which this file marks ${removedTables.includes(c.references)?"removedTable()":"exported()"}. The table can go only once no column references it (the column marked removed(), or without "references").`:`Column "${t.name}"."${c.name}" references "${c.references}", which is not declared in db/schema.ts. Foreign keys can only target tables in the same declaration.`)}}}const keyOf=new Map(tables.map(t=>[t.name,t.columns.find(c=>c.helper==="id")]));for(const t of tables){for(const c of t.columns){const key=c.references?keyOf.get(c.references):void 0;if(!key)continue;const fits=key.uuid?c.helper==="text":c.helper==="integer"||c.helper==="number";if(fits)continue;errors.push(key.uuid?`Column "${t.name}"."${c.name}" references "${c.references}", whose id() is a random text key, but is declared ${c.helper}(). The column type must match the key: text({ references: '${c.references}' }), or an integer key on "${c.references}" with id({ uuid: false }).`:`Column "${t.name}"."${c.name}" references "${c.references}", whose key is an integer (id({ uuid: false })), but is declared ${c.helper}(). The column type must match the key: integer({ references: '${c.references}' }), or a random text key on "${c.references}" with id().`)}}const tableByName=new Map(tables.map(t=>[t.name,t]));const knownColumns=t=>{const s=new Set(t.columns.map(c=>c.name));const owner=scopeOwner(t.scope);if(owner)s.add(owner.column);return s};const privatePolicy=scope=>{if(scope.kind==="owner"&&!scope.visitors)return{kind:"owner",column:scope.column};if(scope.kind==="member")return scope;if(scope.kind==="policy"&&scope.policy.kind!=="parent")return scope.policy;return null};resolveAppRoleScopes(tables,appRoles,errors);resolveColumnRuleRoles(tables,appRoles,groupRoles,errors);resolveGroupsAndParents(tables,tableByName,privatePolicy,groupRoles,errors);validateDeclaredMemberships(tables,tableByName,knownColumns,errors);validateDeclaredRelations(tables,tableByName,knownColumns,table=>removedTables.includes(table)?"removedTable()":exportedTables.includes(table)?"exported()":null,errors);validateRowLinks(tables,tableByName,errors);validateIntake(tables,tableByName,errors);if(fileCollections){errors.push(...fileErrors);validateFileCollections(fileCollections,name=>{const t=tableByName.get(name);return t?{columns:knownColumns(t),clientWrites:tableAllowsClientWrites(t),parentTarget:fileParentTarget(t)}:null},errors)}if(groupRoles||appRoles)errors.push(...validateDeclaredRoles(groupRoles,appRoles));validateBindings({payments,jobs,serviceRoles,groups:groupRoles,appRoles},name=>{const t=tableByName.get(name);return t?{table:t,key:fileParentTarget(t).key,privateUser:fileParentTarget(t).privateUserPolicy,identity:declaredScopeIdentityColumns(t.scope)}:null},errors);if(errors.length>0)return{ok:false,errors};return{ok:true,declaration:{tables,removedTables:removedTables.sort(),exportedTables:exportedTables.sort(),...managedSearch?{search:managedSearch}:{},...fileCollections?{files:fileCollections}:{},...groupRoles?{groups:groupRoles}:{},...appRoles?{appRoles}:{},...payments?{payments}:{},...jobs?{jobs}:{},...serviceRoles?{serviceRoles}:{}}}}catch(err){if(err instanceof SchemaTsError){return{ok:false,errors:[`db/schema.ts could not be read: ${err.message}`]}}throw err}}var MAX_FILE_BYTES=256*1024;var MAX_PAYLOAD_CHARS=8*1024;var COMPARE_WINDOW=96;var MAX_FINDINGS_PER_FILE=20;var MAX_FINDINGS=100;var IDENT2=/^[A-Za-z_$][\w$]*$/;var WRITE=/\.(insert|update)\(\s*(['"`])([A-Za-z_]\w{0,63})\2\s*,\s*/g;var TX=/\.tx\(/g;var STEP=/\{(?=\s*['"]?(?:op|table)['"]?\s*:)/g;var VERIFIED=/\b(?:verifyInvocation|verifyWebhook|constructEvent|verifySignature)\s*\(/;var VERIFIER_NAMES=new Set(["verifyInvocation","verifyWebhook","constructEvent","verifySignature"]);function hasVerifierCall(source){const tokens=tokenizer2(source,{ecmaVersion:"latest",sourceType:"module"});let previous="";let member=false;for(const token of tokens){const kind=token.type.label;if(member&&kind==="(")return true;member=(previous==="."||previous==="?.")&&kind==="name"&&VERIFIER_NAMES.has(source.slice(token.start,token.end));previous=kind}return false}function stripComments(source){let out="";let i=0;while(i<source.length){const ch=source[i];const next=source[i+1];if(ch==='"'||ch==="'"||ch==="`"){let j=i+1;while(j<source.length&&source[j]!==ch&&!(ch!=="`"&&source[j]==="\n"))j+=source[j]==="\\"?2:1;out+=source.slice(i,j+1);i=j+1}else if(ch==="/"&&next==="/"){while(i<source.length&&source[i]!=="\n"){out+=" ";i++}}else if(ch==="/"&&next==="*"){const end=source.indexOf("*/",i+2);const stop=end<0?source.length:end+2;out+=source.slice(i,stop).replace(/[^\n]/g," ");i=stop}else{out+=ch;i++}}return out}function bindings(source){const b={objects:new Set,paths:new Set,forms:new Set,values:new Set,callers:new Set};const input=String.raw`\(?\s*(?:await\s+)?[\w$.]{1,64}\.(json|formData)\(\)`;for(const m of source.matchAll(new RegExp(String.raw`\b(?:const|let|var)\s+([A-Za-z_$][\w$]*)\s*(?::[^=;\n]{0,200})?=\s*${input}`,"g"))){(m[2]==="formData"?b.forms:b.objects).add(m[1])}const destructure=names=>{for(const part of names.split(",")){const name=part.split("=")[0].split(":").pop()?.trim();if(name&&IDENT2.test(name))b.values.add(name.toLowerCase())}};for(const m of source.matchAll(new RegExp(String.raw`\b(?:const|let|var)\s*\{([^{}]{0,2000})\}\s*(?::[^=;\n]{0,200})?=\s*${input}`,"g")))destructure(m[1]);for(const m of source.matchAll(/\b(?:const|let|var)\s*\{([^{}]{0,2000})\}\s*=\s*([A-Za-z_$][\w$]*)\s*[;\n]/g))if(b.objects.has(m[2]))destructure(m[1]);for(const m of source.matchAll(/\b(?:const|let|var)\s+([A-Za-z_$][\w$]*)\s*=\s*[\w$.]{0,64}(?:searchParams|\bparams)\.get\(/g))b.values.add(m[1].toLowerCase());for(const m of source.matchAll(/\b(?:const|let|var)\s+([A-Za-z_$][\w$]*)\s*(?::[^=;\n]{0,200})?=\s*(?:await\s+)?sw\.auth\.\w{1,40}\(/g))b.callers.add(m[1]);for(const m of source.matchAll(/\b(?:const|let|var)\s*\{([^{}]{0,2000})\}\s*=\s*(?:await\s+)?sw\.auth\.\w{1,40}\(/g)){for(const part of m[1].split(",")){const name=part.split("=")[0].split(":").pop()?.trim();if(name&&IDENT2.test(name))b.callers.add(name)}}if(/\bsw\.endpoint\s*\(/.test(source)){for(const m of source.matchAll(/\bhandler\s*(?::\s*)?(?:async\s*)?(?:function\s*)?\(\s*(?:\{([^{}]{0,400})\}|([A-Za-z_$][\w$]*))/g)){if(m[2]){b.paths.add(m[2]+".body");continue}for(const part of m[1].split(",")){const[key,renamed]=part.split("=")[0].split(":").map(x=>x.trim());const local=renamed||key;if(!local||!IDENT2.test(local))continue;if(key==="body")b.objects.add(local);else if(key==="user")b.callers.add(local)}}}return b}function requestObject(expression,b){const v=expression.trim();return b.objects.has(v)||b.paths.has(v)}function serverReceivers(source){const receivers=["sw.db.server"];for(const m of source.matchAll(/\b(?:const|let|var)\s+([A-Za-z_$][\w$]*)\s*=\s*sw\.db\.server\b(?!\.)/g))receivers.push(m[1]);return receivers}function receivedBy(source,dot,receivers){return receivers.some(receiver=>{const start=dot-receiver.length;return start>=0&&source.startsWith(receiver,start)&&!/[\w$.]/.test(source[start-1]??"")})}function objectLiteral(source,index){if(source[index]!=="{")return null;const end=Math.min(source.length,index+MAX_PAYLOAD_CHARS);let depth=0;let quote=null;for(let i=index;i<end;i++){const ch=source[i];if(quote){if(ch==="\\")i++;else if(ch===quote)quote=null;continue}if(ch==='"'||ch==="'"||ch==="`")quote=ch;else if(ch==="{")depth++;else if(ch==="}"&&--depth===0)return source.slice(index,i+1)}return null}function comparedToCaller(source,lower,column,callers){if(callers.size===0)return false;const needle=`.${column.toLowerCase()}`;const callerId=text=>{for(const m of text.matchAll(/([A-Za-z_$][\w$]*)(?:\??\.[A-Za-z_$][\w$]*){0,3}\??\.id\b/g))if(callers.has(m[1]))return true;for(const m of text.matchAll(/([A-Za-z_$][\w$]*)\??\.(?:userId|user_id)\b/g))if(callers.has(m[1]))return true;return false};for(let at2=lower.indexOf(needle);at2>=0;at2=lower.indexOf(needle,at2+1)){const after=at2+needle.length;if(/[\w$]/.test(lower[after]??""))continue;const owner=/([A-Za-z_$][\w$]*)\??$/.exec(source.slice(Math.max(0,at2-64),at2));if(owner&&callers.has(owner[1]))continue;const right=source.slice(after,after+COMPARE_WINDOW);const op=/^\s*[!=]==?\s*/.exec(right);if(op&&callerId(right.slice(op[0].length)))return true;const left=source.slice(Math.max(0,at2-COMPARE_WINDOW),at2);const lop=/[!=]==?\s*[\w$.?]{0,80}$/.exec(left);if(lop&&callerId(left.slice(0,lop.index).slice(-COMPARE_WINDOW)))return true}return false}function lineIndex(source){const starts=[0];for(let i=source.indexOf("\n");i>=0;i=source.indexOf("\n",i+1))starts.push(i+1);return starts}function lineAt2(starts,offset2){let lo=0,hi=starts.length-1;while(lo<hi){const mid=lo+hi+1>>1;if(starts[mid]<=offset2)lo=mid;else hi=mid-1}return lo+1}function requestValue(value,b){const v=value.trim().replace(/^(?:String|Number|BigInt)\(\s*([\s\S]*?)\s*\)$/,"$1").trim();const member=/^([A-Za-z_$][\w$]*(?:\??\.[A-Za-z_$][\w$]*)?)(?:\??\.[A-Za-z_$][\w$]*|\[[^\]]{1,64}\])$/.exec(v);if(member&&(b.objects.has(member[1])||b.paths.has(member[1].replace("?.","."))))return true;const root=/^([A-Za-z_$][\w$]*)(?:\??\.[A-Za-z_$][\w$]*|\[[^\]]{1,64}\])$/.exec(v);if(root&&b.objects.has(root[1]))return true;const form=/^([A-Za-z_$][\w$]*)\.get\(\s*['"`][\w-]{1,64}['"`]\s*\)$/.exec(v);if(form&&b.forms.has(form[1]))return true;return IDENT2.test(v)&&b.values.has(v.toLowerCase())}function entries(payload){const out=[];let depth=0,quote=null,start=1;const push=end=>{const text=payload.slice(start,end);const lead=text.length-text.trimStart().length;const body=text.trim();if(body){const spread=/^\.\.\.\s*([A-Za-z_$][\w$]*)$/.exec(body);const keyed=/^['"]?([A-Za-z_$][\w$]*)['"]?\s*(?::\s*([\s\S]*))?$/.exec(body);if(spread)out.push({key:null,spread:spread[1],value:"",offset:start+lead});else if(keyed)out.push({key:keyed[1],spread:null,value:keyed[2]??keyed[1],offset:start+lead})}start=end+1};for(let i=1;i<payload.length-1;i++){const ch=payload[i];if(quote){if(ch==="\\")i++;else if(ch===quote)quote=null;continue}if(ch==='"'||ch==="'"||ch==="`")quote=ch;else if("{[(".includes(ch))depth++;else if("}])".includes(ch))depth--;else if(ch===","&&depth===0)push(i)}push(payload.length-1);return out}function requestOwnershipFindings(functions,schema){const findings=[];let skippedFiles=0;let truncated=false;for(const[file,raw]of Object.entries(functions)){if(!file.startsWith("api/")||typeof raw!=="string"||!raw.includes("server"))continue;if(raw.length>MAX_FILE_BYTES){skippedFiles++;continue}if(findings.length>=MAX_FINDINGS){truncated=true;break}const source=stripComments(raw);if(VERIFIED.test(source)){if(/\.[jt]sx$/.test(file)||raw.includes("</")){skippedFiles++}else{try{if(hasVerifierCall(raw)){skippedFiles++;continue}}catch{skippedFiles++}}}const b=bindings(source);if(b.objects.size===0&&b.paths.size===0&&b.forms.size===0&&b.values.size===0)continue;const lower=source.toLowerCase();const receivers=serverReceivers(source);const starts=lineIndex(source);const columnsByTable=new Map;const seen=new Set;let fileCount=0;let fileFull=false;const report=(table,columns,offset2)=>{if(fileCount>=MAX_FINDINGS_PER_FILE||findings.length>=MAX_FINDINGS){truncated=true;fileFull=true;return false}const line=lineAt2(starts,offset2);const key=`${line}\0${table}\0${columns.join(",")}`;if(!seen.has(key)){seen.add(key);fileCount++;findings.push({file,line,table,columns})}return true};const ownershipColumns=table=>{const cached=columnsByTable.get(table);if(cached)return cached;const declared=schema.tables.find(t=>t.name===table);let columns=[];if(declared){const owner=declaredOwnerColumn(declared.scope);if(owner)columns=[owner];else if(declared.scope.kind==="server_only"){columns=declared.columns.map(c=>c.name).filter(name=>comparedToCaller(source,lower,name,b.callers))}}columnsByTable.set(table,columns);return columns};const inspect=(table,kind,at2)=>{const columns=ownershipColumns(table);if(columns.length===0)return;const bare=/^([A-Za-z_$][\w$]*(?:\.[A-Za-z_$][\w$]*)?)\s*[,)}]/.exec(source.slice(at2,at2+80));if(bare&&requestObject(bare[1],b)){report(table,columns,at2);return}const payload=objectLiteral(source,at2);if(!payload){if(source[at2]==="{")truncated=true;return}let list=entries(payload);if(kind==="update"){list=list.flatMap(e=>{if(e.key!=="set"&&e.key!=="where")return[e];const valueAt=payload.indexOf(e.value,e.offset);const inner=valueAt<0?null:objectLiteral(payload,valueAt);return inner?entries(inner).map(x=>({...x,offset:valueAt+x.offset})):[]}).filter(e=>e.key!=="op"&&e.key!=="table")}const spreadIndex=list.findIndex(e=>e.spread!==null&&b.objects.has(e.spread));const spreadColumns=[];for(const column of columns){const keyed=list.map((e,index)=>({e,index})).filter(({e})=>e.key?.toLowerCase()===column);const last=keyed[keyed.length-1];if(last&&requestValue(last.e.value,b))report(table,[last.e.key??column],at2+last.e.offset);else if(spreadIndex>=0&&(!last||last.index<spreadIndex))spreadColumns.push(column)}if(spreadColumns.length>0)report(table,spreadColumns,at2+list[spreadIndex].offset)};for(const m of source.matchAll(WRITE)){if(fileFull)break;if(!receivedBy(source,m.index,receivers))continue;inspect(m[3].toLowerCase(),m[1]==="update"?"update":"insert",m.index+m[0].length)}if(!fileFull&&[...source.matchAll(TX)].some(m=>receivedBy(source,m.index,receivers))){for(const m of source.matchAll(STEP)){if(fileFull)break;const step=objectLiteral(source,m.index);if(!step){truncated=true;continue}const fields=entries(step);const field=key=>fields.find(e=>e.key===key);const op=/^['"`](insert|update)['"`]$/.exec(field("op")?.value.trim()??"")?.[1];const table=/^['"`]([A-Za-z_]\w{0,63})['"`]$/.exec(field("table")?.value.trim()??"")?.[1];if(!op||!table)continue;if(op==="update"){inspect(table.toLowerCase(),"update",m.index);continue}const values=field("values");const valueAt=values?step.indexOf(values.value,values.offset):-1;if(valueAt>=0)inspect(table.toLowerCase(),"insert",m.index+valueAt)}}}return{findings,skippedFiles,truncated}}var MAX_FILE_BYTES2=256*1024;var MAX_FINDINGS_PER_FILE2=20;var MAX_FINDINGS2=100;var SEND=/await\s+sw\s*\.\s*email\s*\.\s*send\s*\(/y;var LOOP_HEADER=/(?:^|[^\w$.])(?:for|while)\s*(?:await\s*)?$/;var BLOCK_HEADER=/(?:^|[^\w$.])(?:if|switch|catch|with)\s*$/;function scanFile(source){const offsets=[];const seenLoops=new Set;const stack=[];let lastParen=null;let quote=null;let lastDoClose=-1;const prevNonSpace=i=>{let j=i-1;while(j>=0&&/\s/.test(source[j]))j--;return j};const nextNonSpace=i=>{let j=i;while(j<source.length&&/\s/.test(source[j]))j++;return j};const popLoopStatements=()=>{while(stack.length&&stack[stack.length-1].kind==="loopstmt")stack.pop()};for(let i=0;i<source.length;i++){const ch=source[i];if(quote){if(ch==="\\")i++;else if(ch===quote||ch==="\n"&&quote!=="`")quote=null;continue}const current2=stack[stack.length-1];if(current2?.kind==="loopstmt"){if(ch==="\n"&&current2.started){stack.pop();continue}if(!/\s/.test(ch))current2.started=true}if(ch==='"'||ch==="'"||ch==="`"){quote=ch;continue}if(ch==="/"){const p=prevNonSpace(i);const before=p<0?"":source[p];if(p<0||"(,=:[!&|?{};+-*%~^".includes(before)||/(?:^|[^\w$])(?:return|typeof|case|in|of|await|yield)$/.test(source.slice(Math.max(0,p-7),p+1))){let j=i+1,inClass=false;for(;j<source.length&&source[j]!=="\n";j++){if(source[j]==="\\"){j++;continue}if(source[j]==="[")inClass=true;else if(source[j]==="]")inClass=false;else if(source[j]==="/"&&!inClass)break}i=j;continue}}if(ch==="("){stack.push({kind:"paren",open:i});continue}if(ch===")"){while(stack.length&&stack[stack.length-1].kind==="loopstmt")stack.pop();const top2=stack[stack.length-1];if(top2?.kind==="paren"){stack.pop();lastParen={open:top2.open,close:i};const header=source.slice(Math.max(0,top2.open-24),top2.open);const next=source[nextNonSpace(i+1)];const trailer=/(?:^|[^\w$.])while\s*$/.exec(header);const doTrailer=trailer!==null&&prevNonSpace(top2.open-(header.length-header.lastIndexOf("while")))===lastDoClose;if(LOOP_HEADER.test(header)&&next!=="{"&&next!==";"&&!doTrailer){stack.push({kind:"loopstmt",open:i,depth:stack.length,started:false})}}continue}if(ch==="{"){const p=prevNonSpace(i);let kind="block";if(p>=1&&source[p]===">"&&source[p-1]==="=")kind="function";else if(lastParen&&(lastParen.close===p||lastParen.close<p&&i-lastParen.close<=128&&/^\s*:[^{};=()]*$/.test(source.slice(lastParen.close+1,i)))){const header=source.slice(Math.max(0,lastParen.open-24),lastParen.open);kind=LOOP_HEADER.test(header)?"loop":BLOCK_HEADER.test(header)?"block":"function"}else if(/(?:^|[^\w$.])do\s*$/.test(source.slice(Math.max(0,i-8),i))){stack.push({kind:"loop",open:i,isDo:true});continue}stack.push({kind,open:i});continue}if(ch==="}"){popLoopStatements();let k=stack.length-1;while(k>=0&&stack[k].kind==="paren")k--;const closed=k>=0?stack[k]:void 0;if(closed&&closed.kind==="loop"&&closed.isDo)lastDoClose=i;stack.length=Math.max(0,k);popLoopStatements();continue}if(ch===";"){const top2=stack[stack.length-1];if(top2?.kind==="loopstmt"&&top2.depth===stack.length-1)stack.pop();continue}if(ch!=="a"||/[\w$.]/.test(source[i-1]??""))continue;SEND.lastIndex=i;if(!SEND.test(source))continue;const top=stack[stack.length-1];if(top?.kind==="paren")continue;if(/=>\s*(?:async\s*)?$/.test(source.slice(Math.max(0,i-64),i)))continue;for(let k=stack.length-1;k>=0;k--){const frame=stack[k];if(frame.kind==="function")break;if(frame.kind==="loop"||frame.kind==="loopstmt"){if(!seenLoops.has(frame.open)){seenLoops.add(frame.open);offsets.push(i)}break}}}return offsets}function sequentialEmailFindings(functions){const findings=[];let skippedFiles=0;let truncated=false;for(const[file,raw]of Object.entries(functions)){if(typeof raw!=="string"||!raw.includes("email"))continue;if(raw.length>MAX_FILE_BYTES2){skippedFiles++;continue}const source=stripComments(raw);const offsets=scanFile(source);if(offsets.length===0)continue;const starts=lineIndex(source);for(const[n,offset2]of offsets.entries()){if(n>=MAX_FINDINGS_PER_FILE2||findings.length>=MAX_FINDINGS2){truncated=true;break}findings.push({file,line:lineAt2(starts,offset2)})}}return{findings,skippedFiles,truncated}}var MAX_FILE_BYTES3=256*1024;var MAX_FINDINGS_PER_FILE3=20;var MAX_FINDINGS3=100;var SEARCH_WINDOW=4e3;var CALL=/\blistUsers\s*\(/g;var SEARCH_METHODS="(?:find|filter|some|findIndex|findLast|findLastIndex)";var IDENT3=/^[A-Za-z_$][\w$]*$/;function closeOf(source,open){const pairs={"(":")","[":"]","{":"}"};const stack=[];let quote=null;for(let i=open;i<source.length;i++){const ch=source[i];if(quote){if(ch==="\\")i++;else if(ch===quote)quote=null;continue}if(ch==='"'||ch==="'"||ch==="`"){quote=ch;continue}if(pairs[ch])stack.push(pairs[ch]);else if(ch===")"||ch==="]"||ch==="}"){if(stack.pop()!==ch)return-1;if(stack.length===0)return i+1}}return-1}var escapeRe=s=>s.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");function resultRefs(before){const tail=before.slice(-200);const destructured=/(?:const|let|var)\s*\{([^{}]*)\}\s*=\s*(?:await\s+)?[\w$.?\s]*$/.exec(tail);if(destructured){for(const part of destructured[1].split(",")){const[key,alias]=part.split(":").map(s=>s.trim());if(key==="users")return[escapeRe(alias&&IDENT3.test(alias)?alias:"users")]}return[]}const named=/(?:(?:const|let|var)\s+)?([A-Za-z_$][\w$]*)\s*=\s*(?:await\s+)?[\w$.?\s]*$/.exec(tail);return named?[`${escapeRe(named[1])}\\s*\\??\\.\\s*users`]:[]}function comparesExactEmail(callback){return callback.split(/&&|\|\|/).some(clause=>/\.\s*email\b/.test(clause)&&/(?<![!=<>])={2,3}(?!=)/.test(clause))}function searchesExactEmail(source,from,refs){const window=source.slice(from,from+SEARCH_WINDOW);for(const ref2 of refs){const pattern=new RegExp(`(?:^|[^\\w$.])${ref2}\\s*\\??\\.\\s*${SEARCH_METHODS}\\s*\\(`,"g");for(let m=pattern.exec(window);m;m=pattern.exec(window)){const open=from+m.index+m[0].length-1;const close=closeOf(source,open);if(close>0&&comparesExactEmail(source.slice(open,close)))return true}}return false}function scanFile2(source){const offsets=[];for(let m=CALL.exec(source);m;m=CALL.exec(source)){const open=m.index+m[0].length-1;const close=closeOf(source,open);if(close<0)continue;if(/\bemails\b/.test(source.slice(open,close)))continue;const chained=new RegExp(`^\\s*\\)?\\s*\\??\\.\\s*users\\s*\\??\\.\\s*${SEARCH_METHODS}\\s*\\(`).exec(source.slice(close,close+120));if(chained){const searchOpen=close+chained[0].length-1;const searchClose=closeOf(source,searchOpen);if(searchClose>0&&comparesExactEmail(source.slice(searchOpen,searchClose))){offsets.push(m.index);continue}}const refs=resultRefs(source.slice(0,m.index));if(refs.length&&searchesExactEmail(source,close,refs))offsets.push(m.index)}CALL.lastIndex=0;return offsets}function userEmailScanFindings(functions){const findings=[];let skippedFiles=0;let truncated=false;for(const[file,raw]of Object.entries(functions)){if(typeof raw!=="string"||!raw.includes("listUsers"))continue;if(raw.length>MAX_FILE_BYTES3){skippedFiles++;continue}const source=stripComments(raw);const offsets=scanFile2(source);if(offsets.length===0)continue;const starts=lineIndex(source);for(const[n,offset2]of offsets.entries()){if(n>=MAX_FINDINGS_PER_FILE3||findings.length>=MAX_FINDINGS3){truncated=true;break}findings.push({file,line:lineAt2(starts,offset2)})}}return{findings,skippedFiles,truncated}}var SOURCE_LINT_VERSION="6";async function lintSourceSnapshot(files,functions={}){const entries2=map=>Object.keys(map).sort().map(key=>[key,map[key]]);const sha256=async value=>{const bytes=await crypto.subtle.digest("SHA-256",new TextEncoder().encode(value));return Array.from(new Uint8Array(bytes),byte=>byte.toString(16).padStart(2,"0")).join("")};const schema=files["db/schema.ts"];const[source_sha256,schema_sha256]=await Promise.all([sha256(JSON.stringify([entries2(files),entries2(functions)])),schema===void 0?Promise.resolve(null):sha256(schema)]);return{...lintSource(files,functions),source_sha256,schema_sha256}}function lintSource(files,functions={}){const findings=scanSourceForSecrets(files,functions).map(finding=>({rule:"somewhere/source-secret",severity:"warning",file:finding.file,line:finding.line,message:`${finding.label} in source. The existing deploy secret guard may refuse this source.`,fix:"A credential literal in source is readable by anyone with the source. A project environment variable without a VITE_ or REACT_APP_ prefix, read only inside a server handler, keeps it private.",docs:"https://somewhere.cloud/docs/sw.env.txt"}));const schema=files["db/schema.ts"];let requestOwnership="not-applicable";if(schema!==void 0){const parsed=extractSchemaTs(schema);if(!parsed.ok){requestOwnership="skipped";for(const message of parsed.errors){findings.push({rule:"somewhere/schema-declaration",severity:"warning",file:"db/schema.ts",line:Number(/\bline (\d+):/.exec(message)?.[1]??1),message,fix:"The indicated schema helper, column or access rule is what this declaration accepts. The same schema parser runs during deploy.",docs:"https://somewhere.cloud/docs/declared-data.txt"})}}else{let ownership=[];try{const result=requestOwnershipFindings(functions,parsed.declaration);ownership=result.findings;requestOwnership=result.skippedFiles>0||result.truncated?"partial":"checked"}catch{requestOwnership="skipped"}for(const finding of ownership){findings.push({rule:"somewhere/request-ownership",severity:"warning",file:finding.file,line:finding.line,message:finding.columns.length===1?`${finding.table}.${finding.columns[0]} is set or matched through sw.db.server from request input, so a caller can choose whose row this is. Lint cannot see authorization done elsewhere, so whether this write is authorized is not established.`:`${finding.table} ownership columns ${finding.columns.join(", ")} are set through sw.db.server from the whole request body, so a caller can choose whose row this is. Lint cannot see authorization done elsewhere, so whether this write is authorized is not established.`,fix:`${finding.columns.join(" and ")} set from the signed-in user (sw.auth), or by the user-mode sw.db write which sets ownership itself, cannot be chosen by the caller. A handler that intentionally acts for another user is safe only with a check of the caller's role before this write.`,docs:"https://somewhere.cloud/docs/declared-data.txt"})}}}let sequentialEmail=Object.keys(functions).length===0?"not-applicable":"checked";try{const result=sequentialEmailFindings(functions);if(result.skippedFiles>0||result.truncated)sequentialEmail="partial";for(const finding of result.findings){findings.push({rule:"somewhere/sequential-email",severity:"warning",file:finding.file,line:finding.line,message:"sw.email.send is awaited inside a loop, so each email waits for the previous one to be delivered and the total time grows with the number of recipients. A handler or job that reaches its time limit stops sending the rest without an error.",fix:"Independent emails can be sent a few at a time (for example batches of 5 with Promise.allSettled per batch) or from a job. A sequential loop is needed when order matters or an email depends on an earlier result; one unbounded Promise.all over an arbitrary list has no concurrency limit.",docs:"https://somewhere.cloud/docs/sw.email.txt"})}}catch{sequentialEmail="skipped"}let userEmailLookup=Object.keys(functions).length===0?"not-applicable":"checked";try{const result=userEmailScanFindings(functions);if(result.skippedFiles>0||result.truncated)userEmailLookup="partial";for(const finding of result.findings){findings.push({rule:"somewhere/user-email-scan",severity:"warning",file:finding.file,line:finding.line,message:"sw.auth listUsers is called without emails and its result is then searched for one exact email. That reads whole directory pages to find one user, so it gets slower as the app grows, and a user beyond the pages read is reported as missing.",fix:"sw.auth.server.listUsers({ emails: [email] }) looks the user up directly and returns only that user (users[0], or none). Paging listUsers fits real bulk work such as exports or admin lists.",docs:"https://somewhere.cloud/docs/sw.auth.txt"})}}catch{userEmailLookup="skipped"}for(const finding of apiIndexRouteFindings(functions)){findings.push({rule:"somewhere/index-route",severity:"warning",file:finding.file,line:1,message:finding.warning,fix:"A folder's index file serves the folder's own path. Keep one of the two handlers; a deploy refuses both.",docs:"https://somewhere.cloud/docs/functions.txt"})}findings.sort((a,b)=>a.file.localeCompare(b.file)||a.line-b.line||a.rule.localeCompare(b.rule));return{version:SOURCE_LINT_VERSION,findings,coverage:{schema:schema===void 0?"absent":"checked",request_ownership:requestOwnership,sequential_email:sequentialEmail,user_email_lookup:userEmailLookup,authorization:"not-assessed"}}}