@nan0web/communication.app 0.0.0-stage → 0.1.1

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,15 @@
1
+ ISC License
2
+
3
+ Copyright (c) 2025, ЯRаСлав (YaRaSLove) <support@yaro.page>
4
+
5
+ Permission to use, copy, modify, and distribute this software for any purpose
6
+ with or without fee is hereby granted, provided that the above copyright notice
7
+ and this permission notice appear in all copies.
8
+
9
+ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
10
+ REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
11
+ AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
12
+ INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
13
+ LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
14
+ OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
15
+ PERFORMANCE OF THIS SOFTWARE.
package/bin/nan0com.js ADDED
@@ -0,0 +1,16 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * @file CLI entry point for @nan0web/communication.app (nan0com).
4
+ */
5
+ import { bootstrapApp } from '@nan0web/ui-cli'
6
+ import { CommunicationApp } from '../src/domain/CommunicationApp.js'
7
+ import { GitTransport } from '../src/infra/GitTransport.js'
8
+ import { Notifier } from '../src/infra/Notifier.js'
9
+
10
+ const git = new GitTransport()
11
+ const notify = new Notifier()
12
+
13
+ bootstrapApp(CommunicationApp, { root: '.', git, notify }).catch((err) => {
14
+ console.error(err)
15
+ process.exit(1)
16
+ })
package/package.json CHANGED
@@ -1,6 +1,37 @@
1
1
  {
2
2
  "name": "@nan0web/communication.app",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "0.1.1",
4
+ "description": "Sovereign Git-based messenger and co-creation space (7iOS.CoCreation)",
5
+ "type": "module",
6
+ "main": "src/index.js",
7
+ "bin": {
8
+ "nan0com": "./bin/nan0com.js"
9
+ },
10
+ "exports": {
11
+ ".": "./src/index.js"
12
+ },
13
+ "devDependencies": {
14
+ "@types/node": "^25.6.0",
15
+ "knip": "^5.88.1",
16
+ "typescript": "^5.7.3",
17
+ "@nan0web/inspect": "3.11.1",
18
+ "@nan0web/test": "3.4.0"
19
+ },
20
+ "files": [
21
+ "src/**/*.js",
22
+ "types/**/*.d.ts",
23
+ "!src/**/*.{test,story}.js",
24
+ "!src/test/**",
25
+ "README.md"
26
+ ],
27
+ "scripts": {
28
+ "build": "tsc",
29
+ "test": "node --test \"src/**/*.{test,story}.js\"",
30
+ "test:stories": "node --test \"src/**/*.story.js\"",
31
+ "release:spec": "node --test \"releases/0/1/v0.1.1/task.spec.js\"",
32
+ "release:validate": "nan0inspect release --non-interactive",
33
+ "inspect": "nan0inspect domain --non-interactive",
34
+ "knip": "knip --production",
35
+ "test:all": "npm run build && npm run test && npm run release:spec && npm run inspect && npm run knip && npm run release:validate"
36
+ }
6
37
  }
@@ -0,0 +1,157 @@
1
+ import { ModelError } from '@nan0web/types'
2
+ import { ModelAsApp } from '@nan0web/ui'
3
+ import Markdown from '@nan0web/markdown'
4
+
5
+ /**
6
+ * Formats an author identifier into a filename-safe slug.
7
+ * @param {string} author
8
+ * @returns {string}
9
+ */
10
+ function slugifyAuthor(author) {
11
+ return String(author || 'anon')
12
+ .trim()
13
+ .toLowerCase()
14
+ .replace(/[^a-z0-9_-]+/g, '-')
15
+ .replace(/^-+|-+$/g, '')
16
+ }
17
+
18
+ /**
19
+ * Computes deterministic 2-level prefix shard URI: chats/<xx>/<yy>/<chatId>.
20
+ * @param {string} chatId
21
+ * @param {string} [base='chats']
22
+ * @returns {string}
23
+ */
24
+ export function resolveChatShardUri(chatId, base = 'chats') {
25
+ const slug = slugifyAuthor(chatId)
26
+ let hash = 2166136261
27
+ for (let i = 0; i < slug.length; i += 1) {
28
+ hash ^= slug.charCodeAt(i)
29
+ hash = Math.imul(hash, 16777619)
30
+ }
31
+ const hex = (hash >>> 0).toString(16).padStart(8, '0')
32
+ return `${base}/${hex.slice(0, 2)}/${hex.slice(2, 4)}/${slug}`
33
+ }
34
+
35
+ /**
36
+ * Serializes a chat message into Markdown with metadata header.
37
+ * @param {{ author: string, timestamp: string, text: string }} msg
38
+ * @returns {string}
39
+ */
40
+ function formatMessageMarkdown(msg) {
41
+ return [
42
+ '---',
43
+ `author: ${msg.author}`,
44
+ `timestamp: ${msg.timestamp}`,
45
+ '---',
46
+ '',
47
+ msg.text,
48
+ '',
49
+ ].join('\n')
50
+ }
51
+
52
+ /**
53
+ * Parses a serialized chat message Markdown document using @nan0web/markdown.
54
+ * @param {string} raw
55
+ * @returns {{ author: string, timestamp: string, text: string }}
56
+ */
57
+ export function parseMessageMarkdown(raw) {
58
+ const md = new Markdown()
59
+ const { content, metadata } = md.parseFrontmatter(String(raw || ''))
60
+ return {
61
+ author: String(metadata.author || ''),
62
+ timestamp: String(metadata.timestamp || ''),
63
+ text: String(content || '').trim(),
64
+ }
65
+ }
66
+
67
+ /**
68
+ * 2D Git-native chat repository with time-sharded Markdown messages.
69
+ */
70
+ export class ChatRepoModel extends ModelAsApp {
71
+ static UI = {
72
+ errorAuthorTextRequired: 'Author and text are required',
73
+ }
74
+
75
+ static repo = {
76
+ help: 'Repository base URI (e.g. chats/<xx>/<yy>/<chatId> or we/<circle>/<name>)',
77
+ default: '',
78
+ }
79
+
80
+ /**
81
+ * @param {Partial<ChatRepoModel>} [data]
82
+ * @param {Partial<import('@nan0web/types').ModelOptions>} [options]
83
+ */
84
+ constructor(data = {}, options = {}) {
85
+ super(data, options)
86
+ /** @type {string} Repository base URI */ this.repo
87
+ }
88
+
89
+ /**
90
+ * Sends and persists a message in chat/YYYY/MM/DD/<ts>-<peer>.md and optionally updates README.md.
91
+ * @param {{ author: string, text: string, timestamp?: string, skipIndex?: boolean }} input
92
+ * @returns {Promise<{ uri: string, filename: string, author: string, timestamp: string, text: string }>}
93
+ */
94
+ async sendMessage(input) {
95
+ const { author, text, timestamp = new Date().toISOString(), skipIndex = false } = input || {}
96
+ if (!author || !text) {
97
+ throw new ModelError({ message: this._.t(ChatRepoModel.UI.errorAuthorTextRequired) })
98
+ }
99
+ const [datePart, timePart = '00:00:00.000Z'] = String(timestamp).split('T')
100
+ const [year, month, day] = datePart.split('-')
101
+ const tsSlug = timePart.replace(/[:.]/g, '').replace(/Z$/, '')
102
+ const baseName = `${tsSlug}-${slugifyAuthor(author)}`
103
+ const dayDir = this.$db.normalize(this.repo, 'chat', year, month, day)
104
+
105
+ let filename = `${baseName}.md`
106
+ let uri = this.$db.normalize(dayDir, filename)
107
+ let seq = 1
108
+ while (await this.$db.loadDocument(uri, null)) {
109
+ filename = `${baseName}-${seq}.md`
110
+ uri = this.$db.normalize(dayDir, filename)
111
+ seq += 1
112
+ }
113
+
114
+ await this.$db.saveDocument(uri, formatMessageMarkdown({ author, timestamp, text }))
115
+ if (!skipIndex) {
116
+ await this.#appendDayIndex(dayDir, { filename, author, timestamp })
117
+ }
118
+
119
+ return { uri, filename, author, timestamp, text }
120
+ }
121
+
122
+ /**
123
+ * Lists all messages for a given YYYY-MM-DD date in chronological order.
124
+ * @param {string} dateStr
125
+ * @returns {Promise<Array<{ uri: string, filename: string, author: string, timestamp: string, text: string }>>}
126
+ */
127
+ async listDay(dateStr) {
128
+ const [year, month, day] = String(dateStr || '').split('-')
129
+ const dayDir = this.$db.normalize(this.repo, 'chat', year, month, day)
130
+ const entries = await this.$db.listDir(dayDir)
131
+ const files = entries
132
+ .filter((e) => e.isFile && e.name.endsWith('.md') && e.name !== 'README.md')
133
+ .sort((a, b) => a.name.localeCompare(b.name))
134
+
135
+ const messages = []
136
+ for (const entry of files) {
137
+ const uri = this.$db.normalize(dayDir, entry.name)
138
+ const raw = await this.$db.loadDocument(uri, '')
139
+ const parsed = parseMessageMarkdown(String(raw))
140
+ messages.push({ uri, filename: entry.name, ...parsed })
141
+ }
142
+ return messages
143
+ }
144
+
145
+ /**
146
+ * Appends a deterministic index line to chat/YYYY/MM/DD/README.md.
147
+ * @param {string} dayDir
148
+ * @param {{ filename: string, author: string, timestamp: string }} item
149
+ */
150
+ async #appendDayIndex(dayDir, item) {
151
+ const indexUri = this.$db.normalize(dayDir, 'README.md')
152
+ const existing = await this.$db.loadDocument(indexUri, '')
153
+ const header = existing ? String(existing).trimEnd() : `# Chat Index (${dayDir})`
154
+ const line = `- [${item.timestamp}] **${item.author}** -> [${item.filename}](./${item.filename})`
155
+ await this.$db.saveDocument(indexUri, `${header}\n${line}\n`)
156
+ }
157
+ }