@molecule/api-resource-journal-entry 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 +115 -0
- package/dist/browser-guard.d.ts +2 -0
- package/dist/browser-guard.d.ts.map +1 -0
- package/dist/browser-guard.js +18 -0
- package/dist/index.d.ts +61 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +60 -0
- package/dist/routes.d.ts +10 -0
- package/dist/routes.d.ts.map +1 -0
- package/dist/routes.js +150 -0
- package/dist/service.d.ts +60 -0
- package/dist/service.d.ts.map +1 -0
- package/dist/service.js +291 -0
- package/dist/types.d.ts +61 -0
- package/dist/types.d.ts.map +1 -0
- package/dist/types.js +24 -0
- package/dist/validation.d.ts +45 -0
- package/dist/validation.d.ts.map +1 -0
- package/dist/validation.js +22 -0
- package/package.json +49 -0
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 @@
|
|
|
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-journal-entry` 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-journal-entry 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 {};
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `@molecule/api-resource-journal-entry` — owner-scoped diary entries
|
|
3
|
+
* with optional at-rest encryption, mood-score linkage, daily-write
|
|
4
|
+
* streaks, and JSON/CSV/TXT export.
|
|
5
|
+
*
|
|
6
|
+
* Extracted from the mental-health-journal flagship. When
|
|
7
|
+
* `@molecule/api-encryption` is bonded, entry bodies are stored
|
|
8
|
+
* encrypted-at-rest; otherwise the plaintext column is used (the read
|
|
9
|
+
* path falls back automatically so key rotation never bricks reads).
|
|
10
|
+
*
|
|
11
|
+
* @example
|
|
12
|
+
* ```ts
|
|
13
|
+
* import { createJournalEntryRouter } from '@molecule/api-resource-journal-entry'
|
|
14
|
+
* import express from 'express'
|
|
15
|
+
*
|
|
16
|
+
* const app = express()
|
|
17
|
+
* app.use('/api/journal', createJournalEntryRouter())
|
|
18
|
+
* ```
|
|
19
|
+
*
|
|
20
|
+
* @remarks
|
|
21
|
+
* Schema lives in `__setup__/journal_entries.sql` — two tables:
|
|
22
|
+
* `journal_entries` + `mood_entries`. Mood rows are upserted per
|
|
23
|
+
* (user, day) so multiple entries in a day share one mood row.
|
|
24
|
+
*
|
|
25
|
+
* @e2e
|
|
26
|
+
* Integration checklist — drive the real UI (live preview, no mocks), adapt
|
|
27
|
+
* each item to this app's actual journal screens/flows, and check every box
|
|
28
|
+
* off one by one. A box you can't check is an integration bug to fix — not a
|
|
29
|
+
* skip. This is a PRIVATE journal, so privacy is the defining requirement:
|
|
30
|
+
* - [ ] Writing an entry persists its real fields — title, body, mood
|
|
31
|
+
* (radiant/good/neutral/low/struggling), tags, and date (written_at) — and
|
|
32
|
+
* the entry then appears in the author's journal list dated correctly (the
|
|
33
|
+
* list is newest-first by written_at) with a word_count matching the body.
|
|
34
|
+
* - [ ] Editing an entry (title / body / mood / tags) and deleting one both
|
|
35
|
+
* reflect in the UI immediately AND survive a reload — the change persisted
|
|
36
|
+
* server-side, not just local state.
|
|
37
|
+
* - [ ] If the UI filters or searches the list (by tag, mood, or date), only
|
|
38
|
+
* matching entries come back, and the mood shown per entry matches the mood
|
|
39
|
+
* saved for that day (mood rows upsert once per user per day).
|
|
40
|
+
* - [ ] If a write streak or count is shown, it equals the number of
|
|
41
|
+
* consecutive distinct days the author actually wrote, counted on the UTC
|
|
42
|
+
* day boundary and ending today or yesterday — add or remove entries across
|
|
43
|
+
* a day boundary and confirm it recomputes; a JSON/CSV/TXT export downloads
|
|
44
|
+
* only the author's own entries.
|
|
45
|
+
* - [ ] PRIVACY / AUTHORIZATION — entries are visible ONLY to their author.
|
|
46
|
+
* There is no sharing and no cross-user read path: signed in as a second
|
|
47
|
+
* user, requesting another user's entry id returns 404 (not-owned and truly
|
|
48
|
+
* missing are indistinguishable, so existence is never leaked), and the list
|
|
49
|
+
* and export return only your own rows — no admin or global view surfaces
|
|
50
|
+
* another user's entries. The owner is always the session user, never a
|
|
51
|
+
* userId taken from the request body, and journal content is never written
|
|
52
|
+
* to logs in the clear.
|
|
53
|
+
*
|
|
54
|
+
* @module
|
|
55
|
+
*/
|
|
56
|
+
export * from './browser-guard.js';
|
|
57
|
+
export * from './routes.js';
|
|
58
|
+
export * from './service.js';
|
|
59
|
+
export * from './types.js';
|
|
60
|
+
export * from './validation.js';
|
|
61
|
+
//# sourceMappingURL=index.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAsDG;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,60 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `@molecule/api-resource-journal-entry` — owner-scoped diary entries
|
|
3
|
+
* with optional at-rest encryption, mood-score linkage, daily-write
|
|
4
|
+
* streaks, and JSON/CSV/TXT export.
|
|
5
|
+
*
|
|
6
|
+
* Extracted from the mental-health-journal flagship. When
|
|
7
|
+
* `@molecule/api-encryption` is bonded, entry bodies are stored
|
|
8
|
+
* encrypted-at-rest; otherwise the plaintext column is used (the read
|
|
9
|
+
* path falls back automatically so key rotation never bricks reads).
|
|
10
|
+
*
|
|
11
|
+
* @example
|
|
12
|
+
* ```ts
|
|
13
|
+
* import { createJournalEntryRouter } from '@molecule/api-resource-journal-entry'
|
|
14
|
+
* import express from 'express'
|
|
15
|
+
*
|
|
16
|
+
* const app = express()
|
|
17
|
+
* app.use('/api/journal', createJournalEntryRouter())
|
|
18
|
+
* ```
|
|
19
|
+
*
|
|
20
|
+
* @remarks
|
|
21
|
+
* Schema lives in `__setup__/journal_entries.sql` — two tables:
|
|
22
|
+
* `journal_entries` + `mood_entries`. Mood rows are upserted per
|
|
23
|
+
* (user, day) so multiple entries in a day share one mood row.
|
|
24
|
+
*
|
|
25
|
+
* @e2e
|
|
26
|
+
* Integration checklist — drive the real UI (live preview, no mocks), adapt
|
|
27
|
+
* each item to this app's actual journal screens/flows, and check every box
|
|
28
|
+
* off one by one. A box you can't check is an integration bug to fix — not a
|
|
29
|
+
* skip. This is a PRIVATE journal, so privacy is the defining requirement:
|
|
30
|
+
* - [ ] Writing an entry persists its real fields — title, body, mood
|
|
31
|
+
* (radiant/good/neutral/low/struggling), tags, and date (written_at) — and
|
|
32
|
+
* the entry then appears in the author's journal list dated correctly (the
|
|
33
|
+
* list is newest-first by written_at) with a word_count matching the body.
|
|
34
|
+
* - [ ] Editing an entry (title / body / mood / tags) and deleting one both
|
|
35
|
+
* reflect in the UI immediately AND survive a reload — the change persisted
|
|
36
|
+
* server-side, not just local state.
|
|
37
|
+
* - [ ] If the UI filters or searches the list (by tag, mood, or date), only
|
|
38
|
+
* matching entries come back, and the mood shown per entry matches the mood
|
|
39
|
+
* saved for that day (mood rows upsert once per user per day).
|
|
40
|
+
* - [ ] If a write streak or count is shown, it equals the number of
|
|
41
|
+
* consecutive distinct days the author actually wrote, counted on the UTC
|
|
42
|
+
* day boundary and ending today or yesterday — add or remove entries across
|
|
43
|
+
* a day boundary and confirm it recomputes; a JSON/CSV/TXT export downloads
|
|
44
|
+
* only the author's own entries.
|
|
45
|
+
* - [ ] PRIVACY / AUTHORIZATION — entries are visible ONLY to their author.
|
|
46
|
+
* There is no sharing and no cross-user read path: signed in as a second
|
|
47
|
+
* user, requesting another user's entry id returns 404 (not-owned and truly
|
|
48
|
+
* missing are indistinguishable, so existence is never leaked), and the list
|
|
49
|
+
* and export return only your own rows — no admin or global view surfaces
|
|
50
|
+
* another user's entries. The owner is always the session user, never a
|
|
51
|
+
* userId taken from the request body, and journal content is never written
|
|
52
|
+
* to logs in the clear.
|
|
53
|
+
*
|
|
54
|
+
* @module
|
|
55
|
+
*/
|
|
56
|
+
export * from './browser-guard.js';
|
|
57
|
+
export * from './routes.js';
|
|
58
|
+
export * from './service.js';
|
|
59
|
+
export * from './types.js';
|
|
60
|
+
export * from './validation.js';
|
package/dist/routes.d.ts
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Express router factory for the journal-entry resource. Mount at any
|
|
3
|
+
* path (e.g. `/api/journal`).
|
|
4
|
+
*
|
|
5
|
+
* @module
|
|
6
|
+
*/
|
|
7
|
+
import { Router } from 'express';
|
|
8
|
+
/** Build the journal-entry router. */
|
|
9
|
+
export declare function createJournalEntryRouter(): Router;
|
|
10
|
+
//# sourceMappingURL=routes.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"routes.d.ts","sourceRoot":"","sources":["../src/routes.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAGH,OAAO,EAA+B,MAAM,EAAE,MAAM,SAAS,CAAA;AAiD7D,sCAAsC;AACtC,wBAAgB,wBAAwB,IAAI,MAAM,CAkHjD"}
|
package/dist/routes.js
ADDED
|
@@ -0,0 +1,150 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Express router factory for the journal-entry resource. Mount at any
|
|
3
|
+
* path (e.g. `/api/journal`).
|
|
4
|
+
*
|
|
5
|
+
* @module
|
|
6
|
+
*/
|
|
7
|
+
import { Router } from 'express';
|
|
8
|
+
import { getUserId, idParamSchema } from '@molecule/api-bonds-default-express';
|
|
9
|
+
import { t } from '@molecule/api-i18n';
|
|
10
|
+
import { logger } from '@molecule/api-logger';
|
|
11
|
+
import { validateBody as validateBodyRaw, validateParams, } from '@molecule/api-middleware-validation';
|
|
12
|
+
import { computeStreak, createEntryForOwner, deleteEntryForOwner, exportEntries, formatExport, getEntryForOwner, listEntriesForOwner, updateEntryForOwner, } from './service.js';
|
|
13
|
+
import { createEntrySchema, updateEntrySchema } from './validation.js';
|
|
14
|
+
const validateBody = validateBodyRaw;
|
|
15
|
+
const EXPORT_FORMATS = ['json', 'csv', 'txt'];
|
|
16
|
+
/** Returns a 401 Unauthorized JSON response. */
|
|
17
|
+
function unauthorized(res) {
|
|
18
|
+
return res
|
|
19
|
+
.status(401)
|
|
20
|
+
.json({ error: t('auth.unauthorized', undefined, { defaultValue: 'Unauthorized' }) });
|
|
21
|
+
}
|
|
22
|
+
/** Returns a 404 Not Found JSON response for a missing journal entry. */
|
|
23
|
+
function notFound(res) {
|
|
24
|
+
return res.status(404).json({
|
|
25
|
+
error: t('journal.notFound', undefined, { defaultValue: 'Journal entry not found' }),
|
|
26
|
+
});
|
|
27
|
+
}
|
|
28
|
+
/** Returns a 500 Internal Server Error JSON response. */
|
|
29
|
+
function internalError(res) {
|
|
30
|
+
return res.status(500).json({
|
|
31
|
+
error: t('errors.internalServer', undefined, { defaultValue: 'Internal server error' }),
|
|
32
|
+
});
|
|
33
|
+
}
|
|
34
|
+
/** Build the journal-entry router. */
|
|
35
|
+
export function createJournalEntryRouter() {
|
|
36
|
+
const router = Router();
|
|
37
|
+
router.get('/entries', async (req, res) => {
|
|
38
|
+
const userId = getUserId(res);
|
|
39
|
+
if (!userId)
|
|
40
|
+
return unauthorized(res);
|
|
41
|
+
try {
|
|
42
|
+
const limit = Math.max(1, Math.min(200, Number(req.query.limit) || 100));
|
|
43
|
+
res.json(await listEntriesForOwner(userId, limit));
|
|
44
|
+
}
|
|
45
|
+
catch (error) {
|
|
46
|
+
logger.error('listEntriesForOwner failed', { error });
|
|
47
|
+
internalError(res);
|
|
48
|
+
}
|
|
49
|
+
});
|
|
50
|
+
router.get('/entries/:id', validateParams(idParamSchema), async (req, res) => {
|
|
51
|
+
const userId = getUserId(res);
|
|
52
|
+
if (!userId)
|
|
53
|
+
return unauthorized(res);
|
|
54
|
+
try {
|
|
55
|
+
const entry = await getEntryForOwner(userId, String(req.params.id));
|
|
56
|
+
if (!entry)
|
|
57
|
+
return notFound(res);
|
|
58
|
+
res.json(entry);
|
|
59
|
+
}
|
|
60
|
+
catch (error) {
|
|
61
|
+
logger.error('getEntryForOwner failed', { error });
|
|
62
|
+
internalError(res);
|
|
63
|
+
}
|
|
64
|
+
});
|
|
65
|
+
router.post('/entries', validateBody(createEntrySchema), async (req, res) => {
|
|
66
|
+
const userId = getUserId(res);
|
|
67
|
+
if (!userId)
|
|
68
|
+
return unauthorized(res);
|
|
69
|
+
try {
|
|
70
|
+
const body = req.body;
|
|
71
|
+
const created = await createEntryForOwner(userId, body);
|
|
72
|
+
if (!created)
|
|
73
|
+
return internalError(res);
|
|
74
|
+
res.status(201).json(created);
|
|
75
|
+
}
|
|
76
|
+
catch (error) {
|
|
77
|
+
logger.error('createEntryForOwner failed', { error });
|
|
78
|
+
internalError(res);
|
|
79
|
+
}
|
|
80
|
+
});
|
|
81
|
+
router.put('/entries/:id', validateParams(idParamSchema), validateBody(updateEntrySchema), async (req, res) => {
|
|
82
|
+
const userId = getUserId(res);
|
|
83
|
+
if (!userId)
|
|
84
|
+
return unauthorized(res);
|
|
85
|
+
try {
|
|
86
|
+
const body = req.body;
|
|
87
|
+
const updated = await updateEntryForOwner(userId, String(req.params.id), body);
|
|
88
|
+
if (!updated)
|
|
89
|
+
return notFound(res);
|
|
90
|
+
res.json(updated);
|
|
91
|
+
}
|
|
92
|
+
catch (error) {
|
|
93
|
+
logger.error('updateEntryForOwner failed', { error });
|
|
94
|
+
internalError(res);
|
|
95
|
+
}
|
|
96
|
+
});
|
|
97
|
+
router.delete('/entries/:id', validateParams(idParamSchema), async (req, res) => {
|
|
98
|
+
const userId = getUserId(res);
|
|
99
|
+
if (!userId)
|
|
100
|
+
return unauthorized(res);
|
|
101
|
+
try {
|
|
102
|
+
const ok = await deleteEntryForOwner(userId, String(req.params.id));
|
|
103
|
+
if (!ok)
|
|
104
|
+
return notFound(res);
|
|
105
|
+
res.status(204).end();
|
|
106
|
+
}
|
|
107
|
+
catch (error) {
|
|
108
|
+
logger.error('deleteEntryForOwner failed', { error });
|
|
109
|
+
internalError(res);
|
|
110
|
+
}
|
|
111
|
+
});
|
|
112
|
+
router.get('/streak', async (_req, res) => {
|
|
113
|
+
const userId = getUserId(res);
|
|
114
|
+
if (!userId)
|
|
115
|
+
return unauthorized(res);
|
|
116
|
+
try {
|
|
117
|
+
res.json({ streak: await computeStreak(userId) });
|
|
118
|
+
}
|
|
119
|
+
catch (error) {
|
|
120
|
+
logger.error('computeStreak failed', { error });
|
|
121
|
+
internalError(res);
|
|
122
|
+
}
|
|
123
|
+
});
|
|
124
|
+
router.get('/export/:format', async (req, res) => {
|
|
125
|
+
const userId = getUserId(res);
|
|
126
|
+
if (!userId)
|
|
127
|
+
return unauthorized(res);
|
|
128
|
+
try {
|
|
129
|
+
const format = String(req.params.format).toLowerCase();
|
|
130
|
+
if (!EXPORT_FORMATS.includes(format)) {
|
|
131
|
+
return res.status(400).json({
|
|
132
|
+
error: t('journal.invalidExportFormat', undefined, {
|
|
133
|
+
defaultValue: 'Unsupported export format.',
|
|
134
|
+
}),
|
|
135
|
+
});
|
|
136
|
+
}
|
|
137
|
+
const records = await exportEntries(userId);
|
|
138
|
+
const { contentType, body } = formatExport(records, format);
|
|
139
|
+
const stamp = new Date().toISOString().slice(0, 10);
|
|
140
|
+
res.setHeader('Content-Type', contentType);
|
|
141
|
+
res.setHeader('Content-Disposition', `attachment; filename="journal-${stamp}.${format}"`);
|
|
142
|
+
res.end(body);
|
|
143
|
+
}
|
|
144
|
+
catch (error) {
|
|
145
|
+
logger.error('exportEntries failed', { error });
|
|
146
|
+
internalError(res);
|
|
147
|
+
}
|
|
148
|
+
});
|
|
149
|
+
return router;
|
|
150
|
+
}
|
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Pure service-layer helpers for the journal-entry resource. Usable
|
|
3
|
+
* outside of HTTP contexts (background jobs, exports, AI pipelines).
|
|
4
|
+
*
|
|
5
|
+
* @module
|
|
6
|
+
*/
|
|
7
|
+
import { type JournalEntryRow, type MoodLevel, type PublicJournalEntry } from './types.js';
|
|
8
|
+
/** Decrypt the entry body if encryption is bonded; otherwise return plaintext. */
|
|
9
|
+
export declare function decryptIfNeeded(row: JournalEntryRow): Promise<string>;
|
|
10
|
+
/** Shape a row into the public-facing representation. */
|
|
11
|
+
export declare function shapeEntry(entry: JournalEntryRow, body: string): Promise<PublicJournalEntry>;
|
|
12
|
+
/** List the most-recent entries for an owner. */
|
|
13
|
+
export declare function listEntriesForOwner(userId: string, limit?: number): Promise<PublicJournalEntry[]>;
|
|
14
|
+
/** Owner-scoped read — returns null when missing or not owned. */
|
|
15
|
+
export declare function getEntryForOwner(userId: string, id: string): Promise<PublicJournalEntry | null>;
|
|
16
|
+
/** Input fields accepted when creating a new journal entry. */
|
|
17
|
+
export interface CreateEntryInput {
|
|
18
|
+
mood?: MoodLevel;
|
|
19
|
+
title?: string;
|
|
20
|
+
body: string;
|
|
21
|
+
tags?: string[];
|
|
22
|
+
prompt_id?: string | null;
|
|
23
|
+
written_at?: string | Date;
|
|
24
|
+
}
|
|
25
|
+
/**
|
|
26
|
+
* Create a journal entry and, if `mood` is provided, upsert today's
|
|
27
|
+
* `mood_entries` row + link it to the journal entry.
|
|
28
|
+
*/
|
|
29
|
+
export declare function createEntryForOwner(userId: string, input: CreateEntryInput): Promise<PublicJournalEntry | null>;
|
|
30
|
+
/** Fields that can be patched on an existing journal entry. */
|
|
31
|
+
export interface UpdateEntryInput {
|
|
32
|
+
mood?: MoodLevel;
|
|
33
|
+
title?: string;
|
|
34
|
+
body?: string;
|
|
35
|
+
tags?: string[];
|
|
36
|
+
}
|
|
37
|
+
/** Owner-scoped patch update — returns null when missing or not owned. */
|
|
38
|
+
export declare function updateEntryForOwner(userId: string, id: string, input: UpdateEntryInput): Promise<PublicJournalEntry | null>;
|
|
39
|
+
/** Owner-scoped delete — true if it deleted, false if not owned / missing. */
|
|
40
|
+
export declare function deleteEntryForOwner(userId: string, id: string): Promise<boolean>;
|
|
41
|
+
/** Daily-write streak: consecutive distinct UTC days ending today/yesterday. */
|
|
42
|
+
export declare function computeStreak(userId: string): Promise<number>;
|
|
43
|
+
/** Flattened, export-friendly representation of a single journal entry. */
|
|
44
|
+
export interface ExportRecord {
|
|
45
|
+
id: string;
|
|
46
|
+
date: string;
|
|
47
|
+
title: string;
|
|
48
|
+
mood: MoodLevel;
|
|
49
|
+
tags: string[];
|
|
50
|
+
word_count: number;
|
|
51
|
+
body: string;
|
|
52
|
+
}
|
|
53
|
+
/** Serialize all entries for an owner into an export-friendly array. */
|
|
54
|
+
export declare function exportEntries(userId: string, max?: number): Promise<ExportRecord[]>;
|
|
55
|
+
/** Format export records as JSON / CSV / TXT. */
|
|
56
|
+
export declare function formatExport(records: ExportRecord[], format: 'json' | 'csv' | 'txt'): {
|
|
57
|
+
contentType: string;
|
|
58
|
+
body: string;
|
|
59
|
+
};
|
|
60
|
+
//# sourceMappingURL=service.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"service.d.ts","sourceRoot":"","sources":["../src/service.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAKH,OAAO,EACL,KAAK,eAAe,EAGpB,KAAK,SAAS,EACd,KAAK,kBAAkB,EAExB,MAAM,YAAY,CAAA;AAiCnB,kFAAkF;AAClF,wBAAsB,eAAe,CAAC,GAAG,EAAE,eAAe,GAAG,OAAO,CAAC,MAAM,CAAC,CAS3E;AAWD,yDAAyD;AACzD,wBAAsB,UAAU,CAC9B,KAAK,EAAE,eAAe,EACtB,IAAI,EAAE,MAAM,GACX,OAAO,CAAC,kBAAkB,CAAC,CAc7B;AAED,iDAAiD;AACjD,wBAAsB,mBAAmB,CACvC,MAAM,EAAE,MAAM,EACd,KAAK,SAAM,GACV,OAAO,CAAC,kBAAkB,EAAE,CAAC,CAS/B;AAED,kEAAkE;AAClE,wBAAsB,gBAAgB,CACpC,MAAM,EAAE,MAAM,EACd,EAAE,EAAE,MAAM,GACT,OAAO,CAAC,kBAAkB,GAAG,IAAI,CAAC,CAIpC;AAED,+DAA+D;AAC/D,MAAM,WAAW,gBAAgB;IAC/B,IAAI,CAAC,EAAE,SAAS,CAAA;IAChB,KAAK,CAAC,EAAE,MAAM,CAAA;IACd,IAAI,EAAE,MAAM,CAAA;IACZ,IAAI,CAAC,EAAE,MAAM,EAAE,CAAA;IACf,SAAS,CAAC,EAAE,MAAM,GAAG,IAAI,CAAA;IACzB,UAAU,CAAC,EAAE,MAAM,GAAG,IAAI,CAAA;CAC3B;AAED;;;GAGG;AACH,wBAAsB,mBAAmB,CACvC,MAAM,EAAE,MAAM,EACd,KAAK,EAAE,gBAAgB,GACtB,OAAO,CAAC,kBAAkB,GAAG,IAAI,CAAC,CA2DpC;AAED,+DAA+D;AAC/D,MAAM,WAAW,gBAAgB;IAC/B,IAAI,CAAC,EAAE,SAAS,CAAA;IAChB,KAAK,CAAC,EAAE,MAAM,CAAA;IACd,IAAI,CAAC,EAAE,MAAM,CAAA;IACb,IAAI,CAAC,EAAE,MAAM,EAAE,CAAA;CAChB;AAED,0EAA0E;AAC1E,wBAAsB,mBAAmB,CACvC,MAAM,EAAE,MAAM,EACd,EAAE,EAAE,MAAM,EACV,KAAK,EAAE,gBAAgB,GACtB,OAAO,CAAC,kBAAkB,GAAG,IAAI,CAAC,CAgCpC;AAED,8EAA8E;AAC9E,wBAAsB,mBAAmB,CAAC,MAAM,EAAE,MAAM,EAAE,EAAE,EAAE,MAAM,GAAG,OAAO,CAAC,OAAO,CAAC,CAKtF;AAED,gFAAgF;AAChF,wBAAsB,aAAa,CAAC,MAAM,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC,CA0BnE;AAED,2EAA2E;AAC3E,MAAM,WAAW,YAAY;IAC3B,EAAE,EAAE,MAAM,CAAA;IACV,IAAI,EAAE,MAAM,CAAA;IACZ,KAAK,EAAE,MAAM,CAAA;IACb,IAAI,EAAE,SAAS,CAAA;IACf,IAAI,EAAE,MAAM,EAAE,CAAA;IACd,UAAU,EAAE,MAAM,CAAA;IAClB,IAAI,EAAE,MAAM,CAAA;CACb;AAED,wEAAwE;AACxE,wBAAsB,aAAa,CAAC,MAAM,EAAE,MAAM,EAAE,GAAG,SAAS,GAAG,OAAO,CAAC,YAAY,EAAE,CAAC,CAkBzF;AASD,iDAAiD;AACjD,wBAAgB,YAAY,CAC1B,OAAO,EAAE,YAAY,EAAE,EACvB,MAAM,EAAE,MAAM,GAAG,KAAK,GAAG,KAAK,GAC7B;IAAE,WAAW,EAAE,MAAM,CAAC;IAAC,IAAI,EAAE,MAAM,CAAA;CAAE,CA+BvC"}
|
package/dist/service.js
ADDED
|
@@ -0,0 +1,291 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Pure service-layer helpers for the journal-entry resource. Usable
|
|
3
|
+
* outside of HTTP contexts (background jobs, exports, AI pipelines).
|
|
4
|
+
*
|
|
5
|
+
* @module
|
|
6
|
+
*/
|
|
7
|
+
import { create, deleteById, findById, findMany, query, updateById } from '@molecule/api-database';
|
|
8
|
+
import { decrypt, encrypt, hasProvider as hasEncryption } from '@molecule/api-encryption';
|
|
9
|
+
import { levelByScore, SCORE_BY_LEVEL, } from './types.js';
|
|
10
|
+
const TABLE = 'journal_entries';
|
|
11
|
+
const MOOD_TABLE = 'mood_entries';
|
|
12
|
+
/** Coerce a date-like value to an ISO-8601 string, defaulting to now. */
|
|
13
|
+
function toIso(d) {
|
|
14
|
+
if (!d)
|
|
15
|
+
return new Date().toISOString();
|
|
16
|
+
return new Date(d).toISOString();
|
|
17
|
+
}
|
|
18
|
+
/** Parse a JSON string into a typed array, returning `[]` on invalid input. */
|
|
19
|
+
function toJsonArray(raw) {
|
|
20
|
+
if (Array.isArray(raw))
|
|
21
|
+
return raw;
|
|
22
|
+
if (typeof raw === 'string') {
|
|
23
|
+
try {
|
|
24
|
+
const parsed = JSON.parse(raw);
|
|
25
|
+
return Array.isArray(parsed) ? parsed : [];
|
|
26
|
+
}
|
|
27
|
+
catch (_error) {
|
|
28
|
+
// raw is not valid JSON — safe to return an empty array
|
|
29
|
+
return [];
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
return [];
|
|
33
|
+
}
|
|
34
|
+
/** Trim an entry body to a 200-character preview, collapsing whitespace. */
|
|
35
|
+
function previewText(body) {
|
|
36
|
+
const collapsed = body.replace(/\s+/g, ' ').trim();
|
|
37
|
+
if (collapsed.length <= 200)
|
|
38
|
+
return collapsed;
|
|
39
|
+
return collapsed.slice(0, 197) + '…';
|
|
40
|
+
}
|
|
41
|
+
/** Decrypt the entry body if encryption is bonded; otherwise return plaintext. */
|
|
42
|
+
export async function decryptIfNeeded(row) {
|
|
43
|
+
if (row.body_encrypted && hasEncryption()) {
|
|
44
|
+
try {
|
|
45
|
+
return await decrypt(row.body_encrypted, row.user_id);
|
|
46
|
+
}
|
|
47
|
+
catch (_error) {
|
|
48
|
+
// Decryption failed — fall back to the plaintext column so the entry remains readable
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
return row.body ?? '';
|
|
52
|
+
}
|
|
53
|
+
/** Resolve the mood level for a journal entry by looking up its linked mood row. */
|
|
54
|
+
async function moodLevelForEntry(entry) {
|
|
55
|
+
if (entry.mood_id) {
|
|
56
|
+
const mood = await findById(MOOD_TABLE, entry.mood_id);
|
|
57
|
+
if (mood)
|
|
58
|
+
return levelByScore(mood.score);
|
|
59
|
+
}
|
|
60
|
+
return 'neutral';
|
|
61
|
+
}
|
|
62
|
+
/** Shape a row into the public-facing representation. */
|
|
63
|
+
export async function shapeEntry(entry, body) {
|
|
64
|
+
return {
|
|
65
|
+
id: entry.id,
|
|
66
|
+
date: toIso(entry.written_at),
|
|
67
|
+
title: entry.title ?? '',
|
|
68
|
+
preview: previewText(body),
|
|
69
|
+
body,
|
|
70
|
+
mood: await moodLevelForEntry(entry),
|
|
71
|
+
tags: toJsonArray(entry.tags),
|
|
72
|
+
word_count: entry.word_count,
|
|
73
|
+
ai_summary: entry.ai_summary,
|
|
74
|
+
ai_themes: toJsonArray(entry.ai_themes),
|
|
75
|
+
prompt: entry.prompt_id,
|
|
76
|
+
};
|
|
77
|
+
}
|
|
78
|
+
/** List the most-recent entries for an owner. */
|
|
79
|
+
export async function listEntriesForOwner(userId, limit = 100) {
|
|
80
|
+
const rows = await findMany(TABLE, {
|
|
81
|
+
where: [{ field: 'user_id', operator: '=', value: userId }],
|
|
82
|
+
orderBy: [{ field: 'written_at', direction: 'desc' }],
|
|
83
|
+
limit,
|
|
84
|
+
});
|
|
85
|
+
const out = [];
|
|
86
|
+
for (const row of rows)
|
|
87
|
+
out.push(await shapeEntry(row, await decryptIfNeeded(row)));
|
|
88
|
+
return out;
|
|
89
|
+
}
|
|
90
|
+
/** Owner-scoped read — returns null when missing or not owned. */
|
|
91
|
+
export async function getEntryForOwner(userId, id) {
|
|
92
|
+
const row = await findById(TABLE, id);
|
|
93
|
+
if (!row || row.user_id !== userId)
|
|
94
|
+
return null;
|
|
95
|
+
return shapeEntry(row, await decryptIfNeeded(row));
|
|
96
|
+
}
|
|
97
|
+
/**
|
|
98
|
+
* Create a journal entry and, if `mood` is provided, upsert today's
|
|
99
|
+
* `mood_entries` row + link it to the journal entry.
|
|
100
|
+
*/
|
|
101
|
+
export async function createEntryForOwner(userId, input) {
|
|
102
|
+
let moodId = null;
|
|
103
|
+
if (input.mood) {
|
|
104
|
+
const score = SCORE_BY_LEVEL[input.mood];
|
|
105
|
+
const sameDay = await query(`SELECT id FROM ${MOOD_TABLE}
|
|
106
|
+
WHERE user_id = $1 AND recorded_at::date = NOW()::date
|
|
107
|
+
ORDER BY recorded_at DESC LIMIT 1`, [userId]);
|
|
108
|
+
if (sameDay.rows.length > 0) {
|
|
109
|
+
moodId = sameDay.rows[0].id;
|
|
110
|
+
await updateById(MOOD_TABLE, moodId, { score, label: input.mood });
|
|
111
|
+
}
|
|
112
|
+
else {
|
|
113
|
+
const created = await create(MOOD_TABLE, {
|
|
114
|
+
user_id: userId,
|
|
115
|
+
score,
|
|
116
|
+
label: input.mood,
|
|
117
|
+
activities: '[]',
|
|
118
|
+
recorded_at: new Date(),
|
|
119
|
+
created_at: new Date(),
|
|
120
|
+
});
|
|
121
|
+
moodId = created.data?.id ?? null;
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
const writtenAt = input.written_at ? new Date(input.written_at) : new Date();
|
|
125
|
+
const wordCount = input.body.split(/\s+/).filter(Boolean).length;
|
|
126
|
+
let bodyEncrypted = null;
|
|
127
|
+
if (hasEncryption()) {
|
|
128
|
+
bodyEncrypted = await encrypt(input.body, userId);
|
|
129
|
+
}
|
|
130
|
+
const result = await create(TABLE, {
|
|
131
|
+
user_id: userId,
|
|
132
|
+
title: input.title ?? null,
|
|
133
|
+
body: input.body,
|
|
134
|
+
body_encrypted: bodyEncrypted,
|
|
135
|
+
body_iv: null,
|
|
136
|
+
mood_id: moodId,
|
|
137
|
+
prompt_id: input.prompt_id ?? null,
|
|
138
|
+
activity_ids: '[]',
|
|
139
|
+
tags: JSON.stringify(input.tags ?? []),
|
|
140
|
+
word_count: wordCount,
|
|
141
|
+
ai_summary: null,
|
|
142
|
+
ai_themes: null,
|
|
143
|
+
is_private: true,
|
|
144
|
+
written_at: writtenAt,
|
|
145
|
+
created_at: new Date(),
|
|
146
|
+
});
|
|
147
|
+
const entryId = result.data?.id ?? null;
|
|
148
|
+
if (moodId && entryId) {
|
|
149
|
+
await updateById(MOOD_TABLE, moodId, { journal_entry_id: entryId });
|
|
150
|
+
}
|
|
151
|
+
if (!entryId)
|
|
152
|
+
return null;
|
|
153
|
+
const full = await findById(TABLE, entryId);
|
|
154
|
+
if (!full)
|
|
155
|
+
return null;
|
|
156
|
+
return shapeEntry(full, await decryptIfNeeded(full));
|
|
157
|
+
}
|
|
158
|
+
/** Owner-scoped patch update — returns null when missing or not owned. */
|
|
159
|
+
export async function updateEntryForOwner(userId, id, input) {
|
|
160
|
+
const existing = await findById(TABLE, id);
|
|
161
|
+
if (!existing || existing.user_id !== userId)
|
|
162
|
+
return null;
|
|
163
|
+
const patch = { updated_at: new Date() };
|
|
164
|
+
if (input.title !== undefined)
|
|
165
|
+
patch.title = input.title;
|
|
166
|
+
if (input.body !== undefined) {
|
|
167
|
+
patch.body = input.body;
|
|
168
|
+
patch.word_count = input.body.split(/\s+/).filter(Boolean).length;
|
|
169
|
+
if (hasEncryption())
|
|
170
|
+
patch.body_encrypted = await encrypt(input.body, userId);
|
|
171
|
+
}
|
|
172
|
+
if (input.tags !== undefined)
|
|
173
|
+
patch.tags = JSON.stringify(input.tags);
|
|
174
|
+
if (input.mood) {
|
|
175
|
+
const score = SCORE_BY_LEVEL[input.mood];
|
|
176
|
+
if (existing.mood_id) {
|
|
177
|
+
await updateById(MOOD_TABLE, existing.mood_id, { score, label: input.mood });
|
|
178
|
+
}
|
|
179
|
+
else {
|
|
180
|
+
const created = await create(MOOD_TABLE, {
|
|
181
|
+
user_id: userId,
|
|
182
|
+
score,
|
|
183
|
+
label: input.mood,
|
|
184
|
+
activities: '[]',
|
|
185
|
+
recorded_at: new Date(),
|
|
186
|
+
created_at: new Date(),
|
|
187
|
+
journal_entry_id: id,
|
|
188
|
+
});
|
|
189
|
+
patch.mood_id = created.data?.id ?? null;
|
|
190
|
+
}
|
|
191
|
+
}
|
|
192
|
+
await updateById(TABLE, id, patch);
|
|
193
|
+
const updated = await findById(TABLE, id);
|
|
194
|
+
if (!updated)
|
|
195
|
+
return null;
|
|
196
|
+
return shapeEntry(updated, await decryptIfNeeded(updated));
|
|
197
|
+
}
|
|
198
|
+
/** Owner-scoped delete — true if it deleted, false if not owned / missing. */
|
|
199
|
+
export async function deleteEntryForOwner(userId, id) {
|
|
200
|
+
const existing = await findById(TABLE, id);
|
|
201
|
+
if (!existing || existing.user_id !== userId)
|
|
202
|
+
return false;
|
|
203
|
+
await deleteById(TABLE, id);
|
|
204
|
+
return true;
|
|
205
|
+
}
|
|
206
|
+
/** Daily-write streak: consecutive distinct UTC days ending today/yesterday. */
|
|
207
|
+
export async function computeStreak(userId) {
|
|
208
|
+
const { rows } = await query(`SELECT DISTINCT to_char(written_at AT TIME ZONE 'UTC', 'YYYY-MM-DD') AS day
|
|
209
|
+
FROM ${TABLE}
|
|
210
|
+
WHERE user_id = $1
|
|
211
|
+
ORDER BY day DESC
|
|
212
|
+
LIMIT 365`, [userId]);
|
|
213
|
+
if (rows.length === 0)
|
|
214
|
+
return 0;
|
|
215
|
+
const set = new Set(rows.map((r) => r.day));
|
|
216
|
+
let streak = 0;
|
|
217
|
+
const cursor = new Date();
|
|
218
|
+
cursor.setUTCHours(0, 0, 0, 0);
|
|
219
|
+
for (let i = 0; i < 365; i++) {
|
|
220
|
+
const iso = cursor.toISOString().slice(0, 10);
|
|
221
|
+
if (set.has(iso)) {
|
|
222
|
+
streak++;
|
|
223
|
+
cursor.setUTCDate(cursor.getUTCDate() - 1);
|
|
224
|
+
}
|
|
225
|
+
else if (i === 0) {
|
|
226
|
+
cursor.setUTCDate(cursor.getUTCDate() - 1);
|
|
227
|
+
}
|
|
228
|
+
else {
|
|
229
|
+
break;
|
|
230
|
+
}
|
|
231
|
+
}
|
|
232
|
+
return streak;
|
|
233
|
+
}
|
|
234
|
+
/** Serialize all entries for an owner into an export-friendly array. */
|
|
235
|
+
export async function exportEntries(userId, max = 10_000) {
|
|
236
|
+
const entries = await findMany(TABLE, {
|
|
237
|
+
where: [{ field: 'user_id', operator: '=', value: userId }],
|
|
238
|
+
orderBy: [{ field: 'written_at', direction: 'desc' }],
|
|
239
|
+
limit: max,
|
|
240
|
+
});
|
|
241
|
+
const decrypted = await Promise.all(entries.map((entry) => decryptIfNeeded(entry)));
|
|
242
|
+
return Promise.all(entries.map(async (entry, i) => ({
|
|
243
|
+
id: entry.id,
|
|
244
|
+
date: toIso(entry.written_at),
|
|
245
|
+
title: entry.title ?? '',
|
|
246
|
+
mood: await moodLevelForEntry(entry),
|
|
247
|
+
tags: toJsonArray(entry.tags),
|
|
248
|
+
word_count: entry.word_count,
|
|
249
|
+
body: decrypted[i],
|
|
250
|
+
})));
|
|
251
|
+
}
|
|
252
|
+
/** Escape a value for inclusion in a CSV cell, quoting if necessary. */
|
|
253
|
+
function csvEscape(v) {
|
|
254
|
+
const s = v == null ? '' : String(v);
|
|
255
|
+
if (/[",\n\r]/.test(s))
|
|
256
|
+
return `"${s.replace(/"/g, '""')}"`;
|
|
257
|
+
return s;
|
|
258
|
+
}
|
|
259
|
+
/** Format export records as JSON / CSV / TXT. */
|
|
260
|
+
export function formatExport(records, format) {
|
|
261
|
+
if (format === 'json') {
|
|
262
|
+
return {
|
|
263
|
+
contentType: 'application/json; charset=utf-8',
|
|
264
|
+
body: JSON.stringify({ exported_at: new Date().toISOString(), records }, null, 2),
|
|
265
|
+
};
|
|
266
|
+
}
|
|
267
|
+
if (format === 'csv') {
|
|
268
|
+
const headers = ['id', 'date', 'title', 'mood', 'tags', 'word_count', 'body'];
|
|
269
|
+
const lines = [headers.join(',')];
|
|
270
|
+
for (const r of records) {
|
|
271
|
+
lines.push([r.id, r.date, r.title, r.mood, r.tags.join('|'), String(r.word_count), r.body]
|
|
272
|
+
.map(csvEscape)
|
|
273
|
+
.join(','));
|
|
274
|
+
}
|
|
275
|
+
return { contentType: 'text/csv; charset=utf-8', body: lines.join('\n') };
|
|
276
|
+
}
|
|
277
|
+
const out = [`Journal export — ${new Date().toISOString()}`, ''];
|
|
278
|
+
for (const r of records) {
|
|
279
|
+
out.push(`# ${r.date} • ${r.mood.toUpperCase()}`);
|
|
280
|
+
if (r.title)
|
|
281
|
+
out.push(`## ${r.title}`);
|
|
282
|
+
out.push('');
|
|
283
|
+
out.push(r.body);
|
|
284
|
+
if (r.tags.length > 0)
|
|
285
|
+
out.push(`Tags: ${r.tags.join(', ')}`);
|
|
286
|
+
out.push('');
|
|
287
|
+
out.push('-----');
|
|
288
|
+
out.push('');
|
|
289
|
+
}
|
|
290
|
+
return { contentType: 'text/plain; charset=utf-8', body: out.join('\n') };
|
|
291
|
+
}
|
package/dist/types.d.ts
ADDED
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Shared types for the journal-entry resource.
|
|
3
|
+
*
|
|
4
|
+
* @module
|
|
5
|
+
*/
|
|
6
|
+
/** Discrete mood-level labels mapped to a 1..5 score. */
|
|
7
|
+
export type MoodLevel = 'radiant' | 'good' | 'neutral' | 'low' | 'struggling';
|
|
8
|
+
/** Row shape persisted in `journal_entries`. */
|
|
9
|
+
export interface JournalEntryRow {
|
|
10
|
+
id: string;
|
|
11
|
+
user_id: string;
|
|
12
|
+
written_at: string | Date;
|
|
13
|
+
title: string | null;
|
|
14
|
+
body: string | null;
|
|
15
|
+
body_encrypted: string | null;
|
|
16
|
+
body_iv: string | null;
|
|
17
|
+
mood_id: string | null;
|
|
18
|
+
prompt_id: string | null;
|
|
19
|
+
activity_ids: unknown;
|
|
20
|
+
tags: unknown;
|
|
21
|
+
word_count: number;
|
|
22
|
+
ai_summary: string | null;
|
|
23
|
+
ai_themes: unknown;
|
|
24
|
+
is_private: boolean;
|
|
25
|
+
created_at: string | Date;
|
|
26
|
+
}
|
|
27
|
+
/** Row shape persisted in `mood_entries`. */
|
|
28
|
+
export interface MoodEntryRow {
|
|
29
|
+
id: string;
|
|
30
|
+
user_id: string;
|
|
31
|
+
recorded_at: string | Date;
|
|
32
|
+
score: number;
|
|
33
|
+
energy: number | null;
|
|
34
|
+
anxiety: number | null;
|
|
35
|
+
label: string | null;
|
|
36
|
+
activities: unknown;
|
|
37
|
+
notes: string | null;
|
|
38
|
+
journal_entry_id: string | null;
|
|
39
|
+
created_at: string | Date;
|
|
40
|
+
}
|
|
41
|
+
/** Public-facing decrypted entry (returned by the service / routes). */
|
|
42
|
+
export interface PublicJournalEntry {
|
|
43
|
+
id: string;
|
|
44
|
+
date: string;
|
|
45
|
+
title: string;
|
|
46
|
+
preview: string;
|
|
47
|
+
body: string;
|
|
48
|
+
mood: MoodLevel;
|
|
49
|
+
tags: string[];
|
|
50
|
+
word_count: number;
|
|
51
|
+
ai_summary: string | null;
|
|
52
|
+
ai_themes: string[];
|
|
53
|
+
prompt: string | null;
|
|
54
|
+
}
|
|
55
|
+
/** Maps each MoodLevel label to its corresponding numeric score (1..5). */
|
|
56
|
+
export declare const SCORE_BY_LEVEL: Record<MoodLevel, number>;
|
|
57
|
+
/** Round + clamp a raw score and return its discrete label. */
|
|
58
|
+
export declare function levelByScore(score: number | null | undefined): MoodLevel;
|
|
59
|
+
/** Normalize a 1..5 score to 0..1 (useful for sparkline charts). */
|
|
60
|
+
export declare function normalizeScore(score: number | null | undefined): number;
|
|
61
|
+
//# sourceMappingURL=types.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAEH,yDAAyD;AACzD,MAAM,MAAM,SAAS,GAAG,SAAS,GAAG,MAAM,GAAG,SAAS,GAAG,KAAK,GAAG,YAAY,CAAA;AAE7E,gDAAgD;AAChD,MAAM,WAAW,eAAe;IAC9B,EAAE,EAAE,MAAM,CAAA;IACV,OAAO,EAAE,MAAM,CAAA;IACf,UAAU,EAAE,MAAM,GAAG,IAAI,CAAA;IACzB,KAAK,EAAE,MAAM,GAAG,IAAI,CAAA;IACpB,IAAI,EAAE,MAAM,GAAG,IAAI,CAAA;IACnB,cAAc,EAAE,MAAM,GAAG,IAAI,CAAA;IAC7B,OAAO,EAAE,MAAM,GAAG,IAAI,CAAA;IACtB,OAAO,EAAE,MAAM,GAAG,IAAI,CAAA;IACtB,SAAS,EAAE,MAAM,GAAG,IAAI,CAAA;IACxB,YAAY,EAAE,OAAO,CAAA;IACrB,IAAI,EAAE,OAAO,CAAA;IACb,UAAU,EAAE,MAAM,CAAA;IAClB,UAAU,EAAE,MAAM,GAAG,IAAI,CAAA;IACzB,SAAS,EAAE,OAAO,CAAA;IAClB,UAAU,EAAE,OAAO,CAAA;IACnB,UAAU,EAAE,MAAM,GAAG,IAAI,CAAA;CAC1B;AAED,6CAA6C;AAC7C,MAAM,WAAW,YAAY;IAC3B,EAAE,EAAE,MAAM,CAAA;IACV,OAAO,EAAE,MAAM,CAAA;IACf,WAAW,EAAE,MAAM,GAAG,IAAI,CAAA;IAC1B,KAAK,EAAE,MAAM,CAAA;IACb,MAAM,EAAE,MAAM,GAAG,IAAI,CAAA;IACrB,OAAO,EAAE,MAAM,GAAG,IAAI,CAAA;IACtB,KAAK,EAAE,MAAM,GAAG,IAAI,CAAA;IACpB,UAAU,EAAE,OAAO,CAAA;IACnB,KAAK,EAAE,MAAM,GAAG,IAAI,CAAA;IACpB,gBAAgB,EAAE,MAAM,GAAG,IAAI,CAAA;IAC/B,UAAU,EAAE,MAAM,GAAG,IAAI,CAAA;CAC1B;AAED,wEAAwE;AACxE,MAAM,WAAW,kBAAkB;IACjC,EAAE,EAAE,MAAM,CAAA;IACV,IAAI,EAAE,MAAM,CAAA;IACZ,KAAK,EAAE,MAAM,CAAA;IACb,OAAO,EAAE,MAAM,CAAA;IACf,IAAI,EAAE,MAAM,CAAA;IACZ,IAAI,EAAE,SAAS,CAAA;IACf,IAAI,EAAE,MAAM,EAAE,CAAA;IACd,UAAU,EAAE,MAAM,CAAA;IAClB,UAAU,EAAE,MAAM,GAAG,IAAI,CAAA;IACzB,SAAS,EAAE,MAAM,EAAE,CAAA;IACnB,MAAM,EAAE,MAAM,GAAG,IAAI,CAAA;CACtB;AAED,2EAA2E;AAC3E,eAAO,MAAM,cAAc,EAAE,MAAM,CAAC,SAAS,EAAE,MAAM,CAMpD,CAAA;AAED,+DAA+D;AAC/D,wBAAgB,YAAY,CAAC,KAAK,EAAE,MAAM,GAAG,IAAI,GAAG,SAAS,GAAG,SAAS,CAGxE;AAED,oEAAoE;AACpE,wBAAgB,cAAc,CAAC,KAAK,EAAE,MAAM,GAAG,IAAI,GAAG,SAAS,GAAG,MAAM,CAGvE"}
|
package/dist/types.js
ADDED
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Shared types for the journal-entry resource.
|
|
3
|
+
*
|
|
4
|
+
* @module
|
|
5
|
+
*/
|
|
6
|
+
/** Maps each MoodLevel label to its corresponding numeric score (1..5). */
|
|
7
|
+
export const SCORE_BY_LEVEL = {
|
|
8
|
+
radiant: 5,
|
|
9
|
+
good: 4,
|
|
10
|
+
neutral: 3,
|
|
11
|
+
low: 2,
|
|
12
|
+
struggling: 1,
|
|
13
|
+
};
|
|
14
|
+
/** Round + clamp a raw score and return its discrete label. */
|
|
15
|
+
export function levelByScore(score) {
|
|
16
|
+
const n = Math.max(1, Math.min(5, Math.round(Number(score ?? 3))));
|
|
17
|
+
return ['struggling', 'low', 'neutral', 'good', 'radiant'][n - 1];
|
|
18
|
+
}
|
|
19
|
+
/** Normalize a 1..5 score to 0..1 (useful for sparkline charts). */
|
|
20
|
+
export function normalizeScore(score) {
|
|
21
|
+
if (score == null)
|
|
22
|
+
return 0.5;
|
|
23
|
+
return Math.max(0, Math.min(1, (Number(score) - 1) / 4));
|
|
24
|
+
}
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Zod schemas for journal-entry create / update payloads.
|
|
3
|
+
*
|
|
4
|
+
* @module
|
|
5
|
+
*/
|
|
6
|
+
import { z } from 'zod';
|
|
7
|
+
/** Mood level enum used by journal-entry payloads. */
|
|
8
|
+
export declare const moodLevelSchema: z.ZodEnum<{
|
|
9
|
+
radiant: "radiant";
|
|
10
|
+
good: "good";
|
|
11
|
+
neutral: "neutral";
|
|
12
|
+
low: "low";
|
|
13
|
+
struggling: "struggling";
|
|
14
|
+
}>;
|
|
15
|
+
/** Validator for creating a new journal entry. */
|
|
16
|
+
export declare const createEntrySchema: z.ZodObject<{
|
|
17
|
+
mood: z.ZodOptional<z.ZodEnum<{
|
|
18
|
+
radiant: "radiant";
|
|
19
|
+
good: "good";
|
|
20
|
+
neutral: "neutral";
|
|
21
|
+
low: "low";
|
|
22
|
+
struggling: "struggling";
|
|
23
|
+
}>>;
|
|
24
|
+
title: z.ZodOptional<z.ZodString>;
|
|
25
|
+
body: z.ZodString;
|
|
26
|
+
tags: z.ZodOptional<z.ZodArray<z.ZodString>>;
|
|
27
|
+
prompt_id: z.ZodOptional<z.ZodString>;
|
|
28
|
+
written_at: z.ZodOptional<z.ZodString>;
|
|
29
|
+
}, z.core.$strip>;
|
|
30
|
+
/** Validator for updating an existing journal entry. */
|
|
31
|
+
export declare const updateEntrySchema: z.ZodObject<{
|
|
32
|
+
mood: z.ZodOptional<z.ZodOptional<z.ZodEnum<{
|
|
33
|
+
radiant: "radiant";
|
|
34
|
+
good: "good";
|
|
35
|
+
neutral: "neutral";
|
|
36
|
+
low: "low";
|
|
37
|
+
struggling: "struggling";
|
|
38
|
+
}>>>;
|
|
39
|
+
title: z.ZodOptional<z.ZodOptional<z.ZodString>>;
|
|
40
|
+
tags: z.ZodOptional<z.ZodOptional<z.ZodArray<z.ZodString>>>;
|
|
41
|
+
prompt_id: z.ZodOptional<z.ZodOptional<z.ZodString>>;
|
|
42
|
+
written_at: z.ZodOptional<z.ZodOptional<z.ZodString>>;
|
|
43
|
+
body: z.ZodOptional<z.ZodString>;
|
|
44
|
+
}, z.core.$strip>;
|
|
45
|
+
//# sourceMappingURL=validation.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"validation.d.ts","sourceRoot":"","sources":["../src/validation.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAEH,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAA;AAIvB,sDAAsD;AACtD,eAAO,MAAM,eAAe;;;;;;EAAsB,CAAA;AAElD,kDAAkD;AAClD,eAAO,MAAM,iBAAiB;;;;;;;;;;;;;iBAO5B,CAAA;AAEF,wDAAwD;AACxD,eAAO,MAAM,iBAAiB;;;;;;;;;;;;;iBAE5B,CAAA"}
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Zod schemas for journal-entry create / update payloads.
|
|
3
|
+
*
|
|
4
|
+
* @module
|
|
5
|
+
*/
|
|
6
|
+
import { z } from 'zod';
|
|
7
|
+
const MOOD_VALUES = ['radiant', 'good', 'neutral', 'low', 'struggling'];
|
|
8
|
+
/** Mood level enum used by journal-entry payloads. */
|
|
9
|
+
export const moodLevelSchema = z.enum(MOOD_VALUES);
|
|
10
|
+
/** Validator for creating a new journal entry. */
|
|
11
|
+
export const createEntrySchema = z.object({
|
|
12
|
+
mood: moodLevelSchema.optional(),
|
|
13
|
+
title: z.string().max(240).optional(),
|
|
14
|
+
body: z.string().min(1).max(50_000),
|
|
15
|
+
tags: z.array(z.string().min(1).max(64)).max(50).optional(),
|
|
16
|
+
prompt_id: z.string().uuid().optional(),
|
|
17
|
+
written_at: z.string().optional(),
|
|
18
|
+
});
|
|
19
|
+
/** Validator for updating an existing journal entry. */
|
|
20
|
+
export const updateEntrySchema = createEntrySchema.partial().extend({
|
|
21
|
+
body: z.string().min(1).max(50_000).optional(),
|
|
22
|
+
});
|
package/package.json
ADDED
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@molecule/api-resource-journal-entry",
|
|
3
|
+
"version": "1.0.0",
|
|
4
|
+
"description": "Owner-scoped journal entry resource with optional at-rest encryption, mood linkage, daily streaks, and JSON/CSV/TXT export. Extracted from mental-health-journal flagship.",
|
|
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
|
+
"journal",
|
|
25
|
+
"diary",
|
|
26
|
+
"mood",
|
|
27
|
+
"encryption",
|
|
28
|
+
"resource"
|
|
29
|
+
],
|
|
30
|
+
"license": "Apache-2.0",
|
|
31
|
+
"devDependencies": {
|
|
32
|
+
"@types/express": "5.0.6",
|
|
33
|
+
"@types/node": "26.1.2",
|
|
34
|
+
"express": "5.2.1",
|
|
35
|
+
"typescript": "6.0.3",
|
|
36
|
+
"vitest": "4.1.10",
|
|
37
|
+
"zod": "4.4.3"
|
|
38
|
+
},
|
|
39
|
+
"peerDependencies": {
|
|
40
|
+
"@molecule/api-bonds-default-express": "^1.0.0",
|
|
41
|
+
"@molecule/api-logger": "^1.0.0",
|
|
42
|
+
"@molecule/api-database": "^1.0.0",
|
|
43
|
+
"@molecule/api-encryption": "^1.0.0",
|
|
44
|
+
"@molecule/api-i18n": "^1.0.0",
|
|
45
|
+
"@molecule/api-middleware-validation": "^1.0.0",
|
|
46
|
+
"express": "^5.0.0",
|
|
47
|
+
"zod": "^4.0.0"
|
|
48
|
+
}
|
|
49
|
+
}
|