@needle-tools/engine 4.7.0-next.b344106 → 4.7.0-next.cac0716

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.
@@ -1,7 +1,9 @@
1
1
  import { createWriteStream, existsSync, mkdirSync, readdirSync, rmSync, statSync, write } from "fs";
2
2
 
3
3
  const filename_timestamp = new Date().toISOString().replace(/[:.]/g, '-').slice(0, 19);
4
+ const debug = false;
4
5
 
6
+ // #region public api
5
7
 
6
8
  /**
7
9
  * @typedef {"server" | "client" | "client-http"} ProcessType
@@ -21,23 +23,23 @@ export function patchConsoleLogs() {
21
23
 
22
24
  console.log = (...args) => {
23
25
  originalConsoleLog(...args);
24
- captureLogMessage("server", 'log', args);
26
+ captureLogMessage("server", 'log', args, null);
25
27
  };
26
28
  console.error = (...args) => {
27
29
  originalConsoleError(...args);
28
- captureLogMessage("server", 'error', args);
30
+ captureLogMessage("server", 'error', args, null);
29
31
  };
30
32
  console.warn = (...args) => {
31
33
  originalConsoleWarn(...args);
32
- captureLogMessage("server", 'warn', args);
34
+ captureLogMessage("server", 'warn', args, null);
33
35
  };
34
36
  console.info = (...args) => {
35
37
  originalConsoleInfo(...args);
36
- captureLogMessage("server", 'info', args);
38
+ captureLogMessage("server", 'info', args, null);
37
39
  };
38
40
  console.debug = (...args) => {
39
41
  originalConsoleDebug(...args);
40
- captureLogMessage("server", 'debug', args);
42
+ captureLogMessage("server", 'debug', args, null);
41
43
  };
42
44
 
43
45
  // Restore original console methods
@@ -54,53 +56,54 @@ export function patchConsoleLogs() {
54
56
 
55
57
 
56
58
  let isCapturing = false;
59
+ /** @type {Set<string>} */
60
+ const isCapturingLogMessage = new Set();
57
61
 
58
- /** @type {Array<{ process: ProcessType, key: string, log:any, timestamp:number }>} */
62
+ /** @type {Array<{ process: ProcessType, key: string, log:any, timestamp:number, connectionId: string | null }>} */
59
63
  const queue = new Array();
60
64
 
61
65
  /**
62
66
  * @param {ProcessType} process
63
67
  * @param {string} key
64
68
  * @param {any} log
69
+ * @param {string | null} connectionId - Optional connection ID for client logs.
70
+ * @param {number} [time] - Optional timestamp, defaults to current time.
65
71
  */
66
- export function captureLogMessage(process, key, log, time = Date.now()) {
72
+ export function captureLogMessage(process, key, log, connectionId, time = Date.now()) {
73
+
74
+ if (isCapturingLogMessage.has(log)) {
75
+ return; // prevent circular logs
76
+ }
77
+
67
78
  if (isCapturing) {
68
- queue.push({ process, key, log, timestamp: Date.now() });
79
+ queue.push({ process, key, log, timestamp: Date.now(), connectionId });
69
80
  return;
70
81
  }
71
82
  isCapturing = true;
83
+ isCapturingLogMessage.add(log);
72
84
 
73
85
  try {
74
- const str = stringifyLog(log);
75
- const prefix = `${getTimestamp(time, true)}, ${process}.${key}: `;
76
- const separator = "";
77
- writeToFile(process, indent(`${prefix}${separator}${str}`, prefix.length, separator));
86
+ let str = stringifyLog(log);
87
+ if (str.trim().length > 0) {
88
+ // if(process === "server") str = stripAnsiColors(str);
89
+ const prefix = `${getTimestamp(time, true)}, ${process}${connectionId ? (`[${connectionId}]`) : ""}.${key}: `;
90
+ const separator = "";
91
+ const finalLog = indent(`${prefix}${separator}${removeEmptyLinesAtStart(str)}`, prefix.length, separator)
92
+ writeToFile(process, finalLog, connectionId);
93
+ }
78
94
  } finally {
79
95
  isCapturing = false;
96
+ isCapturingLogMessage.delete(log);
80
97
  }
81
98
 
82
99
  let queued = queue.pop();
83
100
  if (queued) {
84
- captureLogMessage(queued.process, queued.key, queued.log, queued.timestamp);
101
+ captureLogMessage(queued.process, queued.key, queued.log, queued.connectionId, queued.timestamp);
85
102
  }
86
103
  }
87
104
 
88
105
 
89
- // #region utility functions
90
-
91
- /**
92
- * Returns the current timestamp in ISO format.
93
- * @param {number} [date] - Optional date to format, defaults to current date.
94
- */
95
- function getTimestamp(date, timeOnly = false) {
96
- const now = date ? new Date(date) : new Date();
97
- if (timeOnly) {
98
- return now.toTimeString().split(' ')[0]; // HH:MM:SS
99
- }
100
- return now.toISOString();
101
- }
102
-
103
-
106
+ // #region stringify log
104
107
 
105
108
 
106
109
  /**
@@ -108,7 +111,7 @@ function getTimestamp(date, timeOnly = false) {
108
111
  * @param {any} log
109
112
  * @param {Set<any>} [seen]
110
113
  */
111
- function stringifyLog(log, seen = new Set()) {
114
+ function stringifyLog(log, seen = new Set(), depth = 0) {
112
115
 
113
116
  const isServer = typeof window === "undefined";
114
117
  const stringify_limits = {
@@ -118,7 +121,7 @@ function stringifyLog(log, seen = new Set()) {
118
121
  }
119
122
 
120
123
  if (typeof log === "string") {
121
- if (log.length > stringify_limits.string) log = `${log.slice(0, stringify_limits.string)}... <truncated: ${log.length - stringify_limits.string} more characters>`;
124
+ if (log.length > stringify_limits.string) log = `${log.slice(0, stringify_limits.string)}... <truncated ${log.length - stringify_limits.string} characters>`;
122
125
  return log;
123
126
  }
124
127
  if (typeof log === "number" || typeof log === "boolean") {
@@ -135,30 +138,88 @@ function stringifyLog(log, seen = new Set()) {
135
138
  }
136
139
 
137
140
  if (seen.has(log)) return "<circular>";
138
- seen.add(log);
139
141
 
140
142
  if (Array.isArray(log)) {
141
- let res = "";
142
- for (let i = 0; i < log.length; i++) {
143
- let item = log[i];
144
- if (res) res += ", ";
145
- if (i > stringify_limits.array_items) res += "<truncated: " + (log.length - i) + " more items>";
146
- res += stringifyLog(item, seen);
147
- }
148
- return res;
143
+ seen.add(log);
144
+ return stringifyArray(log);
149
145
  }
150
146
  if (typeof log === "object") {
151
- let entries = Object.entries(log).map(([key, value], index) => {
152
- if (index > stringify_limits.object_keys) return `"${key}": <truncated>`;
153
- return `"${key}": ${stringifyLog(value, seen)}`;
154
- });
155
- return `{ ${entries.join(", ")} }`;
147
+ seen.add(log);
148
+ // const str = JSON.stringify(log, (key, value) => {
149
+ // if (typeof value === "function") return "<function>";
150
+ // if (typeof value === "string") return stringifyLog(value, seen, depth + 1);
151
+ // if (typeof value === "object") {
152
+ // if (seen.has(value)) return "<circular>";
153
+ // seen.add(value);
154
+ // }
155
+ // return value;
156
+ // });
157
+ // return str;
158
+ const keys = Object.keys(log);
159
+ let res = "{";
160
+ for (let i = 0; i < keys.length; i++) {
161
+ const key = keys[i];
162
+ let value = log[key];
163
+
164
+ if (typeof value === "number") {
165
+ // clamp precision for numbers
166
+ value = Number(value.toFixed(6));
167
+ }
168
+ let str = stringifyLog(value, seen, depth + 1);
169
+ if (typeof value === "object") {
170
+ if (Array.isArray(value)) {
171
+ str = `[${str}]`;
172
+ }
173
+ }
174
+ else if (typeof value === "string") {
175
+ str = `"${str}"`;
176
+ }
177
+ if (i > 0) res += ", ";
178
+ res += `"${key}":${str}`;
179
+ }
180
+ res += "}";
181
+ return res;
182
+ // let entries = Object.entries(log).map(([key, value], index) => {
183
+ // if (index > stringify_limits.object_keys) return `"${key}": <truncated>`;
184
+ // return `"${key}": ${stringifyLog(value, seen, depth + 1)}`;
185
+ // });
186
+ // return `{ ${entries.join(", ")} }`;
156
187
  }
157
188
  return String(log);
189
+
190
+ function stringifyArray(arr) {
191
+ let res = "";
192
+ for (let i = 0; i < arr.length; i++) {
193
+ let entry = arr[i];
194
+ if (res && i > 0) res += ", ";
195
+ if (i > stringify_limits.array_items) {
196
+ res += "<truncated " + (arr.length - i) + ">";
197
+ break;
198
+ }
199
+ res += stringifyLog(entry, seen, depth + 1);
200
+ }
201
+ return res;
202
+ }
158
203
  }
159
204
 
160
205
 
161
206
 
207
+
208
+ // #region utility functions
209
+
210
+ /**
211
+ * Returns the current timestamp in ISO format.
212
+ * @param {number} [date] - Optional date to format, defaults to current date.
213
+ */
214
+ function getTimestamp(date, timeOnly = false) {
215
+ const now = date ? new Date(date) : new Date();
216
+ if (timeOnly) {
217
+ return now.toTimeString().split(' ')[0]; // HH:MM:SS
218
+ }
219
+ return now.toISOString();
220
+ }
221
+
222
+
162
223
  /**
163
224
  * Indents a string by a specified length.
164
225
  * @param {string} str - The string to indent.
@@ -177,10 +238,35 @@ function indent(str, length, separator = "") {
177
238
  return lines.join("\n");
178
239
  }
179
240
 
241
+ /**
242
+ * Removes empty lines at the start of a string.
243
+ * @param {string} str - The string to process.
244
+ */
245
+ function removeEmptyLinesAtStart(str) {
246
+ const lines = str.split("\n");
247
+ for (let i = 0; i < lines.length; i++) {
248
+ const line = lines[i].trim();
249
+ if (line.length > 0) {
250
+ lines[i] = line; // keep the first non-empty line
251
+ return lines.slice(i).join("\n");
252
+ }
253
+ }
254
+ return "";
255
+ }
256
+
257
+ /**
258
+ * Strips ANSI color codes from a string.
259
+ * @param {string} str - The string to process.
260
+ */
261
+ function stripAnsiColors(str) {
262
+ // This pattern catches most ANSI escape sequences
263
+ return str.replace(/\x1b\[[0-9;]*[a-zA-Z]/g, '');
264
+ }
265
+
180
266
 
181
267
  // #region log to file
182
268
 
183
- /** @type {Map<ProcessType, import("fs").WriteStream>} */
269
+ /** @type {Map<string, import("fs").WriteStream>} */
184
270
  const filestreams = new Map();
185
271
  const fileLogDirectory = "node_modules/.needle/logs";
186
272
  // cleanup old log files
@@ -203,17 +289,20 @@ if (existsSync(fileLogDirectory)) {
203
289
  * Writes a log message to the file.
204
290
  * @param {ProcessType} process
205
291
  * @param {string} log
292
+ * @param {string | null} connectionId - Optional connection ID for client logs.
206
293
  */
207
- function writeToFile(process, log) {
208
- if (!filestreams.has(process)) {
294
+ function writeToFile(process, log, connectionId) {
295
+ const filename = `${process}.needle.log`; //connectionId && process === "client" ? `${process}-${connectionId}.needle.log` : `${process}.needle.log`;
296
+
297
+ if (!filestreams.has(filename)) {
209
298
  if (!existsSync(fileLogDirectory)) {
210
299
  mkdirSync(fileLogDirectory, { recursive: true });
211
300
  }
212
- filestreams.set(process, createWriteStream(`${fileLogDirectory}/needle.${filename_timestamp}.${process}.log`, { flags: 'a' }));
301
+ filestreams.set(filename, createWriteStream(`${fileLogDirectory}/${filename_timestamp}.${filename}`, { flags: 'a' }));
213
302
  }
214
- const writeStream = filestreams.get(process);
303
+ const writeStream = filestreams.get(filename);
215
304
  if (!writeStream) {
216
- console.error(`No write stream for process: ${process}`);
305
+ if (debug) console.error(`No write stream for process: ${filename}`);
217
306
  return;
218
307
  }
219
308
  writeStream.write(log + '\n');
@@ -1,5 +1,4 @@
1
1
  import { License } from "./license";
2
- import { NeedlePWAOptions } from "./webmanifest.js";
3
2
 
4
3
  export type needleModules = {
5
4
  webpack: object | undefined
@@ -118,5 +117,8 @@ export type userSettings = {
118
117
  */
119
118
  openBrowser?: boolean;
120
119
 
120
+ /** Automatically import MaterialX for needle engine in 'main.ts' */
121
121
  loadMaterialX?: boolean;
122
+
123
+ disableLogging?: boolean;
122
124
  }
@@ -163,12 +163,13 @@ User Activation: ${"userActivation" in navigator ? JSON.stringify(navigator.user
163
163
 
164
164
  // #region copied from common/logger.js
165
165
 
166
+
166
167
  /**
167
168
  * Stringifies a log message, handling circular references and formatting.
168
169
  * @param {any} log
169
170
  * @param {Set<any>} [seen]
170
171
  */
171
- function stringifyLog(log, seen = new Set()) {
172
+ function stringifyLog(log, seen = new Set(), depth = 0) {
172
173
 
173
174
  const isServer = typeof window === "undefined";
174
175
  const stringify_limits = {
@@ -178,7 +179,7 @@ function stringifyLog(log, seen = new Set()) {
178
179
  }
179
180
 
180
181
  if (typeof log === "string") {
181
- if (log.length > stringify_limits.string) log = `${log.slice(0, stringify_limits.string)}... <truncated: ${log.length - stringify_limits.string} more characters>`;
182
+ if (log.length > stringify_limits.string) log = `${log.slice(0, stringify_limits.string)}... <truncated ${log.length - stringify_limits.string} characters>`;
182
183
  return log;
183
184
  }
184
185
  if (typeof log === "number" || typeof log === "boolean") {
@@ -195,24 +196,67 @@ function stringifyLog(log, seen = new Set()) {
195
196
  }
196
197
 
197
198
  if (seen.has(log)) return "<circular>";
198
- seen.add(log);
199
199
 
200
200
  if (Array.isArray(log)) {
201
- let res = "";
202
- for (let i = 0; i < log.length; i++) {
203
- let item = log[i];
204
- if (res) res += ", ";
205
- if (i > stringify_limits.array_items) res += "<truncated: " + (log.length - i) + " more items>";
206
- res += stringifyLog(item, seen);
207
- }
208
- return res;
201
+ seen.add(log);
202
+ return stringifyArray(log);
209
203
  }
210
204
  if (typeof log === "object") {
211
- let entries = Object.entries(log).map(([key, value], index) => {
212
- if (index > stringify_limits.object_keys) return `"${key}": <truncated>`;
213
- return `"${key}": ${stringifyLog(value, seen)}`;
214
- });
215
- return `{ ${entries.join(", ")} }`;
205
+ seen.add(log);
206
+ // const str = JSON.stringify(log, (key, value) => {
207
+ // if (typeof value === "function") return "<function>";
208
+ // if (typeof value === "string") return stringifyLog(value, seen, depth + 1);
209
+ // if (typeof value === "object") {
210
+ // if (seen.has(value)) return "<circular>";
211
+ // seen.add(value);
212
+ // }
213
+ // return value;
214
+ // });
215
+ // return str;
216
+ const keys = Object.keys(log);
217
+ let res = "{";
218
+ for (let i = 0; i < keys.length; i++) {
219
+ const key = keys[i];
220
+ let value = log[key];
221
+
222
+ if (typeof value === "number") {
223
+ // clamp precision for numbers
224
+ value = Number(value.toFixed(6));
225
+ }
226
+ let str = stringifyLog(value, seen, depth + 1);
227
+ if (typeof value === "object") {
228
+ if (Array.isArray(value)) {
229
+ str = `[${str}]`;
230
+ }
231
+ }
232
+ else if (typeof value === "string") {
233
+ str = `"${str}"`;
234
+ }
235
+ if (i > 0) res += ", ";
236
+ res += `"${key}":${str}`;
237
+ }
238
+ res += "}";
239
+ return res;
240
+ // let entries = Object.entries(log).map(([key, value], index) => {
241
+ // if (index > stringify_limits.object_keys) return `"${key}": <truncated>`;
242
+ // return `"${key}": ${stringifyLog(value, seen, depth + 1)}`;
243
+ // });
244
+ // return `{ ${entries.join(", ")} }`;
216
245
  }
217
246
  return String(log);
218
- }
247
+
248
+ function stringifyArray(arr) {
249
+ let res = "";
250
+ for (let i = 0; i < arr.length; i++) {
251
+ let entry = arr[i];
252
+ if (res && i > 0) res += ", ";
253
+ if (i > stringify_limits.array_items) {
254
+ res += "<truncated " + (arr.length - i) + ">";
255
+ break;
256
+ }
257
+ res += stringifyLog(entry, seen, depth + 1);
258
+ }
259
+ return res;
260
+ }
261
+ }
262
+
@@ -10,12 +10,16 @@ const __dirname = path.dirname(__filename);
10
10
  /**
11
11
  * write logs to local file
12
12
  * @param {import('../types/userconfig.js').userSettings} userSettings
13
- * @returns {import('vite').Plugin}
13
+ * @returns {import('vite').Plugin | null}
14
14
  */
15
15
  export const needleLogger = (command, config, userSettings) => {
16
16
 
17
+ if (userSettings?.disableLogging === true) {
18
+ return null;
19
+ }
20
+
17
21
  patchConsoleLogs();
18
- captureLogMessage("server", "info", "Vite started with command \"" + command + "\" in " + __dirname);
22
+ captureLogMessage("server", "info", "Vite started with command \"" + command + "\" in " + __dirname, null);
19
23
 
20
24
  return {
21
25
  name: "needle:logger",
@@ -58,12 +62,22 @@ export const needleLogger = (command, config, userSettings) => {
58
62
  * @param {import('vite').PreviewServer | import('vite').ViteDevServer} server
59
63
  */
60
64
  function logRequests(server, log_http_requests = false) {
65
+ /**
66
+ * Logs a message to the server console and captures it.
67
+ * @type {Map<import("vite").WebSocket, {id:string}>}
68
+ */
69
+ const connectedClients = new Map();
70
+ let index = 0;
71
+
61
72
  if ("ws" in server) {
62
73
  // Clent connections
63
74
  server.ws.on('connection', (socket, request) => {
64
- captureLogMessage("server", "connection", "New websocket connection established");
75
+ const clientId = String(index++);
76
+ connectedClients.set(socket, { id: clientId });
77
+ const ip = request.socket.remoteAddress || 'unknown';
78
+ captureLogMessage("server", "connection", `New websocket connection established ${clientId} from ${ip}`, clientId);
65
79
  socket.on('close', () => {
66
- captureLogMessage("server", "connection", "Websocket connection closed");
80
+ captureLogMessage("server", "connection", `Websocket connection closed ${clientId}`, clientId);
67
81
  });
68
82
  });
69
83
  // Client log messages via websocket
@@ -72,13 +86,15 @@ function logRequests(server, log_http_requests = false) {
72
86
  console.warn("Received empty log data, ignoring");
73
87
  return;
74
88
  }
75
- captureLogMessage("client", data.level, data.message);
89
+ const socket = client.socket;
90
+ const info = connectedClients.get(socket);
91
+ captureLogMessage("client", data.level, data.message, info ? info.id : null);
76
92
  });
77
93
  }
78
94
  // Log HTTP requests
79
95
  if (log_http_requests) {
80
96
  server.middlewares.use((req, res, next) => {
81
- captureLogMessage("client-http", "info", [req.method, req.url]);
97
+ captureLogMessage("client-http", "info", [req.method, req.url], null);
82
98
  next();
83
99
  });
84
100
  }
@@ -188,14 +188,11 @@ export class AssetReference {
188
188
  private _urlName: string;
189
189
  private _progressListeners: ProgressCallback[] = [];
190
190
 
191
- private _hash?: string;
192
- private _hashedUri: string;
193
-
194
191
  private _isLoadingRawBinary: boolean = false;
195
192
  private _rawBinary?: ArrayBufferLike | null;
196
193
 
197
194
  /** @internal */
198
- constructor(uri: string, hash?: string, asset: any = null) {
195
+ constructor(uri: string, _hash?: string, asset: any = null) {
199
196
  this._url = uri;
200
197
 
201
198
  const lastUriPart = uri.lastIndexOf("/");
@@ -210,14 +207,8 @@ export class AssetReference {
210
207
  else {
211
208
  this._urlName = uri;
212
209
  }
213
-
214
- this._hash = hash;
215
- if (uri.includes("?v="))
216
- this._hashedUri = uri;
217
- else
218
- this._hashedUri = hash ? uri + "?v=" + hash : uri;
210
+
219
211
  if (asset !== null) this.asset = asset;
220
-
221
212
  registerPrefabProvider(this._url, this.onResolvePrefab.bind(this));
222
213
  }
223
214
 
@@ -263,8 +254,8 @@ export class AssetReference {
263
254
  if (this._isLoadingRawBinary) return null;
264
255
  if (this._rawBinary !== undefined) return this._rawBinary;
265
256
  this._isLoadingRawBinary = true;
266
- if (debug) console.log("Preload", this._hashedUri);
267
- const res = await BlobStorage.download(this._hashedUri, p => {
257
+ if (debug) console.log("Preload", this.url);
258
+ const res = await BlobStorage.download(this.url, p => {
268
259
  this.raiseProgressEvent(p);
269
260
  });
270
261
  this._rawBinary = res?.buffer ?? null;
@@ -294,7 +285,7 @@ export class AssetReference {
294
285
  // console.log("START LOADING");
295
286
  if (this._rawBinary) {
296
287
  if (!(this._rawBinary instanceof ArrayBuffer)) {
297
- console.error("Invalid raw binary data", this._rawBinary);
288
+ console.error("Failed loading: Invalid raw binary data. Must be of type ArrayBuffer. " + (typeof this._rawBinary));
298
289
  return null;
299
290
  }
300
291
  this._loading = getLoader().parseSync(context, this._rawBinary, this.url, null);
@@ -302,7 +293,7 @@ export class AssetReference {
302
293
  }
303
294
  else {
304
295
  if (debug) console.log("Load async", this.url);
305
- this._loading = getLoader().loadSync(context, this._hashedUri, this.url, null, prog => {
296
+ this._loading = getLoader().loadSync(context, this.url, this.url, null, prog => {
306
297
  this.raiseProgressEvent(prog);
307
298
  });
308
299
  }
@@ -53,10 +53,12 @@ export class LightDataRegistry implements ILightDataRegistry {
53
53
  }
54
54
 
55
55
  tryGetSkybox(sourceId?: SourceIdentifier | null): Texture | null {
56
+ if (debugLightmap) console.log("[Get Skybox]", sourceId, this._lightmaps)
56
57
  return this.tryGet(sourceId, LightmapType.Skybox, 0);
57
58
  }
58
59
 
59
60
  tryGetReflection(sourceId?: SourceIdentifier | null): Texture | null {
61
+ if (debugLightmap) console.log("[Get Reflection]", sourceId, this._lightmaps)
60
62
  return this.tryGet(sourceId, LightmapType.Reflection, 0);
61
63
  }
62
64
 
@@ -66,9 +68,15 @@ export class LightDataRegistry implements ILightDataRegistry {
66
68
  return null;
67
69
  }
68
70
  const entry = this._lightmaps.get(sourceId);
69
- if (!entry) return null;
71
+ if (!entry) {
72
+ if (debugLightmap) console.warn(`[Lighting] No ${LightmapType[type]} texture entry for`, sourceId);
73
+ return null;
74
+ }
70
75
  const arr = entry.get(type);
71
- if (arr === undefined) return null;
76
+ if (arr === undefined) {
77
+ if (debugLightmap) console.warn(`[Lighting] No ${LightmapType[type]} texture for`, sourceId, "index", index);
78
+ return null;
79
+ }
72
80
  if (!arr?.length || arr.length <= index) return null;
73
81
  return arr[index];
74
82
  }