@book000/pixivts-db-mysql 0.64.1-beta.46 → 0.64.1-beta.48

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/README.md CHANGED
@@ -2,7 +2,7 @@
2
2
 
3
3
  MySQL response recorder for [`@book000/pixivts`](https://www.npmjs.com/package/@book000/pixivts).
4
4
 
5
- Persists every pixiv API response to a MySQL database using [Drizzle ORM](https://orm.drizzle.team/).
5
+ Persists every successful (2xx) pixiv API response to a MySQL database using [Drizzle ORM](https://orm.drizzle.team/).
6
6
 
7
7
  ## Installation
8
8
 
@@ -37,7 +37,7 @@ const client = await PixivClient.of(process.env.PIXIV_REFRESH_TOKEN!, {
37
37
  onResponse: interceptor,
38
38
  })
39
39
 
40
- // Every API call is now recorded to MySQL automatically
40
+ // Every successful API call is now recorded to MySQL automatically
41
41
  const result = await client.illusts.detail({ illustId: 12345 })
42
42
 
43
43
  // Close the pool when done
@@ -101,7 +101,7 @@ The `responses` table stores one row per API call:
101
101
  | `response_body` | `LONGTEXT` | NO | Raw response body |
102
102
  | `created_at` | `DATETIME(3)` | NO | Timestamp (millisecond precision) |
103
103
 
104
- Duplicate rows (same method + endpoint + statusCode + createdAt + urlHash) are silently ignored via `ON DUPLICATE KEY UPDATE`.
104
+ Duplicate rows (same method + endpoint + statusCode + urlHash) are silently ignored via `ON DUPLICATE KEY UPDATE`, so the first recorded response for a given URL is kept.
105
105
 
106
106
  ## Database Migration
107
107
 
package/dist/index.cjs CHANGED
@@ -45,7 +45,7 @@ let drizzle_orm = require("drizzle-orm");
45
45
  */
46
46
  var schema_exports = /* @__PURE__ */ __exportAll({ responsesTable: () => responsesTable });
47
47
  /**
48
- * The `responses` table stores every HTTP response returned by the pixiv API.
48
+ * The `responses` table stores every successful (2xx) HTTP response returned by the pixiv API.
49
49
  *
50
50
  * A unique composite index on (method, endpoint, status_code, url_hash) ensures
51
51
  * that each unique request/response combination is stored only once, regardless
@@ -167,24 +167,6 @@ async function bootstrapSchema(db) {
167
167
  * The recorder uses Drizzle ORM's `onDuplicateKeyUpdate` to silently ignore
168
168
  * duplicate entries (same method + endpoint + statusCode + urlHash).
169
169
  */
170
- /**
171
- * Creates a response recorder that persists every pixiv API response to MySQL.
172
- *
173
- * @param opts - Connection and bootstrapping options
174
- * @returns `{ interceptor, db, close }`
175
- *
176
- * @example
177
- * ```ts
178
- * const { interceptor, close } = await createResponseRecorder({
179
- * host: 'localhost',
180
- * database: 'pixivts',
181
- * bootstrap: true,
182
- * })
183
- * const client = await PixivClient.of(token, { onResponse: interceptor })
184
- * // ...
185
- * await close()
186
- * ```
187
- */
188
170
  function ninetyDaysAgo() {
189
171
  return /* @__PURE__ */ new Date(Date.now() - 7776e6);
190
172
  }
@@ -231,7 +213,7 @@ function createRecorderBundle(db, close) {
231
213
  };
232
214
  }
233
215
  /**
234
- * Creates a response recorder that persists every pixiv API response to MySQL.
216
+ * Creates a response recorder that persists every successful (2xx) pixiv API response to MySQL.
235
217
  *
236
218
  * @param opts - Connection and bootstrapping options
237
219
  * @returns `{ interceptor, db, close }`
package/dist/index.d.cts CHANGED
@@ -32,7 +32,7 @@ declare namespace schema_d_exports {
32
32
  * so that existing databases can be used without migration.
33
33
  */
34
34
  /**
35
- * The `responses` table stores every HTTP response returned by the pixiv API.
35
+ * The `responses` table stores every successful (2xx) HTTP response returned by the pixiv API.
36
36
  *
37
37
  * A unique composite index on (method, endpoint, status_code, url_hash) ensures
38
38
  * that each unique request/response combination is stored only once, regardless
@@ -340,7 +340,7 @@ export declare function addResponse(db: DbInstance, record: ResponseRecord): Pro
340
340
  */
341
341
  export declare function createRecorderBundle(db: DbInstance, close: () => Promise<void>): RecorderBundle;
342
342
  /**
343
- * Creates a response recorder that persists every pixiv API response to MySQL.
343
+ * Creates a response recorder that persists every successful (2xx) pixiv API response to MySQL.
344
344
  *
345
345
  * @param opts - Connection and bootstrapping options
346
346
  * @returns `{ interceptor, db, close }`
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.cts","names":["schema"],"sources":["../src/schema.ts","../src/connection.ts","../src/recorder.ts","../src/migrations.ts"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;qBAwBa,iDAAc;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;KAuCf,qBAAqB,eAAe;;KAGpC,qBAAqB,eAAe;;UCvD/B;;;;;EAKf;;;;;EAMA;;;;;EAMA;;;;;EAMA;;;;;EAMA;;;;;;;KAQU,aAAa,kBAAkB,eAAeA;;;;;;;;wBAe1C,mBAAmB,MAAM;EACvC,MAAM,MAAM;EACZ,IAAI;;;UCrCW;;;;;EAKf,aAAa;;EAGb,IAAI;;EAGJ,SAAS;;;UAQM,wBAAwB;;;;;;;EAOvC;;;;;;;;;;;wBA8CoB,YACpB,IAAI,YACJ,QAAQ,iBACP;;;;;;;;;wBA+Ba,qBACd,IAAI,YACJ,aAAa,gBACZ;;;;;;;;;;;;;;;;;;;wBAwBmB,uBACpB,MAAM,kBACL,QAAQ;;UAeM;;EAEf;;EAEA;;EAEA;;;UAIe;;EAEf;;EAEA;;;;;;;;;;wBAWoB,aACpB,IAAI,YACJ,SAAS,gBACT,QAAQ,eACP,QAAQ;;;;;;;;wBAgCW,iBACpB,IAAI,YACJ,SAAS,iBACR;;UAqBc;;EAEf;;EAEA;;EAEA;;EAEA;;;;;;;;;wBAUoB,aACpB,IAAI,aACH,QAAQ;;;;;;;;;wBCrQW,gBAAgB,IAAI,aAAa"}
1
+ {"version":3,"file":"index.d.cts","names":["schema"],"sources":["../src/schema.ts","../src/connection.ts","../src/recorder.ts","../src/migrations.ts"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;qBAwBa,iDAAc;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;KAuCf,qBAAqB,eAAe;;KAGpC,qBAAqB,eAAe;;UCvD/B;;;;;EAKf;;;;;EAMA;;;;;EAMA;;;;;EAMA;;;;;EAMA;;;;;;;KAQU,aAAa,kBAAkB,eAAeA;;;;;;;;wBAe1C,mBAAmB,MAAM;EACvC,MAAM,MAAM;EACZ,IAAI;;;UCrCW;;;;;EAKf,aAAa;;EAGb,IAAI;;EAGJ,SAAS;;;UAQM,wBAAwB;;;;;;;EAOvC;;;;;;;;;;;wBAwBoB,YACpB,IAAI,YACJ,QAAQ,iBACP;;;;;;;;;wBA+Ba,qBACd,IAAI,YACJ,aAAa,gBACZ;;;;;;;;;;;;;;;;;;;wBAwBmB,uBACpB,MAAM,kBACL,QAAQ;;UAeM;;EAEf;;EAEA;;EAEA;;;UAIe;;EAEf;;EAEA;;;;;;;;;;wBAWoB,aACpB,IAAI,YACJ,SAAS,gBACT,QAAQ,eACP,QAAQ;;;;;;;;wBAgCW,iBACpB,IAAI,YACJ,SAAS,iBACR;;UAqBc;;EAEf;;EAEA;;EAEA;;EAEA;;;;;;;;;wBAUoB,aACpB,IAAI,aACH,QAAQ;;;;;;;;;wBC/OW,gBAAgB,IAAI,aAAa"}
package/dist/index.d.ts CHANGED
@@ -32,7 +32,7 @@ declare namespace schema_d_exports {
32
32
  * so that existing databases can be used without migration.
33
33
  */
34
34
  /**
35
- * The `responses` table stores every HTTP response returned by the pixiv API.
35
+ * The `responses` table stores every successful (2xx) HTTP response returned by the pixiv API.
36
36
  *
37
37
  * A unique composite index on (method, endpoint, status_code, url_hash) ensures
38
38
  * that each unique request/response combination is stored only once, regardless
@@ -340,7 +340,7 @@ export declare function addResponse(db: DbInstance, record: ResponseRecord): Pro
340
340
  */
341
341
  export declare function createRecorderBundle(db: DbInstance, close: () => Promise<void>): RecorderBundle;
342
342
  /**
343
- * Creates a response recorder that persists every pixiv API response to MySQL.
343
+ * Creates a response recorder that persists every successful (2xx) pixiv API response to MySQL.
344
344
  *
345
345
  * @param opts - Connection and bootstrapping options
346
346
  * @returns `{ interceptor, db, close }`
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","names":["schema"],"sources":["../src/schema.ts","../src/connection.ts","../src/recorder.ts","../src/migrations.ts"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;qBAwBa,iDAAc;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;KAuCf,qBAAqB,eAAe;;KAGpC,qBAAqB,eAAe;;UCvD/B;;;;;EAKf;;;;;EAMA;;;;;EAMA;;;;;EAMA;;;;;EAMA;;;;;;;KAQU,aAAa,kBAAkB,eAAeA;;;;;;;;wBAe1C,mBAAmB,MAAM;EACvC,MAAM,MAAM;EACZ,IAAI;;;UCrCW;;;;;EAKf,aAAa;;EAGb,IAAI;;EAGJ,SAAS;;;UAQM,wBAAwB;;;;;;;EAOvC;;;;;;;;;;;wBA8CoB,YACpB,IAAI,YACJ,QAAQ,iBACP;;;;;;;;;wBA+Ba,qBACd,IAAI,YACJ,aAAa,gBACZ;;;;;;;;;;;;;;;;;;;wBAwBmB,uBACpB,MAAM,kBACL,QAAQ;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,YACJ,SAAS,gBACT,QAAQ,eACP,QAAQ;;;;;;;;wBAgCW,iBACpB,IAAI,YACJ,SAAS,iBACR;;UAqBc;;EAEf;;EAEA;;EAEA;;EAEA;;;;;;;;;wBAUoB,aACpB,IAAI,aACH,QAAQ;;;;;;;;;wBC/OW,gBAAgB,IAAI,aAAa"}
package/dist/index.js CHANGED
@@ -13,7 +13,7 @@ import { and, count, desc, eq, gte, sql } from "drizzle-orm";
13
13
  */
14
14
  var schema_exports = /* @__PURE__ */ __exportAll({ responsesTable: () => responsesTable });
15
15
  /**
16
- * The `responses` table stores every HTTP response returned by the pixiv API.
16
+ * The `responses` table stores every successful (2xx) HTTP response returned by the pixiv API.
17
17
  *
18
18
  * A unique composite index on (method, endpoint, status_code, url_hash) ensures
19
19
  * that each unique request/response combination is stored only once, regardless
@@ -135,24 +135,6 @@ async function bootstrapSchema(db) {
135
135
  * The recorder uses Drizzle ORM's `onDuplicateKeyUpdate` to silently ignore
136
136
  * duplicate entries (same method + endpoint + statusCode + urlHash).
137
137
  */
138
- /**
139
- * Creates a response recorder that persists every pixiv API response to MySQL.
140
- *
141
- * @param opts - Connection and bootstrapping options
142
- * @returns `{ interceptor, db, close }`
143
- *
144
- * @example
145
- * ```ts
146
- * const { interceptor, close } = await createResponseRecorder({
147
- * host: 'localhost',
148
- * database: 'pixivts',
149
- * bootstrap: true,
150
- * })
151
- * const client = await PixivClient.of(token, { onResponse: interceptor })
152
- * // ...
153
- * await close()
154
- * ```
155
- */
156
138
  function ninetyDaysAgo() {
157
139
  return /* @__PURE__ */ new Date(Date.now() - 7776e6);
158
140
  }
@@ -199,7 +181,7 @@ function createRecorderBundle(db, close) {
199
181
  };
200
182
  }
201
183
  /**
202
- * Creates a response recorder that persists every pixiv API response to MySQL.
184
+ * Creates a response recorder that persists every successful (2xx) pixiv API response to MySQL.
203
185
  *
204
186
  * @param opts - Connection and bootstrapping options
205
187
  * @returns `{ interceptor, db, close }`
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":[],"sources":["../src/schema.ts","../src/connection.ts","../src/migrations.ts","../src/recorder.ts"],"sourcesContent":["/**\n * Drizzle ORM schema for the `responses` table.\n *\n * Column names are kept in snake_case to match the legacy TypeORM schema\n * so that existing databases can be used without migration.\n */\n\nimport {\n int,\n datetime,\n longtext,\n mysqlTable,\n text,\n varchar,\n uniqueIndex,\n} from 'drizzle-orm/mysql-core'\n\n/**\n * The `responses` table stores every HTTP response returned by the pixiv API.\n *\n * A unique composite index on (method, endpoint, status_code, url_hash) ensures\n * that each unique request/response combination is stored only once, regardless\n * of when it was recorded.\n */\nexport const responsesTable = mysqlTable(\n 'responses',\n {\n /** Auto-increment primary key. */\n id: int('id').autoincrement().primaryKey(),\n /** HTTP method (GET or POST). */\n method: varchar('method', { length: 10 }).notNull(),\n /** API endpoint path (e.g. /v1/illust/detail). */\n endpoint: varchar('endpoint', { length: 255 }).notNull(),\n /** Full request URL (may be null for internal requests). */\n url: text('url'),\n /** SHA-256 hash of the request URL for deduplication. */\n urlHash: varchar('url_hash', { length: 255 }).notNull(),\n /** Serialised request headers (JSON string). */\n requestHeaders: longtext('request_headers'),\n /** Request body (URL-encoded string for POST, null for GET). */\n requestBody: longtext('request_body'),\n /** Response content type (\"JSON\" or \"TEXT\"). */\n responseType: varchar('response_type', { length: 10 }).notNull(),\n /** HTTP response status code. */\n statusCode: int('status_code').notNull(),\n /** Serialised response headers (JSON string). */\n responseHeaders: longtext('response_headers'),\n /** Raw response body. */\n responseBody: longtext('response_body').notNull(),\n /** Timestamp when the record was created. */\n createdAt: datetime('created_at', { mode: 'date', fsp: 3 }).notNull(),\n },\n (table) => [\n uniqueIndex('idx_unique').on(\n table.method,\n table.endpoint,\n table.statusCode,\n table.urlHash\n ),\n ]\n)\n\n/** Type for inserting a new response record. */\nexport type NewResponse = typeof responsesTable.$inferInsert\n\n/** Type for a selected response record. */\nexport type ResponseRow = typeof responsesTable.$inferSelect\n","/**\n * MySQL connection factory for @book000/pixivts-db-mysql.\n *\n * Creates a mysql2 connection pool and wraps it in a Drizzle ORM instance.\n */\n\nimport { drizzle } from 'drizzle-orm/mysql2'\nimport mysql from 'mysql2/promise'\nimport * as schema from './schema'\n\n/** Options for establishing a MySQL connection. */\nexport interface ConnectionOptions {\n /**\n * Database hostname.\n * Falls back to the `RESPONSE_DB_HOSTNAME` environment variable.\n */\n host?: string\n\n /**\n * Database port.\n * Falls back to the `RESPONSE_DB_PORT` environment variable (default: 3306).\n */\n port?: number\n\n /**\n * Database username.\n * Falls back to the `RESPONSE_DB_USERNAME` environment variable.\n */\n user?: string\n\n /**\n * Database password.\n * Falls back to the `RESPONSE_DB_PASSWORD` environment variable.\n */\n password?: string\n\n /**\n * Database name.\n * Falls back to the `RESPONSE_DB_DATABASE` environment variable.\n */\n database?: string\n}\n\n/**\n * The Drizzle ORM database instance type returned by `createConnection`.\n *\n * Typed with the `schema` so that relational queries are available.\n */\nexport type DbInstance = ReturnType<typeof drizzle<typeof schema>>\n\nfunction parsePort(value: string | undefined): number {\n if (!value) return 3306\n const parsed = Number.parseInt(value, 10)\n return Number.isNaN(parsed) ? 3306 : parsed\n}\n\n/**\n * Creates a mysql2 connection pool and returns both the raw pool and the\n * Drizzle ORM wrapper.\n *\n * @param opts - Connection options (fall back to environment variables)\n * @returns `{ pool, db }` — raw pool for `close()`, db for queries\n */\nexport function createDbConnection(opts: ConnectionOptions): {\n pool: mysql.Pool\n db: DbInstance\n} {\n const pool = mysql.createPool({\n host: opts.host ?? process.env.RESPONSE_DB_HOSTNAME ?? 'localhost',\n port: opts.port ?? parsePort(process.env.RESPONSE_DB_PORT),\n user: opts.user ?? process.env.RESPONSE_DB_USERNAME,\n password: opts.password ?? process.env.RESPONSE_DB_PASSWORD,\n database: opts.database ?? process.env.RESPONSE_DB_DATABASE,\n timezone: '+09:00',\n supportBigNumbers: true,\n bigNumberStrings: true,\n })\n\n // Type assertion required: pnpm's peer-dep resolution for the patched drizzle-orm\n // creates a structurally-incompatible Pool type for the $client property.\n // The runtime value is correct; only the declaration paths differ.\n const db = drizzle(pool, { schema, mode: 'default' }) as unknown as DbInstance\n return { pool, db }\n}\n","/**\n * Schema bootstrapping for @book000/pixivts-db-mysql.\n *\n * Provides a `CREATE TABLE IF NOT EXISTS` helper that can be used at startup\n * without requiring drizzle-kit to be installed in production.\n *\n * For full migrations, use:\n * pnpm drizzle-kit generate\n * pnpm drizzle-kit migrate\n */\n\nimport { sql } from 'drizzle-orm'\nimport type { DbInstance } from './connection'\n\n/**\n * Creates the `responses` table if it does not already exist.\n *\n * This is a lightweight alternative to running drizzle-kit migrations in\n * environments where the table has not been set up yet.\n *\n * @param db - Drizzle ORM database instance\n */\nexport async function bootstrapSchema(db: DbInstance): Promise<void> {\n await db.execute(sql`\n CREATE TABLE IF NOT EXISTS responses (\n id INT AUTO_INCREMENT PRIMARY KEY COMMENT 'Response ID',\n method VARCHAR(10) NOT NULL COMMENT 'HTTP method',\n endpoint VARCHAR(255) NOT NULL COMMENT 'API endpoint path',\n url TEXT NULL COMMENT 'Full request URL',\n url_hash VARCHAR(255) NOT NULL COMMENT 'SHA-256 hash of the request URL',\n request_headers LONGTEXT NULL COMMENT 'Request headers (JSON)',\n request_body LONGTEXT NULL COMMENT 'Request body',\n response_type VARCHAR(10) NOT NULL COMMENT 'Response content type',\n status_code INT NOT NULL COMMENT 'HTTP status code',\n response_headers LONGTEXT NULL COMMENT 'Response headers (JSON)',\n response_body LONGTEXT NOT NULL COMMENT 'Response body',\n created_at DATETIME(3) NOT NULL COMMENT 'Record creation timestamp',\n UNIQUE INDEX idx_unique (method, endpoint, status_code, url_hash)\n ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci\n `)\n}\n","/**\n * Response recorder for @book000/pixivts-db-mysql.\n *\n * `createResponseRecorder()` returns a `{ interceptor, db, close }` bundle:\n * - `interceptor` — pass to `PixivClient.of(token, { onResponse: interceptor })`\n * - `db` — the raw Drizzle instance for custom queries\n * - `close()` — shuts down the connection pool\n *\n * The recorder uses Drizzle ORM's `onDuplicateKeyUpdate` to silently ignore\n * duplicate entries (same method + endpoint + statusCode + urlHash).\n */\n\nimport crypto from 'node:crypto'\nimport { and, count, desc, eq, gte, sql } from 'drizzle-orm'\nimport type { ResponseInterceptor, ResponseRecord } from '@book000/pixivts'\nimport {\n createDbConnection,\n type ConnectionOptions,\n type DbInstance,\n} from './connection'\nimport { responsesTable, type ResponseRow } from './schema'\nimport { bootstrapSchema } from './migrations'\n\n// ---------------------------------------------------------------------------\n// Result bundle\n// ---------------------------------------------------------------------------\n\n/** The object returned by `createResponseRecorder()`. */\nexport interface RecorderBundle {\n /**\n * Response interceptor — pass directly to `PixivClient.of()` as\n * the `onResponse` option.\n */\n interceptor: ResponseInterceptor\n\n /** Drizzle ORM database instance for custom queries. */\n db: DbInstance\n\n /** Closes the underlying connection pool. */\n close(): Promise<void>\n}\n\n// ---------------------------------------------------------------------------\n// Options\n// ---------------------------------------------------------------------------\n\n/** Options for `createResponseRecorder()`. */\nexport interface RecorderOptions extends ConnectionOptions {\n /**\n * If `true`, runs `CREATE TABLE IF NOT EXISTS` before returning.\n * Useful for first-run bootstrapping without a separate migration step.\n *\n * @default false\n */\n bootstrap?: boolean\n}\n\n// ---------------------------------------------------------------------------\n// Factory\n// ---------------------------------------------------------------------------\n\n/**\n * Creates a response recorder that persists every pixiv API response to MySQL.\n *\n * @param opts - Connection and bootstrapping options\n * @returns `{ interceptor, db, close }`\n *\n * @example\n * ```ts\n * const { interceptor, close } = await createResponseRecorder({\n * host: 'localhost',\n * database: 'pixivts',\n * bootstrap: true,\n * })\n * const client = await PixivClient.of(token, { onResponse: interceptor })\n * // ...\n * await close()\n * ```\n */\n// ---------------------------------------------------------------------------\n// Internal helpers\n// ---------------------------------------------------------------------------\n\nfunction ninetyDaysAgo(): Date {\n return new Date(Date.now() - 90 * 24 * 60 * 60 * 1000)\n}\n\n// ---------------------------------------------------------------------------\n// Core DB helpers (exported for testing)\n// ---------------------------------------------------------------------------\n\n/**\n * Inserts a response record into the database.\n *\n * If the unique composite index fires (duplicate method + endpoint + statusCode\n * + urlHash), the insert is silently ignored via `ON DUPLICATE KEY UPDATE id = id`.\n *\n * @param db - Drizzle ORM database instance\n * @param record - Response record from the HTTP client interceptor\n */\nexport async function addResponse(\n db: DbInstance,\n record: ResponseRecord\n): Promise<void> {\n // Hash the URL if present; fall back to \"method:endpoint\" so the column is never empty.\n const urlToHash = record.url ?? `${record.method}:${record.endpoint}`\n const urlHash = crypto.createHash('sha256').update(urlToHash).digest('hex')\n\n await db\n .insert(responsesTable)\n .values({\n method: record.method,\n endpoint: record.endpoint,\n url: record.url,\n urlHash,\n requestHeaders: record.requestHeaders,\n requestBody: record.requestBody,\n responseType: record.responseType,\n statusCode: record.statusCode,\n responseHeaders: record.responseHeaders,\n responseBody: record.responseBody,\n createdAt: new Date(),\n })\n .onDuplicateKeyUpdate({ set: { id: sql`id` } })\n}\n\n/**\n * Creates a `RecorderBundle` from an existing Drizzle instance.\n *\n * Useful for testing — pass a mock `db` and a no-op `close`.\n *\n * @param db - Drizzle ORM database instance\n * @param close - Function that closes the underlying connection\n */\nexport function createRecorderBundle(\n db: DbInstance,\n close: () => Promise<void>\n): RecorderBundle {\n const interceptor: ResponseInterceptor = (record) => addResponse(db, record)\n\n return { interceptor, db, close }\n}\n\n/**\n * Creates a response recorder that persists every pixiv API response to MySQL.\n *\n * @param opts - Connection and bootstrapping options\n * @returns `{ interceptor, db, close }`\n *\n * @example\n * ```ts\n * const { interceptor, close } = await createResponseRecorder({\n * host: 'localhost',\n * database: 'pixivts',\n * bootstrap: true,\n * })\n * const client = await PixivClient.of(token, { onResponse: interceptor })\n * // ...\n * await close()\n * ```\n */\nexport async function createResponseRecorder(\n opts: RecorderOptions\n): Promise<RecorderBundle> {\n const { pool, db } = createDbConnection(opts)\n\n if (opts.bootstrap) {\n await bootstrapSchema(db)\n }\n\n return createRecorderBundle(db, () => pool.end())\n}\n\n// ---------------------------------------------------------------------------\n// Query helpers\n// ---------------------------------------------------------------------------\n\n/** Filter criteria for response queries. */\nexport interface ResponseFilter {\n /** HTTP method to filter by (e.g. `\"GET\"`). Omit to match all methods. */\n method?: string\n /** API endpoint path to filter by (e.g. `\"/v1/illust/detail\"`). Omit to match all endpoints. */\n endpoint?: string\n /** HTTP status code to filter by (e.g. `200`). Omit to match all status codes. */\n statusCode?: number\n}\n\n/** Pagination options for `getResponses`. */\nexport interface RangeOptions {\n /** 1-based page number (default: 1). */\n page?: number\n /** Items per page (default: 100). */\n limit?: number\n}\n\n/**\n * Retrieves response records from the last 90 days.\n *\n * @param db - Drizzle ORM database instance\n * @param filter - Optional filter criteria\n * @param range - Optional pagination options\n * @returns Array of response rows, newest first\n */\nexport async function getResponses(\n db: DbInstance,\n filter?: ResponseFilter,\n range?: RangeOptions\n): Promise<ResponseRow[]> {\n const since = ninetyDaysAgo()\n const limit = range?.limit ?? 100\n const offset = ((range?.page ?? 1) - 1) * limit\n\n return db\n .select()\n .from(responsesTable)\n .where(\n and(\n gte(responsesTable.createdAt, since),\n filter?.method ? eq(responsesTable.method, filter.method) : undefined,\n filter?.endpoint\n ? eq(responsesTable.endpoint, filter.endpoint)\n : undefined,\n filter?.statusCode\n ? eq(responsesTable.statusCode, filter.statusCode)\n : undefined\n )\n )\n .orderBy(desc(responsesTable.createdAt))\n .limit(limit)\n .offset(offset)\n}\n\n/**\n * Returns the total count of response records from the last 90 days.\n *\n * @param db - Drizzle ORM database instance\n * @param filter - Optional filter criteria\n * @returns Total row count matching the filter\n */\nexport async function getResponseCount(\n db: DbInstance,\n filter?: ResponseFilter\n): Promise<number> {\n const since = ninetyDaysAgo()\n const rows = await db\n .select({ value: count() })\n .from(responsesTable)\n .where(\n and(\n gte(responsesTable.createdAt, since),\n filter?.method ? eq(responsesTable.method, filter.method) : undefined,\n filter?.endpoint\n ? eq(responsesTable.endpoint, filter.endpoint)\n : undefined,\n filter?.statusCode\n ? eq(responsesTable.statusCode, filter.statusCode)\n : undefined\n )\n )\n return rows[0]?.value ?? 0\n}\n\n/** An endpoint with its response count. */\nexport interface EndpointWithCount {\n /** HTTP method (e.g. `\"GET\"` or `\"POST\"`). */\n method: string\n /** API endpoint path (e.g. `\"/v1/illust/detail\"`). */\n endpoint: string\n /** HTTP status code returned by the endpoint. */\n statusCode: number\n /** Number of recorded responses for this (method, endpoint, statusCode) combination. */\n count: number\n}\n\n/**\n * Returns all unique (method, endpoint, statusCode) combinations seen in the\n * last 90 days, along with the count of matching records.\n *\n * @param db - Drizzle ORM database instance\n * @returns Endpoints sorted by count descending\n */\nexport async function getEndpoints(\n db: DbInstance\n): Promise<EndpointWithCount[]> {\n const since = ninetyDaysAgo()\n const rows = await db\n .select({\n method: responsesTable.method,\n endpoint: responsesTable.endpoint,\n statusCode: responsesTable.statusCode,\n count: count(),\n })\n .from(responsesTable)\n .where(gte(responsesTable.createdAt, since))\n .groupBy(\n responsesTable.method,\n responsesTable.endpoint,\n responsesTable.statusCode\n )\n .orderBy(desc(count()))\n\n return rows.map((r) => ({ ...r, count: r.count }))\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAwBA,MAAa,iBAAiB,WAC5B,aACA;;CAEE,IAAI,IAAI,IAAI,CAAC,CAAC,cAAc,CAAC,CAAC,WAAW;;CAEzC,QAAQ,QAAQ,UAAU,EAAE,QAAQ,GAAG,CAAC,CAAC,CAAC,QAAQ;;CAElD,UAAU,QAAQ,YAAY,EAAE,QAAQ,IAAI,CAAC,CAAC,CAAC,QAAQ;;CAEvD,KAAK,KAAK,KAAK;;CAEf,SAAS,QAAQ,YAAY,EAAE,QAAQ,IAAI,CAAC,CAAC,CAAC,QAAQ;;CAEtD,gBAAgB,SAAS,iBAAiB;;CAE1C,aAAa,SAAS,cAAc;;CAEpC,cAAc,QAAQ,iBAAiB,EAAE,QAAQ,GAAG,CAAC,CAAC,CAAC,QAAQ;;CAE/D,YAAY,IAAI,aAAa,CAAC,CAAC,QAAQ;;CA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pB,IACA,QACiB;CACjB,MAAM,QAAQ,cAAc;CAgB5B,QAAO,MAfY,GAChB,OAAO,EAAE,OAAO,MAAM,EAAE,CAAC,CAAC,CAC1B,KAAK,cAAc,CAAC,CACpB,MACC,IACE,IAAI,eAAe,WAAW,KAAK,GACnC,QAAQ,SAAS,GAAG,eAAe,QAAQ,OAAO,MAAM,IAAI,KAAA,GAC5D,QAAQ,WACJ,GAAG,eAAe,UAAU,OAAO,QAAQ,IAC3C,KAAA,GACJ,QAAQ,aACJ,GAAG,eAAe,YAAY,OAAO,UAAU,IAC/C,KAAA,CACN,CACF,EAAA,CACU,EAAE,EAAE,SAAS;AAC3B;;;;;;;;AAqBA,eAAsB,aACpB,IAC8B;CAC9B,MAAM,QAAQ,cAAc;CAiB5B,QAAO,MAhBY,GAChB,OAAO;EACN,QAAQ,eAAe;EACvB,UAAU,eAAe;EACzB,YAAY,eAAe;EAC3B,OAAO,MAAM;CACf,CAAC,CAAC,CACD,KAAK,cAAc,CAAC,CACpB,MAAM,IAAI,eAAe,WAAW,KAAK,CAAC,CAAC,CAC3C,QACC,eAAe,QACf,eAAe,UACf,eAAe,UACjB,CAAC,CACA,QAAQ,KAAK,MAAM,CAAC,CAAC,EAAA,CAEZ,KAAK,OAAO;EAAE,GAAG;EAAG,OAAO,EAAE;CAAM,EAAE;AACnD"}
1
+ {"version":3,"file":"index.js","names":[],"sources":["../src/schema.ts","../src/connection.ts","../src/migrations.ts","../src/recorder.ts"],"sourcesContent":["/**\n * Drizzle ORM schema for the `responses` table.\n *\n * Column names are kept in snake_case to match the legacy TypeORM schema\n * so that existing databases can be used without migration.\n */\n\nimport {\n int,\n datetime,\n longtext,\n mysqlTable,\n text,\n varchar,\n uniqueIndex,\n} from 'drizzle-orm/mysql-core'\n\n/**\n * The `responses` table stores every successful (2xx) HTTP response returned by the pixiv API.\n *\n * A unique composite index on (method, endpoint, status_code, url_hash) ensures\n * that each unique request/response combination is stored only once, regardless\n * of when it was recorded.\n */\nexport const responsesTable = mysqlTable(\n 'responses',\n {\n /** Auto-increment primary key. */\n id: int('id').autoincrement().primaryKey(),\n /** HTTP method (GET or POST). */\n method: varchar('method', { length: 10 }).notNull(),\n /** API endpoint path (e.g. /v1/illust/detail). */\n endpoint: varchar('endpoint', { length: 255 }).notNull(),\n /** Full request URL (may be null for internal requests). */\n url: text('url'),\n /** SHA-256 hash of the request URL for deduplication. */\n urlHash: varchar('url_hash', { length: 255 }).notNull(),\n /** Serialised request headers (JSON string). */\n requestHeaders: longtext('request_headers'),\n /** Request body (URL-encoded string for POST, null for GET). */\n requestBody: longtext('request_body'),\n /** Response content type (\"JSON\" or \"TEXT\"). */\n responseType: varchar('response_type', { length: 10 }).notNull(),\n /** HTTP response status code. */\n statusCode: int('status_code').notNull(),\n /** Serialised response headers (JSON string). */\n responseHeaders: longtext('response_headers'),\n /** Raw response body. */\n responseBody: longtext('response_body').notNull(),\n /** Timestamp when the record was created. */\n createdAt: datetime('created_at', { mode: 'date', fsp: 3 }).notNull(),\n },\n (table) => [\n uniqueIndex('idx_unique').on(\n table.method,\n table.endpoint,\n table.statusCode,\n table.urlHash\n ),\n ]\n)\n\n/** Type for inserting a new response record. */\nexport type NewResponse = typeof responsesTable.$inferInsert\n\n/** Type for a selected response record. */\nexport type ResponseRow = typeof responsesTable.$inferSelect\n","/**\n * MySQL connection factory for @book000/pixivts-db-mysql.\n *\n * Creates a mysql2 connection pool and wraps it in a Drizzle ORM instance.\n */\n\nimport { drizzle } from 'drizzle-orm/mysql2'\nimport mysql from 'mysql2/promise'\nimport * as schema from './schema'\n\n/** Options for establishing a MySQL connection. */\nexport interface ConnectionOptions {\n /**\n * Database hostname.\n * Falls back to the `RESPONSE_DB_HOSTNAME` environment variable.\n */\n host?: string\n\n /**\n * Database port.\n * Falls back to the `RESPONSE_DB_PORT` environment variable (default: 3306).\n */\n port?: number\n\n /**\n * Database username.\n * Falls back to the `RESPONSE_DB_USERNAME` environment variable.\n */\n user?: string\n\n /**\n * Database password.\n * Falls back to the `RESPONSE_DB_PASSWORD` environment variable.\n */\n password?: string\n\n /**\n * Database name.\n * Falls back to the `RESPONSE_DB_DATABASE` environment variable.\n */\n database?: string\n}\n\n/**\n * The Drizzle ORM database instance type returned by `createConnection`.\n *\n * Typed with the `schema` so that relational queries are available.\n */\nexport type DbInstance = ReturnType<typeof drizzle<typeof schema>>\n\nfunction parsePort(value: string | undefined): number {\n if (!value) return 3306\n const parsed = Number.parseInt(value, 10)\n return Number.isNaN(parsed) ? 3306 : parsed\n}\n\n/**\n * Creates a mysql2 connection pool and returns both the raw pool and the\n * Drizzle ORM wrapper.\n *\n * @param opts - Connection options (fall back to environment variables)\n * @returns `{ pool, db }` — raw pool for `close()`, db for queries\n */\nexport function createDbConnection(opts: ConnectionOptions): {\n pool: mysql.Pool\n db: DbInstance\n} {\n const pool = mysql.createPool({\n host: opts.host ?? process.env.RESPONSE_DB_HOSTNAME ?? 'localhost',\n port: opts.port ?? parsePort(process.env.RESPONSE_DB_PORT),\n user: opts.user ?? process.env.RESPONSE_DB_USERNAME,\n password: opts.password ?? process.env.RESPONSE_DB_PASSWORD,\n database: opts.database ?? process.env.RESPONSE_DB_DATABASE,\n timezone: '+09:00',\n supportBigNumbers: true,\n bigNumberStrings: true,\n })\n\n // Type assertion required: pnpm's peer-dep resolution for the patched drizzle-orm\n // creates a structurally-incompatible Pool type for the $client property.\n // The runtime value is correct; only the declaration paths differ.\n const db = drizzle(pool, { schema, mode: 'default' }) as unknown as DbInstance\n return { pool, db }\n}\n","/**\n * Schema bootstrapping for @book000/pixivts-db-mysql.\n *\n * Provides a `CREATE TABLE IF NOT EXISTS` helper that can be used at startup\n * without requiring drizzle-kit to be installed in production.\n *\n * For full migrations, use:\n * pnpm drizzle-kit generate\n * pnpm drizzle-kit migrate\n */\n\nimport { sql } from 'drizzle-orm'\nimport type { DbInstance } from './connection'\n\n/**\n * Creates the `responses` table if it does not already exist.\n *\n * This is a lightweight alternative to running drizzle-kit migrations in\n * environments where the table has not been set up yet.\n *\n * @param db - Drizzle ORM database instance\n */\nexport async function bootstrapSchema(db: DbInstance): Promise<void> {\n await db.execute(sql`\n CREATE TABLE IF NOT EXISTS responses (\n id INT AUTO_INCREMENT PRIMARY KEY COMMENT 'Response ID',\n method VARCHAR(10) NOT NULL COMMENT 'HTTP method',\n endpoint VARCHAR(255) NOT NULL COMMENT 'API endpoint path',\n url TEXT NULL COMMENT 'Full request URL',\n url_hash VARCHAR(255) NOT NULL COMMENT 'SHA-256 hash of the request URL',\n request_headers LONGTEXT NULL COMMENT 'Request headers (JSON)',\n request_body LONGTEXT NULL COMMENT 'Request body',\n response_type VARCHAR(10) NOT NULL COMMENT 'Response content type',\n status_code INT NOT NULL COMMENT 'HTTP status code',\n response_headers LONGTEXT NULL COMMENT 'Response headers (JSON)',\n response_body LONGTEXT NOT NULL COMMENT 'Response body',\n created_at DATETIME(3) NOT NULL COMMENT 'Record creation timestamp',\n UNIQUE INDEX idx_unique (method, endpoint, status_code, url_hash)\n ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci\n `)\n}\n","/**\n * Response recorder for @book000/pixivts-db-mysql.\n *\n * `createResponseRecorder()` returns a `{ interceptor, db, close }` bundle:\n * - `interceptor` — pass to `PixivClient.of(token, { onResponse: interceptor })`\n * - `db` — the raw Drizzle instance for custom queries\n * - `close()` — shuts down the connection pool\n *\n * The recorder uses Drizzle ORM's `onDuplicateKeyUpdate` to silently ignore\n * duplicate entries (same method + endpoint + statusCode + urlHash).\n */\n\nimport crypto from 'node:crypto'\nimport { and, count, desc, eq, gte, sql } from 'drizzle-orm'\nimport type { ResponseInterceptor, ResponseRecord } from '@book000/pixivts'\nimport {\n createDbConnection,\n type ConnectionOptions,\n type DbInstance,\n} from './connection'\nimport { responsesTable, type ResponseRow } from './schema'\nimport { bootstrapSchema } from './migrations'\n\n// ---------------------------------------------------------------------------\n// Result bundle\n// ---------------------------------------------------------------------------\n\n/** The object returned by `createResponseRecorder()`. */\nexport interface RecorderBundle {\n /**\n * Response interceptor — pass directly to `PixivClient.of()` as\n * the `onResponse` option.\n */\n interceptor: ResponseInterceptor\n\n /** Drizzle ORM database instance for custom queries. */\n db: DbInstance\n\n /** Closes the underlying connection pool. */\n close(): Promise<void>\n}\n\n// ---------------------------------------------------------------------------\n// Options\n// ---------------------------------------------------------------------------\n\n/** Options for `createResponseRecorder()`. */\nexport interface RecorderOptions extends ConnectionOptions {\n /**\n * If `true`, runs `CREATE TABLE IF NOT EXISTS` before returning.\n * Useful for first-run bootstrapping without a separate migration step.\n *\n * @default false\n */\n bootstrap?: boolean\n}\n\n// ---------------------------------------------------------------------------\n// Internal helpers\n// ---------------------------------------------------------------------------\n\nfunction ninetyDaysAgo(): Date {\n return new Date(Date.now() - 90 * 24 * 60 * 60 * 1000)\n}\n\n// ---------------------------------------------------------------------------\n// Core DB helpers (exported for testing)\n// ---------------------------------------------------------------------------\n\n/**\n * Inserts a response record into the database.\n *\n * If the unique composite index fires (duplicate method + endpoint + statusCode\n * + urlHash), the insert is silently ignored via `ON DUPLICATE KEY UPDATE id = id`.\n *\n * @param db - Drizzle ORM database instance\n * @param record - Response record from the HTTP client interceptor\n */\nexport async function addResponse(\n db: DbInstance,\n record: ResponseRecord\n): Promise<void> {\n // Hash the URL if present; fall back to \"method:endpoint\" so the column is never empty.\n const urlToHash = record.url ?? `${record.method}:${record.endpoint}`\n const urlHash = crypto.createHash('sha256').update(urlToHash).digest('hex')\n\n await db\n .insert(responsesTable)\n .values({\n method: record.method,\n endpoint: record.endpoint,\n url: record.url,\n urlHash,\n requestHeaders: record.requestHeaders,\n requestBody: record.requestBody,\n responseType: record.responseType,\n statusCode: record.statusCode,\n responseHeaders: record.responseHeaders,\n responseBody: record.responseBody,\n createdAt: new Date(),\n })\n .onDuplicateKeyUpdate({ set: { id: sql`id` } })\n}\n\n/**\n * Creates a `RecorderBundle` from an existing Drizzle instance.\n *\n * Useful for testing — pass a mock `db` and a no-op `close`.\n *\n * @param db - Drizzle ORM database instance\n * @param close - Function that closes the underlying connection\n */\nexport function createRecorderBundle(\n db: DbInstance,\n close: () => Promise<void>\n): RecorderBundle {\n const interceptor: ResponseInterceptor = (record) => addResponse(db, record)\n\n return { interceptor, db, close }\n}\n\n/**\n * Creates a response recorder that persists every successful (2xx) pixiv API response to MySQL.\n *\n * @param opts - Connection and bootstrapping options\n * @returns `{ interceptor, db, close }`\n *\n * @example\n * ```ts\n * const { interceptor, close } = await createResponseRecorder({\n * host: 'localhost',\n * database: 'pixivts',\n * bootstrap: true,\n * })\n * const client = await PixivClient.of(token, { onResponse: interceptor })\n * // ...\n * await close()\n * ```\n */\nexport async function createResponseRecorder(\n opts: RecorderOptions\n): Promise<RecorderBundle> {\n const { pool, db } = createDbConnection(opts)\n\n if (opts.bootstrap) {\n await bootstrapSchema(db)\n }\n\n return createRecorderBundle(db, () => pool.end())\n}\n\n// ---------------------------------------------------------------------------\n// Query helpers\n// ---------------------------------------------------------------------------\n\n/** Filter criteria for response queries. */\nexport interface ResponseFilter {\n /** HTTP method to filter by (e.g. `\"GET\"`). Omit to match all methods. */\n method?: string\n /** API endpoint path to filter by (e.g. `\"/v1/illust/detail\"`). Omit to match all endpoints. */\n endpoint?: string\n /** HTTP status code to filter by (e.g. `200`). Omit to match all status codes. */\n statusCode?: number\n}\n\n/** Pagination options for `getResponses`. */\nexport interface RangeOptions {\n /** 1-based page number (default: 1). */\n page?: number\n /** Items per page (default: 100). */\n limit?: number\n}\n\n/**\n * Retrieves response records from the last 90 days.\n *\n * @param db - Drizzle ORM database instance\n * @param filter - Optional filter criteria\n * @param range - Optional pagination options\n * @returns Array of response rows, newest first\n */\nexport async function getResponses(\n db: DbInstance,\n filter?: ResponseFilter,\n range?: RangeOptions\n): Promise<ResponseRow[]> {\n const since = ninetyDaysAgo()\n const limit = range?.limit ?? 100\n const offset = ((range?.page ?? 1) - 1) * limit\n\n return db\n .select()\n .from(responsesTable)\n .where(\n and(\n gte(responsesTable.createdAt, since),\n filter?.method ? eq(responsesTable.method, filter.method) : undefined,\n filter?.endpoint\n ? eq(responsesTable.endpoint, filter.endpoint)\n : undefined,\n filter?.statusCode\n ? eq(responsesTable.statusCode, filter.statusCode)\n : undefined\n )\n )\n .orderBy(desc(responsesTable.createdAt))\n .limit(limit)\n .offset(offset)\n}\n\n/**\n * Returns the total count of response records from the last 90 days.\n *\n * @param db - Drizzle ORM database instance\n * @param filter - Optional filter criteria\n * @returns Total row count matching the filter\n */\nexport async function getResponseCount(\n db: DbInstance,\n filter?: ResponseFilter\n): Promise<number> {\n const since = ninetyDaysAgo()\n const rows = await db\n .select({ value: count() })\n .from(responsesTable)\n .where(\n and(\n gte(responsesTable.createdAt, since),\n filter?.method ? eq(responsesTable.method, filter.method) : undefined,\n filter?.endpoint\n ? eq(responsesTable.endpoint, filter.endpoint)\n : undefined,\n filter?.statusCode\n ? eq(responsesTable.statusCode, filter.statusCode)\n : undefined\n )\n )\n return rows[0]?.value ?? 0\n}\n\n/** An endpoint with its response count. */\nexport interface EndpointWithCount {\n /** HTTP method (e.g. `\"GET\"` or `\"POST\"`). */\n method: string\n /** API endpoint path (e.g. `\"/v1/illust/detail\"`). */\n endpoint: string\n /** HTTP status code returned by the endpoint. */\n statusCode: number\n /** Number of recorded responses for this (method, endpoint, statusCode) combination. */\n count: number\n}\n\n/**\n * Returns all unique (method, endpoint, statusCode) combinations seen in the\n * last 90 days, along with the count of matching records.\n *\n * @param db - Drizzle ORM database instance\n * @returns Endpoints sorted by count descending\n */\nexport async function getEndpoints(\n db: DbInstance\n): Promise<EndpointWithCount[]> {\n const since = ninetyDaysAgo()\n const rows = await db\n .select({\n method: responsesTable.method,\n endpoint: responsesTable.endpoint,\n statusCode: responsesTable.statusCode,\n count: count(),\n })\n .from(responsesTable)\n .where(gte(responsesTable.createdAt, since))\n .groupBy(\n responsesTable.method,\n responsesTable.endpoint,\n responsesTable.statusCode\n )\n .orderBy(desc(count()))\n\n return rows.map((r) => ({ ...r, count: r.count }))\n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f,eAAe,UACjB,CAAC,CACA,QAAQ,KAAK,MAAM,CAAC,CAAC,EAAA,CAEZ,KAAK,OAAO;EAAE,GAAG;EAAG,OAAO,EAAE;CAAM,EAAE;AACnD"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@book000/pixivts-db-mysql",
3
- "version": "0.64.1-beta.46",
3
+ "version": "0.64.1-beta.48",
4
4
  "description": "MySQL response recorder for @book000/pixivts (Drizzle ORM)",
5
5
  "keywords": [
6
6
  "pixiv",
@@ -46,7 +46,7 @@
46
46
  "mysql2": "3.24.6"
47
47
  },
48
48
  "peerDependencies": {
49
- "@book000/pixivts": "0.64.1-beta.46"
49
+ "@book000/pixivts": "0.64.1-beta.48"
50
50
  },
51
51
  "devDependencies": {
52
52
  "@types/node": "26.6.6",