@nagi-js/pgmq 0.1.1-rc.24 → 0.1.1-rc.25
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/dist/index.js +15 -4
- package/dist/index.js.map +1 -1
- package/package.json +5 -6
package/dist/index.js
CHANGED
|
@@ -64,9 +64,17 @@ function buildQueue(executor, config) {
|
|
|
64
64
|
const { rows } = await sql`SELECT msg_id::text AS msg_id, read_ct, message FROM pgmq.read(${queueName}, ${vtSeconds}::int, ${count}::int)`.execute(
|
|
65
65
|
executor
|
|
66
66
|
);
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
67
|
+
const messages = [];
|
|
68
|
+
for (const row of rows) {
|
|
69
|
+
if (isEnvelope(row.message)) {
|
|
70
|
+
messages.push(projectMessage(row.msg_id, row.message, row.read_ct));
|
|
71
|
+
continue;
|
|
72
|
+
}
|
|
73
|
+
await sql`SELECT pgmq.archive(${queueName}, ${row.msg_id}::bigint)`.execute(
|
|
74
|
+
executor
|
|
75
|
+
);
|
|
76
|
+
}
|
|
77
|
+
return messages;
|
|
70
78
|
},
|
|
71
79
|
async ack(receipt) {
|
|
72
80
|
const msgId = parseReceipt(receipt);
|
|
@@ -112,8 +120,11 @@ function buildQueue(executor, config) {
|
|
|
112
120
|
}
|
|
113
121
|
};
|
|
114
122
|
}
|
|
123
|
+
function isEnvelope(raw) {
|
|
124
|
+
return raw !== null && typeof raw === "object" && typeof raw.runId === "string" && typeof raw.stepId === "string" && typeof raw.attempt === "number";
|
|
125
|
+
}
|
|
115
126
|
function projectMessage(msgId, raw, readCount) {
|
|
116
|
-
if (raw
|
|
127
|
+
if (!isEnvelope(raw)) {
|
|
117
128
|
throw new Error(
|
|
118
129
|
`pgmq: malformed message envelope ${JSON.stringify(raw)} \u2014 expected { runId, stepId, attempt }`
|
|
119
130
|
);
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/pgm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,CAAU,GAAG,CAAC,CAAA,2CAAA;AAAA,KACzD;AAAA,EACF;AACA,EAAA,MAAM,QAAA,GAAW,GAAA;AACjB,EAAA,OAAO;AAAA,IACL,OAAA,EAAS,KAAA;AAAA,IACT,OAAO,QAAA,CAAS,KAAA;AAAA,IAChB,QAAQ,QAAA,CAAS,MAAA;AAAA,IACjB,SAAS,QAAA,CAAS,OAAA;AAAA,IAClB,SAAA;AAAA,IACA,OAAA,EAAS,IAAA;AAAA,IACT,GAAI,SAAS,MAAA,KAAW,MAAA,GAAY,EAAE,MAAA,EAAQ,QAAA,CAAS,MAAA,EAAO,GAAI;AAAC,GACrE;AACF;AAEA,SAAS,aAAa,OAAA,EAAyB;AAC7C,EAAA,IAAI;AACF,IAAA,MAAA,CAAO,OAAO,CAAA;AAAA,EAChB,CAAA,CAAA,MAAQ;AACN,IAAA,MAAM,IAAA,GACJ,OAAA,KAAY,WAAA,GACR,wIAAA,GACA,EAAA;AACN,IAAA,MAAM,IAAI,KAAA;AAAA,MACR,2BAA2B,IAAA,CAAK,SAAA,CAAU,OAAO,CAAC,6CAAwC,IAAI,CAAA;AAAA,KAChG;AAAA,EACF;AACA,EAAA,OAAO,OAAA;AACT","file":"index.js","sourcesContent":["import type {\n AttemptNumber,\n Millis,\n Queue,\n QueueDequeueOpts,\n QueueEnqueueOpts,\n QueueInspectEntry,\n QueueMessage,\n RunId,\n StepId,\n Tx,\n} from \"@nagi-js/core\";\nimport { type Kysely, sql } from \"kysely\";\n\nconst DEFAULT_QUEUE_NAME = \"nagi\";\n// Must exceed core's DEFAULT_HEARTBEAT_INTERVAL_MS (40s), or a slow step is\n// redelivered before its first lease extension. Matches core's\n// DEFAULT_HEARTBEAT_LEASE_MS so a crashed worker's message and its store\n// lease become reclaimable at the same time.\nconst DEFAULT_VISIBILITY_TIMEOUT_MS: Millis = 120_000;\n// pgmq's client rule (max 47 keeps archived_at_idx_<name> within 63 bytes);\n// stricter than the extension because inspect() splices it unquoted.\nconst QUEUE_NAME_RE = /^[A-Za-z0-9_]{1,47}$/;\n\nexport interface PgmqQueueOpts<DB = unknown> {\n readonly db: Kysely<DB>;\n readonly queueName?: string;\n readonly visibilityTimeoutMs?: Millis;\n readonly partitioned?: boolean;\n readonly archiveOnAck?: boolean;\n}\n\n// Narrows the optional core capabilities to required: pgmq always provides both.\nexport interface PgmqQueue extends Queue {\n ensureSchema(): Promise<void>;\n withTx(tx: Tx): Queue;\n}\n\ninterface MessageEnvelope {\n readonly runId: string;\n readonly stepId: string;\n readonly attempt: number;\n // Absent on messages enqueued before the field existed; see QueueMessage.\n readonly flowId?: string;\n}\n\ninterface QueueConfig {\n readonly queueName: string;\n readonly vtSeconds: number;\n readonly archiveOnAck: boolean;\n}\n\nexport function pgmqQueue<DB = unknown>(opts: PgmqQueueOpts<DB>): PgmqQueue {\n const queueName = opts.queueName ?? DEFAULT_QUEUE_NAME;\n if (!QUEUE_NAME_RE.test(queueName)) {\n throw new Error(\n `@nagi-js/pgmq: invalid queue name \"${queueName}\". Must match ${QUEUE_NAME_RE}.`,\n );\n }\n // Caller-installed Kysely plugins (notably CamelCasePlugin) rewrite the result\n // transformer, turning our internal `msg_id` reads into `msgId` and breaking\n // parseReceipt. Strip plugins from the executor used for our own SQL only —\n // the caller's `db` is untouched so their CamelCase reads still work.\n const db = stripPlugins(opts.db as unknown as Kysely<unknown>);\n const vtSeconds = Math.max(\n 1,\n Math.ceil(\n (opts.visibilityTimeoutMs ?? DEFAULT_VISIBILITY_TIMEOUT_MS) / 1000,\n ),\n );\n const partitioned = opts.partitioned ?? false;\n const archiveOnAck = opts.archiveOnAck ?? false;\n const config: QueueConfig = { queueName, vtSeconds, archiveOnAck };\n\n return {\n ...buildQueue(db, config),\n\n async ensureSchema(): Promise<void> {\n await sql`CREATE EXTENSION IF NOT EXISTS pgmq`.execute(db);\n if (partitioned) {\n await sql`SELECT pgmq.create_partitioned(${queueName})`.execute(db);\n } else {\n await sql`SELECT pgmq.create(${queueName})`.execute(db);\n }\n },\n\n withTx(tx: Tx): Queue {\n return buildQueue(stripPlugins(tx as unknown as Kysely<unknown>), config);\n },\n };\n}\n\ninterface PluginStrippable {\n withoutPlugins?: () => Kysely<unknown>;\n}\n\nfunction stripPlugins(executor: Kysely<unknown>): Kysely<unknown> {\n const candidate = executor as Kysely<unknown> & PluginStrippable;\n return typeof candidate.withoutPlugins === \"function\"\n ? candidate.withoutPlugins()\n : executor;\n}\n\nfunction buildQueue(executor: Kysely<unknown>, config: QueueConfig): Queue {\n const { queueName, vtSeconds, archiveOnAck } = config;\n\n return {\n async enqueue(\n runId: RunId,\n stepId: StepId,\n options?: QueueEnqueueOpts,\n ): Promise<void> {\n const envelope: MessageEnvelope = {\n runId,\n stepId,\n attempt: options?.attempt ?? 1,\n ...(options?.flowId !== undefined ? { flowId: options.flowId } : {}),\n };\n const delaySeconds = Math.max(\n 0,\n Math.ceil((options?.delayMs ?? 0) / 1000),\n );\n await sql`SELECT pgmq.send(${queueName}, ${JSON.stringify(envelope)}::jsonb, ${delaySeconds}::int)`.execute(\n executor,\n );\n },\n\n async dequeue({\n count,\n }: QueueDequeueOpts): Promise<readonly QueueMessage[]> {\n // ::text: a consumer int8 parser would round msg_id past 2^53.\n const { rows } = await sql<{\n msg_id: string;\n read_ct: number;\n message: unknown;\n }>`SELECT msg_id::text AS msg_id, read_ct, message FROM pgmq.read(${queueName}, ${vtSeconds}::int, ${count}::int)`.execute(\n executor,\n );\n return rows.map((row) =>\n projectMessage(row.msg_id, row.message, row.read_ct),\n );\n },\n\n async ack(receipt: string): Promise<void> {\n const msgId = parseReceipt(receipt);\n if (archiveOnAck) {\n await sql`SELECT pgmq.archive(${queueName}, ${msgId}::bigint)`.execute(\n executor,\n );\n } else {\n await sql`SELECT pgmq.delete(${queueName}, ${msgId}::bigint)`.execute(\n executor,\n );\n }\n },\n\n async nack(\n receipt: string,\n options?: { readonly delayMs?: Millis },\n ): Promise<void> {\n const msgId = parseReceipt(receipt);\n const delaySeconds = Math.max(\n 0,\n Math.ceil((options?.delayMs ?? 0) / 1000),\n );\n await sql`SELECT pgmq.set_vt(${queueName}, ${msgId}::bigint, ${delaySeconds}::int)`.execute(\n executor,\n );\n },\n\n async extend(receipt: string, leaseMs: Millis): Promise<void> {\n const msgId = parseReceipt(receipt);\n const vt = Math.max(1, Math.ceil(leaseMs / 1000));\n await sql`SELECT pgmq.set_vt(${queueName}, ${msgId}::bigint, ${vt}::int)`.execute(\n executor,\n );\n },\n\n async inspect(runId: RunId): Promise<readonly QueueInspectEntry[]> {\n // Direct table read (pgmq stores queue \"x\" as pgmq.q_x) — pgmq has no\n // query-by-payload API. Read-only; safe alongside consuming workers.\n const { rows } = await sql<{\n read_ct: number;\n vt: Date | string;\n message: unknown;\n }>`SELECT read_ct, vt, message FROM ${sql.raw(`pgmq.q_${queueName}`)}\n WHERE message->>'runId' = ${runId}`.execute(executor);\n return rows.map((row) => {\n const m = projectMessage(\"0\", row.message, row.read_ct);\n return {\n stepId: m.stepId,\n attempt: m.attempt,\n readCount: row.read_ct,\n visibleAt: row.vt instanceof Date ? row.vt : new Date(row.vt),\n };\n });\n },\n };\n}\n\nfunction projectMessage(\n msgId: string,\n raw: unknown,\n readCount: number,\n): QueueMessage {\n if (\n raw === null ||\n typeof raw !== \"object\" ||\n typeof (raw as { runId?: unknown }).runId !== \"string\" ||\n typeof (raw as { stepId?: unknown }).stepId !== \"string\" ||\n typeof (raw as { attempt?: unknown }).attempt !== \"number\"\n ) {\n throw new Error(\n `pgmq: malformed message envelope ${JSON.stringify(raw)} — expected { runId, stepId, attempt }`,\n );\n }\n const envelope = raw as MessageEnvelope;\n return {\n receipt: msgId,\n runId: envelope.runId as RunId,\n stepId: envelope.stepId as StepId,\n attempt: envelope.attempt as AttemptNumber,\n readCount,\n payload: null,\n ...(envelope.flowId !== undefined ? { flowId: envelope.flowId } : {}),\n };\n}\n\nfunction parseReceipt(receipt: string): string {\n try {\n BigInt(receipt);\n } catch {\n const hint =\n receipt === \"undefined\"\n ? \" (likely caller installed a Kysely CamelCasePlugin that rewrote msg_id → msgId; nagi internal executor should be plugin-stripped)\"\n : \"\";\n throw new Error(\n `pgmq: malformed receipt ${JSON.stringify(receipt)} — expected stringified bigint msg_id${hint}`,\n );\n }\n return receipt;\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/pgmq-queue.ts"],"names":[],"mappings":";;;AAcA,IAAM,kBAAA,GAAqB,MAAA;AAK3B,IAAM,6BAAA,GAAwC,IAAA;AAG9C,IAAM,aAAA,GAAgB,sBAAA;AA8Bf,SAAS,UAAwB,IAAA,EAAoC;AAC1E,EAAA,MAAM,SAAA,GAAY,KAAK,SAAA,IAAa,kBAAA;AACpC,EAAA,IAAI,CAAC,aAAA,CAAc,IAAA,CAAK,SAAS,CAAA,EAAG;AAClC,IAAA,MAAM,IAAI,KAAA;AAAA,MACR,CAAA,mCAAA,EAAsC,SAAS,CAAA,cAAA,EAAiB,aAAa,CAAA,CAAA;AAAA,KAC/E;AAAA,EACF;AAKA,EAAA,MAAM,EAAA,GAAK,YAAA,CAAa,IAAA,CAAK,EAAgC,CAAA;AAC7D,EAAA,MAAM,YAAY,IAAA,CAAK,GAAA;AAAA,IACrB,CAAA;AAAA,IACA,IAAA,CAAK,IAAA;AAAA,MAAA,CACF,IAAA,CAAK,uBAAuB,6BAAA,IAAiC;AAAA;AAChE,GACF;AACA,EAAA,MAAM,WAAA,GAAc,KAAK,WAAA,IAAe,KAAA;AACxC,EAAA,MAAM,YAAA,GAAe,KAAK,YAAA,IAAgB,KAAA;AAC1C,EAAA,MAAM,MAAA,GAAsB,EAAE,SAAA,EAAW,SAAA,EAAW,YAAA,EAAa;AAEjE,EAAA,OAAO;AAAA,IACL,GAAG,UAAA,CAAW,EAAA,EAAI,MAAM,CAAA;AAAA,IAExB,MAAM,YAAA,GAA8B;AAClC,MAAA,MAAM,GAAA,CAAA,mCAAA,CAAA,CAAyC,QAAQ,EAAE,CAAA;AACzD,MAAA,IAAI,WAAA,EAAa;AACf,QA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,2BAA2B,IAAA,CAAK,SAAA,CAAU,OAAO,CAAC,6CAAwC,IAAI,CAAA;AAAA,KAChG;AAAA,EACF;AACA,EAAA,OAAO,OAAA;AACT","file":"index.js","sourcesContent":["import type {\n AttemptNumber,\n Millis,\n Queue,\n QueueDequeueOpts,\n QueueEnqueueOpts,\n QueueInspectEntry,\n QueueMessage,\n RunId,\n StepId,\n Tx,\n} from \"@nagi-js/core\";\nimport { type Kysely, sql } from \"kysely\";\n\nconst DEFAULT_QUEUE_NAME = \"nagi\";\n// Must exceed core's DEFAULT_HEARTBEAT_INTERVAL_MS (40s), or a slow step is\n// redelivered before its first lease extension. Matches core's\n// DEFAULT_HEARTBEAT_LEASE_MS so a crashed worker's message and its store\n// lease become reclaimable at the same time.\nconst DEFAULT_VISIBILITY_TIMEOUT_MS: Millis = 120_000;\n// pgmq's client rule (max 47 keeps archived_at_idx_<name> within 63 bytes);\n// stricter than the extension because inspect() splices it unquoted.\nconst QUEUE_NAME_RE = /^[A-Za-z0-9_]{1,47}$/;\n\nexport interface PgmqQueueOpts<DB = unknown> {\n readonly db: Kysely<DB>;\n readonly queueName?: string;\n readonly visibilityTimeoutMs?: Millis;\n readonly partitioned?: boolean;\n readonly archiveOnAck?: boolean;\n}\n\n// Narrows the optional core capabilities to required: pgmq always provides both.\nexport interface PgmqQueue extends Queue {\n ensureSchema(): Promise<void>;\n withTx(tx: Tx): Queue;\n}\n\ninterface MessageEnvelope {\n readonly runId: string;\n readonly stepId: string;\n readonly attempt: number;\n // Absent on messages enqueued before the field existed; see QueueMessage.\n readonly flowId?: string;\n}\n\ninterface QueueConfig {\n readonly queueName: string;\n readonly vtSeconds: number;\n readonly archiveOnAck: boolean;\n}\n\nexport function pgmqQueue<DB = unknown>(opts: PgmqQueueOpts<DB>): PgmqQueue {\n const queueName = opts.queueName ?? DEFAULT_QUEUE_NAME;\n if (!QUEUE_NAME_RE.test(queueName)) {\n throw new Error(\n `@nagi-js/pgmq: invalid queue name \"${queueName}\". Must match ${QUEUE_NAME_RE}.`,\n );\n }\n // Caller-installed Kysely plugins (notably CamelCasePlugin) rewrite the result\n // transformer, turning our internal `msg_id` reads into `msgId` and breaking\n // parseReceipt. Strip plugins from the executor used for our own SQL only —\n // the caller's `db` is untouched so their CamelCase reads still work.\n const db = stripPlugins(opts.db as unknown as Kysely<unknown>);\n const vtSeconds = Math.max(\n 1,\n Math.ceil(\n (opts.visibilityTimeoutMs ?? DEFAULT_VISIBILITY_TIMEOUT_MS) / 1000,\n ),\n );\n const partitioned = opts.partitioned ?? false;\n const archiveOnAck = opts.archiveOnAck ?? false;\n const config: QueueConfig = { queueName, vtSeconds, archiveOnAck };\n\n return {\n ...buildQueue(db, config),\n\n async ensureSchema(): Promise<void> {\n await sql`CREATE EXTENSION IF NOT EXISTS pgmq`.execute(db);\n if (partitioned) {\n await sql`SELECT pgmq.create_partitioned(${queueName})`.execute(db);\n } else {\n await sql`SELECT pgmq.create(${queueName})`.execute(db);\n }\n },\n\n withTx(tx: Tx): Queue {\n return buildQueue(stripPlugins(tx as unknown as Kysely<unknown>), config);\n },\n };\n}\n\ninterface PluginStrippable {\n withoutPlugins?: () => Kysely<unknown>;\n}\n\nfunction stripPlugins(executor: Kysely<unknown>): Kysely<unknown> {\n const candidate = executor as Kysely<unknown> & PluginStrippable;\n return typeof candidate.withoutPlugins === \"function\"\n ? candidate.withoutPlugins()\n : executor;\n}\n\nfunction buildQueue(executor: Kysely<unknown>, config: QueueConfig): Queue {\n const { queueName, vtSeconds, archiveOnAck } = config;\n\n return {\n async enqueue(\n runId: RunId,\n stepId: StepId,\n options?: QueueEnqueueOpts,\n ): Promise<void> {\n const envelope: MessageEnvelope = {\n runId,\n stepId,\n attempt: options?.attempt ?? 1,\n ...(options?.flowId !== undefined ? { flowId: options.flowId } : {}),\n };\n const delaySeconds = Math.max(\n 0,\n Math.ceil((options?.delayMs ?? 0) / 1000),\n );\n await sql`SELECT pgmq.send(${queueName}, ${JSON.stringify(envelope)}::jsonb, ${delaySeconds}::int)`.execute(\n executor,\n );\n },\n\n async dequeue({\n count,\n }: QueueDequeueOpts): Promise<readonly QueueMessage[]> {\n // ::text: a consumer int8 parser would round msg_id past 2^53.\n const { rows } = await sql<{\n msg_id: string;\n read_ct: number;\n message: unknown;\n }>`SELECT msg_id::text AS msg_id, read_ct, message FROM pgmq.read(${queueName}, ${vtSeconds}::int, ${count}::int)`.execute(\n executor,\n );\n const messages: QueueMessage[] = [];\n for (const row of rows) {\n if (isEnvelope(row.message)) {\n messages.push(projectMessage(row.msg_id, row.message, row.read_ct));\n continue;\n }\n // A malformed envelope must not block the rest of the batch behind\n // pgmq's visibility timeout forever — archive it out of the way\n // (not delete: it stays inspectable in pgmq's archive table).\n await sql`SELECT pgmq.archive(${queueName}, ${row.msg_id}::bigint)`.execute(\n executor,\n );\n }\n return messages;\n },\n\n async ack(receipt: string): Promise<void> {\n const msgId = parseReceipt(receipt);\n if (archiveOnAck) {\n await sql`SELECT pgmq.archive(${queueName}, ${msgId}::bigint)`.execute(\n executor,\n );\n } else {\n await sql`SELECT pgmq.delete(${queueName}, ${msgId}::bigint)`.execute(\n executor,\n );\n }\n },\n\n async nack(\n receipt: string,\n options?: { readonly delayMs?: Millis },\n ): Promise<void> {\n const msgId = parseReceipt(receipt);\n const delaySeconds = Math.max(\n 0,\n Math.ceil((options?.delayMs ?? 0) / 1000),\n );\n await sql`SELECT pgmq.set_vt(${queueName}, ${msgId}::bigint, ${delaySeconds}::int)`.execute(\n executor,\n );\n },\n\n async extend(receipt: string, leaseMs: Millis): Promise<void> {\n const msgId = parseReceipt(receipt);\n const vt = Math.max(1, Math.ceil(leaseMs / 1000));\n await sql`SELECT pgmq.set_vt(${queueName}, ${msgId}::bigint, ${vt}::int)`.execute(\n executor,\n );\n },\n\n async inspect(runId: RunId): Promise<readonly QueueInspectEntry[]> {\n // Direct table read (pgmq stores queue \"x\" as pgmq.q_x) — pgmq has no\n // query-by-payload API. Read-only; safe alongside consuming workers.\n const { rows } = await sql<{\n read_ct: number;\n vt: Date | string;\n message: unknown;\n }>`SELECT read_ct, vt, message FROM ${sql.raw(`pgmq.q_${queueName}`)}\n WHERE message->>'runId' = ${runId}`.execute(executor);\n return rows.map((row) => {\n const m = projectMessage(\"0\", row.message, row.read_ct);\n return {\n stepId: m.stepId,\n attempt: m.attempt,\n readCount: row.read_ct,\n visibleAt: row.vt instanceof Date ? row.vt : new Date(row.vt),\n };\n });\n },\n };\n}\n\nfunction isEnvelope(raw: unknown): raw is MessageEnvelope {\n return (\n raw !== null &&\n typeof raw === \"object\" &&\n typeof (raw as { runId?: unknown }).runId === \"string\" &&\n typeof (raw as { stepId?: unknown }).stepId === \"string\" &&\n typeof (raw as { attempt?: unknown }).attempt === \"number\"\n );\n}\n\nfunction projectMessage(\n msgId: string,\n raw: unknown,\n readCount: number,\n): QueueMessage {\n if (!isEnvelope(raw)) {\n throw new Error(\n `pgmq: malformed message envelope ${JSON.stringify(raw)} — expected { runId, stepId, attempt }`,\n );\n }\n const envelope = raw;\n return {\n receipt: msgId,\n runId: envelope.runId as RunId,\n stepId: envelope.stepId as StepId,\n attempt: envelope.attempt as AttemptNumber,\n readCount,\n payload: null,\n ...(envelope.flowId !== undefined ? { flowId: envelope.flowId } : {}),\n };\n}\n\nfunction parseReceipt(receipt: string): string {\n try {\n BigInt(receipt);\n } catch {\n const hint =\n receipt === \"undefined\"\n ? \" (likely caller installed a Kysely CamelCasePlugin that rewrote msg_id → msgId; nagi internal executor should be plugin-stripped)\"\n : \"\";\n throw new Error(\n `pgmq: malformed receipt ${JSON.stringify(receipt)} — expected stringified bigint msg_id${hint}`,\n );\n }\n return receipt;\n}\n"]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@nagi-js/pgmq",
|
|
3
|
-
"version": "0.1.1-rc.
|
|
3
|
+
"version": "0.1.1-rc.25",
|
|
4
4
|
"description": "PGMQ Queue adapter for nagi.",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"type": "module",
|
|
@@ -34,16 +34,15 @@
|
|
|
34
34
|
"README.md",
|
|
35
35
|
"LICENSE"
|
|
36
36
|
],
|
|
37
|
-
"dependencies": {
|
|
38
|
-
"@nagi-js/core": "0.1.1-rc.23"
|
|
39
|
-
},
|
|
40
37
|
"peerDependencies": {
|
|
41
|
-
"kysely": "^0.29.0"
|
|
38
|
+
"kysely": "^0.29.0",
|
|
39
|
+
"@nagi-js/core": "0.1.1-rc.24"
|
|
42
40
|
},
|
|
43
41
|
"devDependencies": {
|
|
44
42
|
"@types/pg": "^8.23.1",
|
|
45
43
|
"kysely": "^0.29.0",
|
|
46
|
-
"pg": "^8.23.0"
|
|
44
|
+
"pg": "^8.23.0",
|
|
45
|
+
"@nagi-js/core": "0.1.1-rc.24"
|
|
47
46
|
},
|
|
48
47
|
"repository": {
|
|
49
48
|
"type": "git",
|