Skip to content
Merged
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 24 additions & 6 deletions mod.ts
Original file line number Diff line number Diff line change
Expand Up @@ -180,6 +180,19 @@ function setSessionKey(ctx: Context, key?: string) {
});
}

/**
* Deep copies a value to prevent shared references between sessions.
* Handles primitives, objects, arrays, dates, and other common types.
*/
function deepCopy<T>(value: T): T {
Comment thread
LWJerri marked this conversation as resolved.
Resolved
// Handle primitives and null/undefined
if (value === null || value === undefined || typeof value !== "object") {
return value;
}

return structuredClone(value);
}

/**
* Session middleware provides a persistent data storage for your bot. You can
* use it to let your bot remember any data you want, for example the messages
Expand Down Expand Up @@ -378,7 +391,9 @@ class PropertySession<O extends {}, P extends keyof O> {
// Check for write op in the meantime
if (!this.wrote) {
// Store received value in `this.value`
this.value = val ?? this.initial?.();
this.value = val !== undefined
? deepCopy(val)
: this.initial?.();
}
return this.value;
});
Expand Down Expand Up @@ -426,7 +441,7 @@ class PropertySession<O extends {}, P extends keyof O> {
if (this.read || this.wrote) {
const value = await this.value;
if (value === undefined) await this.storage.delete(this.key);
else await this.storage.write(this.key, value);
else await this.storage.write(this.key, deepCopy(value));
}
}
}
Expand Down Expand Up @@ -635,8 +650,11 @@ function wrapStorage<T>(
storage: StorageAdapter<Enhance<T>>,
): StorageAdapter<T> {
return {
read: (k) => Promise.resolve(storage.read(k)).then((v) => v?.__d),
write: (k, v) => storage.write(k, { __d: v }),
read: (k) =>
Promise.resolve(storage.read(k)).then((v) =>
v?.__d ? deepCopy(v.__d) : undefined
),
write: (k, v) => storage.write(k, { __d: deepCopy(v) }),
delete: (k) => storage.delete(k),
};
}
Expand Down Expand Up @@ -682,7 +700,7 @@ export class MemorySessionStorage<S> implements StorageAdapter<S> {
this.delete(key);
return undefined;
}
return value.session;
return deepCopy(value.session);
}

readAllKeys(): string[] {
Expand All @@ -707,7 +725,7 @@ export class MemorySessionStorage<S> implements StorageAdapter<S> {
}

write(key: string, value: S) {
this.storage.set(key, addExpiryDate(value, this.timeToLive));
this.storage.set(key, addExpiryDate(deepCopy(value), this.timeToLive));
}

delete(key: string) {
Expand Down