admindb 2.1.1 → 2.2.1

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 (91) hide show
  1. package/README.md +41 -12
  2. package/dist/app.js +230 -1
  3. package/dist/auth/config.js +121 -1
  4. package/dist/auth/crypto.js +108 -1
  5. package/dist/auth/index.js +21 -1
  6. package/dist/auth/middleware.js +85 -1
  7. package/dist/auth/routes.js +70 -1
  8. package/dist/auth/types.js +7 -1
  9. package/dist/cli/args.js +320 -1
  10. package/dist/cli/config.js +128 -1
  11. package/dist/cli/index.js +20 -1
  12. package/dist/cli/runner.js +211 -1
  13. package/dist/cli.js +4 -1
  14. package/dist/data/chain.d.ts +1 -0
  15. package/dist/data/chain.js +707 -0
  16. package/dist/data/datasets.js +129 -1
  17. package/dist/data/detector.d.ts +1 -1
  18. package/dist/data/detector.js +511 -1
  19. package/dist/data/engine.d.ts +1 -1
  20. package/dist/data/engine.js +245 -1
  21. package/dist/data/index.d.ts +1 -1
  22. package/dist/data/index.js +22 -1
  23. package/dist/data/strategies.d.ts +1 -1
  24. package/dist/data/strategies.js +339 -1
  25. package/dist/data/types.d.ts +1 -1
  26. package/dist/data/types.js +5 -1
  27. package/dist/db/database.d.ts +1 -1
  28. package/dist/db/database.js +477 -1
  29. package/dist/db/export.d.ts +1 -1
  30. package/dist/db/export.js +90 -1
  31. package/dist/db/filters.js +142 -1
  32. package/dist/db/index.js +24 -1
  33. package/dist/db/introspection.js +167 -1
  34. package/dist/db/manager.js +351 -1
  35. package/dist/db/migrations.js +107 -1
  36. package/dist/db/postgres.d.ts +1 -1
  37. package/dist/db/postgres.js +735 -1
  38. package/dist/db/types.d.ts +1 -1
  39. package/dist/db/types.js +6 -1
  40. package/dist/index.js +52 -1
  41. package/dist/public/css/app.css +1 -1
  42. package/dist/public/js/api.js +1 -1
  43. package/dist/public/js/browse.js +1 -1
  44. package/dist/public/js/common.js +1 -0
  45. package/dist/public/js/databases.js +1 -1
  46. package/dist/public/js/designer.js +1 -1
  47. package/dist/public/js/forms.js +1 -1
  48. package/dist/public/js/home.js +1 -0
  49. package/dist/public/js/inspector.js +1 -1
  50. package/dist/public/js/query.js +1 -1
  51. package/dist/public/js/schema.js +1 -1
  52. package/dist/public/js/seed.js +1 -1
  53. package/dist/routes/api/erd.d.ts +1 -0
  54. package/dist/routes/api/erd.js +50 -0
  55. package/dist/routes/api/helpers.d.ts +1 -1
  56. package/dist/routes/api/helpers.js +163 -1
  57. package/dist/routes/api/import-export.js +83 -1
  58. package/dist/routes/api/index.js +48 -1
  59. package/dist/routes/api/query.js +78 -1
  60. package/dist/routes/api/rows.js +362 -1
  61. package/dist/routes/api/seed.js +153 -1
  62. package/dist/routes/api/tables.js +231 -1
  63. package/dist/routes/databases.js +228 -1
  64. package/dist/routes/index.js +19 -1
  65. package/dist/routes/pages.js +397 -1
  66. package/dist/serverless.js +174 -1
  67. package/dist/sql/classifier.js +24 -1
  68. package/dist/sql/error-analyzer.d.ts +1 -0
  69. package/dist/sql/error-analyzer.js +550 -0
  70. package/dist/sql/generator.js +319 -1
  71. package/dist/sql/index.js +18 -1
  72. package/dist/types/api.js +2 -1
  73. package/dist/utils/colors.js +54 -1
  74. package/dist/utils/common.d.ts +1 -1
  75. package/dist/utils/common.js +225 -1
  76. package/dist/utils/csv.js +67 -1
  77. package/dist/utils/datatype.js +181 -1
  78. package/dist/utils/icons.js +81 -1
  79. package/dist/utils/index.js +20 -1
  80. package/dist/utils/logger.js +36 -1
  81. package/dist/views/layouts/main.hbs +14 -1
  82. package/dist/views/pages/erd.hbs +1241 -0
  83. package/dist/views/pages/home.hbs +98 -2
  84. package/dist/views/pages/info.hbs +107 -0
  85. package/dist/views/pages/query.hbs +54 -12
  86. package/dist/views/pages/seed.hbs +435 -171
  87. package/dist/views/partials/sidebar.hbs +12 -0
  88. package/docs/API.md +6 -1
  89. package/docs/EXAMPLES.md +3 -0
  90. package/package.json +5 -4
  91. package/dist/public/js/icons.js +0 -1
@@ -1 +1,511 @@
1
- Object.defineProperty(exports,"__esModule",{value:!0}),exports.normName=void 0,exports.isTimestampName=isTimestampName,exports.findInMap=findInMap,exports.extractCheckExprs=extractCheckExprs,exports.parseChecks=parseChecks,exports.detectPlan=detectPlan,exports.buildColumnConfigs=function(info){const fkByColumn=new Map(info.foreignKeys.map(fk=>[fk.from,fk])),uniqueCols=new Set,jsonIndexKeys=new Map;for(const ix of info.indexes??[])if(ix.unique&&1===ix.columns.length&&ix.columns[0]&&uniqueCols.add(ix.columns[0]),ix.sql&&/json_extract|->>|->\s*'|json_/i.test(ix.sql))for(const{col:col,keys:keys}of extractJsonColumns(ix.sql)){if(!col)continue;const merged=new Set([...jsonIndexKeys.get(col)??[],...keys]);merged.size&&jsonIndexKeys.set(col,[...merged])}const checkInfo=parseChecks(info.sql??null);return info.columns.map(col=>{const fk=fkByColumn.get(col.name)??null,strategies=(0,strategies_1.strategiesFor)(col,fk),unique=uniqueCols.has(col.name);let defaultPlan=detectPlan(col,fk);if("fk"!==defaultPlan.strategy&&!col.pk&&function(col,hasJsonIndex){if(!(0,strategies_1.isTextishType)(col.type))return!1;if(hasJsonIndex)return!0;const dflt=String(col.dflt_value??"").trim();if(dflt.startsWith("{")||dflt.startsWith("'{\""))return!0;const name=(0,exports.normName)(col.name);return/^(permissions|settings|config|configuration|preferences|prefs|metadata|meta|attributes|payload|options|allowedapps|socialaccounts|positions|fcmtokens|fcm_tokens|scopes|profile|json|jsonb)$/.test(name)||/(^|_)(settings|config|configuration|permissions|prefs|metadata|attributes|payload|options|allowedapps|scopes|profile)$/.test(name)}(col,jsonIndexKeys.has(col.name))){const keys=jsonIndexKeys.get(col.name),useKeys=keys&&keys.length?keys:["scope","enabled","allowedApps"],allowed=findInMap(checkInfo.jsonAllowed,col.name),jsonValues={};if(allowed)for(const k of useKeys){const vals=allowed.get(k);vals&&vals.length&&(jsonValues[k]=vals)}defaultPlan={strategy:"json",jsonKeys:useKeys,...Object.keys(jsonValues).length?{jsonValues:jsonValues}:{}}}const colAllowed=findInMap(checkInfo.columnAllowed,col.name);colAllowed&&colAllowed.length>0&&"fk"!==defaultPlan.strategy&&!col.pk&&(defaultPlan=1===colAllowed.length?{strategy:"fixed",value:colAllowed[0]}:{strategy:"list",values:[...colAllowed]});const colRange=findInMap(checkInfo.columnRange,col.name);return!colRange||"int"!==defaultPlan.strategy&&"decimal"!==defaultPlan.strategy||(null!=colRange.min&&(defaultPlan.min=colRange.min),null!=colRange.max&&(defaultPlan.max=colRange.max)),strategies.some(s=>s.id===defaultPlan.strategy)&&(col.pk||!col.notnull||null!=col.dflt_value||"skip"!==defaultPlan.strategy&&"null"!==defaultPlan.strategy)||(defaultPlan=(0,strategies_1.fallbackPlanFor)(col)),{name:col.name,type:col.type,pk:col.pk>0,notnull:!!col.notnull,hasDefault:null!=col.dflt_value,unique:unique,fk:fk,strategies:strategies,defaultPlan:defaultPlan}})},exports.sanitizeColumnPlan=function(raw){if(!raw||"object"!=typeof raw)return null;const r=raw;if("string"!=typeof r.strategy||!r.strategy)return null;const out={strategy:r.strategy};void 0!==r.values&&null!==r.values&&Array.isArray(r.values)&&(out.values=r.values.map(x=>String(x)));if(void 0!==r.jsonKeys&&null!==r.jsonKeys){const rawKeys=Array.isArray(r.jsonKeys)?r.jsonKeys.map(String):String(r.jsonKeys).split(/[,;]/);out.jsonKeys=rawKeys.map(s=>s.trim()).filter(Boolean)}for(const key of STR_PLAN_KEYS)void 0!==r[key]&&null!==r[key]&&(out[key]=String(r[key]));for(const key of NUM_PLAN_KEYS)if(void 0!==r[key]&&null!==r[key]){const n=Number(r[key]);Number.isFinite(n)&&(out[key]=n)}if(r.jsonValues&&"object"==typeof r.jsonValues&&!Array.isArray(r.jsonValues)){const jv={};for(const[k,vals]of Object.entries(r.jsonValues))if(Array.isArray(vals)){const cleaned=vals.map(x=>String(x).trim()).filter(Boolean);cleaned.length&&(jv[k]=cleaned)}Object.keys(jv).length&&(out.jsonValues=jv)}return out};const strategies_1=require("./strategies");function isTimestampName(name){return/created|updated|modified|registered|joined|timestamp|lastused|lastseen|lastlogin|lastactivity|accessed|viewed|visited|^ts$/.test(name)||/^(created|updated|deleted|archived|occurred|started|ended|expires|published|processed|completed|inserted|requested|resolved|used|seen|accessed|viewed|visited|logged|active)at$/.test(name)}function findInMap(map,colName){if(map.has(colName))return map.get(colName);const lower=colName.toLowerCase();for(const[k,v]of map.entries())if(k.toLowerCase()===lower)return v}function extractCheckExprs(sql){const out=[],re=/CHECK\s*\(/gi;let m;for(;m=re.exec(sql);){let depth=1,i=m.index+m[0].length;const start=i;for(;i<sql.length&&depth>0;){const ch=sql[i];if("'"!==ch){if('"'===ch||"`"===ch||"["===ch){const close="["===ch?"]":ch;for(i+=1;i<sql.length&&sql[i]!==close;)sql[i]===close&&sql[i+1]===close?i+=2:i+=1;i+=1;continue}if("("===ch)depth+=1;else if(")"===ch&&(depth-=1,0===depth))break;i+=1}else for(i+=1;i<sql.length;)if("'"===sql[i]){if("'"!==sql[i+1]){i+=1;break}i+=2}else i+=1}out.push(sql.slice(start,i))}return out}function parseChecks(sql){const info={columnAllowed:new Map,columnRange:new Map,jsonAllowed:new Map,ordering:new Map};if(!sql)return info;const setOrdering=(col,other,key,orEqual)=>{const c=info.ordering.get(col)??{};c[key]={column:other,orEqual:orEqual},info.ordering.set(col,c)},setColumnAllowed=(col,vals)=>{if(!col||!vals.length)return;const existing=findInMap(info.columnAllowed,col);if(existing)for(const v of vals)existing.includes(v)||existing.push(v);else info.columnAllowed.set(col,[...vals])};for(const expr of extractCheckExprs(sql)){const jw1=/(?:"([^"]+)"|`([^`]+)`|\[([^\]]+)\]|([A-Za-z_][A-Za-z0-9_]*))\s*(?:->>|->)\s*'([^']+)'\s*\)*\s*IN\s*\(([^)]*)\)/gi,jw2=/json_extract\s*\(\s*(?:"([^"]+)"|`([^`]+)`|\[([^\]]+)\]|([A-Za-z_][A-Za-z0-9_]*))\s*,\s*'(?:\$\??|\.)?\.?([^']+)'\s*\)\s*\)*\s*IN\s*\(([^)]*)\)/gi;for(const re of[jw1,jw2]){let m;for(;m=re.exec(expr);){const col=m[1]||m[2]||m[3]||m[4],key=m[5],inContent=m[6],strValues=(inContent.match(/'(?:[^']|'')*'/g)??[]).map(s=>s.slice(1,-1).replace(/''/g,"'")),values=strValues.length?strValues:inContent.match(/-?\b\d+(?:\.\d+)?\b/g)??[];if(values.length&&col&&key){const byCol=findInMap(info.jsonAllowed,col)??new Map;byCol.set(key,values),info.jsonAllowed.set(col,byCol)}}}const colIn=/(?:^|[^(->>\w])(?:\(\s*)?(?:(?:lower|upper|trim|coalesce)\s*\(\s*)?(?:"([^"]+)"|`([^`]+)`|\[([^\]]+)\]|([A-Za-z_][A-Za-z0-9_]*))(?:\s*,\s*[^)]+)?\s*\)?\s*\)?\s*IN\s*\(([^)]*)\)/gi;let mColIn;for(;mColIn=colIn.exec(expr);){const col=mColIn[1]||mColIn[2]||mColIn[3]||mColIn[4];if(!col||["json_extract","strftime","datetime","date","length","typeof"].includes(col.toLowerCase()))continue;const matchPos=mColIn.index;if(expr.slice(Math.max(0,matchPos-5),matchPos).includes("->"))continue;const inContent=mColIn[5],strValues=(inContent.match(/'(?:[^']|'')*'/g)??[]).map(s=>s.slice(1,-1).replace(/''/g,"'")),values=strValues.length?strValues:inContent.match(/-?\b\d+(?:\.\d+)?\b/g)??[];values.length&&setColumnAllowed(col,values)}const eqOr=/(?:"([^"]+)"|`([^`]+)`|\[([^\]]+)\]|([A-Za-z_][A-Za-z0-9_]*))\s*=\s*'((?:[^']|'')*)'/gi;let mEq;const eqByCol=new Map;for(;mEq=eqOr.exec(expr);){const col=mEq[1]||mEq[2]||mEq[3]||mEq[4],val=mEq[5].replace(/''/g,"'");if(col&&!["json_extract","lower","upper","trim","strftime","datetime"].includes(col.toLowerCase())){const cur=eqByCol.get(col)??[];cur.includes(val)||cur.push(val),eqByCol.set(col,cur)}}for(const[col,vals]of eqByCol.entries())setColumnAllowed(col,vals);const numCmp1=/(?:"([^"]+)"|`([^`]+)`|\[([^\]]+)\]|([A-Za-z_][A-Za-z0-9_]*))\s*(>=|>|<=|<)\s*(-?\d+(?:\.\d+)?)/g;let mNum1;for(;mNum1=numCmp1.exec(expr);){const col=mNum1[1]||mNum1[2]||mNum1[3]||mNum1[4],op=mNum1[5],val=Number(mNum1[6]);if(col&&Number.isFinite(val)&&!["json_extract","length","strftime","datetime"].includes(col.toLowerCase())){const cur=findInMap(info.columnRange,col)??{};">="===op||">"===op?cur.min=null!=cur.min?Math.max(cur.min,">"===op?val+1:val):">"===op?val+1:val:cur.max=null!=cur.max?Math.min(cur.max,"<"===op?val-1:val):"<"===op?val-1:val,info.columnRange.set(col,cur)}}const ord=/(?:"([^"]+)"|`([^`]+)`|\[([^\]]+)\]|([A-Za-z_][A-Za-z0-9_]*))\s*(>=|<=|>|<)\s*(?:"([^"]+)"|`([^`]+)`|\[([^\]]+)\]|([A-Za-z_][A-Za-z0-9_]*))/g;let m2;for(;m2=ord.exec(expr);){const a=m2[1]||m2[2]||m2[3]||m2[4],op=m2[5],b=m2[6]||m2[7]||m2[8]||m2[9];a&&b&&!/^\d+$/.test(a)&&!/^\d+$/.test(b)&&(["json_extract","strftime","datetime","date","length"].includes(a.toLowerCase())||["json_extract","strftime","datetime","date","length"].includes(b.toLowerCase())||(">"===op||">="===op?(setOrdering(a,b,"after",">="===op),setOrdering(b,a,"before",">="===op)):(setOrdering(a,b,"before","<="===op),setOrdering(b,a,"after","<="===op))))}}return info}exports.normName=s=>String(s).toLowerCase().replace(/[^a-z0-9]/g,"");const isHashName=name=>/^(hash|digest|secret|passphrase)$|tokenhash|passwordhash|passhash|accesskey|apikey|api_key|secretkey|clientsecret|appsecret|appid|privatekey|publickey/.test(name),isTokenName=name=>/^prefix$|tokenprefix|(code|ref|reference|sku|ticketno|ticketnum|orderno|order_no|trackingno|trackingnum|invno|invoiceno|serialno)$/.test(name);function extractJsonColumns(sql){const out=[],push=(col,key)=>{let entry=out.find(e=>e.col===col);if(entry||(entry={col:col,keys:[]},out.push(entry)),key){const last=key.split(".").pop().replace(/[\[\]"]/g,"");last&&!entry.keys.includes(last)&&entry.keys.push(last)}},arrow=/"([^"]+)"\s*(?:->>|->)\s*'([^']+)'|([A-Za-z_][A-Za-z0-9_]*)\s*(?:->>|->)\s*'([^']+)'/g;let m;for(;m=arrow.exec(sql);)push(m[1]||m[3],m[2]||m[4]);const jx=/json_extract\s*\(\s*(?:"([^"]+)"|([A-Za-z_][A-Za-z0-9_]*))\s*,\s*'(?:\$\??|\.)?\.?([^']+)'/g;for(;m=jx.exec(sql);)push(m[1]||m[2],m[3]);return out}const TEXT_PATTERNS=[[/avatar|picture|photo|image|img|thumbnail|icon|logo/,()=>({strategy:"avatar"})],[/company|organization|org|firm|corp|employer|agency/,()=>({strategy:"company"})],[/job|title|role|position|occupation|profession/,()=>({strategy:"job"})],[/currency|curr|currencycode/,()=>({strategy:"currency"})],[/countrycode|countryiso|isocountry|cca2/,()=>({strategy:"countryCode"})],[/state|province|region/,n=>/status|statement/.test(n)?{strategy:"status"}:{strategy:"state"}],[/status|stage|phase|state/,()=>({strategy:"status"})],[/color|colour|theme|hexcolor/,()=>({strategy:"color",format:"hex"})],[/mac|macaddress|hwaddr/,()=>({strategy:"mac"})],[/creditcard|cardnumber|cardno|ccnumber|ccno/,()=>({strategy:"creditCard"})],[/slug|permalink|handle|alias/,()=>({strategy:"slug"})],[/(lastname|surname|familyname)/,()=>({strategy:"last"})],[/email|mail/,()=>({strategy:"email"})],[/(username|login|handle|nick|nickname|account|user)/,()=>({strategy:"username"})],[/(phone|mobile|telephone|cell|fax)/,()=>({strategy:"phone"})],[/city|town/,()=>({strategy:"city"})],[/country|nation/,()=>({strategy:"country"})],[/postal|zip/,()=>({strategy:"postal"})],[/address|street|addr/,()=>({strategy:"address"})],[/url|website|site|link|homepage|href/,()=>({strategy:"url"})],[/domain|host/,()=>({strategy:"domain"})],[/^ip$|ipaddr|ipv4|ip_address/,()=>({strategy:"ip"})],[/bio|about|overview|article|body|post|story/,()=>({strategy:"paragraph"})],[/description|content|comment|message|note|summary|details|remarks/,()=>({strategy:"sentence",minLen:1,maxLen:2})],[/title|subject|category|type|tag|label/,()=>({strategy:"words",minLen:1,maxLen:3})]];function detectPlan(col,fk){const type=(col.type||"").toUpperCase(),rawName=col.name.toLowerCase(),name=(0,exports.normName)(col.name);if(fk)return{strategy:"fk"};if(col.pk)return type.startsWith("INT")||"SERIAL"===type||"BIGSERIAL"===type?{strategy:"skip"}:"TEXT"===type||"BLOB"===type||"UUID"===type?{strategy:"uuid"}:{strategy:"skip"};if("UUID"===type)return{strategy:"uuid"};if("JSON"===type||"JSONB"===type)return{strategy:"json"};if("INET"===type)return{strategy:"ip"};if("BOOLEAN"===type||"BOOL"===type)return{strategy:"bool"};if("BYTEA"===type||"BLOB"===type)return{strategy:"bytes",minLen:8,maxLen:32};if((type.startsWith("INT")||type.startsWith("INTEGER"))&&/(^|_)(is|has|can|should|did)_|_flag$|active|enabled|verified|published|deleted|archived|paid|completed|approved/.test(rawName))return{strategy:"bool"};if("DATE"===type||/^date|birthdate|dob|birthday/.test(rawName))return name.includes("birth")?{strategy:"date",from:"1950-01-01",to:"2000-12-31"}:{strategy:"date",from:"2020-01-01",to:"2026-12-31"};if("DATETIME"===type||"TIMESTAMP"===type||isTimestampName(name))return{strategy:"datetime",from:"2024-01-01T00:00:00",to:"2026-12-31T23:59:59"};if("TIME"===type||"time"===name)return{strategy:"time"};if(type.startsWith("INTEGER")&&/(timestamp|epoch|unix|createdtime|updatedtime)/.test(name))return{strategy:"timestampUnix",format:"sec"};if(/^(lat|latitude)$/.test(name))return{strategy:"latitude"};if(/^(lng|lon|longitude)$/.test(name))return{strategy:"longitude"};if(type.startsWith("INTEGER"))return name.includes("year")?{strategy:"int",min:1990,max:2026}:name.includes("age")?{strategy:"int",min:18,max:90}:/(count|quantity|qty|stock|views|likes|total|num|number)$/.test(name)?{strategy:"int",min:0,max:1e5}:name.includes("rating")||name.includes("score")?{strategy:"int",min:1,max:5}:/(order|rank|position|seq|sequence|priority|sort|step)$/.test(name)?{strategy:"sequence",start:1,step:1}:{strategy:"int",min:1,max:1e3};if("REAL"===type||type.includes("DECIMAL")||type.includes("NUMERIC")||type.includes("FLOAT")||type.includes("DOUBLE"))return/(price|cost|amount|total|salary|balance|fee|charge|budget)/.test(name)?{strategy:"decimal",min:1,max:5e3,precision:2}:name.includes("rating")?{strategy:"decimal",min:1,max:5,precision:1}:{strategy:"decimal",min:1,max:1e3,precision:2};if("BLOB"===type)return{strategy:"bytes",minLen:8,maxLen:32};if(/currency|curr|currencycode/.test(name))return{strategy:"currency"};if(/countrycode|countryiso|isocountry|cca2/.test(name))return{strategy:"countryCode"};if(/state|province|region/.test(name)&&!/status|statement/.test(name))return{strategy:"state"};if(/status|stage|phase|state/.test(name))return{strategy:"status"};if(/color|colour|theme|hexcolor/.test(name))return{strategy:"color",format:"hex"};if(/mac|macaddress|hwaddr/.test(name))return{strategy:"mac"};if(/creditcard|cardnumber|cardno|ccnumber|ccno/.test(name))return{strategy:"creditCard"};if(/slug|permalink|handle|alias/.test(name))return{strategy:"slug"};if(isHashName(name))return{strategy:"hash",minLen:32,maxLen:64};if(isTokenName(name))return{strategy:"token",minLen:6,maxLen:12};if(/uuid|guid/.test(name)||"id"===name||"uid"===name||"key"===name)return{strategy:"uuid"};if(name.includes("first")&&name.includes("name"))return{strategy:"first"};if(/(lastname|surname|familyname)/.test(name)||name.includes("last")&&name.includes("name"))return{strategy:"last"};if("name"===name||"fullname"===name||name.includes("full")&&name.includes("name"))return{strategy:"fullname"};for(const[pattern,createPlan]of TEXT_PATTERNS)if(pattern.test(name))return createPlan(name);return{strategy:"words",minLen:1,maxLen:4}}const STR_PLAN_KEYS=["value","from","to","prefix","suffix","pattern","format"],NUM_PLAN_KEYS=["min","max","precision","minLen","maxLen","nullPct","start","step"];
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.normName = void 0;
4
+ exports.isTimestampName = isTimestampName;
5
+ exports.findInMap = findInMap;
6
+ exports.extractCheckExprs = extractCheckExprs;
7
+ exports.parseChecks = parseChecks;
8
+ exports.detectPlan = detectPlan;
9
+ exports.buildColumnConfigs = buildColumnConfigs;
10
+ exports.sanitizeColumnPlan = sanitizeColumnPlan;
11
+ const strategies_1 = require("./strategies");
12
+ const normName = (s) => String(s).toLowerCase().replace(/[^a-z0-9]/g, '');
13
+ exports.normName = normName;
14
+ function isTimestampName(name) {
15
+ return (/created|updated|modified|registered|joined|timestamp|lastused|lastseen|lastlogin|lastactivity|accessed|viewed|visited|^ts$/.test(name) ||
16
+ /^(created|updated|deleted|archived|occurred|started|ended|expires|published|processed|completed|inserted|requested|resolved|used|seen|accessed|viewed|visited|logged|active)at$/.test(name));
17
+ }
18
+ function findInMap(map, colName) {
19
+ if (map.has(colName))
20
+ return map.get(colName);
21
+ const lower = colName.toLowerCase();
22
+ for (const [k, v] of map.entries()) {
23
+ if (k.toLowerCase() === lower)
24
+ return v;
25
+ }
26
+ return undefined;
27
+ }
28
+ function extractCheckExprs(sql) {
29
+ const out = [];
30
+ const re = /CHECK\s*\(/gi;
31
+ let m;
32
+ while ((m = re.exec(sql))) {
33
+ let depth = 1;
34
+ let i = m.index + m[0].length;
35
+ const start = i;
36
+ while (i < sql.length && depth > 0) {
37
+ const ch = sql[i];
38
+ if (ch === "'") {
39
+ i += 1;
40
+ while (i < sql.length) {
41
+ if (sql[i] === "'") {
42
+ if (sql[i + 1] === "'")
43
+ i += 2;
44
+ else {
45
+ i += 1;
46
+ break;
47
+ }
48
+ }
49
+ else
50
+ i += 1;
51
+ }
52
+ continue;
53
+ }
54
+ if (ch === '"' || ch === '`' || ch === '[') {
55
+ const close = ch === '[' ? ']' : ch;
56
+ i += 1;
57
+ while (i < sql.length && sql[i] !== close) {
58
+ if (sql[i] === close && sql[i + 1] === close)
59
+ i += 2;
60
+ else
61
+ i += 1;
62
+ }
63
+ i += 1;
64
+ continue;
65
+ }
66
+ if (ch === '(')
67
+ depth += 1;
68
+ else if (ch === ')') {
69
+ depth -= 1;
70
+ if (depth === 0)
71
+ break;
72
+ }
73
+ i += 1;
74
+ }
75
+ out.push(sql.slice(start, i));
76
+ }
77
+ return out;
78
+ }
79
+ function parseChecks(sql) {
80
+ const info = {
81
+ columnAllowed: new Map(),
82
+ columnRange: new Map(),
83
+ columnLength: new Map(),
84
+ jsonAllowed: new Map(),
85
+ ordering: new Map(),
86
+ };
87
+ if (!sql)
88
+ return info;
89
+ const setOrdering = (col, other, key, orEqual) => {
90
+ const c = info.ordering.get(col) ?? {};
91
+ c[key] = { column: other, orEqual };
92
+ info.ordering.set(col, c);
93
+ };
94
+ const setColumnAllowed = (col, vals) => {
95
+ if (!col || !vals.length)
96
+ return;
97
+ const existing = findInMap(info.columnAllowed, col);
98
+ if (existing) {
99
+ for (const v of vals)
100
+ if (!existing.includes(v))
101
+ existing.push(v);
102
+ }
103
+ else {
104
+ info.columnAllowed.set(col, [...vals]);
105
+ }
106
+ };
107
+ for (const expr of extractCheckExprs(sql)) {
108
+ const jw1 = /(?:"([^"]+)"|`([^`]+)`|\[([^\]]+)\]|([A-Za-z_][A-Za-z0-9_]*))\s*(?:->>|->)\s*'([^']+)'\s*(?:\)\s*)*IN\s*\(([^)]*)\)/gi;
109
+ const jw2 = /json_extract\s*\(\s*(?:"([^"]+)"|`([^`]+)`|\[([^\]]+)\]|([A-Za-z_][A-Za-z0-9_]*))\s*,\s*'(?:\$\??|\.)?\.?([^']+)'\s*\)\s*(?:\)\s*)*IN\s*\(([^)]*)\)/gi;
110
+ for (const re of [jw1, jw2]) {
111
+ let m;
112
+ while ((m = re.exec(expr))) {
113
+ const col = m[1] || m[2] || m[3] || m[4];
114
+ const key = m[5];
115
+ const inContent = m[6];
116
+ const strValues = (inContent.match(/'(?:[^']|'')*'/g) ?? []).map((s) => s.slice(1, -1).replace(/''/g, "'"));
117
+ const values = strValues.length ? strValues : (inContent.match(/-?\b\d+(?:\.\d+)?\b/g) ?? []);
118
+ if (values.length && col && key) {
119
+ const byCol = findInMap(info.jsonAllowed, col) ?? new Map();
120
+ byCol.set(key, values);
121
+ info.jsonAllowed.set(col, byCol);
122
+ }
123
+ }
124
+ }
125
+ const colIn = /(?:^|[^\w"'\`\[])(?:\s*\(\s*)*(?:(?:lower|upper|trim|coalesce)\s*\(\s*)?(?:"([^"]+)"|`([^`]+)`|\[([^\]]+)\]|([A-Za-z_][A-Za-z0-9_]*))(?:\s*,\s*[^)]+)?(?:\s*\)\s*)*\s*IN\s*\(([^)]*)\)/gi;
126
+ let mColIn;
127
+ while ((mColIn = colIn.exec(expr))) {
128
+ const col = mColIn[1] || mColIn[2] || mColIn[3] || mColIn[4];
129
+ if (!col || ['json_extract', 'strftime', 'datetime', 'date', 'length', 'typeof'].includes(col.toLowerCase()))
130
+ continue;
131
+ const matchPos = mColIn.index;
132
+ if (expr.slice(Math.max(0, matchPos - 5), matchPos).includes('->'))
133
+ continue;
134
+ const inContent = mColIn[5];
135
+ const strValues = (inContent.match(/'(?:[^']|'')*'/g) ?? []).map((s) => s.slice(1, -1).replace(/''/g, "'"));
136
+ const values = strValues.length ? strValues : (inContent.match(/-?\b\d+(?:\.\d+)?\b/g) ?? []);
137
+ if (values.length)
138
+ setColumnAllowed(col, values);
139
+ }
140
+ const eqOr = /(?:^|[^\w"'\`\[])(?:\s*\(\s*)*(?:"([^"]+)"|`([^`]+)`|\[([^\]]+)\]|([A-Za-z_][A-Za-z0-9_]*))(?:\s*\)\s*)*\s*=\s*'((?:[^']|'')*)'/gi;
141
+ let mEq;
142
+ const eqByCol = new Map();
143
+ while ((mEq = eqOr.exec(expr))) {
144
+ const col = mEq[1] || mEq[2] || mEq[3] || mEq[4];
145
+ const val = mEq[5].replace(/''/g, "'");
146
+ if (col && !['json_extract', 'lower', 'upper', 'trim', 'strftime', 'datetime'].includes(col.toLowerCase())) {
147
+ const cur = eqByCol.get(col) ?? [];
148
+ if (!cur.includes(val))
149
+ cur.push(val);
150
+ eqByCol.set(col, cur);
151
+ }
152
+ }
153
+ for (const [col, vals] of eqByCol.entries())
154
+ setColumnAllowed(col, vals);
155
+ const numCmp1 = /(?:^|[^\w"'\`\[])(?:\s*\(\s*)*(?:"([^"]+)"|`([^`]+)`|\[([^\]]+)\]|([A-Za-z_][A-Za-z0-9_]*))(?:\s*\)\s*)*\s*(>=|>|<=|<)\s*(-?\d+(?:\.\d+)?)/g;
156
+ let mNum1;
157
+ while ((mNum1 = numCmp1.exec(expr))) {
158
+ const col = mNum1[1] || mNum1[2] || mNum1[3] || mNum1[4];
159
+ const op = mNum1[5];
160
+ const val = Number(mNum1[6]);
161
+ if (col && Number.isFinite(val) && !['json_extract', 'length', 'strftime', 'datetime'].includes(col.toLowerCase())) {
162
+ const cur = findInMap(info.columnRange, col) ?? {};
163
+ if (op === '>=' || op === '>')
164
+ cur.min = cur.min != null ? Math.max(cur.min, op === '>' ? val + 1 : val) : (op === '>' ? val + 1 : val);
165
+ else
166
+ cur.max = cur.max != null ? Math.min(cur.max, op === '<' ? val - 1 : val) : (op === '<' ? val - 1 : val);
167
+ info.columnRange.set(col, cur);
168
+ }
169
+ }
170
+ const lenRe1 = /length\s*\(\s*(?:\s*\(\s*)*(?:"([^"]+)"|`([^`]+)`|\[([^\]]+)\]|([A-Za-z_][A-Za-z0-9_]*))(?:\s*\)\s*)*\s*\)\s*(=|==|>=|>|<=|<)\s*(\d+)/gi;
171
+ let mLen1;
172
+ while ((mLen1 = lenRe1.exec(expr))) {
173
+ const col = mLen1[1] || mLen1[2] || mLen1[3] || mLen1[4];
174
+ const op = mLen1[5];
175
+ const val = Number(mLen1[6]);
176
+ if (col && Number.isFinite(val)) {
177
+ const cur = findInMap(info.columnLength, col) ?? {};
178
+ if (op === '=' || op === '==') {
179
+ cur.exact = val;
180
+ cur.min = val;
181
+ cur.max = val;
182
+ }
183
+ else if (op === '>=' || op === '>') {
184
+ cur.min = op === '>' ? val + 1 : val;
185
+ }
186
+ else if (op === '<=' || op === '<') {
187
+ cur.max = op === '<' ? val - 1 : val;
188
+ }
189
+ info.columnLength.set(col, cur);
190
+ }
191
+ }
192
+ const ord = /(?:"([^"]+)"|`([^`]+)`|\[([^\]]+)\]|([A-Za-z_][A-Za-z0-9_]*))\s*(>=|<=|>|<)\s*(?:"([^"]+)"|`([^`]+)`|\[([^\]]+)\]|([A-Za-z_][A-Za-z0-9_]*))/g;
193
+ let m2;
194
+ while ((m2 = ord.exec(expr))) {
195
+ const a = m2[1] || m2[2] || m2[3] || m2[4];
196
+ const op = m2[5];
197
+ const b = m2[6] || m2[7] || m2[8] || m2[9];
198
+ if (!a || !b || /^\d+$/.test(a) || /^\d+$/.test(b))
199
+ continue;
200
+ if (['json_extract', 'strftime', 'datetime', 'date', 'length'].includes(a.toLowerCase()))
201
+ continue;
202
+ if (['json_extract', 'strftime', 'datetime', 'date', 'length'].includes(b.toLowerCase()))
203
+ continue;
204
+ if (op === '>' || op === '>=') {
205
+ setOrdering(a, b, 'after', op === '>=');
206
+ setOrdering(b, a, 'before', op === '>=');
207
+ }
208
+ else {
209
+ setOrdering(a, b, 'before', op === '<=');
210
+ setOrdering(b, a, 'after', op === '<=');
211
+ }
212
+ }
213
+ }
214
+ return info;
215
+ }
216
+ const isHashName = (name) => /^(hash|digest|secret|passphrase)$|tokenhash|passwordhash|passhash|accesskey|apikey|api_key|secretkey|clientsecret|appsecret|appid|privatekey|publickey/.test(name);
217
+ const isTokenName = (name) => /^prefix$|tokenprefix|(code|ref|reference|sku|ticketno|ticketnum|orderno|order_no|trackingno|trackingnum|invno|invoiceno|serialno)$/.test(name);
218
+ function isJsonColumn(col, hasJsonIndex) {
219
+ if (!(0, strategies_1.isTextishType)(col.type))
220
+ return false;
221
+ if (hasJsonIndex)
222
+ return true;
223
+ const dflt = String(col.dflt_value ?? '').trim();
224
+ if (dflt.startsWith('{') || dflt.startsWith("'{\""))
225
+ return true;
226
+ const name = (0, exports.normName)(col.name);
227
+ return /^(permissions|settings|config|configuration|preferences|prefs|metadata|meta|attributes|payload|options|allowedapps|socialaccounts|positions|fcmtokens|fcm_tokens|scopes|profile|json|jsonb)$/.test(name) ||
228
+ /(^|_)(settings|config|configuration|permissions|prefs|metadata|attributes|payload|options|allowedapps|scopes|profile)$/.test(name);
229
+ }
230
+ function extractJsonColumns(sql) {
231
+ const out = [];
232
+ const push = (col, key) => {
233
+ let entry = out.find((e) => e.col === col);
234
+ if (!entry) {
235
+ entry = { col, keys: [] };
236
+ out.push(entry);
237
+ }
238
+ if (key) {
239
+ const last = key.split('.').pop().replace(/[\[\]"]/g, '');
240
+ if (last && !entry.keys.includes(last))
241
+ entry.keys.push(last);
242
+ }
243
+ };
244
+ const arrow = /"([^"]+)"\s*(?:->>|->)\s*'([^']+)'|([A-Za-z_][A-Za-z0-9_]*)\s*(?:->>|->)\s*'([^']+)'/g;
245
+ let m;
246
+ while ((m = arrow.exec(sql)))
247
+ push(m[1] || m[3], m[2] || m[4]);
248
+ const jx = /json_extract\s*\(\s*(?:"([^"]+)"|([A-Za-z_][A-Za-z0-9_]*))\s*,\s*'(?:\$\??|\.)?\.?([^']+)'/g;
249
+ while ((m = jx.exec(sql)))
250
+ push(m[1] || m[2], m[3]);
251
+ return out;
252
+ }
253
+ const TEXT_PATTERNS = [
254
+ [/avatar|picture|photo|image|img|thumbnail|icon|logo/, () => ({ strategy: 'avatar' })],
255
+ [/company|organization|org|firm|corp|employer|agency/, () => ({ strategy: 'company' })],
256
+ [/job|title|role|position|occupation|profession/, () => ({ strategy: 'job' })],
257
+ [/currency|curr|currencycode/, () => ({ strategy: 'currency' })],
258
+ [/countrycode|countryiso|isocountry|cca2/, () => ({ strategy: 'countryCode' })],
259
+ [/state|province|region/, (n) => (/status|statement/.test(n) ? { strategy: 'status' } : { strategy: 'state' })],
260
+ [/status|stage|phase|state/, () => ({ strategy: 'status' })],
261
+ [/color|colour|theme|hexcolor/, () => ({ strategy: 'color', format: 'hex' })],
262
+ [/mac|macaddress|hwaddr/, () => ({ strategy: 'mac' })],
263
+ [/creditcard|cardnumber|cardno|ccnumber|ccno/, () => ({ strategy: 'creditCard' })],
264
+ [/slug|permalink|handle|alias/, () => ({ strategy: 'slug' })],
265
+ [/(lastname|surname|familyname)/, () => ({ strategy: 'last' })],
266
+ [/email|mail/, () => ({ strategy: 'email' })],
267
+ [/(username|login|handle|nick|nickname|account|user)/, () => ({ strategy: 'username' })],
268
+ [/(phone|mobile|telephone|cell|fax)/, () => ({ strategy: 'phone' })],
269
+ [/city|town/, () => ({ strategy: 'city' })],
270
+ [/country|nation/, () => ({ strategy: 'country' })],
271
+ [/postal|zip/, () => ({ strategy: 'postal' })],
272
+ [/address|street|addr/, () => ({ strategy: 'address' })],
273
+ [/url|website|site|link|homepage|href/, () => ({ strategy: 'url' })],
274
+ [/domain|host/, () => ({ strategy: 'domain' })],
275
+ [/^ip$|ipaddr|ipv4|ip_address/, () => ({ strategy: 'ip' })],
276
+ [/bio|about|overview|article|body|post|story/, () => ({ strategy: 'paragraph' })],
277
+ [/description|content|comment|message|note|summary|details|remarks/, () => ({ strategy: 'sentence', minLen: 1, maxLen: 2 })],
278
+ [/title|subject|category|type|tag|label/, () => ({ strategy: 'words', minLen: 1, maxLen: 3 })],
279
+ ];
280
+ function detectPlan(col, fk) {
281
+ const type = (col.type || '').toUpperCase();
282
+ const rawName = col.name.toLowerCase();
283
+ const name = (0, exports.normName)(col.name);
284
+ if (fk)
285
+ return { strategy: 'fk' };
286
+ if (col.pk) {
287
+ if (type.startsWith('INT') || type === 'SERIAL' || type === 'BIGSERIAL')
288
+ return { strategy: 'skip' };
289
+ if (type.includes('TEXT') || type.includes('CHAR') || type.includes('VARCHAR') || type.includes('STRING') || type === 'BLOB' || type === 'UUID')
290
+ return { strategy: 'uuid' };
291
+ if (col.notnull && col.dflt_value == null)
292
+ return { strategy: 'uuid' };
293
+ return { strategy: 'skip' };
294
+ }
295
+ if (type === 'UUID')
296
+ return { strategy: 'uuid' };
297
+ if (type === 'JSON' || type === 'JSONB')
298
+ return { strategy: 'json' };
299
+ if (type === 'INET')
300
+ return { strategy: 'ip' };
301
+ if (type === 'BOOLEAN' || type === 'BOOL')
302
+ return { strategy: 'bool' };
303
+ if (type === 'BYTEA' || type === 'BLOB')
304
+ return { strategy: 'bytes', minLen: 8, maxLen: 32 };
305
+ if ((type.startsWith('INT') || type.startsWith('INTEGER')) && /(^|_)(is|has|can|should|did)_|_flag$|active|enabled|verified|published|deleted|archived|paid|completed|approved/.test(rawName)) {
306
+ return { strategy: 'bool' };
307
+ }
308
+ if (type === 'DATE' || /^date|birthdate|dob|birthday/.test(rawName)) {
309
+ return name.includes('birth') ? { strategy: 'date', from: '1950-01-01', to: '2000-12-31' } : { strategy: 'date', from: '2020-01-01', to: '2026-12-31' };
310
+ }
311
+ if (type === 'DATETIME' || type === 'TIMESTAMP' || isTimestampName(name)) {
312
+ return { strategy: 'datetime', from: '2024-01-01T00:00:00', to: '2026-12-31T23:59:59' };
313
+ }
314
+ if (type === 'TIME' || name === 'time')
315
+ return { strategy: 'time' };
316
+ if (type.startsWith('INTEGER') && /(timestamp|epoch|unix|createdtime|updatedtime)/.test(name)) {
317
+ return { strategy: 'timestampUnix', format: 'sec' };
318
+ }
319
+ if (/^(lat|latitude)$/.test(name))
320
+ return { strategy: 'latitude' };
321
+ if (/^(lng|lon|longitude)$/.test(name))
322
+ return { strategy: 'longitude' };
323
+ if (type.startsWith('INTEGER')) {
324
+ if (name.includes('year'))
325
+ return { strategy: 'int', min: 1990, max: 2026 };
326
+ if (name.includes('age'))
327
+ return { strategy: 'int', min: 18, max: 90 };
328
+ if (/(count|quantity|qty|stock|views|likes|total|num|number)$/.test(name))
329
+ return { strategy: 'int', min: 0, max: 100000 };
330
+ if (name.includes('rating') || name.includes('score'))
331
+ return { strategy: 'int', min: 1, max: 5 };
332
+ if (/(order|rank|position|seq|sequence|priority|sort|step)$/.test(name))
333
+ return { strategy: 'sequence', start: 1, step: 1 };
334
+ return { strategy: 'int', min: 1, max: 1000 };
335
+ }
336
+ if (type === 'REAL' || type.includes('DECIMAL') || type.includes('NUMERIC') || type.includes('FLOAT') || type.includes('DOUBLE')) {
337
+ if (/(price|cost|amount|total|salary|balance|fee|charge|budget)/.test(name))
338
+ return { strategy: 'decimal', min: 1, max: 5000, precision: 2 };
339
+ if (name.includes('rating'))
340
+ return { strategy: 'decimal', min: 1, max: 5, precision: 1 };
341
+ return { strategy: 'decimal', min: 1, max: 1000, precision: 2 };
342
+ }
343
+ if (type === 'BLOB')
344
+ return { strategy: 'bytes', minLen: 8, maxLen: 32 };
345
+ if (/currency|curr|currencycode/.test(name))
346
+ return { strategy: 'currency' };
347
+ if (/countrycode|countryiso|isocountry|cca2/.test(name))
348
+ return { strategy: 'countryCode' };
349
+ if (/state|province|region/.test(name) && !/status|statement/.test(name))
350
+ return { strategy: 'state' };
351
+ if (/status|stage|phase|state/.test(name))
352
+ return { strategy: 'status' };
353
+ if (/color|colour|theme|hexcolor/.test(name))
354
+ return { strategy: 'color', format: 'hex' };
355
+ if (/mac|macaddress|hwaddr/.test(name))
356
+ return { strategy: 'mac' };
357
+ if (/creditcard|cardnumber|cardno|ccnumber|ccno/.test(name))
358
+ return { strategy: 'creditCard' };
359
+ if (/slug|permalink|handle|alias/.test(name))
360
+ return { strategy: 'slug' };
361
+ if (isHashName(name))
362
+ return { strategy: 'hash', minLen: 32, maxLen: 64 };
363
+ if (isTokenName(name))
364
+ return { strategy: 'token', minLen: 6, maxLen: 12 };
365
+ if (/uuid|guid/.test(name) || name === 'id' || name === 'uid' || name === 'key')
366
+ return { strategy: 'uuid' };
367
+ if (name.includes('first') && name.includes('name'))
368
+ return { strategy: 'first' };
369
+ if (/(lastname|surname|familyname)/.test(name) || (name.includes('last') && name.includes('name')))
370
+ return { strategy: 'last' };
371
+ if (name === 'name' || name === 'fullname' || (name.includes('full') && name.includes('name')))
372
+ return { strategy: 'fullname' };
373
+ for (const [pattern, createPlan] of TEXT_PATTERNS) {
374
+ if (pattern.test(name))
375
+ return createPlan(name);
376
+ }
377
+ return { strategy: 'words', minLen: 1, maxLen: 4 };
378
+ }
379
+ function buildColumnConfigs(info) {
380
+ const fkByColumn = new Map(info.foreignKeys.map((fk) => [fk.from, fk]));
381
+ const uniqueCols = new Set();
382
+ const jsonIndexKeys = new Map();
383
+ for (const ix of info.indexes ?? []) {
384
+ if (ix.unique && ix.columns.length === 1 && ix.columns[0])
385
+ uniqueCols.add(ix.columns[0]);
386
+ if (ix.sql && /json_extract|->>|->\s*'|json_/i.test(ix.sql)) {
387
+ for (const { col, keys } of extractJsonColumns(ix.sql)) {
388
+ if (!col)
389
+ continue;
390
+ const merged = new Set([...(jsonIndexKeys.get(col) ?? []), ...keys]);
391
+ if (merged.size)
392
+ jsonIndexKeys.set(col, [...merged]);
393
+ }
394
+ }
395
+ }
396
+ if (info.sql) {
397
+ const uqRe = /UNIQUE\s*\(\s*([^)]+)\s*\)/gi;
398
+ let uqM;
399
+ while ((uqM = uqRe.exec(info.sql))) {
400
+ const rawCols = uqM[1].split(',').map((s) => s.trim().replace(/[`"\[\]]/g, ''));
401
+ if (rawCols.length === 1 && rawCols[0]) {
402
+ uniqueCols.add(rawCols[0]);
403
+ }
404
+ }
405
+ }
406
+ const checkInfo = parseChecks(info.sql ?? null);
407
+ return info.columns.map((col) => {
408
+ const fk = fkByColumn.get(col.name) ?? null;
409
+ const strategies = (0, strategies_1.strategiesFor)(col, fk);
410
+ const unique = uniqueCols.has(col.name);
411
+ let defaultPlan = detectPlan(col, fk);
412
+ if (defaultPlan.strategy !== 'fk' && !col.pk && isJsonColumn(col, jsonIndexKeys.has(col.name))) {
413
+ const keys = jsonIndexKeys.get(col.name);
414
+ const useKeys = keys && keys.length ? keys : ['scope', 'enabled', 'allowedApps'];
415
+ const allowed = findInMap(checkInfo.jsonAllowed, col.name);
416
+ const jsonValues = {};
417
+ if (allowed) {
418
+ for (const k of useKeys) {
419
+ const vals = allowed.get(k);
420
+ if (vals && vals.length)
421
+ jsonValues[k] = vals;
422
+ }
423
+ }
424
+ defaultPlan = {
425
+ strategy: 'json',
426
+ jsonKeys: useKeys,
427
+ ...(Object.keys(jsonValues).length ? { jsonValues } : {}),
428
+ };
429
+ }
430
+ const colAllowed = findInMap(checkInfo.columnAllowed, col.name);
431
+ if (colAllowed && colAllowed.length > 0 && defaultPlan.strategy !== 'fk' && !col.pk) {
432
+ defaultPlan = colAllowed.length === 1 ? { strategy: 'fixed', value: colAllowed[0] } : { strategy: 'list', values: [...colAllowed] };
433
+ }
434
+ const colRange = findInMap(checkInfo.columnRange, col.name);
435
+ if (colRange && (defaultPlan.strategy === 'int' || defaultPlan.strategy === 'decimal')) {
436
+ if (colRange.min != null)
437
+ defaultPlan.min = colRange.min;
438
+ if (colRange.max != null)
439
+ defaultPlan.max = colRange.max;
440
+ }
441
+ const colLen = findInMap(checkInfo.columnLength, col.name);
442
+ if (colLen && defaultPlan.strategy !== 'fk' && !col.pk) {
443
+ if (colLen.exact != null) {
444
+ defaultPlan = { strategy: 'token', minLen: colLen.exact, maxLen: colLen.exact };
445
+ }
446
+ else {
447
+ if (colLen.min != null)
448
+ defaultPlan.minLen = colLen.min;
449
+ if (colLen.max != null)
450
+ defaultPlan.maxLen = colLen.max;
451
+ }
452
+ }
453
+ if (!strategies.some((s) => s.id === defaultPlan.strategy) || (!col.pk && col.notnull && col.dflt_value == null && (defaultPlan.strategy === 'skip' || defaultPlan.strategy === 'null'))) {
454
+ defaultPlan = (0, strategies_1.fallbackPlanFor)(col);
455
+ }
456
+ return {
457
+ name: col.name,
458
+ type: col.type,
459
+ pk: col.pk > 0,
460
+ notnull: !!col.notnull,
461
+ hasDefault: col.dflt_value != null,
462
+ unique,
463
+ fk,
464
+ strategies,
465
+ defaultPlan,
466
+ };
467
+ });
468
+ }
469
+ const STR_PLAN_KEYS = ['value', 'from', 'to', 'prefix', 'suffix', 'pattern', 'format'];
470
+ const NUM_PLAN_KEYS = ['min', 'max', 'precision', 'minLen', 'maxLen', 'nullPct', 'start', 'step'];
471
+ function sanitizeColumnPlan(raw) {
472
+ if (!raw || typeof raw !== 'object')
473
+ return null;
474
+ const r = raw;
475
+ if (typeof r.strategy !== 'string' || !r.strategy)
476
+ return null;
477
+ const out = { strategy: r.strategy };
478
+ if (r.values !== undefined && r.values !== null && Array.isArray(r.values)) {
479
+ out.values = r.values.map((x) => String(x));
480
+ }
481
+ if (r.jsonKeys !== undefined && r.jsonKeys !== null) {
482
+ const rawKeys = Array.isArray(r.jsonKeys) ? r.jsonKeys.map(String) : String(r.jsonKeys).split(/[,;]/);
483
+ out.jsonKeys = rawKeys.map((s) => s.trim()).filter(Boolean);
484
+ }
485
+ for (const key of STR_PLAN_KEYS) {
486
+ if (r[key] !== undefined && r[key] !== null) {
487
+ out[key] = String(r[key]);
488
+ }
489
+ }
490
+ for (const key of NUM_PLAN_KEYS) {
491
+ if (r[key] !== undefined && r[key] !== null) {
492
+ const n = Number(r[key]);
493
+ if (Number.isFinite(n)) {
494
+ out[key] = n;
495
+ }
496
+ }
497
+ }
498
+ if (r.jsonValues && typeof r.jsonValues === 'object' && !Array.isArray(r.jsonValues)) {
499
+ const jv = {};
500
+ for (const [k, vals] of Object.entries(r.jsonValues)) {
501
+ if (Array.isArray(vals)) {
502
+ const cleaned = vals.map((x) => String(x).trim()).filter(Boolean);
503
+ if (cleaned.length)
504
+ jv[k] = cleaned;
505
+ }
506
+ }
507
+ if (Object.keys(jv).length)
508
+ out.jsonValues = jv;
509
+ }
510
+ return out;
511
+ }
@@ -1 +1 @@
1
- import type {IDatabase,TableInfoData,WhereClause} from '../db/index';import{type ColumnGeneratorConfig,type ColumnPlan,type GenerateResult} from './types';export declare function generateRows(db:IDatabase,info:TableInfoData,configs:ColumnGeneratorConfig[],count:number,plan?:Record<string,ColumnPlan>):Promise<GenerateResult>;export declare function buildSeedInsertSql(table:string,rows:WhereClause[][]):string;
1
+ import type {IDatabase,TableInfoData,WhereClause} from '../db/index';import{type ColumnGeneratorConfig,type ColumnPlan,type GenerateResult} from './types';export declare function generateRows(db:IDatabase,info:TableInfoData,configs:ColumnGeneratorConfig[],count:number,plan?:Record<string,ColumnPlan>,truncate?:boolean):Promise<GenerateResult>;export declare function buildSeedInsertSql(table:string,rows:WhereClause[][]):string;