@erxes/plugin-sdk 0.1.0-v2.5 → 0.1.0-v2.7

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/client.d.ts CHANGED
@@ -107,6 +107,9 @@ export declare const createCoreClient: (options: CoreClientOptions) => {
107
107
  INVALID_CLIENT: {
108
108
  status: number;
109
109
  };
110
+ INVALID_SCHEDULE: {
111
+ status: number;
112
+ };
110
113
  LIMIT_EXCEEDED: {
111
114
  status: number;
112
115
  };
@@ -216,6 +219,9 @@ export declare const createCoreClient: (options: CoreClientOptions) => {
216
219
  INVALID_CLIENT: {
217
220
  status: number;
218
221
  };
222
+ INVALID_SCHEDULE: {
223
+ status: number;
224
+ };
219
225
  LIMIT_EXCEEDED: {
220
226
  status: number;
221
227
  };
package/dist/index.d.ts CHANGED
@@ -29,6 +29,19 @@
29
29
  * // An invoice may list what it pays for; `plugin` names another plugin's line (it gets the events):
30
30
  * // lines: [{ productId, quantity: 1, unitPrice: 150000 }, { name: 'Delivery', quantity: 1, unitPrice: 10000, plugin: 'tms' }]
31
31
  *
32
+ * Fields on customers and companies (rollups; scope `fields:write`): declare them in the manifest,
33
+ * then write their values. Members see them read-only and filter by them; no timeline entry or event.
34
+ *
35
+ * fields: [{ code: 'total_spent', contentType: 'customer', label: 'Total spent', type: 'number' }],
36
+ * await core.forOrg(orgId).fields.setPluginValues({
37
+ * contentType: 'customer', values: [{ recordId: customerId, code: 'total_spent', value: 150000 }],
38
+ * }); // → { written, skipped }; up to 500, value null clears
39
+ *
40
+ * Segments (scope `views:read`): a shared view members built in core is the audience.
41
+ *
42
+ * const { data } = await core.forOrg(orgId).views.list({ recordType: 'customer' }); // shared only
43
+ * const { recordIds } = await core.forOrg(orgId).views.matches({ viewId, recordIds: [customerId] });
44
+ *
32
45
  * Customers (a shop, tracking, booking): core signs them in; the plugin never builds sign-up or
33
46
  * sign-in. Declare `customerApp: { origins: ['https://{subdomain}.shop.example.com'] }` in the
34
47
  * manifest. The app's own form makes two calls to core: `POST /core/v1/customer-auth/code`
@@ -50,11 +63,27 @@
50
63
  * if (!member.canChange()) throw new Error('HR is read-only: buy it again on erxes.io');
51
64
  * // server-side jobs: await core.forOrg(orgId).saas.pluginPlan() → { tier, access }
52
65
  *
66
+ * Jobs (plugins on core's database): declare them in the manifest, queue them in the
67
+ * plugin's own transaction, and serve each at `<api.url>/jobs/<name>`. Core retries
68
+ * until the route answers 2xx (`retry`: attempts in all, the first wait and the
69
+ * longest, in seconds; default 8, 30 s, 6 h). A `cron` (UTC) job runs once per
70
+ * organisation that has the plugin.
71
+ *
72
+ * jobs: [{ name: 'mail.sync', retry: { attempts: 5, delay: 60, maxDelay: 3600 } },
73
+ * { name: 'sla.check', cron: '*\/5 * * * *' }],
74
+ * await enqueueJob(tx, { orgId, name: 'mail.sync', payload: { accountId }, dedupeKey: accountId });
75
+ * app.post('/api/jobs/:name', express.text({ type: '*\/*' }), async (req, res) => {
76
+ * const job = await verifyCoreJob(req.headers.authorization, req.body, { coreUrl, plugin: 'frontline' });
77
+ * await JOBS[job.name](job); // { jobId, orgId, name, attempt, payload }; may repeat
78
+ * res.sendStatus(204);
79
+ * });
80
+ *
53
81
  * The client secret is only ever sent to `POST /plugins/token`; API calls use
54
82
  * 15-minute tokens, fetched and renewed here. Plugins on core's database can
55
83
  * also call `core_publish_event()`, `core_record_audit()` and
56
84
  * `core_live_signal()` inside their own transactions.
57
85
  */
58
86
  import { CoreClient, CoreClientOptions, CoreTokenError, createCoreClient } from "./client.js";
59
- import { CoreCall, CustomerSignIn, DeliveredEvent, ErxesSignIn, PluginMember, bearerOf, verifyCoreCall, verifyCoreEvent, verifyCustomerToken, verifyErxesAccessToken, verifyPluginSession } from "./verify.js";
60
- export { CoreCall, CoreClient, CoreClientOptions, CoreTokenError, CustomerSignIn, DeliveredEvent, ErxesSignIn, PluginMember, bearerOf, createCoreClient, verifyCoreCall, verifyCoreEvent, verifyCustomerToken, verifyErxesAccessToken, verifyPluginSession };
87
+ import { JobInput, enqueueJob } from "./jobs.js";
88
+ import { CoreCall, CustomerSignIn, DeliveredEvent, ErxesSignIn, PluginMember, bearerOf, verifyCoreCall, verifyCoreEvent, verifyCoreJob, verifyCustomerToken, verifyErxesAccessToken, verifyPluginSession } from "./verify.js";
89
+ export { CoreCall, CoreClient, CoreClientOptions, CoreTokenError, CustomerSignIn, DeliveredEvent, ErxesSignIn, JobInput, PluginMember, bearerOf, createCoreClient, enqueueJob, verifyCoreCall, verifyCoreEvent, verifyCoreJob, verifyCustomerToken, verifyErxesAccessToken, verifyPluginSession };
package/dist/index.js CHANGED
@@ -1,3 +1,4 @@
1
1
  import { CoreTokenError, createCoreClient } from "./client.js";
2
- import { DeliveredEvent, bearerOf, verifyCoreCall, verifyCoreEvent, verifyCustomerToken, verifyErxesAccessToken, verifyPluginSession } from "./verify.js";
3
- export { CoreTokenError, DeliveredEvent, bearerOf, createCoreClient, verifyCoreCall, verifyCoreEvent, verifyCustomerToken, verifyErxesAccessToken, verifyPluginSession };
2
+ import { enqueueJob } from "./jobs.js";
3
+ import { DeliveredEvent, bearerOf, verifyCoreCall, verifyCoreEvent, verifyCoreJob, verifyCustomerToken, verifyErxesAccessToken, verifyPluginSession } from "./verify.js";
4
+ export { CoreTokenError, DeliveredEvent, bearerOf, createCoreClient, enqueueJob, verifyCoreCall, verifyCoreEvent, verifyCoreJob, verifyCustomerToken, verifyErxesAccessToken, verifyPluginSession };
package/dist/jobs.d.ts ADDED
@@ -0,0 +1,23 @@
1
+ import { SQL } from "drizzle-orm";
2
+ /** A transaction on core's database, as the plugin's own role (Drizzle's `tx`). */
3
+ interface Transaction {
4
+ execute(query: SQL): PromiseLike<unknown>;
5
+ }
6
+ export interface JobInput {
7
+ orgId: string;
8
+ /** A job the manifest's `jobs` declares. */
9
+ name: string;
10
+ payload?: Record<string, unknown>;
11
+ /** Run no earlier than this. */
12
+ runAt?: Date;
13
+ /** One queued or running job per key: queueing it again adds nothing. */
14
+ dedupeKey?: string;
15
+ }
16
+ /**
17
+ * Queues one of the plugin's jobs in its own transaction (`core_enqueue_job`),
18
+ * so the job exists only if the transaction commits. Core then POSTs it to
19
+ * `<api.url>/jobs/<name>` until the plugin answers 2xx. The database refuses a
20
+ * name the manifest doesn't declare and an organisation without the plugin.
21
+ */
22
+ export declare const enqueueJob: (tx: Transaction, job: JobInput) => Promise<void>;
23
+ export {};
package/dist/jobs.js ADDED
@@ -0,0 +1,18 @@
1
+ import { sql } from "drizzle-orm";
2
+ // src/jobs.ts
3
+ /**
4
+ * Queues one of the plugin's jobs in its own transaction (`core_enqueue_job`),
5
+ * so the job exists only if the transaction commits. Core then POSTs it to
6
+ * `<api.url>/jobs/<name>` until the plugin answers 2xx. The database refuses a
7
+ * name the manifest doesn't declare and an organisation without the plugin.
8
+ */
9
+ const enqueueJob = async (tx, job) => {
10
+ await tx.execute(sql`select core_enqueue_job(
11
+ ${job.orgId},
12
+ ${job.name},
13
+ ${JSON.stringify(job.payload ?? {})}::jsonb,
14
+ ${job.runAt?.toISOString() ?? null}::timestamptz,
15
+ ${job.dedupeKey ?? null}
16
+ )`);
17
+ };
18
+ export { enqueueJob };
package/dist/verify.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { PluginAccess, PluginTier } from "@erxes/core-contract";
1
+ import { PluginAccess, PluginJobDelivery, PluginTier } from "@erxes/core-contract";
2
2
  import { z } from "zod";
3
3
  /** The signed-in member a plugin UI calls the plugin's API for. */
4
4
  export interface PluginMember {
@@ -127,4 +127,12 @@ export declare const verifyCustomerToken: (authorization: string | undefined | n
127
127
  * once, and act on the totals in the payload, not on arrival order.
128
128
  */
129
129
  export declare const verifyCoreEvent: (authorization: string | undefined | null, rawBody: string, options: VerifyOptions) => Promise<DeliveredEvent>;
130
+ /**
131
+ * Verifies one attempt of a job core POSTed to `<api.url>/jobs/<name>` and
132
+ * returns it: the token is core's, for this plugin, unexpired, and signs this
133
+ * exact body (pass the raw body text). Throws if anything is off. Answer 2xx
134
+ * when done; anything else retries. A job can run more than once: the
135
+ * `Idempotency-Key` header is its `jobId`.
136
+ */
137
+ export declare const verifyCoreJob: (authorization: string | undefined | null, rawBody: string, options: VerifyOptions) => Promise<PluginJobDelivery>;
130
138
  export {};
package/dist/verify.js CHANGED
@@ -1,4 +1,4 @@
1
- import { CORE_API_PREFIX, CoreEvent, PluginAccess, PluginTier } from "@erxes/core-contract";
1
+ import { CORE_API_PREFIX, CoreEvent, PluginAccess, PluginJobDelivery, PluginTier } from "@erxes/core-contract";
2
2
  import { z } from "zod";
3
3
  import { createRemoteJWKSet, jwtVerify } from "jose";
4
4
  // src/verify.ts
@@ -153,4 +153,25 @@ const verifyCoreEvent = async (authorization, rawBody, options) => {
153
153
  if (event.id !== claims.event || event.organizationId !== claims.org) throw new Error("the event does not match the token");
154
154
  return event;
155
155
  };
156
- export { DeliveredEvent, bearerOf, verifyCoreCall, verifyCoreEvent, verifyCustomerToken, verifyErxesAccessToken, verifyPluginSession };
156
+ const JobClaims = z.object({
157
+ sha: z.string(),
158
+ job: z.string(),
159
+ org: z.string()
160
+ });
161
+ /**
162
+ * Verifies one attempt of a job core POSTed to `<api.url>/jobs/<name>` and
163
+ * returns it: the token is core's, for this plugin, unexpired, and signs this
164
+ * exact body (pass the raw body text). Throws if anything is off. Answer 2xx
165
+ * when done; anything else retries. A job can run more than once: the
166
+ * `Idempotency-Key` header is its `jobId`.
167
+ */
168
+ const verifyCoreJob = async (authorization, rawBody, options) => {
169
+ const token = bearerOf(authorization);
170
+ if (!token) throw new Error("no core token");
171
+ const claims = await verifyCoreToken(token, options, "erxes-core-job+jwt", JobClaims);
172
+ if (claims.sha !== await sha256(rawBody)) throw new Error("the body does not match the token");
173
+ const job = PluginJobDelivery.parse(JSON.parse(rawBody));
174
+ if (job.jobId !== claims.job || job.orgId !== claims.org) throw new Error("the job does not match the token");
175
+ return job;
176
+ };
177
+ export { DeliveredEvent, bearerOf, verifyCoreCall, verifyCoreEvent, verifyCoreJob, verifyCustomerToken, verifyErxesAccessToken, verifyPluginSession };
package/package.json CHANGED
@@ -1,8 +1,8 @@
1
1
  {
2
2
  "name": "@erxes/plugin-sdk",
3
- "version": "0.1.0-v2.5",
3
+ "version": "0.1.0-v2.7",
4
4
  "private": false,
5
- "description": "For erxes plugin servers: a typed core client with automatic plugin tokens, and verification of members' plugin session tokens",
5
+ "description": "For erxes plugin servers: a typed core client with automatic plugin tokens, verification of members' plugin session tokens and of core's deliveries, and plugin jobs",
6
6
  "license": "AGPL-3.0-only",
7
7
  "repository": {
8
8
  "type": "git",
@@ -17,6 +17,7 @@
17
17
  "exports": {
18
18
  ".": "./dist/index.js",
19
19
  "./client": "./dist/client.js",
20
+ "./jobs": "./dist/jobs.js",
20
21
  "./verify": "./dist/verify.js",
21
22
  "./package.json": "./package.json"
22
23
  },
@@ -31,7 +32,13 @@
31
32
  "@orpc/openapi-client": "1.16.2",
32
33
  "jose": "^6.2.17",
33
34
  "zod": "^4.6.7",
34
- "@erxes/core-contract": "0.1.0-v2.6"
35
+ "@erxes/core-contract": "0.1.0-v2.8"
36
+ },
37
+ "devDependencies": {
38
+ "drizzle-orm": "0.45.4"
39
+ },
40
+ "peerDependencies": {
41
+ "drizzle-orm": "0.45.4"
35
42
  },
36
43
  "scripts": {
37
44
  "build": "tsdown"