@aifivem/build 0.0.0-stage → 0.1.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,41 @@
1
+ #!/usr/bin/env bun
2
+ /**
3
+ * Client script errors reach the server console (ai-core logs them with the player): every client bundle
4
+ * gets a small reporter in front and a try/catch around itself.
5
+ *
6
+ * - Runtime errors: FiveM's JS runtime prints handler, tick and unhandled promise errors through this
7
+ * resource's own `console.log` as "SCRIPT ERROR ..."; the reporter forwards those lines.
8
+ * - Load errors: an error thrown while the file itself runs is printed by the native side, which no script
9
+ * sees; the try/catch reports it, then throws it on so FiveM still prints it.
10
+ *
11
+ * Same lines are sent once, at most 20 per resource start. Plain ES5-ish JS: it runs before anything else.
12
+ *
13
+ * Usage (package.json build script, after tsdown): aicore-client-errors dist/client.js
14
+ */
15
+ import { existsSync } from "node:fs";
16
+ import { readFile, writeFile } from "node:fs/promises";
17
+ import { CORE } from "@aifivem/shared";
18
+
19
+ const MARKER = "/*aicore-client-errors*/";
20
+
21
+ const REPORTER = `${MARKER}(function(){var n=GetCurrentResourceName(),s={},c=0;var r=function(t){t=String(t).replace(/\\^\\d/g,"");var k=t.slice(0,300);if(s[k]||c>=20)return;s[k]=1;c++;try{TriggerServerEvent("${CORE.clientErrorEvent}",n,t.slice(0,4000))}catch(e){}};globalThis.__aicoreReportError=r;var l=console.log;console.log=function(){var a=arguments[0];if(typeof a==="string"&&a.indexOf("SCRIPT ERROR")!==-1)r(a);return l.apply(console,arguments)}})();`;
22
+
23
+ /** The bundle with the reporter in front and its own run inside a try/catch. */
24
+ export function withClientErrors(code: string): string {
25
+ return `${REPORTER}\ntry{\n${code}\n}catch(e){globalThis.__aicoreReportError&&globalThis.__aicoreReportError("load: "+(e&&e.stack||e));throw e}\n`;
26
+ }
27
+
28
+ if (import.meta.main) {
29
+ const files = process.argv.slice(2);
30
+ if (files.length === 0) {
31
+ console.error("usage: aicore-client-errors <client bundle>...");
32
+ process.exit(1);
33
+ }
34
+ for (const file of files) {
35
+ // A server-only resource has no client bundle.
36
+ if (!existsSync(file)) continue;
37
+ const code = await readFile(file, "utf8");
38
+ if (code.startsWith(MARKER)) continue;
39
+ await writeFile(file, withClientErrors(code));
40
+ }
41
+ }
package/dbTypes.ts ADDED
@@ -0,0 +1,118 @@
1
+ #!/usr/bin/env bun
2
+ /**
3
+ * Database types from the resource's own tables: reads every `CREATE TABLE` in `sql/main.sql` and writes
4
+ * `resource/server/tables.ts` with each table's row type (what a SELECT returns through @aifivem/mysql) and its
5
+ * insert type (columns with a default, NULL or AUTO_INCREMENT may be left out). The SQL file stays the one source of
6
+ * truth: change it, build, and every query written with `typedDb<Tables, TableInserts>()` is checked against it.
7
+ *
8
+ * Usage (package.json build script, before tsdown): aicore-db-types [sql/main.sql] [resource/server/tables.ts]
9
+ */
10
+ import { existsSync, readFileSync, writeFileSync } from "node:fs";
11
+
12
+ interface Column {
13
+ name: string;
14
+ /** TypeScript type of the value a SELECT returns. */
15
+ ts: string;
16
+ optionalOnInsert: boolean;
17
+ }
18
+
19
+ interface Table {
20
+ name: string;
21
+ columns: Column[];
22
+ }
23
+
24
+ /** SQL type -> the value @aifivem/mysql returns (same as oxmysql: dates as epoch ms, TINYINT(1) as boolean). */
25
+ function tsType(sqlType: string): string {
26
+ const t = sqlType.toLowerCase().trim();
27
+ const base = t.replace(/\s+unsigned|\s+zerofill/g, "");
28
+ if (/^tinyint\(1\)/.test(base) || /^bool(ean)?\b/.test(base) || /^bit\(1\)/.test(base)) return "boolean";
29
+ if (/^bigint\b/.test(base)) return "number | string";
30
+ if (/^(tinyint|smallint|mediumint|int|integer|float|double|real|year)\b/.test(base)) return "number";
31
+ if (/^(decimal|numeric|dec|fixed)\b/.test(base)) return "string";
32
+ if (/^(date|datetime|timestamp)\b/.test(base)) return "number";
33
+ if (/^enum\s*\(/.test(base)) {
34
+ const values = [...sqlType.matchAll(/'((?:[^']|'')*)'/g)].map((m) => JSON.stringify((m[1] ?? "").replace(/''/g, "'")));
35
+ return values.length > 0 ? values.join(" | ") : "string";
36
+ }
37
+ if (/^(binary|varbinary|tinyblob|blob|mediumblob|longblob)\b/.test(base)) return "number[]";
38
+ return "string";
39
+ }
40
+
41
+ /** The body between the first `(` after a CREATE TABLE and its matching `)`, split on top-level commas. */
42
+ function definitions(body: string): string[] {
43
+ const out: string[] = [];
44
+ let depth = 0;
45
+ let quote: string | null = null;
46
+ let current = "";
47
+ for (const ch of body) {
48
+ if (quote) {
49
+ if (ch === quote) quote = null;
50
+ } else if (ch === "'" || ch === '"' || ch === "`") quote = ch;
51
+ else if (ch === "(") depth++;
52
+ else if (ch === ")") depth--;
53
+ else if (ch === "," && depth === 0) {
54
+ out.push(current.trim());
55
+ current = "";
56
+ continue;
57
+ }
58
+ current += ch;
59
+ }
60
+ if (current.trim()) out.push(current.trim());
61
+ return out;
62
+ }
63
+
64
+ /** Every `CREATE TABLE` of a SQL file (comments stripped). */
65
+ export function parseTables(sql: string): Table[] {
66
+ const clean = sql.replace(/--[^\n]*/g, "").replace(/\/\*[\s\S]*?\*\//g, "");
67
+ const tables: Table[] = [];
68
+ const head = /create\s+table\s+(?:if\s+not\s+exists\s+)?[`"]?(\w+)[`"]?\s*\(/gi;
69
+ for (let m = head.exec(clean); m; m = head.exec(clean)) {
70
+ let depth = 1;
71
+ let i = head.lastIndex;
72
+ for (; i < clean.length && depth > 0; i++) {
73
+ if (clean[i] === "(") depth++;
74
+ else if (clean[i] === ")") depth--;
75
+ }
76
+ const columns: Column[] = [];
77
+ for (const def of definitions(clean.slice(head.lastIndex, i - 1))) {
78
+ if (/^(primary|unique|key|index|constraint|foreign|check|fulltext|spatial)\b/i.test(def)) continue;
79
+ const col = /^[`"]?(\w+)[`"]?\s+(\w+(?:\s*\([^)]*\))?(?:\s+unsigned)?(?:\s+zerofill)?)/i.exec(def);
80
+ if (!col?.[1] || !col[2]) continue;
81
+ const rest = def.slice(col[0].length).toLowerCase();
82
+ const notNull = /\bnot\s+null\b/.test(rest);
83
+ const optionalOnInsert = !notNull || /\bdefault\b/.test(rest) || /\bauto_increment\b/.test(rest);
84
+ const ts = tsType(col[2]);
85
+ columns.push({ name: col[1], ts: notNull ? ts : `${ts} | null`, optionalOnInsert });
86
+ }
87
+ tables.push({ name: m[1] ?? "", columns });
88
+ }
89
+ return tables;
90
+ }
91
+
92
+ /** The generated module: `Tables` (rows) and `TableInserts` (insert shapes). */
93
+ export function renderTables(tables: Table[], source: string): string {
94
+ const key = (name: string) => (/^[A-Za-z_$][\w$]*$/.test(name) ? name : JSON.stringify(name));
95
+ const rows = tables.map((t) => ` ${t.name}: {\n${t.columns.map((c) => ` ${key(c.name)}: ${c.ts};`).join("\n")}\n };`);
96
+ const inserts = tables.map(
97
+ (t) => ` ${t.name}: {\n${t.columns.map((c) => ` ${key(c.name)}${c.optionalOnInsert ? "?" : ""}: ${c.ts};`).join("\n")}\n };`,
98
+ );
99
+ return `// Generated from ${source} by aicore-db-types (the build runs it). Do not edit: change the SQL and build.
100
+
101
+ /** Row of each table as @aifivem/mysql returns it. */
102
+ export type Tables = {
103
+ ${rows.join("\n")}
104
+ };
105
+
106
+ /** What an INSERT needs: columns with a default, NULL or AUTO_INCREMENT may be left out. */
107
+ export type TableInserts = {
108
+ ${inserts.join("\n")}
109
+ };
110
+ `;
111
+ }
112
+
113
+ if (import.meta.main) {
114
+ const [sqlPath = "sql/main.sql", outPath = "resource/server/tables.ts"] = process.argv.slice(2);
115
+ if (!existsSync(sqlPath)) process.exit(0);
116
+ const next = renderTables(parseTables(readFileSync(sqlPath, "utf8")), sqlPath);
117
+ if (!existsSync(outPath) || readFileSync(outPath, "utf8") !== next) writeFileSync(outPath, next);
118
+ }
package/package.json CHANGED
@@ -1,6 +1,28 @@
1
1
  {
2
2
  "name": "@aifivem/build",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.4",
4
+ "description": "Build steps every ai-core resource runs (client error wrapper, database types).",
5
+ "license": "GPL-3.0-only",
6
+ "repository": {
7
+ "type": "git",
8
+ "url": "git+https://github.com/aifivem/aicore-packages.git",
9
+ "directory": "build"
10
+ },
11
+ "type": "module",
12
+ "bin": {
13
+ "aicore-client-errors": "./clientErrors.ts",
14
+ "aicore-db-types": "./dbTypes.ts"
15
+ },
16
+ "files": [
17
+ "*.ts"
18
+ ],
19
+ "publishConfig": {
20
+ "access": "public"
21
+ },
22
+ "dependencies": {
23
+ "@aifivem/shared": "^0.5.0"
24
+ },
25
+ "devDependencies": {
26
+ "@types/bun": "latest"
27
+ }
28
+ }
package/README.md DELETED
@@ -1,3 +0,0 @@
1
- # Temporary Holding Version
2
-
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.