nucleus-core-ts 0.10.190 → 0.10.191

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/.build-ok CHANGED
@@ -1 +1 @@
1
- 0.10.190
1
+ 0.10.191
package/dist/server.js CHANGED
@@ -672,4 +672,4 @@ ${content}
672
672
  ip_address = null, user_agent = null, query = null,
673
673
  old_values = '{}'::jsonb, new_values = '{}'::jsonb, summary = ${REDACTED2}
674
674
  where user_id::text = ${userId} or entity_id::text = ${userId}
675
- or entity_id::text = any (${ids}::text[])`),count6=typeof result==="object"&&result!==null?Reflect.get(result,"rowCount"):0;return typeof count6==="number"?count6:0}var log7=logger.scoped("auth.accountErasure"),ERASURE_REASON="Account erasure (KVKK/GDPR right to erasure)";async function plan(executor,schema3,userId,policy2,options){let planned=[],refused=[],foreignKeys=await userReferences(executor,schema3),declared=await declaredReferences(executor,schema3,declaredColumns(options),foreignKeys);for(let ref3 of[...foreignKeys,...declared]){if(ref3.table===AUDIT_TABLE)continue;let rows=await countReferences(executor,schema3,ref3,userId);if(rows===0)continue;let rule=ruleFor(policy2,ref3),name2=`${ref3.table}.${ref3.column}`;if(rule===void 0)refused.push(`${name2}: no rule`);else{let problem=problemOf(ref3,rule);if(problem===null)planned.push({ref:ref3,rule,rows});else refused.push(`${name2}: ${problem}`)}}if(refused.length>0)throw new AccountErasureError(`Erasure refused, references left unhandled: ${refused.join("; ")}`,refused.map((line)=>line.split(":")[0]??line));return planned}async function apply2(executor,schema3,userId,{ref:ref3,rule},summary){let table2=sql47`${sql47.identifier(schema3)}.${sql47.identifier(ref3.table)}`,column3=sql47.identifier(ref3.column),own=ref3.table==="users"?sql47` and id <> ${userId}`:sql47``,returning=ref3.hasId?sql47` returning id`:sql47``;if(rule==="delete"){let done=touchedOf(await executor.execute(sql47`delete from ${table2} where ${column3} = ${userId}${own}${returning}`),ref3.hasId);return summary.deleted[ref3.table]=(summary.deleted[ref3.table]??0)+done.count,done.ids}if(rule==="nullify"){let done=touchedOf(await executor.execute(sql47`update ${table2} set ${column3} = null where ${column3} = ${userId}${own}${returning}`),ref3.hasId);return summary.nullified[ref3.table]=(summary.nullified[ref3.table]??0)+done.count,[]}let rows=(summary.kept[ref3.table]?.rows??0)+await countReferences(executor,schema3,ref3,userId);return summary.kept[ref3.table]={rows,reason:rule.keep},[]}async function eraseUser(unit,userId,policy2,options={}){return assertKeepReasons(policy2),unit.withoutRules(ERASURE_REASON,()=>erase(unit,userId,policy2,options))}async function erase(unit,userId,policy2,options){let executor=executorOf2(unit),schema3=unit.schema,summary={sessions:await endUserSessions(unit,userId),deleted:{},nullified:{},kept:{},users:0,auditScrubbed:0},planned=await plan(executor,schema3,userId,policy2,options),deletedIds=[];for(let step of planned)deletedIds.push(...await apply2(executor,schema3,userId,step,summary));summary.auditScrubbed=await scrubAuditRows(executor,schema3,userId,deletedIds);let removed=await executor.execute(sql47`delete from ${sql47.identifier(schema3)}.users where id = ${userId}`);return summary.users=touchedOf(removed,!1).count,await unit.audit({entityName:"users",operation:"ERASE_USER",summary:"An account was erased.",severity:"info",category:"system",newValues:{...summary}}),log7.info("Account erased",{schema:schema3,...summary}),summary}init_hostPasswordCheck();init_hooks();init_linkAuthorization();init_profileSync();init_profileSyncHooks();import{sql as sql48}from"drizzle-orm";init_Logger2();init_schema();var log8=logger.scoped("tenant.purge"),PROTECTED_SCHEMAS=new Set(["public","information_schema"]);class TenantPurgeRefusedError extends Error{tenantId;status;constructor(tenantId,status){super(`Tenant ${tenantId} is ${status}: purging it needs force`);this.tenantId=tenantId;this.status=status;this.name="TenantPurgeRefusedError"}}function toRow(row){if(row===void 0)return null;return{subdomain:String(Reflect.get(row,"subdomain")),schemaName:String(Reflect.get(row,"schema_name")),status:String(Reflect.get(row,"status"))}}function assertDroppable(schemaName,mainSchema){if(validateIdentifier(schemaName),schemaName===mainSchema||PROTECTED_SCHEMAS.has(schemaName)||schemaName.startsWith("pg_"))throw Error(`Refusing to drop protected schema "${schemaName}"`)}async function purgeTenant(tenantId,options){let registry5=options.registry===void 0?currentRegistry():options.registry,main=sql48.identifier(validateIdentifier(options.mainSchema)),outcome=await options.db.transaction(async(tx)=>{await tx.execute(sql48`select pg_advisory_xact_lock(hashtext(${`tenant_purge:${tenantId}`}))`);let found=await tx.execute(sql48`select subdomain, schema_name, status from ${main}.tenants where id = ${tenantId} for update`),row=toRow(rowsOfResult(found)[0]);if(row===null){let leftover=registry5?.getTenantById(tenantId)?.schemaName;if(leftover!==void 0)assertDroppable(leftover,options.mainSchema),await tx.execute(sql48`drop schema if exists ${sql48.identifier(leftover)} cascade`);return{purged:!1,tenantId,alreadyPurged:!0}}if(row.status==="active"&&options.force!==!0)throw new TenantPurgeRefusedError(tenantId,row.status);return assertDroppable(row.schemaName,options.mainSchema),await writeTenantAudit(tx,options.mainSchema,{entityName:"tenants",entityId:tenantId,operation:"TENANT_PURGE",summary:`${row.subdomain} hard-deleted${options.reason?` (${options.reason})`:""}`,category:"admin",severity:"critical",oldValues:{subdomain:row.subdomain,schemaName:row.schemaName,status:row.status},newValues:{reason:options.reason??null,performedBy:options.performedBy??null}}),await tx.execute(sql48`drop schema if exists ${sql48.identifier(row.schemaName)} cascade`),await tx.execute(sql48`delete from ${main}.tenants where id = ${tenantId}`),{purged:!0,tenantId,subdomain:row.subdomain,schemaName:row.schemaName}});return await registry5?.forgetTenant(tenantId),log8.info(outcome.purged?"Tenant purged":"Tenant already purged",{tenantId}),outcome}function formErrors(rule,fields,context){let merged={...context.item,...context.entered},checked=validateFieldValues(fields,merged,{party:context.actor.side}).errors,errors2=new Map;for(let id of Object.keys(context.entered))if(!rule.form.includes(id))errors2.set(id,"unknown_field");for(let id of rule.form){let code=Object.hasOwn(checked,id)?checked[id]:void 0;if(code===void 0)continue;if(Object.hasOwn(context.entered,id)&&!isEmptyValue(context.entered[id])||code==="required")errors2.set(id,code)}return Object.fromEntries(errors2)}var holdsRole=(rule,context)=>context.actor.roles.some((role)=>rule.roles.includes(role)),onForm=(rule)=>rule.when!==null&&rule.form.includes(rule.when.field),conditionFails=(rule,context)=>rule.when!==null&&!evaluateCondition(rule.when,{...context.item,...context.entered});function ruleFailure(rule,fields,context){if(rule.side!==context.actor.side)return{code:"transition_side_forbidden"};if(!holdsRole(rule,context))return{code:"transition_role_forbidden"};if(rule.onlyCreator&&!context.isCreator)return{code:"transition_creator_only"};if(!onForm(rule)&&conditionFails(rule,context))return{code:"transition_condition_not_met"};if(context.mode==="offer")return null;let fieldErrors=formErrors(rule,fields,context);if(Object.keys(fieldErrors).length>0)return{code:"transition_fields_invalid",fieldErrors};if(onForm(rule)&&conditionFails(rule,context))return{code:"transition_condition_not_met"};if(rule.requireNote&&(context.note??"").trim()==="")return{code:"transition_note_required"};return null}var FLOW_FAILURE_CODES=["transition_unknown","transition_unknown_state","transition_source_mismatch","transition_from_final","transition_start_forbidden","transition_side_forbidden","transition_role_forbidden","transition_creator_only","transition_condition_not_met","transition_fields_invalid","transition_note_required"];function failureCodeOf(message){return FLOW_FAILURE_CODES.find((code)=>code===message)??null}function rulesOf(document){return document.transitions.flatMap((transition)=>{let common={key:transition.key,to:transition.to,side:transition.side,roles:transition.roles,form:transition.form,requireNote:transition.requireNote,onlyCreator:transition.onlyCreator===!0,when:transition.when??null};return(transition.from==="create"?[null]:transition.from).map((from)=>({...common,from}))})}function edgesOf(rules,fields){let grouped=new Map;for(let rule of rules){if(rule.from===null)continue;let targets=grouped.get(rule.from)??new Map;targets.set(rule.to,[...targets.get(rule.to)??[],rule]),grouped.set(rule.from,targets)}let edges=new Map;for(let[from,targets]of grouped)edges.set(from,[...targets].map(([to,edgeRules])=>({to,guard:(context)=>{let rule=edgeRules.find((candidate)=>candidate.key===context.key);if(rule===void 0)return"transition_source_mismatch";return ruleFailure(rule,fields,context)?.code??!0}})));return edges}function buildFlow(document,options={}){let rules=rulesOf(document),fields=document.fields??[],edges=edgesOf(rules,fields),transitions=Object.fromEntries(document.states.map((state)=>[state.key,edges.get(state.key)??[]])),terminal=document.states.filter((state)=>state.terminal===!0||options.isTerminal?.(state)===!0).map((state)=>state.key),declared=new Set(document.states.map((state)=>state.key));return{table:{initial:[...new Set(rules.filter((rule)=>rule.from===null&&declared.has(rule.to)).map((rule)=>rule.to))],terminal,transitions},rules,fields}}var REFUSALS={unknown_state:"transition_unknown_state",terminal_state:"transition_from_final",no_transition:"transition_source_mismatch"};function ruleOf(flow,key2,from){let found=flow.rules.find((rule)=>rule.key===key2&&rule.from===from);if(found!==void 0)return found;return flow.rules.some((rule)=>rule.key===key2)?"transition_source_mismatch":"transition_unknown"}function judge2(flow,rule,context){if(rule.from===null){if(!canStartIn(flow.table,rule.to))return{ok:!1,code:"transition_start_forbidden"};let failure2=ruleFailure(rule,flow.fields,context);return failure2===null?{ok:!0,rule}:{ok:!1,...failure2}}if(!Object.hasOwn(flow.table.transitions,rule.to))return{ok:!1,code:"transition_unknown_state"};let evaluation=evaluate(flow.table,rule.from,rule.to,context);if(evaluation.allowed)return{ok:!0,rule};if(evaluation.reason!=="guard_rejected")return{ok:!1,code:REFUSALS[evaluation.reason]};let failure=ruleFailure(rule,flow.fields,context),code=failure?.code??failureCodeOf(evaluation.message);return code===null?{ok:!1,code:"transition_source_mismatch"}:{ok:!1,code,...failure?.fieldErrors?{fieldErrors:failure.fieldErrors}:{}}}function decideTransition(flow,attempt3){let rule=ruleOf(flow,attempt3.key,attempt3.from);if(typeof rule==="string")return{ok:!1,code:rule};return judge2(flow,rule,{...attempt3,mode:"perform"})}function allowedTransitions(flow,offer){return flow.rules.filter((rule)=>rule.from===offer.state&&ruleOf(flow,rule.key,rule.from)===rule&&judge2(flow,rule,{...offer,from:offer.state,key:rule.key,entered:{},mode:"offer"}).ok)}function flowProblems(document,options={}){let problems=[],add2=(code,subject,message)=>problems.push({code,subject,message}),states=new Set;for(let state of document.states){if(states.has(state.key))add2("duplicate_state",state.key,`State "${state.key}" is declared twice`);states.add(state.key)}let defined=new Set((document.fields??[]).map((field2)=>field2.id)),keys=new Set;for(let transition of document.transitions){if(keys.has(transition.key))add2("duplicate_transition",transition.key,`Transition "${transition.key}" is declared twice`);keys.add(transition.key);let sources=transition.from==="create"?[]:transition.from;if(transition.roles.length===0)add2("no_roles",transition.key,`Transition "${transition.key}" lists no role: nobody could make it`);if(transition.from!=="create"&&sources.length===0)add2("no_source",transition.key,`Transition "${transition.key}" starts from no state`);for(let state of[...sources,transition.to])if(!states.has(state))add2("unknown_state",transition.key,`Transition "${transition.key}" names unknown state "${state}"`);for(let id of transition.form)if(!defined.has(id))add2("unknown_form_field",transition.key,`Transition "${transition.key}" asks for unknown field "${id}"`);if(transition.when!==void 0&&!defined.has(transition.when.field))add2("unknown_condition_field",transition.key,`Transition "${transition.key}" has a condition on unknown field "${transition.when.field}"`)}let flow=buildFlow(document,options);if(!flow.rules.some((rule)=>rule.from===null))add2("no_create_transition","","The flow has no transition that creates an item");for(let message of tableProblems(flow.table))add2("unusable_table","",message);return problems}function numberPeriod(format2,clock={}){if(!format2.yearly)return"";let year=new Intl.DateTimeFormat("en-US",{timeZone:clock.timeZone??"UTC",year:"numeric"}).formatToParts(clock.now??new Date).find((part)=>part.type==="year")?.value;if(year===void 0)throw RangeError("Could not read the year of the clock");return year.padStart(4,"0")}function formatNumber(format2,period,counter){if(!Number.isSafeInteger(counter)||counter<1)throw RangeError("A counter value is a positive integer");let separator=format2.separator??"-",padded=String(counter).padStart(format2.digits,"0");return[format2.prefix,period,padded].filter((part)=>part!=="").join(separator)}var NUMBER_COUNTER_TABLE="number_counters";function numberCounterTable(){return{table_name:NUMBER_COUNTER_TABLE,add_base_columns:!1,excluded_methods:["GET","POST","PUT","PATCH","DELETE","TOGGLE","VERIFICATION"],columns:[{name:"sequence",type:"varchar",length:128,notNull:!0},{name:"period",type:"varchar",length:16,notNull:!0,default:""},{name:"counter",type:"integer",notNull:!0,check:"counter >= 0"}],constraints:{unique:[{name:`${NUMBER_COUNTER_TABLE}_sequence_period_key`,columns:["sequence","period"]}]}}}var MAX_SEQUENCE_LENGTH=128;function assertSequenceKey(key2){if(key2===""||key2.length>MAX_SEQUENCE_LENGTH)throw RangeError(`A sequence key is 1 to ${MAX_SEQUENCE_LENGTH} characters`)}async function nextNumber(unit,sequence,clock={}){assertSequenceKey(sequence.key);let period=numberPeriod(sequence.format,clock),row=await unit.store.from(NUMBER_COUNTER_TABLE).upsert({conflict:{columns:["sequence","period"]},insert:{sequence:sequence.key,period,counter:1},set:{counter:{$inc:1}}});return{reference:formatNumber(sequence.format,period,row.counter),counter:row.counter,period}}async function raiseNumberCounter(unit,sequence,period,atLeast){if(!Number.isSafeInteger(atLeast)||atLeast<0)throw RangeError("A counter is raised to a non-negative integer");assertSequenceKey(sequence);let counters=unit.store.from(NUMBER_COUNTER_TABLE),row=await counters.upsert({conflict:{columns:["sequence","period"]},insert:{sequence,period,counter:atLeast},set:{counter:{$inc:0}}});if(row.counter>=atLeast)return row.counter;let[raised]=await counters.updateWhere({sequence,period,counter:{lt:atLeast}},{counter:atLeast});return raised?.counter??atLeast}export{writeTenantNotifications,writeTenantNotification,writeTenantAudit,visibleFieldIds,viewGroup,viewClaimOf,versionedDocumentTables,versionedDocumentImmutabilitySql,verifyUserPassword,validatePasswordStrength,validateNucleusConfig,validateFieldValues,validateFieldValue,validateFieldDefinitions,upper,unsafeExecutorOf,unitOfWorkFor,translate,toIndexEntries,tableProblems,tableExists,sum,sub,storeFromExecutor,statesOf,serve,safeRegExp,safeCast,runUnitOfWork,runRowView,runMigrations,runAggregateView,rulesOf,ruleFailure,round,resolveProfileSyncUpdates,replace,refreshTenantFeatures,refreshTenant,refreshAllTenants,readView,readMoney,readLedger,readDateRange,raiseNumberCounter,qualified,purgeTenant,purgeExpiredIdempotencyKeys,pruneFieldValues,provisionWithMigrations,profileSyncHooks,payloadHash,parseParams,parseFilterValue,param,ownedObjects,optionLabel,objectExists,numberPeriod,numberCounterTable,nucleusDataOf,now,nextNumber,min,migrationOwnedDropGuard,measure,max,lower,localize,lit,least,json,isTerminal,isTenantFeatureEnabled,isSystemActor,isStringList2 as isStringList,isRowView,isJsonObject2 as isJsonObject,isIndexed,isExpr,isEmptyValue,isCalendarDate,initialFieldValues,indexedFieldIds,indexColumnFor,hiddenFieldIds,hashPassword,hasEntityRules,greatest,getResolvedOptions2 as getResolvedOptions,formatNumber,formatConfigIssues,formErrors,flowProblems,fieldValuesSchema,fieldValueSchema,fieldDefinitionsSchema,fieldDefinitionSchema,failureCodeOf,evaluateCondition,evaluate,eraseUser,endUserSessions,encodeViewCursor,documentTransactionsOf,documentTableNames,documentLeaves,diffSeconds,diffDocuments,defineWebSocketRoute,defineViewRoute,defineRules,defineRoute,defineJobFor,defineJob,defineDocumentType,defineActionFor,defineAction,decodeViewCursor,decodeHeaderList,decideTransition,cursorValues,createViewBuilder,createUserAccount,createPgDocumentTransactions,createNucleusServer,createJobRunner,createEntityStore,createDocumentStore,createBootMigrations,countView,countRowView,countAggregateView,count,configureProfileSync,configureOAuthLinkAuthorization,configureAuthorizationDiscovery,concatWs,concat,computed,completeIdempotency,compileRowView,collectRoutes,col,codePointLength,coalesce,claimIdempotencyKey,checksumOf,caseWhen,canStartIn,canEnter,buildOpenApiDocument,buildNucleus,buildFlow,buildEntityRules,buildConfigViews,buildConfigView,bucket,bindDocumentStore,avg,allowedTransitions,allowedTargets,aggregateOf,add,actionGroup,WhereError,ViewParamError,ViewError,TenantPurgeRefusedError,StoreError,ScopeViolationError,SYSTEM_ACTOR_KINDS,RuleSet,RuleError,RESERVED_IDS,REFERENCE_PATTERN,NucleusTestApp,NUMBER_COUNTER_TABLE,MigrationFailedError,MigrationDefinitionError,MigrationChecksumError,MAX_VIEW_LIMIT,MAX_PREFIX_LENGTH,MAX_OPTIONS,MAX_FIELDS,LOCK_MODES,LENGTH_LIMITS,LEDGER_TABLE,IdempotencyConflictError,ID_PATTERN,IDEMPOTENCY_TABLE,FLOW_FAILURE_CODES,FIELD_PARTIES,FIELD_LOCALES,FIELD_KINDS,FIELD_ERROR_CODES,ExprError,EntityStore,EMAIL_PATTERN,DocumentUnreadableError,DEFINITION_ISSUE_CODES,DEFAULT_VIEW_LIMIT,DEFAULT_LOCK_TIMEOUT_MS,DEFAULT_ARRAY_IDENTITY,ConstraintError,CURRENCY_PATTERN,CONDITION_OPS,ActionError,AccountErasureError};
675
+ or entity_id::text = any (${ids}::text[])`),count6=typeof result==="object"&&result!==null?Reflect.get(result,"rowCount"):0;return typeof count6==="number"?count6:0}var log7=logger.scoped("auth.accountErasure"),ERASURE_REASON="Account erasure (KVKK/GDPR right to erasure)";async function plan(executor,schema3,userId,policy2,options){let planned=[],refused=[],foreignKeys=await userReferences(executor,schema3),declared=await declaredReferences(executor,schema3,declaredColumns(options),foreignKeys);for(let ref3 of[...foreignKeys,...declared]){if(ref3.table===AUDIT_TABLE)continue;let rows=await countReferences(executor,schema3,ref3,userId);if(rows===0)continue;let rule=ruleFor(policy2,ref3),name2=`${ref3.table}.${ref3.column}`;if(rule===void 0)refused.push(`${name2}: no rule`);else{let problem=problemOf(ref3,rule);if(problem===null)planned.push({ref:ref3,rule,rows});else refused.push(`${name2}: ${problem}`)}}if(refused.length>0)throw new AccountErasureError(`Erasure refused, references left unhandled: ${refused.join("; ")}`,refused.map((line)=>line.split(":")[0]??line));return planned}async function apply2(executor,schema3,userId,{ref:ref3,rule},summary){let table2=sql47`${sql47.identifier(schema3)}.${sql47.identifier(ref3.table)}`,column3=sql47.identifier(ref3.column),own=ref3.table==="users"?sql47` and id <> ${userId}`:sql47``,returning=ref3.hasId?sql47` returning id`:sql47``;if(rule==="delete"){let done=touchedOf(await executor.execute(sql47`delete from ${table2} where ${column3} = ${userId}${own}${returning}`),ref3.hasId);return summary.deleted[ref3.table]=(summary.deleted[ref3.table]??0)+done.count,done.ids}if(rule==="nullify"){let done=touchedOf(await executor.execute(sql47`update ${table2} set ${column3} = null where ${column3} = ${userId}${own}${returning}`),ref3.hasId);return summary.nullified[ref3.table]=(summary.nullified[ref3.table]??0)+done.count,[]}let rows=(summary.kept[ref3.table]?.rows??0)+await countReferences(executor,schema3,ref3,userId);return summary.kept[ref3.table]={rows,reason:rule.keep},[]}async function eraseUser(unit,userId,policy2,options={}){return assertKeepReasons(policy2),unit.withoutRules(ERASURE_REASON,()=>erase(unit,userId,policy2,options))}async function erase(unit,userId,policy2,options){let executor=executorOf2(unit),schema3=unit.schema,summary={sessions:await endUserSessions(unit,userId),deleted:{},nullified:{},kept:{},users:0,auditScrubbed:0},planned=await plan(executor,schema3,userId,policy2,options),deletedIds=[];for(let step of planned)deletedIds.push(...await apply2(executor,schema3,userId,step,summary));summary.auditScrubbed=await scrubAuditRows(executor,schema3,userId,deletedIds);let removed=await executor.execute(sql47`delete from ${sql47.identifier(schema3)}.users where id = ${userId}`);return summary.users=touchedOf(removed,!1).count,await unit.audit({entityName:"users",operation:"ERASE_USER",summary:"An account was erased.",severity:"info",category:"system",newValues:{...summary}}),log7.info("Account erased",{schema:schema3,...summary}),summary}init_hostPasswordCheck();init_hooks();init_linkAuthorization();init_profileSync();init_profileSyncHooks();import{sql as sql48}from"drizzle-orm";init_Logger2();init_schema();var log8=logger.scoped("tenant.purge"),PROTECTED_SCHEMAS=new Set(["public","information_schema"]);class TenantPurgeRefusedError extends Error{tenantId;status;constructor(tenantId,status){super(`Tenant ${tenantId} is ${status}: purging it needs force`);this.tenantId=tenantId;this.status=status;this.name="TenantPurgeRefusedError"}}function toRow(row){if(row===void 0)return null;return{subdomain:String(Reflect.get(row,"subdomain")),schemaName:String(Reflect.get(row,"schema_name")),status:String(Reflect.get(row,"status"))}}function assertDroppable(schemaName,mainSchema){if(validateIdentifier(schemaName),schemaName===mainSchema||PROTECTED_SCHEMAS.has(schemaName)||schemaName.startsWith("pg_"))throw Error(`Refusing to drop protected schema "${schemaName}"`)}async function purgeTenant(tenantId,options){let registry5=options.registry===void 0?currentRegistry():options.registry,done=(outcome2)=>{log8.info(outcome2.purged?"Tenant purged":"Tenant already purged",{tenantId})};if(options.unit!==void 0&&options.db!==void 0)throw Error("purgeTenant takes a db or a unit, not both");if(options.unit!==void 0){if(options.unit.schema!==options.mainSchema)throw Error(`purgeTenant joins a unit on the main schema "${options.mainSchema}", not "${options.unit.schema}"`);return options.unit.nested(async(inner)=>{let outcome2=await purgeIn(executorOf2(inner),inner.audit,tenantId,options,registry5);return inner.afterCommit(async()=>{await registry5?.forgetTenant(tenantId),done(outcome2)}),outcome2})}if(options.db===void 0)throw Error("purgeTenant needs a db or a unit");let outcome=await options.db.transaction((tx)=>purgeIn(tx,(entry)=>writeTenantAudit(tx,options.mainSchema,entry),tenantId,options,registry5));return await registry5?.forgetTenant(tenantId),done(outcome),outcome}async function purgeIn(tx,audit,tenantId,options,registry5){let main=sql48.identifier(validateIdentifier(options.mainSchema));await tx.execute(sql48`select pg_advisory_xact_lock(hashtext(${`tenant_purge:${tenantId}`}))`);let found=await tx.execute(sql48`select subdomain, schema_name, status from ${main}.tenants where id = ${tenantId} for update`),row=toRow(rowsOfResult(found)[0]);if(row===null){let leftover=registry5?.getTenantById(tenantId)?.schemaName;if(leftover!==void 0)assertDroppable(leftover,options.mainSchema),await tx.execute(sql48`drop schema if exists ${sql48.identifier(leftover)} cascade`);return{purged:!1,tenantId,alreadyPurged:!0}}if(row.status==="active"&&options.force!==!0)throw new TenantPurgeRefusedError(tenantId,row.status);return assertDroppable(row.schemaName,options.mainSchema),await audit({entityName:"tenants",entityId:tenantId,operation:"TENANT_PURGE",summary:`${row.subdomain} hard-deleted${options.reason?` (${options.reason})`:""}`,category:"admin",severity:"critical",oldValues:{subdomain:row.subdomain,schemaName:row.schemaName,status:row.status},newValues:{reason:options.reason??null,performedBy:options.performedBy??null}}),await tx.execute(sql48`drop schema if exists ${sql48.identifier(row.schemaName)} cascade`),await tx.execute(sql48`delete from ${main}.tenants where id = ${tenantId}`),{purged:!0,tenantId,subdomain:row.subdomain,schemaName:row.schemaName}}function formErrors(rule,fields,context){let merged={...context.item,...context.entered},checked=validateFieldValues(fields,merged,{party:context.actor.side}).errors,errors2=new Map;for(let id of Object.keys(context.entered))if(!rule.form.includes(id))errors2.set(id,"unknown_field");for(let id of rule.form){let code=Object.hasOwn(checked,id)?checked[id]:void 0;if(code===void 0)continue;if(Object.hasOwn(context.entered,id)&&!isEmptyValue(context.entered[id])||code==="required")errors2.set(id,code)}return Object.fromEntries(errors2)}var holdsRole=(rule,context)=>context.actor.roles.some((role)=>rule.roles.includes(role)),onForm=(rule)=>rule.when!==null&&rule.form.includes(rule.when.field),conditionFails=(rule,context)=>rule.when!==null&&!evaluateCondition(rule.when,{...context.item,...context.entered});function ruleFailure(rule,fields,context){if(rule.side!==context.actor.side)return{code:"transition_side_forbidden"};if(!holdsRole(rule,context))return{code:"transition_role_forbidden"};if(rule.onlyCreator&&!context.isCreator)return{code:"transition_creator_only"};if(!onForm(rule)&&conditionFails(rule,context))return{code:"transition_condition_not_met"};if(context.mode==="offer")return null;let fieldErrors=formErrors(rule,fields,context);if(Object.keys(fieldErrors).length>0)return{code:"transition_fields_invalid",fieldErrors};if(onForm(rule)&&conditionFails(rule,context))return{code:"transition_condition_not_met"};if(rule.requireNote&&(context.note??"").trim()==="")return{code:"transition_note_required"};return null}var FLOW_FAILURE_CODES=["transition_unknown","transition_unknown_state","transition_source_mismatch","transition_from_final","transition_start_forbidden","transition_side_forbidden","transition_role_forbidden","transition_creator_only","transition_condition_not_met","transition_fields_invalid","transition_note_required"];function failureCodeOf(message){return FLOW_FAILURE_CODES.find((code)=>code===message)??null}function rulesOf(document){return document.transitions.flatMap((transition)=>{let common={key:transition.key,to:transition.to,side:transition.side,roles:transition.roles,form:transition.form,requireNote:transition.requireNote,onlyCreator:transition.onlyCreator===!0,when:transition.when??null};return(transition.from==="create"?[null]:transition.from).map((from)=>({...common,from}))})}function edgesOf(rules,fields){let grouped=new Map;for(let rule of rules){if(rule.from===null)continue;let targets=grouped.get(rule.from)??new Map;targets.set(rule.to,[...targets.get(rule.to)??[],rule]),grouped.set(rule.from,targets)}let edges=new Map;for(let[from,targets]of grouped)edges.set(from,[...targets].map(([to,edgeRules])=>({to,guard:(context)=>{let rule=edgeRules.find((candidate)=>candidate.key===context.key);if(rule===void 0)return"transition_source_mismatch";return ruleFailure(rule,fields,context)?.code??!0}})));return edges}function buildFlow(document,options={}){let rules=rulesOf(document),fields=document.fields??[],edges=edgesOf(rules,fields),transitions=Object.fromEntries(document.states.map((state)=>[state.key,edges.get(state.key)??[]])),terminal=document.states.filter((state)=>state.terminal===!0||options.isTerminal?.(state)===!0).map((state)=>state.key),declared=new Set(document.states.map((state)=>state.key));return{table:{initial:[...new Set(rules.filter((rule)=>rule.from===null&&declared.has(rule.to)).map((rule)=>rule.to))],terminal,transitions},rules,fields}}var REFUSALS={unknown_state:"transition_unknown_state",terminal_state:"transition_from_final",no_transition:"transition_source_mismatch"};function ruleOf(flow,key2,from){let found=flow.rules.find((rule)=>rule.key===key2&&rule.from===from);if(found!==void 0)return found;return flow.rules.some((rule)=>rule.key===key2)?"transition_source_mismatch":"transition_unknown"}function judge2(flow,rule,context){if(rule.from===null){if(!canStartIn(flow.table,rule.to))return{ok:!1,code:"transition_start_forbidden"};let failure2=ruleFailure(rule,flow.fields,context);return failure2===null?{ok:!0,rule}:{ok:!1,...failure2}}if(!Object.hasOwn(flow.table.transitions,rule.to))return{ok:!1,code:"transition_unknown_state"};let evaluation=evaluate(flow.table,rule.from,rule.to,context);if(evaluation.allowed)return{ok:!0,rule};if(evaluation.reason!=="guard_rejected")return{ok:!1,code:REFUSALS[evaluation.reason]};let failure=ruleFailure(rule,flow.fields,context),code=failure?.code??failureCodeOf(evaluation.message);return code===null?{ok:!1,code:"transition_source_mismatch"}:{ok:!1,code,...failure?.fieldErrors?{fieldErrors:failure.fieldErrors}:{}}}function decideTransition(flow,attempt3){let rule=ruleOf(flow,attempt3.key,attempt3.from);if(typeof rule==="string")return{ok:!1,code:rule};return judge2(flow,rule,{...attempt3,mode:"perform"})}function allowedTransitions(flow,offer){return flow.rules.filter((rule)=>rule.from===offer.state&&ruleOf(flow,rule.key,rule.from)===rule&&judge2(flow,rule,{...offer,from:offer.state,key:rule.key,entered:{},mode:"offer"}).ok)}function flowProblems(document,options={}){let problems=[],add2=(code,subject,message)=>problems.push({code,subject,message}),states=new Set;for(let state of document.states){if(states.has(state.key))add2("duplicate_state",state.key,`State "${state.key}" is declared twice`);states.add(state.key)}let defined=new Set((document.fields??[]).map((field2)=>field2.id)),keys=new Set;for(let transition of document.transitions){if(keys.has(transition.key))add2("duplicate_transition",transition.key,`Transition "${transition.key}" is declared twice`);keys.add(transition.key);let sources=transition.from==="create"?[]:transition.from;if(transition.roles.length===0)add2("no_roles",transition.key,`Transition "${transition.key}" lists no role: nobody could make it`);if(transition.from!=="create"&&sources.length===0)add2("no_source",transition.key,`Transition "${transition.key}" starts from no state`);for(let state of[...sources,transition.to])if(!states.has(state))add2("unknown_state",transition.key,`Transition "${transition.key}" names unknown state "${state}"`);for(let id of transition.form)if(!defined.has(id))add2("unknown_form_field",transition.key,`Transition "${transition.key}" asks for unknown field "${id}"`);if(transition.when!==void 0&&!defined.has(transition.when.field))add2("unknown_condition_field",transition.key,`Transition "${transition.key}" has a condition on unknown field "${transition.when.field}"`)}let flow=buildFlow(document,options);if(!flow.rules.some((rule)=>rule.from===null))add2("no_create_transition","","The flow has no transition that creates an item");for(let message of tableProblems(flow.table))add2("unusable_table","",message);return problems}function numberPeriod(format2,clock={}){if(!format2.yearly)return"";let year=new Intl.DateTimeFormat("en-US",{timeZone:clock.timeZone??"UTC",year:"numeric"}).formatToParts(clock.now??new Date).find((part)=>part.type==="year")?.value;if(year===void 0)throw RangeError("Could not read the year of the clock");return year.padStart(4,"0")}function formatNumber(format2,period,counter){if(!Number.isSafeInteger(counter)||counter<1)throw RangeError("A counter value is a positive integer");let separator=format2.separator??"-",padded=String(counter).padStart(format2.digits,"0");return[format2.prefix,period,padded].filter((part)=>part!=="").join(separator)}var NUMBER_COUNTER_TABLE="number_counters";function numberCounterTable(){return{table_name:NUMBER_COUNTER_TABLE,add_base_columns:!1,excluded_methods:["GET","POST","PUT","PATCH","DELETE","TOGGLE","VERIFICATION"],columns:[{name:"sequence",type:"varchar",length:128,notNull:!0},{name:"period",type:"varchar",length:16,notNull:!0,default:""},{name:"counter",type:"integer",notNull:!0,check:"counter >= 0"}],constraints:{unique:[{name:`${NUMBER_COUNTER_TABLE}_sequence_period_key`,columns:["sequence","period"]}]}}}var MAX_SEQUENCE_LENGTH=128;function assertSequenceKey(key2){if(key2===""||key2.length>MAX_SEQUENCE_LENGTH)throw RangeError(`A sequence key is 1 to ${MAX_SEQUENCE_LENGTH} characters`)}async function nextNumber(unit,sequence,clock={}){assertSequenceKey(sequence.key);let period=numberPeriod(sequence.format,clock),row=await unit.store.from(NUMBER_COUNTER_TABLE).upsert({conflict:{columns:["sequence","period"]},insert:{sequence:sequence.key,period,counter:1},set:{counter:{$inc:1}}});return{reference:formatNumber(sequence.format,period,row.counter),counter:row.counter,period}}async function raiseNumberCounter(unit,sequence,period,atLeast){if(!Number.isSafeInteger(atLeast)||atLeast<0)throw RangeError("A counter is raised to a non-negative integer");assertSequenceKey(sequence);let counters=unit.store.from(NUMBER_COUNTER_TABLE),row=await counters.upsert({conflict:{columns:["sequence","period"]},insert:{sequence,period,counter:atLeast},set:{counter:{$inc:0}}});if(row.counter>=atLeast)return row.counter;let[raised]=await counters.updateWhere({sequence,period,counter:{lt:atLeast}},{counter:atLeast});return raised?.counter??atLeast}export{writeTenantNotifications,writeTenantNotification,writeTenantAudit,visibleFieldIds,viewGroup,viewClaimOf,versionedDocumentTables,versionedDocumentImmutabilitySql,verifyUserPassword,validatePasswordStrength,validateNucleusConfig,validateFieldValues,validateFieldValue,validateFieldDefinitions,upper,unsafeExecutorOf,unitOfWorkFor,translate,toIndexEntries,tableProblems,tableExists,sum,sub,storeFromExecutor,statesOf,serve,safeRegExp,safeCast,runUnitOfWork,runRowView,runMigrations,runAggregateView,rulesOf,ruleFailure,round,resolveProfileSyncUpdates,replace,refreshTenantFeatures,refreshTenant,refreshAllTenants,readView,readMoney,readLedger,readDateRange,raiseNumberCounter,qualified,purgeTenant,purgeExpiredIdempotencyKeys,pruneFieldValues,provisionWithMigrations,profileSyncHooks,payloadHash,parseParams,parseFilterValue,param,ownedObjects,optionLabel,objectExists,numberPeriod,numberCounterTable,nucleusDataOf,now,nextNumber,min,migrationOwnedDropGuard,measure,max,lower,localize,lit,least,json,isTerminal,isTenantFeatureEnabled,isSystemActor,isStringList2 as isStringList,isRowView,isJsonObject2 as isJsonObject,isIndexed,isExpr,isEmptyValue,isCalendarDate,initialFieldValues,indexedFieldIds,indexColumnFor,hiddenFieldIds,hashPassword,hasEntityRules,greatest,getResolvedOptions2 as getResolvedOptions,formatNumber,formatConfigIssues,formErrors,flowProblems,fieldValuesSchema,fieldValueSchema,fieldDefinitionsSchema,fieldDefinitionSchema,failureCodeOf,evaluateCondition,evaluate,eraseUser,endUserSessions,encodeViewCursor,documentTransactionsOf,documentTableNames,documentLeaves,diffSeconds,diffDocuments,defineWebSocketRoute,defineViewRoute,defineRules,defineRoute,defineJobFor,defineJob,defineDocumentType,defineActionFor,defineAction,decodeViewCursor,decodeHeaderList,decideTransition,cursorValues,createViewBuilder,createUserAccount,createPgDocumentTransactions,createNucleusServer,createJobRunner,createEntityStore,createDocumentStore,createBootMigrations,countView,countRowView,countAggregateView,count,configureProfileSync,configureOAuthLinkAuthorization,configureAuthorizationDiscovery,concatWs,concat,computed,completeIdempotency,compileRowView,collectRoutes,col,codePointLength,coalesce,claimIdempotencyKey,checksumOf,caseWhen,canStartIn,canEnter,buildOpenApiDocument,buildNucleus,buildFlow,buildEntityRules,buildConfigViews,buildConfigView,bucket,bindDocumentStore,avg,allowedTransitions,allowedTargets,aggregateOf,add,actionGroup,WhereError,ViewParamError,ViewError,TenantPurgeRefusedError,StoreError,ScopeViolationError,SYSTEM_ACTOR_KINDS,RuleSet,RuleError,RESERVED_IDS,REFERENCE_PATTERN,NucleusTestApp,NUMBER_COUNTER_TABLE,MigrationFailedError,MigrationDefinitionError,MigrationChecksumError,MAX_VIEW_LIMIT,MAX_PREFIX_LENGTH,MAX_OPTIONS,MAX_FIELDS,LOCK_MODES,LENGTH_LIMITS,LEDGER_TABLE,IdempotencyConflictError,ID_PATTERN,IDEMPOTENCY_TABLE,FLOW_FAILURE_CODES,FIELD_PARTIES,FIELD_LOCALES,FIELD_KINDS,FIELD_ERROR_CODES,ExprError,EntityStore,EMAIL_PATTERN,DocumentUnreadableError,DEFINITION_ISSUE_CODES,DEFAULT_VIEW_LIMIT,DEFAULT_LOCK_TIMEOUT_MS,DEFAULT_ARRAY_IDENTITY,ConstraintError,CURRENCY_PATTERN,CONDITION_OPS,ActionError,AccountErasureError};
@@ -1,8 +1,29 @@
1
- import type { UnitDatabase } from '../../Data/unitTypes';
1
+ import type { AfterCommitCallback, UnitDatabase } from '../../Data/unitTypes';
2
+ import { type TenantAuditRow } from './hostWrites';
2
3
  import type { TenantRegistry } from './TenantRegistry';
4
+ /** What the purge needs of the savepoint unit it runs in. */
5
+ interface PurgeInner {
6
+ readonly schema: string;
7
+ audit(entry: TenantAuditRow): Promise<void>;
8
+ afterCommit(callback: AfterCommitCallback): void;
9
+ }
10
+ /**
11
+ * A unit of work on the MAIN schema to purge inside (any `UnitOfWork`, a main-scope job's for one): the
12
+ * purge runs in a savepoint on the unit's own connection, its audit row is the unit's, and the registry
13
+ * forgets the tenant only after the unit's outermost commit.
14
+ */
15
+ export interface PurgeUnit {
16
+ readonly schema: string;
17
+ nested<T>(work: (inner: PurgeInner) => Promise<T>): Promise<T>;
18
+ }
3
19
  export interface PurgeTenantOptions {
4
- /** The database the purge runs on (a drizzle `db`). */
5
- db: UnitDatabase;
20
+ /** The database the purge runs on (a drizzle `db`): the purge is its own transaction. */
21
+ db?: UnitDatabase;
22
+ /**
23
+ * Or the unit of work it joins (a job's unit, a request's unit): no second pool connection, and the
24
+ * purge commits or rolls back with the unit. Exactly one of `db` and `unit`.
25
+ */
26
+ unit?: PurgeUnit;
6
27
  /** The main (control-plane) schema holding `tenants`, `tenant_features` and the platform `audit_logs`. */
7
28
  mainSchema: string;
8
29
  /** The registry to forget the tenant in. Default: the registry of this process (none: nothing to forget). */
@@ -33,7 +54,9 @@ export declare class TenantPurgeRefusedError extends Error {
33
54
  constructor(tenantId: string, status: string);
34
55
  }
35
56
  /**
36
- * Hard-deletes one tenant, in ONE transaction: its schema (`drop schema ... cascade`), its main-schema
57
+ * Hard-deletes one tenant, in ONE transaction (its own on `db`, or a savepoint of the caller's `unit`,
58
+ * which then needs no second pool connection and commits or rolls back the purge with its own work):
59
+ * its schema (`drop schema ... cascade`), its main-schema
37
60
  * rows (`tenants`, which cascades `tenant_features`, `tenant_events`, ...) and a `TENANT_PURGE` row in
38
61
  * the main schema's `audit_logs`, which outlives the tenant. After the commit the registry forgets the
39
62
  * tenant (indices, schema context, hostnames, features, Redis resolution cache), so its host answers
@@ -46,3 +69,4 @@ export declare class TenantPurgeRefusedError extends Error {
46
69
  * - Never drops the main schema, `public`, `information_schema` or a `pg_*` schema.
47
70
  */
48
71
  export declare function purgeTenant(tenantId: string, options: PurgeTenantOptions): Promise<PurgeTenantOutcome>;
72
+ export {};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "nucleus-core-ts",
3
- "version": "0.10.190",
3
+ "version": "0.10.191",
4
4
  "description": "Production-ready, enterprise-grade TypeScript framework for building multi-tenant APIs",
5
5
  "author": "Hidayet Can Özcan <hidayetcan@gmail.com>",
6
6
  "license": "SEE LICENSE IN LICENSE",