@molecule/api-resource-medication 1.0.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.
package/LICENSE ADDED
@@ -0,0 +1,115 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work.
38
+
39
+ "Derivative Works" shall mean any work, whether in Source or Object
40
+ form, that is based on (or derived from) the Work and for which the
41
+ editorial revisions, annotations, elaborations, or other modifications
42
+ represent, as a whole, an original work of authorship.
43
+
44
+ "Contribution" shall mean any work of authorship, including the
45
+ original version of the Work and any modifications or additions
46
+ to that Work, that is intentionally submitted to the Licensor for
47
+ inclusion in the Work by the copyright owner or by an individual or
48
+ Legal Entity authorized to submit on behalf of the copyright owner.
49
+
50
+ "Contributor" shall mean Licensor and any individual or Legal Entity
51
+ on behalf of whom a Contribution has been received by the Licensor and
52
+ subsequently incorporated within the Work.
53
+
54
+ 2. Grant of Copyright License. Subject to the terms and conditions of
55
+ this License, each Contributor hereby grants to You a perpetual,
56
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
57
+ copyright license to reproduce, prepare Derivative Works of,
58
+ publicly display, publicly perform, sublicense, and distribute the
59
+ Work and such Derivative Works in Source or Object form.
60
+
61
+ 3. Grant of Patent License. Subject to the terms and conditions of
62
+ this License, each Contributor hereby grants to You a perpetual,
63
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
64
+ patent license to make, have made, use, offer to sell, sell, import,
65
+ and otherwise transfer the Work.
66
+
67
+ 4. Redistribution. You may reproduce and distribute copies of the
68
+ Work or Derivative Works thereof in any medium, with or without
69
+ modifications, and in Source or Object form, provided that You
70
+ meet the following conditions:
71
+
72
+ (a) You must give any other recipients of the Work or
73
+ Derivative Works a copy of this License; and
74
+
75
+ (b) You must cause any modified files to carry prominent notices
76
+ stating that You changed the files; and
77
+
78
+ (c) You must retain, in the Source form of any Derivative Works
79
+ that You distribute, all copyright, patent, trademark, and
80
+ attribution notices from the Source form of the Work,
81
+ excluding those notices that do not pertain to any part of
82
+ the Derivative Works; and
83
+
84
+ (d) If the Work includes a "NOTICE" text file as part of its
85
+ distribution, then any Derivative Works that You distribute must
86
+ include a readable copy of the attribution notices contained
87
+ within such NOTICE file.
88
+
89
+ 5. Submission of Contributions.
90
+
91
+ 6. Trademarks. This License does not grant permission to use the trade
92
+ names, trademarks, service marks, or product names of the Licensor.
93
+
94
+ 7. Disclaimer of Warranty. Unless required by applicable law or
95
+ agreed to in writing, Licensor provides the Work on an "AS IS" BASIS,
96
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND.
97
+
98
+ 8. Limitation of Liability. In no event and under no legal theory shall
99
+ any Contributor be liable to You for damages.
100
+
101
+ 9. Accepting Warranty or Additional Liability.
102
+
103
+ Copyright 2026 Molecule Dev, Inc.
104
+
105
+ Licensed under the Apache License, Version 2.0 (the "License");
106
+ you may not use this file except in compliance with the License.
107
+ You may obtain a copy of the License at
108
+
109
+ http://www.apache.org/licenses/LICENSE-2.0
110
+
111
+ Unless required by applicable law or agreed to in writing, software
112
+ distributed under the License is distributed on an "AS IS" BASIS,
113
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
114
+ See the License for the specific language governing permissions and
115
+ limitations under the License.
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=browser-guard.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"browser-guard.d.ts","sourceRoot":"","sources":["../src/browser-guard.ts"],"names":[],"mappings":"AAuBA,OAAO,EAAE,CAAA"}
@@ -0,0 +1,18 @@
1
+ /**
2
+ * Browser guard — `@molecule/api-resource-medication` is SERVER-ONLY.
3
+ *
4
+ * Generated by scripts/gen-browser-guards.mjs (workspace root) — edit THAT, not this.
5
+ * Evaluating a server package in a browser bundle is always an import-graph mistake
6
+ * (node APIs, secrets); without this guard it surfaces as a cryptic downstream crash
7
+ * ("Buffer is not defined") far from the culprit. Throwing here names the package and
8
+ * the fix at the exact moment the client bundle evaluates it. jsdom tests and SSR are
9
+ * unaffected: the throw requires browser globals AND the absence of a node runtime.
10
+ */
11
+ const g = globalThis;
12
+ if (g.window !== undefined && g.document !== undefined && !g.process?.versions?.node) {
13
+ throw new Error('@molecule/api-resource-medication is SERVER-ONLY: it was bundled into browser/client code. Import it only ' +
14
+ 'from server code (a server route/function or your API), or dynamic-import it inside ' +
15
+ 'the server handler — never from components or shared client modules, and never ' +
16
+ 'polyfill Buffer/process to silence this.');
17
+ }
18
+ export {};
@@ -0,0 +1,86 @@
1
+ /**
2
+ * `@molecule/api-resource-medication` — medication tracking with
3
+ * dosing schedule + adherence log + adherence-rate calc.
4
+ *
5
+ * Owner-scoped: every medication and dose log belongs to the authenticated
6
+ * user. Medications carry dosage, `frequency` (e.g. `daily`, `twice_daily`),
7
+ * `times_of_day`, and active date range; dose logs record
8
+ * taken/skipped/late/missed and `adherenceRate` aggregates them over a date
9
+ * range.
10
+ *
11
+ * @example
12
+ * ```ts
13
+ * import { createMedicationRouter } from '@molecule/api-resource-medication'
14
+ * app.use('/medications', createMedicationRouter())
15
+ * // GET / · POST / · GET /adherence?from=…&to=… · GET|PUT|DELETE /:id
16
+ * // GET /:id/logs · POST /:id/logs
17
+ * ```
18
+ *
19
+ * @example
20
+ * ```ts
21
+ * import {
22
+ * adherenceRate,
23
+ * createMedicationForOwner,
24
+ * logDose,
25
+ * } from '@molecule/api-resource-medication'
26
+ *
27
+ * const med = await createMedicationForOwner(userId, {
28
+ * name: 'Metformin',
29
+ * dosage: '500 mg',
30
+ * frequency: 'twice_daily',
31
+ * })
32
+ * await logDose(med.id, userId, { status: 'taken' })
33
+ * const { rate } = await adherenceRate(userId, '2026-01-01', '2026-01-31')
34
+ * ```
35
+ *
36
+ * @remarks
37
+ * Tables: `src/__setup__/medications.sql` creates `medications` +
38
+ * `medication_logs`. An mlcl-scaffolded API replays `__setup__/*.sql`
39
+ * automatically on migrate; anywhere else run it once — nothing at runtime
40
+ * creates them.
41
+ *
42
+ * The router does not authenticate — it reads the caller from
43
+ * `res.locals.session` (populated by your global auth middleware) and 401s
44
+ * without a session. All service functions are `…ForOwner(…, ownerId)` and
45
+ * return `null` for rows the caller doesn't own — always pass the
46
+ * AUTHENTICATED user's id, never a client-sent one.
47
+ *
48
+ * @e2e
49
+ * Integration checklist — drive the real UI (live preview, no mocks), adapt
50
+ * each item to this app's actual screens/flows, and check every box off one by
51
+ * one. This is HEALTH data: a box you can't check is a correctness or privacy
52
+ * bug to fix, never a skip:
53
+ * - [ ] Adding a medication persists its real fields — `name`, `dosage`,
54
+ * `frequency`, `times_of_day` — and the med then appears in the user's list
55
+ * (`GET /`) carrying those exact values, not a truncated or defaulted copy.
56
+ * - [ ] The schedule matches the frequency: a `twice_daily` med carries two
57
+ * `times_of_day` entries and the UI shows two dose slots for the day — not one
58
+ * and not three; a `daily` med shows exactly one. (Nothing derives the times
59
+ * from `frequency` automatically, so a mismatch is a real bug to catch here.)
60
+ * - [ ] Logging a dose records it against the right medication and time:
61
+ * `POST /:id/logs` with `status: 'taken'` (and its `taken_at`) then shows in
62
+ * `GET /:id/logs`, and the adherence figure (`GET /adherence`) moves.
63
+ * - [ ] A skipped or missed dose is reflected HONESTLY — logged with
64
+ * `status: 'missed'`/`'skipped'` it counts toward `total` but NOT `taken`, so
65
+ * it lowers the adherence rate; it is never silently counted as taken (the
66
+ * default status is `taken`, so a miss must be logged as a miss, not omitted).
67
+ * - [ ] CORRECTNESS — adherence is a true ratio of logged doses: a brand-new
68
+ * med with zero logged doses reads 0% (`rate` 0, `total` 0), never 100%; a
69
+ * partial day (some doses logged, some not yet) is never shown as complete.
70
+ * - [ ] If the app tracks refills/supply on top of this resource (the core does
71
+ * not model one), recording a fill decrements the refills-remaining count and
72
+ * a low-supply threshold raises a visible refill flag — verify both live.
73
+ * - [ ] PRIVACY/AUTHORIZATION — medication data is strictly per-user: signed in
74
+ * as user B, guessing user A's medication id on `GET /:id`, `PUT /:id`,
75
+ * `DELETE /:id`, or `/:id/logs` returns 404 (owner-scoped), never A's row; an
76
+ * unauthenticated request 401s. Confirm PHI (name, dosage, notes) is never
77
+ * written to server logs in the clear.
78
+ *
79
+ * @module
80
+ */
81
+ export * from './browser-guard.js';
82
+ export * from './routes.js';
83
+ export * from './service.js';
84
+ export * from './types.js';
85
+ export * from './validation.js';
86
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA+EG;AAEH,cAAc,oBAAoB,CAAA;AAClC,cAAc,aAAa,CAAA;AAC3B,cAAc,cAAc,CAAA;AAC5B,cAAc,YAAY,CAAA;AAC1B,cAAc,iBAAiB,CAAA"}
package/dist/index.js ADDED
@@ -0,0 +1,85 @@
1
+ /**
2
+ * `@molecule/api-resource-medication` — medication tracking with
3
+ * dosing schedule + adherence log + adherence-rate calc.
4
+ *
5
+ * Owner-scoped: every medication and dose log belongs to the authenticated
6
+ * user. Medications carry dosage, `frequency` (e.g. `daily`, `twice_daily`),
7
+ * `times_of_day`, and active date range; dose logs record
8
+ * taken/skipped/late/missed and `adherenceRate` aggregates them over a date
9
+ * range.
10
+ *
11
+ * @example
12
+ * ```ts
13
+ * import { createMedicationRouter } from '@molecule/api-resource-medication'
14
+ * app.use('/medications', createMedicationRouter())
15
+ * // GET / · POST / · GET /adherence?from=…&to=… · GET|PUT|DELETE /:id
16
+ * // GET /:id/logs · POST /:id/logs
17
+ * ```
18
+ *
19
+ * @example
20
+ * ```ts
21
+ * import {
22
+ * adherenceRate,
23
+ * createMedicationForOwner,
24
+ * logDose,
25
+ * } from '@molecule/api-resource-medication'
26
+ *
27
+ * const med = await createMedicationForOwner(userId, {
28
+ * name: 'Metformin',
29
+ * dosage: '500 mg',
30
+ * frequency: 'twice_daily',
31
+ * })
32
+ * await logDose(med.id, userId, { status: 'taken' })
33
+ * const { rate } = await adherenceRate(userId, '2026-01-01', '2026-01-31')
34
+ * ```
35
+ *
36
+ * @remarks
37
+ * Tables: `src/__setup__/medications.sql` creates `medications` +
38
+ * `medication_logs`. An mlcl-scaffolded API replays `__setup__/*.sql`
39
+ * automatically on migrate; anywhere else run it once — nothing at runtime
40
+ * creates them.
41
+ *
42
+ * The router does not authenticate — it reads the caller from
43
+ * `res.locals.session` (populated by your global auth middleware) and 401s
44
+ * without a session. All service functions are `…ForOwner(…, ownerId)` and
45
+ * return `null` for rows the caller doesn't own — always pass the
46
+ * AUTHENTICATED user's id, never a client-sent one.
47
+ *
48
+ * @e2e
49
+ * Integration checklist — drive the real UI (live preview, no mocks), adapt
50
+ * each item to this app's actual screens/flows, and check every box off one by
51
+ * one. This is HEALTH data: a box you can't check is a correctness or privacy
52
+ * bug to fix, never a skip:
53
+ * - [ ] Adding a medication persists its real fields — `name`, `dosage`,
54
+ * `frequency`, `times_of_day` — and the med then appears in the user's list
55
+ * (`GET /`) carrying those exact values, not a truncated or defaulted copy.
56
+ * - [ ] The schedule matches the frequency: a `twice_daily` med carries two
57
+ * `times_of_day` entries and the UI shows two dose slots for the day — not one
58
+ * and not three; a `daily` med shows exactly one. (Nothing derives the times
59
+ * from `frequency` automatically, so a mismatch is a real bug to catch here.)
60
+ * - [ ] Logging a dose records it against the right medication and time:
61
+ * `POST /:id/logs` with `status: 'taken'` (and its `taken_at`) then shows in
62
+ * `GET /:id/logs`, and the adherence figure (`GET /adherence`) moves.
63
+ * - [ ] A skipped or missed dose is reflected HONESTLY — logged with
64
+ * `status: 'missed'`/`'skipped'` it counts toward `total` but NOT `taken`, so
65
+ * it lowers the adherence rate; it is never silently counted as taken (the
66
+ * default status is `taken`, so a miss must be logged as a miss, not omitted).
67
+ * - [ ] CORRECTNESS — adherence is a true ratio of logged doses: a brand-new
68
+ * med with zero logged doses reads 0% (`rate` 0, `total` 0), never 100%; a
69
+ * partial day (some doses logged, some not yet) is never shown as complete.
70
+ * - [ ] If the app tracks refills/supply on top of this resource (the core does
71
+ * not model one), recording a fill decrements the refills-remaining count and
72
+ * a low-supply threshold raises a visible refill flag — verify both live.
73
+ * - [ ] PRIVACY/AUTHORIZATION — medication data is strictly per-user: signed in
74
+ * as user B, guessing user A's medication id on `GET /:id`, `PUT /:id`,
75
+ * `DELETE /:id`, or `/:id/logs` returns 404 (owner-scoped), never A's row; an
76
+ * unauthenticated request 401s. Confirm PHI (name, dosage, notes) is never
77
+ * written to server logs in the clear.
78
+ *
79
+ * @module
80
+ */
81
+ export * from './browser-guard.js';
82
+ export * from './routes.js';
83
+ export * from './service.js';
84
+ export * from './types.js';
85
+ export * from './validation.js';
@@ -0,0 +1,4 @@
1
+ import { Router } from 'express';
2
+ /** Creates and returns the Express router for medication CRUD and dose-logging endpoints. */
3
+ export declare function createMedicationRouter(): Router;
4
+ //# sourceMappingURL=routes.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"routes.d.ts","sourceRoot":"","sources":["../src/routes.ts"],"names":[],"mappings":"AAAA,OAAO,EAAoD,MAAM,EAAE,MAAM,SAAS,CAAA;AAqBlF,6FAA6F;AAC7F,wBAAgB,sBAAsB,IAAI,MAAM,CAwG/C"}
package/dist/routes.js ADDED
@@ -0,0 +1,102 @@
1
+ import { Router } from 'express';
2
+ import { getParamId, requireUser } from '@molecule/api-bonds-default-express';
3
+ import { t } from '@molecule/api-i18n';
4
+ import { validateBody as validateBodyRaw } from '@molecule/api-middleware-validation';
5
+ import { adherenceRate, createMedicationForOwner, deleteMedicationForOwner, getMedicationForOwner, listLogs, listMedicationsForOwner, logDose, updateMedicationForOwner, } from './service.js';
6
+ import { logCreateSchema, medicationCreateSchema, medicationUpdateSchema } from './validation.js';
7
+ const validateBody = validateBodyRaw;
8
+ /** Creates and returns the Express router for medication CRUD and dose-logging endpoints. */
9
+ export function createMedicationRouter() {
10
+ const router = Router();
11
+ router.get('/', async (_req, res) => {
12
+ const userId = requireUser(res);
13
+ if (!userId)
14
+ return;
15
+ res.json(await listMedicationsForOwner(userId, { include_inactive: true }));
16
+ });
17
+ router.post('/', validateBody(medicationCreateSchema), async (req, res) => {
18
+ const userId = requireUser(res);
19
+ if (!userId)
20
+ return;
21
+ res
22
+ .status(201)
23
+ .json(await createMedicationForOwner(userId, req.body));
24
+ });
25
+ router.get('/adherence', async (req, res) => {
26
+ const userId = requireUser(res);
27
+ if (!userId)
28
+ return;
29
+ const from = req.query.from ?? new Date(Date.now() - 30 * 24 * 60 * 60 * 1000).toISOString();
30
+ const to = req.query.to ?? new Date().toISOString();
31
+ res.json(await adherenceRate(userId, from, to));
32
+ });
33
+ router.get('/:id', async (req, res) => {
34
+ const userId = requireUser(res);
35
+ if (!userId)
36
+ return;
37
+ const m = await getMedicationForOwner(getParamId(req), userId);
38
+ if (!m) {
39
+ res.status(404).json({
40
+ error: t('medication.notFound', undefined, { defaultValue: 'Medication not found' }),
41
+ });
42
+ return;
43
+ }
44
+ res.json(m);
45
+ });
46
+ router.put('/:id', validateBody(medicationUpdateSchema), async (req, res) => {
47
+ const userId = requireUser(res);
48
+ if (!userId)
49
+ return;
50
+ const m = await updateMedicationForOwner(getParamId(req), userId, req.body);
51
+ if (!m) {
52
+ res.status(404).json({
53
+ error: t('medication.notFound', undefined, { defaultValue: 'Medication not found' }),
54
+ });
55
+ return;
56
+ }
57
+ res.json(m);
58
+ });
59
+ router.delete('/:id', async (req, res) => {
60
+ const userId = requireUser(res);
61
+ if (!userId)
62
+ return;
63
+ const ok = await deleteMedicationForOwner(getParamId(req), userId);
64
+ if (!ok) {
65
+ res.status(404).json({
66
+ error: t('medication.notFound', undefined, { defaultValue: 'Medication not found' }),
67
+ });
68
+ return;
69
+ }
70
+ res.status(204).end();
71
+ });
72
+ router.get('/:id/logs', async (req, res) => {
73
+ const userId = requireUser(res);
74
+ if (!userId)
75
+ return;
76
+ const logs = await listLogs(getParamId(req), userId, {
77
+ from: typeof req.query.from === 'string' ? req.query.from : undefined,
78
+ to: typeof req.query.to === 'string' ? req.query.to : undefined,
79
+ });
80
+ if (logs === null) {
81
+ res.status(404).json({
82
+ error: t('medication.notFound', undefined, { defaultValue: 'Medication not found' }),
83
+ });
84
+ return;
85
+ }
86
+ res.json(logs);
87
+ });
88
+ router.post('/:id/logs', validateBody(logCreateSchema), async (req, res) => {
89
+ const userId = requireUser(res);
90
+ if (!userId)
91
+ return;
92
+ const log = await logDose(getParamId(req), userId, req.body);
93
+ if (!log) {
94
+ res.status(404).json({
95
+ error: t('medication.notFound', undefined, { defaultValue: 'Medication not found' }),
96
+ });
97
+ return;
98
+ }
99
+ res.status(201).json(log);
100
+ });
101
+ return router;
102
+ }
@@ -0,0 +1,47 @@
1
+ /**
2
+ * Medication-tracking service.
3
+ *
4
+ * @module
5
+ */
6
+ import type { MedicationFrequency, MedicationLogRow, MedicationRow } from './types.js';
7
+ /** Returns all medications belonging to the given owner, optionally including inactive ones. */
8
+ export declare function listMedicationsForOwner(ownerId: string, opts?: {
9
+ include_inactive?: boolean;
10
+ }): Promise<MedicationRow[]>;
11
+ /** Fetches a single medication by ID, returning null if not found or not owned by the given owner. */
12
+ export declare function getMedicationForOwner(medicationId: string, ownerId: string): Promise<MedicationRow | null>;
13
+ /** Creates a new medication record owned by the given owner and returns the persisted row. */
14
+ export declare function createMedicationForOwner(ownerId: string, data: {
15
+ name: string;
16
+ generic_name?: string | null;
17
+ dosage: string;
18
+ unit?: string | null;
19
+ frequency?: MedicationFrequency;
20
+ times_of_day?: string[];
21
+ start_date?: string | null;
22
+ end_date?: string | null;
23
+ notes?: string | null;
24
+ }): Promise<MedicationRow>;
25
+ /** Applies a partial patch to a medication, returning the updated row or null if not found or not owned. */
26
+ export declare function updateMedicationForOwner(medicationId: string, ownerId: string, patch: Partial<MedicationRow>): Promise<MedicationRow | null>;
27
+ /** Deletes a medication by ID, returning true on success or false if not found or not owned. */
28
+ export declare function deleteMedicationForOwner(medicationId: string, ownerId: string): Promise<boolean>;
29
+ /** Log a dose. If `status` not provided, infers from `taken_at` vs scheduled times. */
30
+ export declare function logDose(medicationId: string, ownerId: string, data: {
31
+ taken_at?: string;
32
+ status?: 'taken' | 'skipped' | 'late' | 'missed';
33
+ notes?: string | null;
34
+ }): Promise<MedicationLogRow | null>;
35
+ /** Returns dose logs for a medication within an optional time window, or null if the medication is not found or not owned. */
36
+ export declare function listLogs(medicationId: string, ownerId: string, opts?: {
37
+ from?: string;
38
+ to?: string;
39
+ limit?: number;
40
+ }): Promise<MedicationLogRow[] | null>;
41
+ /** Adherence summary: percentage of `taken` logs out of all logs in window. */
42
+ export declare function adherenceRate(ownerId: string, from: string, to: string): Promise<{
43
+ taken: number;
44
+ total: number;
45
+ rate: number;
46
+ }>;
47
+ //# sourceMappingURL=service.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"service.d.ts","sourceRoot":"","sources":["../src/service.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAaH,OAAO,KAAK,EAAE,mBAAmB,EAAE,gBAAgB,EAAE,aAAa,EAAE,MAAM,YAAY,CAAA;AAKtF,gGAAgG;AAChG,wBAAsB,uBAAuB,CAC3C,OAAO,EAAE,MAAM,EACf,IAAI,GAAE;IAAE,gBAAgB,CAAC,EAAE,OAAO,CAAA;CAAO,GACxC,OAAO,CAAC,aAAa,EAAE,CAAC,CAK1B;AAED,sGAAsG;AACtG,wBAAsB,qBAAqB,CACzC,YAAY,EAAE,MAAM,EACpB,OAAO,EAAE,MAAM,GACd,OAAO,CAAC,aAAa,GAAG,IAAI,CAAC,CAI/B;AAED,8FAA8F;AAC9F,wBAAsB,wBAAwB,CAC5C,OAAO,EAAE,MAAM,EACf,IAAI,EAAE;IACJ,IAAI,EAAE,MAAM,CAAA;IACZ,YAAY,CAAC,EAAE,MAAM,GAAG,IAAI,CAAA;IAC5B,MAAM,EAAE,MAAM,CAAA;IACd,IAAI,CAAC,EAAE,MAAM,GAAG,IAAI,CAAA;IACpB,SAAS,CAAC,EAAE,mBAAmB,CAAA;IAC/B,YAAY,CAAC,EAAE,MAAM,EAAE,CAAA;IACvB,UAAU,CAAC,EAAE,MAAM,GAAG,IAAI,CAAA;IAC1B,QAAQ,CAAC,EAAE,MAAM,GAAG,IAAI,CAAA;IACxB,KAAK,CAAC,EAAE,MAAM,GAAG,IAAI,CAAA;CACtB,GACA,OAAO,CAAC,aAAa,CAAC,CAexB;AAED,4GAA4G;AAC5G,wBAAsB,wBAAwB,CAC5C,YAAY,EAAE,MAAM,EACpB,OAAO,EAAE,MAAM,EACf,KAAK,EAAE,OAAO,CAAC,aAAa,CAAC,GAC5B,OAAO,CAAC,aAAa,GAAG,IAAI,CAAC,CAK/B;AAED,gGAAgG;AAChG,wBAAsB,wBAAwB,CAC5C,YAAY,EAAE,MAAM,EACpB,OAAO,EAAE,MAAM,GACd,OAAO,CAAC,OAAO,CAAC,CAKlB;AAED,uFAAuF;AACvF,wBAAsB,OAAO,CAC3B,YAAY,EAAE,MAAM,EACpB,OAAO,EAAE,MAAM,EACf,IAAI,EAAE;IACJ,QAAQ,CAAC,EAAE,MAAM,CAAA;IACjB,MAAM,CAAC,EAAE,OAAO,GAAG,SAAS,GAAG,MAAM,GAAG,QAAQ,CAAA;IAChD,KAAK,CAAC,EAAE,MAAM,GAAG,IAAI,CAAA;CACtB,GACA,OAAO,CAAC,gBAAgB,GAAG,IAAI,CAAC,CAWlC;AAED,8HAA8H;AAC9H,wBAAsB,QAAQ,CAC5B,YAAY,EAAE,MAAM,EACpB,OAAO,EAAE,MAAM,EACf,IAAI,GAAE;IAAE,IAAI,CAAC,EAAE,MAAM,CAAC;IAAC,EAAE,CAAC,EAAE,MAAM,CAAC;IAAC,KAAK,CAAC,EAAE,MAAM,CAAA;CAAO,GACxD,OAAO,CAAC,gBAAgB,EAAE,GAAG,IAAI,CAAC,CAcpC;AAED,+EAA+E;AAC/E,wBAAsB,aAAa,CACjC,OAAO,EAAE,MAAM,EACf,IAAI,EAAE,MAAM,EACZ,EAAE,EAAE,MAAM,GACT,OAAO,CAAC;IAAE,KAAK,EAAE,MAAM,CAAC;IAAC,KAAK,EAAE,MAAM,CAAC;IAAC,IAAI,EAAE,MAAM,CAAA;CAAE,CAAC,CAYzD"}
@@ -0,0 +1,103 @@
1
+ /**
2
+ * Medication-tracking service.
3
+ *
4
+ * @module
5
+ */
6
+ import { count, create, deleteById, findById, findMany, updateById, } from '@molecule/api-database';
7
+ const MEDS_TABLE = 'medications';
8
+ const LOGS_TABLE = 'medication_logs';
9
+ /** Returns all medications belonging to the given owner, optionally including inactive ones. */
10
+ export async function listMedicationsForOwner(ownerId, opts = {}) {
11
+ const where = [{ field: 'owner_id', operator: '=', value: ownerId }];
12
+ if (!opts.include_inactive)
13
+ where.push({ field: 'is_active', operator: '=', value: true });
14
+ const orderBy = [{ field: 'name', direction: 'asc' }];
15
+ return findMany(MEDS_TABLE, { where, orderBy });
16
+ }
17
+ /** Fetches a single medication by ID, returning null if not found or not owned by the given owner. */
18
+ export async function getMedicationForOwner(medicationId, ownerId) {
19
+ const row = await findById(MEDS_TABLE, medicationId);
20
+ if (!row || row.owner_id !== ownerId)
21
+ return null;
22
+ return row;
23
+ }
24
+ /** Creates a new medication record owned by the given owner and returns the persisted row. */
25
+ export async function createMedicationForOwner(ownerId, data) {
26
+ const result = await create(MEDS_TABLE, {
27
+ owner_id: ownerId,
28
+ name: data.name,
29
+ generic_name: data.generic_name ?? null,
30
+ dosage: data.dosage,
31
+ unit: data.unit ?? null,
32
+ frequency: data.frequency ?? 'daily',
33
+ times_of_day: data.times_of_day ?? [],
34
+ start_date: data.start_date ?? null,
35
+ end_date: data.end_date ?? null,
36
+ notes: data.notes ?? null,
37
+ is_active: true,
38
+ });
39
+ return result.data;
40
+ }
41
+ /** Applies a partial patch to a medication, returning the updated row or null if not found or not owned. */
42
+ export async function updateMedicationForOwner(medicationId, ownerId, patch) {
43
+ const existing = await findById(MEDS_TABLE, medicationId);
44
+ if (!existing || existing.owner_id !== ownerId)
45
+ return null;
46
+ await updateById(MEDS_TABLE, medicationId, patch);
47
+ return findById(MEDS_TABLE, medicationId);
48
+ }
49
+ /** Deletes a medication by ID, returning true on success or false if not found or not owned. */
50
+ export async function deleteMedicationForOwner(medicationId, ownerId) {
51
+ const row = await findById(MEDS_TABLE, medicationId);
52
+ if (!row || row.owner_id !== ownerId)
53
+ return false;
54
+ await deleteById(MEDS_TABLE, medicationId);
55
+ return true;
56
+ }
57
+ /** Log a dose. If `status` not provided, infers from `taken_at` vs scheduled times. */
58
+ export async function logDose(medicationId, ownerId, data) {
59
+ const med = await getMedicationForOwner(medicationId, ownerId);
60
+ if (!med)
61
+ return null;
62
+ const result = await create(LOGS_TABLE, {
63
+ medication_id: medicationId,
64
+ owner_id: ownerId,
65
+ taken_at: data.taken_at ?? new Date().toISOString(),
66
+ status: data.status ?? 'taken',
67
+ notes: data.notes ?? null,
68
+ });
69
+ return result.data;
70
+ }
71
+ /** Returns dose logs for a medication within an optional time window, or null if the medication is not found or not owned. */
72
+ export async function listLogs(medicationId, ownerId, opts = {}) {
73
+ const med = await getMedicationForOwner(medicationId, ownerId);
74
+ if (!med)
75
+ return null;
76
+ const where = [
77
+ { field: 'medication_id', operator: '=', value: medicationId },
78
+ { field: 'owner_id', operator: '=', value: ownerId },
79
+ ];
80
+ if (opts.from)
81
+ where.push({ field: 'taken_at', operator: '>=', value: opts.from });
82
+ if (opts.to)
83
+ where.push({ field: 'taken_at', operator: '<=', value: opts.to });
84
+ return findMany(LOGS_TABLE, {
85
+ where,
86
+ orderBy: [{ field: 'taken_at', direction: 'desc' }],
87
+ limit: opts.limit ?? 200,
88
+ });
89
+ }
90
+ /** Adherence summary: percentage of `taken` logs out of all logs in window. */
91
+ export async function adherenceRate(ownerId, from, to) {
92
+ const where = [
93
+ { field: 'owner_id', operator: '=', value: ownerId },
94
+ { field: 'taken_at', operator: '>=', value: from },
95
+ { field: 'taken_at', operator: '<=', value: to },
96
+ ];
97
+ const total = await count(LOGS_TABLE, where);
98
+ const taken = await count(LOGS_TABLE, [
99
+ ...where,
100
+ { field: 'status', operator: '=', value: 'taken' },
101
+ ]);
102
+ return { taken, total, rate: total > 0 ? taken / total : 0 };
103
+ }
@@ -0,0 +1,36 @@
1
+ /**
2
+ * Describes how often a medication is taken (e.g. daily, twice daily, as needed).
3
+ */
4
+ export type MedicationFrequency = 'once' | 'daily' | 'twice_daily' | 'three_times_daily' | 'four_times_daily' | 'as_needed' | 'weekly' | 'custom';
5
+ /**
6
+ * Database row shape for a medication record.
7
+ */
8
+ export interface MedicationRow {
9
+ id: string;
10
+ owner_id: string;
11
+ name: string;
12
+ generic_name: string | null;
13
+ dosage: string;
14
+ unit: string | null;
15
+ frequency: MedicationFrequency;
16
+ times_of_day: string[];
17
+ start_date: string | Date | null;
18
+ end_date: string | Date | null;
19
+ notes: string | null;
20
+ is_active: boolean;
21
+ created_at: string | Date;
22
+ updated_at: string | Date;
23
+ }
24
+ /**
25
+ * Database row shape for a medication intake log entry.
26
+ */
27
+ export interface MedicationLogRow {
28
+ id: string;
29
+ medication_id: string;
30
+ owner_id: string;
31
+ taken_at: string | Date;
32
+ status: 'taken' | 'skipped' | 'late' | 'missed';
33
+ notes: string | null;
34
+ created_at: string | Date;
35
+ }
36
+ //# sourceMappingURL=types.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"AAAA;;GAEG;AACH,MAAM,MAAM,mBAAmB,GAC3B,MAAM,GACN,OAAO,GACP,aAAa,GACb,mBAAmB,GACnB,kBAAkB,GAClB,WAAW,GACX,QAAQ,GACR,QAAQ,CAAA;AAEZ;;GAEG;AACH,MAAM,WAAW,aAAa;IAC5B,EAAE,EAAE,MAAM,CAAA;IACV,QAAQ,EAAE,MAAM,CAAA;IAChB,IAAI,EAAE,MAAM,CAAA;IACZ,YAAY,EAAE,MAAM,GAAG,IAAI,CAAA;IAC3B,MAAM,EAAE,MAAM,CAAA;IACd,IAAI,EAAE,MAAM,GAAG,IAAI,CAAA;IACnB,SAAS,EAAE,mBAAmB,CAAA;IAC9B,YAAY,EAAE,MAAM,EAAE,CAAA;IACtB,UAAU,EAAE,MAAM,GAAG,IAAI,GAAG,IAAI,CAAA;IAChC,QAAQ,EAAE,MAAM,GAAG,IAAI,GAAG,IAAI,CAAA;IAC9B,KAAK,EAAE,MAAM,GAAG,IAAI,CAAA;IACpB,SAAS,EAAE,OAAO,CAAA;IAClB,UAAU,EAAE,MAAM,GAAG,IAAI,CAAA;IACzB,UAAU,EAAE,MAAM,GAAG,IAAI,CAAA;CAC1B;AAED;;GAEG;AACH,MAAM,WAAW,gBAAgB;IAC/B,EAAE,EAAE,MAAM,CAAA;IACV,aAAa,EAAE,MAAM,CAAA;IACrB,QAAQ,EAAE,MAAM,CAAA;IAChB,QAAQ,EAAE,MAAM,GAAG,IAAI,CAAA;IACvB,MAAM,EAAE,OAAO,GAAG,SAAS,GAAG,MAAM,GAAG,QAAQ,CAAA;IAC/C,KAAK,EAAE,MAAM,GAAG,IAAI,CAAA;IACpB,UAAU,EAAE,MAAM,GAAG,IAAI,CAAA;CAC1B"}
package/dist/types.js ADDED
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,60 @@
1
+ import { z } from 'zod';
2
+ /** Valid dosing frequency options for a medication schedule. */
3
+ export declare const MEDICATION_FREQUENCIES: readonly ["once", "daily", "twice_daily", "three_times_daily", "four_times_daily", "as_needed", "weekly", "custom"];
4
+ /** Valid status values for a medication dose log entry. */
5
+ export declare const LOG_STATUSES: readonly ["taken", "skipped", "late", "missed"];
6
+ /** Zod schema for validating medication creation request payloads. */
7
+ export declare const medicationCreateSchema: z.ZodObject<{
8
+ name: z.ZodString;
9
+ generic_name: z.ZodOptional<z.ZodNullable<z.ZodString>>;
10
+ dosage: z.ZodString;
11
+ unit: z.ZodOptional<z.ZodNullable<z.ZodString>>;
12
+ frequency: z.ZodOptional<z.ZodEnum<{
13
+ once: "once";
14
+ daily: "daily";
15
+ twice_daily: "twice_daily";
16
+ three_times_daily: "three_times_daily";
17
+ four_times_daily: "four_times_daily";
18
+ as_needed: "as_needed";
19
+ weekly: "weekly";
20
+ custom: "custom";
21
+ }>>;
22
+ times_of_day: z.ZodOptional<z.ZodArray<z.ZodString>>;
23
+ start_date: z.ZodOptional<z.ZodNullable<z.ZodString>>;
24
+ end_date: z.ZodOptional<z.ZodNullable<z.ZodString>>;
25
+ notes: z.ZodOptional<z.ZodNullable<z.ZodString>>;
26
+ }, z.core.$strip>;
27
+ /** Zod schema for validating medication update request payloads; all create fields become optional and `is_active` is added. */
28
+ export declare const medicationUpdateSchema: z.ZodObject<{
29
+ name: z.ZodOptional<z.ZodString>;
30
+ generic_name: z.ZodOptional<z.ZodOptional<z.ZodNullable<z.ZodString>>>;
31
+ dosage: z.ZodOptional<z.ZodString>;
32
+ unit: z.ZodOptional<z.ZodOptional<z.ZodNullable<z.ZodString>>>;
33
+ frequency: z.ZodOptional<z.ZodOptional<z.ZodEnum<{
34
+ once: "once";
35
+ daily: "daily";
36
+ twice_daily: "twice_daily";
37
+ three_times_daily: "three_times_daily";
38
+ four_times_daily: "four_times_daily";
39
+ as_needed: "as_needed";
40
+ weekly: "weekly";
41
+ custom: "custom";
42
+ }>>>;
43
+ times_of_day: z.ZodOptional<z.ZodOptional<z.ZodArray<z.ZodString>>>;
44
+ start_date: z.ZodOptional<z.ZodOptional<z.ZodNullable<z.ZodString>>>;
45
+ end_date: z.ZodOptional<z.ZodOptional<z.ZodNullable<z.ZodString>>>;
46
+ notes: z.ZodOptional<z.ZodOptional<z.ZodNullable<z.ZodString>>>;
47
+ is_active: z.ZodOptional<z.ZodBoolean>;
48
+ }, z.core.$strip>;
49
+ /** Zod schema for validating medication dose log creation request payloads. */
50
+ export declare const logCreateSchema: z.ZodObject<{
51
+ taken_at: z.ZodOptional<z.ZodString>;
52
+ status: z.ZodOptional<z.ZodEnum<{
53
+ taken: "taken";
54
+ skipped: "skipped";
55
+ late: "late";
56
+ missed: "missed";
57
+ }>>;
58
+ notes: z.ZodOptional<z.ZodNullable<z.ZodString>>;
59
+ }, z.core.$strip>;
60
+ //# sourceMappingURL=validation.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"validation.d.ts","sourceRoot":"","sources":["../src/validation.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAA;AAEvB,gEAAgE;AAChE,eAAO,MAAM,sBAAsB,qHASzB,CAAA;AAEV,2DAA2D;AAC3D,eAAO,MAAM,YAAY,iDAAkD,CAAA;AAE3E,sEAAsE;AACtE,eAAO,MAAM,sBAAsB;;;;;;;;;;;;;;;;;;;iBAUjC,CAAA;AAEF,gIAAgI;AAChI,eAAO,MAAM,sBAAsB;;;;;;;;;;;;;;;;;;;;iBAEjC,CAAA;AAEF,+EAA+E;AAC/E,eAAO,MAAM,eAAe;;;;;;;;;iBAI1B,CAAA"}
@@ -0,0 +1,36 @@
1
+ import { z } from 'zod';
2
+ /** Valid dosing frequency options for a medication schedule. */
3
+ export const MEDICATION_FREQUENCIES = [
4
+ 'once',
5
+ 'daily',
6
+ 'twice_daily',
7
+ 'three_times_daily',
8
+ 'four_times_daily',
9
+ 'as_needed',
10
+ 'weekly',
11
+ 'custom',
12
+ ];
13
+ /** Valid status values for a medication dose log entry. */
14
+ export const LOG_STATUSES = ['taken', 'skipped', 'late', 'missed'];
15
+ /** Zod schema for validating medication creation request payloads. */
16
+ export const medicationCreateSchema = z.object({
17
+ name: z.string().min(1).max(255),
18
+ generic_name: z.string().max(255).nullable().optional(),
19
+ dosage: z.string().min(1).max(80),
20
+ unit: z.string().max(40).nullable().optional(),
21
+ frequency: z.enum(MEDICATION_FREQUENCIES).optional(),
22
+ times_of_day: z.array(z.string().regex(/^\d{2}:\d{2}$/)).optional(),
23
+ start_date: z.string().nullable().optional(),
24
+ end_date: z.string().nullable().optional(),
25
+ notes: z.string().max(2000).nullable().optional(),
26
+ });
27
+ /** Zod schema for validating medication update request payloads; all create fields become optional and `is_active` is added. */
28
+ export const medicationUpdateSchema = medicationCreateSchema.partial().extend({
29
+ is_active: z.boolean().optional(),
30
+ });
31
+ /** Zod schema for validating medication dose log creation request payloads. */
32
+ export const logCreateSchema = z.object({
33
+ taken_at: z.string().optional(),
34
+ status: z.enum(LOG_STATUSES).optional(),
35
+ notes: z.string().max(2000).nullable().optional(),
36
+ });
package/package.json ADDED
@@ -0,0 +1,46 @@
1
+ {
2
+ "name": "@molecule/api-resource-medication",
3
+ "version": "1.0.0",
4
+ "description": "Medication tracking + dosing schedule + adherence log",
5
+ "type": "module",
6
+ "main": "dist/index.js",
7
+ "types": "dist/index.d.ts",
8
+ "scripts": {
9
+ "build": "tsc",
10
+ "test": "vitest run",
11
+ "test:watch": "vitest"
12
+ },
13
+ "exports": {
14
+ ".": {
15
+ "types": "./dist/index.d.ts",
16
+ "import": "./dist/index.js"
17
+ }
18
+ },
19
+ "files": [
20
+ "dist"
21
+ ],
22
+ "keywords": [
23
+ "molecule",
24
+ "medication",
25
+ "health",
26
+ "adherence",
27
+ "resource"
28
+ ],
29
+ "license": "Apache-2.0",
30
+ "devDependencies": {
31
+ "@types/express": "5.0.6",
32
+ "@types/node": "26.1.2",
33
+ "express": "5.2.1",
34
+ "typescript": "6.0.3",
35
+ "vitest": "4.1.10",
36
+ "zod": "4.4.3"
37
+ },
38
+ "peerDependencies": {
39
+ "@molecule/api-bonds-default-express": "^1.0.0",
40
+ "@molecule/api-database": "^1.0.0",
41
+ "@molecule/api-i18n": "^1.0.0",
42
+ "@molecule/api-middleware-validation": "^1.0.0",
43
+ "express": "^5.0.0",
44
+ "zod": "^4.0.0"
45
+ }
46
+ }