powr-sdk-api 4.16.1 → 4.18.0

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.
@@ -0,0 +1,117 @@
1
+ "use strict";
2
+
3
+ const {
4
+ ObjectId
5
+ } = require("mongodb");
6
+ const MAX_USER_IDS = 100;
7
+ function reject(message, statusCode = 400) {
8
+ const error = new Error(message);
9
+ error.statusCode = statusCode;
10
+ throw error;
11
+ }
12
+ function isObjectIdString(id) {
13
+ return typeof id === "string" && id.length === 24 && ObjectId.isValid(id);
14
+ }
15
+ function normalizeId(id) {
16
+ if (id == null || id === "") return null;
17
+ if (typeof id === "string" && isObjectIdString(id)) return new ObjectId(id);
18
+ return id;
19
+ }
20
+ function parseNotify(notify) {
21
+ if (notify == null) return null;
22
+ if (typeof notify !== "object" || Array.isArray(notify)) {
23
+ reject("notify must be an object.");
24
+ }
25
+ if (!Array.isArray(notify.userIds)) {
26
+ reject("notify.userIds is required.");
27
+ }
28
+ const userIds = notify.userIds.map(id => String(id || "").trim()).filter(Boolean);
29
+ if (userIds.length === 0) reject("notify.userIds is required.");
30
+ if (userIds.length > MAX_USER_IDS) {
31
+ reject("notify.userIds must be 100 or fewer.");
32
+ }
33
+ const title = String(notify.title || "").trim();
34
+ if (!title) reject("notify.title is required.");
35
+ if (title.length > 140) reject("notify.title must be under 140 characters.");
36
+ const body = String(notify.body || "").trim();
37
+ if (!body) reject("notify.body is required.");
38
+ if (body.length > 2000) reject("notify.body must be under 2000 characters.");
39
+ const linkRaw = notify.link == null ? "" : String(notify.link).trim();
40
+ if (linkRaw.length > 500) reject("notify.link must be under 500 characters.");
41
+ const projectId = notify.projectId == null || notify.projectId === "" ? null : String(notify.projectId).trim();
42
+ return {
43
+ userIds,
44
+ title,
45
+ body,
46
+ link: linkRaw || null,
47
+ projectId
48
+ };
49
+ }
50
+ function parseEvent(options, {
51
+ allowNotify = false
52
+ } = {}) {
53
+ const source = options || {};
54
+ const projectId = String(source.projectId || "").trim();
55
+ const action = String(source.action || "").trim();
56
+ if (!projectId) reject("projectId is required.");
57
+ if (!action) reject("action is required.");
58
+ if (action.length > 80) reject("action must be under 80 characters.");
59
+ if (source.kind != null && source.kind !== "") {
60
+ reject("kind is not used. POST /activities/emit or POST /audit/emit.");
61
+ }
62
+ if (!allowNotify && source.notify != null) {
63
+ reject("audit does not notify.");
64
+ }
65
+ const metadata = source.metadata && typeof source.metadata === "object" && !Array.isArray(source.metadata) ? source.metadata : {};
66
+ return {
67
+ projectId,
68
+ action,
69
+ userId: normalizeId(source.userId),
70
+ targetType: source.targetType ? String(source.targetType).trim() : null,
71
+ targetId: normalizeId(source.targetId),
72
+ metadata,
73
+ notify: allowNotify ? parseNotify(source.notify) : null
74
+ };
75
+ }
76
+ function buildEventDoc(parsed, now = new Date()) {
77
+ return {
78
+ projectId: parsed.projectId,
79
+ action: parsed.action,
80
+ userId: parsed.userId,
81
+ targetType: parsed.targetType,
82
+ targetId: parsed.targetId,
83
+ metadata: parsed.metadata,
84
+ createdAt: now
85
+ };
86
+ }
87
+ function buildListQuery({
88
+ projectId,
89
+ contentId,
90
+ action,
91
+ source,
92
+ limit
93
+ } = {}) {
94
+ const query = {
95
+ projectId
96
+ };
97
+ if (contentId) query.contentId = contentId;
98
+ if (action) query.action = String(action);
99
+ if (source) query["metadata.source"] = String(source);
100
+ const lim = Math.min(Math.max(parseInt(limit, 10) || 100, 1), 500);
101
+ return {
102
+ query,
103
+ limit: lim
104
+ };
105
+ }
106
+ function defaultGetDb() {
107
+ return require("../services/mongo").getDb();
108
+ }
109
+ module.exports = {
110
+ reject,
111
+ normalizeId,
112
+ parseNotify,
113
+ parseEvent,
114
+ buildEventDoc,
115
+ buildListQuery,
116
+ defaultGetDb
117
+ };
@@ -0,0 +1,120 @@
1
+ "use strict";
2
+
3
+ const {
4
+ ObjectId
5
+ } = require("mongodb");
6
+ const {
7
+ parseEvent,
8
+ parseNotify,
9
+ buildEventDoc,
10
+ buildListQuery,
11
+ normalizeId
12
+ } = require("./eventLog");
13
+ const projectId = "69ca11dbdbc0b193a48e6ccd";
14
+ const actor = "6893ec11c19c093a5bf21720";
15
+ const other = "aaaaaaaaaaaaaaaaaaaaaaaa";
16
+ const uuid = "9ad595de-babf-44c4-baec-cb7b82675e47";
17
+ function validEvent(extra) {
18
+ return {
19
+ projectId,
20
+ action: "task_assigned",
21
+ userId: actor,
22
+ targetType: "task",
23
+ targetId: other,
24
+ metadata: {
25
+ source: "spriny-api"
26
+ },
27
+ ...extra
28
+ };
29
+ }
30
+ describe("parseEvent", () => {
31
+ it("requires projectId and action", () => {
32
+ expect(() => parseEvent({})).toThrow("projectId");
33
+ expect(() => parseEvent({
34
+ projectId
35
+ })).toThrow("action");
36
+ });
37
+ it("rejects kind — use the activity or audit door", () => {
38
+ expect(() => parseEvent(validEvent({
39
+ kind: "audit"
40
+ }))).toThrow("kind is not used");
41
+ });
42
+ it("keeps a UUID targetId as a string", () => {
43
+ const parsed = parseEvent(validEvent({
44
+ targetId: uuid
45
+ }));
46
+ expect(parsed.targetId).toBe(uuid);
47
+ expect(parsed.userId).toBeInstanceOf(ObjectId);
48
+ expect(String(parsed.userId)).toBe(actor);
49
+ });
50
+ it("rejects notify on audit", () => {
51
+ expect(() => parseEvent(validEvent({
52
+ notify: {
53
+ userIds: [other],
54
+ title: "Ping",
55
+ body: "Hi"
56
+ }
57
+ }), {
58
+ allowNotify: false
59
+ })).toThrow("audit does not notify");
60
+ });
61
+ });
62
+ describe("normalizeId", () => {
63
+ it("does not coerce a 12-character string", () => {
64
+ expect(normalizeId("hello-worlds")).toBe("hello-worlds");
65
+ });
66
+ });
67
+ describe("parseNotify", () => {
68
+ it("returns null when omitted", () => {
69
+ expect(parseNotify(undefined)).toBeNull();
70
+ });
71
+ it("requires userIds, title, and body", () => {
72
+ expect(() => parseNotify({})).toThrow("userIds");
73
+ expect(() => parseNotify({
74
+ userIds: [actor]
75
+ })).toThrow("title");
76
+ expect(() => parseNotify({
77
+ userIds: [actor],
78
+ title: "Ping"
79
+ })).toThrow("body");
80
+ });
81
+ });
82
+ describe("buildListQuery", () => {
83
+ it("filters action and source, and caps limit", () => {
84
+ const {
85
+ query,
86
+ limit
87
+ } = buildListQuery({
88
+ projectId,
89
+ action: "urbanstall_refund_payment",
90
+ source: "urbanstall-api",
91
+ limit: "999"
92
+ });
93
+ expect(query).toEqual({
94
+ projectId,
95
+ action: "urbanstall_refund_payment",
96
+ "metadata.source": "urbanstall-api"
97
+ });
98
+ expect(query.kind).toBeUndefined();
99
+ expect(limit).toBe(500);
100
+ });
101
+ });
102
+ describe("buildEventDoc", () => {
103
+ it("does not persist kind or notify on the row", () => {
104
+ const parsed = parseEvent(validEvent({
105
+ notify: {
106
+ userIds: [other],
107
+ title: "Assigned",
108
+ body: "A task is yours"
109
+ }
110
+ }), {
111
+ allowNotify: true
112
+ });
113
+ const now = new Date("2026-10-12T00:00:00.000Z");
114
+ const doc = buildEventDoc(parsed, now);
115
+ expect(doc.kind).toBeUndefined();
116
+ expect(doc.notify).toBeUndefined();
117
+ expect(doc.createdAt).toBe(now);
118
+ expect(doc.action).toBe("task_assigned");
119
+ });
120
+ });
@@ -0,0 +1,155 @@
1
+ "use strict";
2
+
3
+ const STATUSES = ["draft", "in_review", "published", "archived"];
4
+ const ROLES = ["writer", "editor"];
5
+ const TITLE_MAX = 140;
6
+ const DESC_MAX = 300;
7
+ const BODY_MAX = 80000;
8
+ const TAG_MAX = 8;
9
+ const TAG_LEN = 40;
10
+ const SLUG_MAX = 80;
11
+ function bad(message) {
12
+ const error = new Error(message);
13
+ error.statusCode = 400;
14
+ throw error;
15
+ }
16
+ function slugify(value) {
17
+ const base = String(value || "").normalize("NFKD").replace(/[\u0300-\u036f]/g, "").toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "").slice(0, SLUG_MAX).replace(/-+$/g, "");
18
+ return base || "post";
19
+ }
20
+ function parseTags(value) {
21
+ const list = Array.isArray(value) ? value : String(value || "").split(",");
22
+ const tags = [];
23
+ for (const raw of list) {
24
+ const tag = String(raw || "").trim().toLowerCase().replace(/\s+/g, "-").replace(/[^a-z0-9-]/g, "").replace(/^-+|-+$/g, "").slice(0, TAG_LEN);
25
+ if (!tag || tags.includes(tag)) continue;
26
+ tags.push(tag);
27
+ if (tags.length >= TAG_MAX) break;
28
+ }
29
+ return tags;
30
+ }
31
+ function readMinutes(markdown) {
32
+ const words = String(markdown || "").trim().split(/\s+/).filter(Boolean).length;
33
+ if (!words) return 1;
34
+ return Math.max(1, Math.round(words / 200));
35
+ }
36
+ function parsePostWrite(body, partial) {
37
+ const source = body || {};
38
+ const out = {};
39
+ const has = key => !partial || Object.prototype.hasOwnProperty.call(source, key);
40
+ if (has("title")) {
41
+ const title = String(source.title || "").trim();
42
+ if (!title) bad("Title is required.");
43
+ if (title.length > TITLE_MAX) bad("Title must be under 140 characters.");
44
+ out.title = title;
45
+ }
46
+ if (has("description")) {
47
+ const description = String(source.description || "").trim();
48
+ if (description.length > DESC_MAX) bad("Description must be under 300 characters.");
49
+ out.description = description;
50
+ }
51
+ if (has("bodyMd")) {
52
+ const bodyMd = String(source.bodyMd || "");
53
+ if (bodyMd.length > BODY_MAX) bad("Article is too long.");
54
+ out.bodyMd = bodyMd;
55
+ out.readMinutes = readMinutes(bodyMd);
56
+ }
57
+ if (has("tags")) out.tags = parseTags(source.tags);
58
+ if (has("coverUrl")) {
59
+ const coverUrl = String(source.coverUrl || "").trim();
60
+ if (coverUrl && !/^https:\/\//i.test(coverUrl)) bad("Cover must be an https link.");
61
+ out.coverUrl = coverUrl;
62
+ }
63
+ if (Object.prototype.hasOwnProperty.call(source, "slug")) {
64
+ out.slug = slugify(source.slug);
65
+ }
66
+ return out;
67
+ }
68
+ function parseAuthorWrite(body) {
69
+ const source = body || {};
70
+ const displayName = String(source.displayName || "").trim();
71
+ if (!displayName) bad("Name is required.");
72
+ if (displayName.length > 80) bad("Name must be under 80 characters.");
73
+ const handle = slugify(source.handle || displayName).slice(0, 40);
74
+ if (handle.length < 2) bad("Handle is too short.");
75
+ const role = String(source.role || "writer").trim().toLowerCase();
76
+ if (!ROLES.includes(role)) bad("Role must be writer or editor.");
77
+ const bio = String(source.bio || "").trim();
78
+ if (bio.length > 300) bad("Bio must be under 300 characters.");
79
+ const avatarUrl = String(source.avatarUrl || "").trim();
80
+ if (avatarUrl && !/^https:\/\//i.test(avatarUrl)) bad("Photo must be an https link.");
81
+ const powrId = String(source.powrId || "").trim();
82
+ const phone = String(source.phone || "").trim();
83
+ if (!powrId && !phone) bad("A Powr user or a phone is required.");
84
+ return {
85
+ displayName,
86
+ handle,
87
+ role,
88
+ bio,
89
+ avatarUrl,
90
+ powrId,
91
+ phone
92
+ };
93
+ }
94
+ function publicAuthor(author) {
95
+ if (!author) return null;
96
+ return {
97
+ handle: author.handle || "",
98
+ displayName: author.displayName || "",
99
+ avatarUrl: author.avatarUrl || "",
100
+ bio: author.bio || ""
101
+ };
102
+ }
103
+ function publicCard(row, author) {
104
+ return {
105
+ _id: String(row._id),
106
+ slug: row.slug || "",
107
+ title: row.title || "",
108
+ description: row.description || "",
109
+ coverUrl: row.coverUrl || "",
110
+ tags: row.tags || [],
111
+ publishedAt: row.publishedAt || null,
112
+ readMinutes: row.readMinutes || 1,
113
+ author: publicAuthor(author)
114
+ };
115
+ }
116
+ function publicPost(row, author) {
117
+ return Object.assign({}, publicCard(row, author), {
118
+ bodyMd: row.bodyMd || ""
119
+ });
120
+ }
121
+ function staffPost(row, author) {
122
+ return Object.assign({}, publicPost(row, author), {
123
+ status: row.status || "draft",
124
+ authorId: row.authorId ? String(row.authorId) : "",
125
+ slugLocked: !!row.slugLocked,
126
+ createdAt: row.createdAt || null,
127
+ updatedAt: row.updatedAt || null
128
+ });
129
+ }
130
+ function authorView(row) {
131
+ return {
132
+ _id: String(row._id),
133
+ powrId: row.powrId ? String(row.powrId) : "",
134
+ handle: row.handle || "",
135
+ displayName: row.displayName || "",
136
+ bio: row.bio || "",
137
+ avatarUrl: row.avatarUrl || "",
138
+ role: row.role || "writer",
139
+ createdAt: row.createdAt || null
140
+ };
141
+ }
142
+ module.exports = {
143
+ STATUSES,
144
+ ROLES,
145
+ slugify,
146
+ parseTags,
147
+ readMinutes,
148
+ parsePostWrite,
149
+ parseAuthorWrite,
150
+ publicAuthor,
151
+ publicCard,
152
+ publicPost,
153
+ staffPost,
154
+ authorView
155
+ };
@@ -0,0 +1,78 @@
1
+ "use strict";
2
+
3
+ const {
4
+ slugify,
5
+ parsePostWrite,
6
+ parseAuthorWrite,
7
+ publicCard,
8
+ readMinutes
9
+ } = require("./posts");
10
+ describe("slugify", () => {
11
+ it("makes a url piece from a title", () => {
12
+ expect(slugify(" Cursor for a new student! ")).toBe("cursor-for-a-new-student");
13
+ });
14
+ it("falls back when the title has no letters", () => {
15
+ expect(slugify("???")).toBe("post");
16
+ });
17
+ });
18
+ describe("parsePostWrite", () => {
19
+ it("keeps a draft's fields", () => {
20
+ const fields = parsePostWrite({
21
+ title: " Hello ",
22
+ description: "A short line",
23
+ bodyMd: "One two three",
24
+ tags: "Vibe, vibe, AI",
25
+ coverUrl: "https://cdn.example/a.png"
26
+ });
27
+ expect(fields.title).toBe("Hello");
28
+ expect(fields.tags).toEqual(["vibe", "ai"]);
29
+ expect(fields.readMinutes).toBe(1);
30
+ });
31
+ it("rejects a cover that is not https", () => {
32
+ expect(() => parsePostWrite({
33
+ title: "Hi",
34
+ coverUrl: "http://x"
35
+ })).toThrow("Cover must be an https link.");
36
+ });
37
+ it("on a partial update only touches the keys that were sent", () => {
38
+ expect(parsePostWrite({
39
+ description: "Only this"
40
+ }, true)).toEqual({
41
+ description: "Only this"
42
+ });
43
+ });
44
+ });
45
+ describe("readMinutes", () => {
46
+ it("rounds about 200 words to a minute", () => {
47
+ const words = new Array(400).fill("word").join(" ");
48
+ expect(readMinutes(words)).toBe(2);
49
+ });
50
+ });
51
+ describe("parseAuthorWrite", () => {
52
+ it("builds a writer from a phone", () => {
53
+ const author = parseAuthorWrite({
54
+ displayName: "Om",
55
+ phone: "9999999999"
56
+ });
57
+ expect(author.handle).toBe("om");
58
+ expect(author.role).toBe("writer");
59
+ expect(author.phone).toBe("9999999999");
60
+ });
61
+ });
62
+ describe("publicCard", () => {
63
+ it("does not include the article body", () => {
64
+ const card = publicCard({
65
+ _id: "a",
66
+ slug: "hi",
67
+ title: "Hi",
68
+ bodyMd: "secret",
69
+ status: "published"
70
+ }, {
71
+ handle: "om",
72
+ displayName: "Om"
73
+ });
74
+ expect(card.bodyMd).toBeUndefined();
75
+ expect(card.status).toBeUndefined();
76
+ expect(card.author.displayName).toBe("Om");
77
+ });
78
+ });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "powr-sdk-api",
3
- "version": "4.16.1",
3
+ "version": "4.18.0",
4
4
  "description": "Shared API core library for PowrStack projects. Zero dependencies - works with Express, Next.js API routes, and other frameworks. All features are optional and install only what you need.",
5
5
  "main": "dist/index.js",
6
6
  "types": "dist/index.d.ts",