@nanostores/logger 0.1.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,20 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright 2020 Eduard Aksamitov <e@euaaaio.ru>
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy of
6
+ this software and associated documentation files (the "Software"), to deal in
7
+ the Software without restriction, including without limitation the rights to
8
+ use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
9
+ the Software, and to permit persons to whom the Software is furnished to do so,
10
+ subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
17
+ FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
18
+ COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
19
+ IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
20
+ CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,12 @@
1
+ # Nano Stores Logger
2
+
3
+ <img align="right" width="92" height="92" title="Nano Stores logo"
4
+ src="https://nanostores.github.io/nanostores/logo.svg">
5
+
6
+ Logger of lifecycles, actions and changes for **[Nano Stores]**,
7
+ a tiny state manager with many atomic tree-shakable stores.
8
+
9
+ [Nano Stores]: https://github.com/nanostores/nanostores/
10
+
11
+ ## Docs
12
+ Read full docs **[here](https://github.com/nanostores/logger#readme)**.
package/index.d.ts ADDED
@@ -0,0 +1 @@
1
+ export { logger } from './logger/index.js'
package/index.js ADDED
@@ -0,0 +1 @@
1
+ export { logger } from './logger/index.js'
@@ -0,0 +1,57 @@
1
+ import type { AnyStore } from 'nanostores'
2
+
3
+ interface LoggerOptionsMessages {
4
+ /**
5
+ * Disable action logs.
6
+ */
7
+ action?: boolean
8
+
9
+ /**
10
+ * Disable change logs.
11
+ */
12
+ change?: boolean
13
+
14
+ /**
15
+ * Disable mount logs.
16
+ */
17
+ mount?: boolean
18
+
19
+ /**
20
+ * Disable unmount logs.
21
+ */
22
+ unmount?: boolean
23
+ }
24
+
25
+ interface LoggerOptions {
26
+ /**
27
+ * Disable action logs with specific name.
28
+ */
29
+ ignoreActions?: string[]
30
+
31
+ /**
32
+ * Disable specific log types.
33
+ */
34
+ messages?: LoggerOptionsMessages
35
+ }
36
+
37
+ /**
38
+ * Display Nanostores events in browser console.
39
+ *
40
+ * ```js
41
+ * import { logger } from '@nanostores/logger'
42
+ * import { $profile, $users } from './stores/index.js'
43
+ *
44
+ * let destroy = logger({
45
+ * 'Profile Store': $profile,
46
+ * 'Users Store': $users
47
+ * })
48
+ * ```
49
+ *
50
+ * @param stores Stores for logging.
51
+ * @param opts Logger options.
52
+ * @returns A function to destroy logger.
53
+ */
54
+ export function logger(
55
+ stores: { [key: string]: AnyStore },
56
+ opts?: LoggerOptions
57
+ ): () => void
@@ -0,0 +1,260 @@
1
+ import {
2
+ actionId,
3
+ lastAction,
4
+ onAction,
5
+ onMount,
6
+ onNotify,
7
+ onSet
8
+ } from 'nanostores'
9
+
10
+ function badge(color) {
11
+ return `
12
+ padding: 0 5px 2px;
13
+ margin-right: 5px;
14
+ font-weight: 400;
15
+ color: white;
16
+ background-color: ${color};
17
+ `
18
+ }
19
+
20
+ function borders(full) {
21
+ return `border-radius: ${full ? '4px' : '0 4px 4px 0'};`
22
+ }
23
+
24
+ const STYLES = {
25
+ badges: {
26
+ action: badge('#5351A4'),
27
+ arguments: badge('#429BD7'),
28
+ change: badge('#0E8A00'),
29
+ error: badge('#c21f1f'),
30
+ mount: badge('#1F49E0'),
31
+ new: badge('#4FA574'),
32
+ old: badge('#a44f4f'),
33
+ unmount: badge('#5C5C5C'),
34
+ value: badge('#429BD7')
35
+ },
36
+ bold: 'font-weight: 700',
37
+ logo: `
38
+ padding: 0 5px 2px;
39
+ color: white;
40
+ background-color: black;
41
+ border-radius: 4px 0 0 4px;
42
+ `,
43
+ regular: 'font-weight: 400'
44
+ }
45
+
46
+ function createLog({ logo, message, type, value }) {
47
+ let template = ''
48
+ let args = []
49
+
50
+ if (logo) {
51
+ template = `%c𝖓`
52
+ args.push(STYLES.logo)
53
+ }
54
+
55
+ template += `%c${type}`
56
+ args.push(STYLES.badges[type] + borders(!logo))
57
+
58
+ if (message) {
59
+ if (Array.isArray(message)) {
60
+ message.forEach(([style, text]) => {
61
+ template += `%c ${text}`
62
+ args.push(STYLES[style])
63
+ })
64
+ } else {
65
+ template += `%c ${message}`
66
+ args.push(STYLES.text)
67
+ }
68
+ }
69
+
70
+ if (value) {
71
+ args.push(value)
72
+ }
73
+
74
+ args.unshift(template)
75
+
76
+ return args
77
+ }
78
+
79
+ const log = args => console.log(...createLog(args))
80
+ const group = args => console.groupCollapsed(...createLog(args))
81
+ const groupEnd = () => console.groupEnd()
82
+
83
+ const isAtom = store => store.setKey === undefined
84
+ const isDeepMapKey = key => /.+(\..+|\[\d+\.*])/.test(key)
85
+
86
+ function handleMount(store, storeName, messages) {
87
+ return onMount(store, () => {
88
+ if (messages.mount !== false) {
89
+ log({
90
+ logo: true,
91
+ message: [
92
+ ['bold', storeName],
93
+ ['regular', 'store was mounted']
94
+ ],
95
+ type: 'mount'
96
+ })
97
+ }
98
+ return () => {
99
+ if (messages.unmount !== false) {
100
+ log({
101
+ logo: true,
102
+ message: [
103
+ ['bold', storeName],
104
+ ['regular', 'store was unmounted']
105
+ ],
106
+ type: 'unmount'
107
+ })
108
+ }
109
+ }
110
+ })
111
+ }
112
+
113
+ function handleAction(store, storeName, queue, ignoreActions) {
114
+ return onAction(store, ({ actionName, args, id, onEnd, onError }) => {
115
+ if (ignoreActions && ignoreActions.includes(actionName)) return
116
+
117
+ queue[id] = []
118
+
119
+ let message = [
120
+ ['bold', storeName],
121
+ ['regular', 'store was changed by action'],
122
+ ['bold', actionName]
123
+ ]
124
+
125
+ queue[id].push(() =>
126
+ group({
127
+ logo: true,
128
+ message,
129
+ type: 'action'
130
+ })
131
+ )
132
+ if (args.length > 0) {
133
+ message.push(['regular', 'with arguments'])
134
+ queue[id].push(() =>
135
+ log({
136
+ type: 'arguments',
137
+ value: args
138
+ })
139
+ )
140
+ }
141
+
142
+ onError(({ error }) => {
143
+ queue[id].push(() =>
144
+ log({
145
+ message: [
146
+ ['bold', storeName],
147
+ ['regular', 'store handled error in action'],
148
+ ['bold', actionName]
149
+ ],
150
+ type: 'error',
151
+ value: {
152
+ message: error.message
153
+ }
154
+ })
155
+ )
156
+ })
157
+
158
+ onEnd(() => {
159
+ for (let i of queue[id]) i()
160
+ delete queue[id]
161
+ groupEnd()
162
+ })
163
+ })
164
+ }
165
+
166
+ function handleSet(store, storeName, queue, messages, ignoreActions) {
167
+ return onSet(store, ({ changed }) => {
168
+ let currentActionId = store[actionId]
169
+ let currentActionName = store[lastAction]
170
+
171
+ if (messages.action === false && currentActionId) return
172
+ if (ignoreActions && ignoreActions.includes(currentActionName)) return
173
+
174
+ let groupLog = {
175
+ logo: typeof currentActionId === 'undefined',
176
+ message: [
177
+ ['bold', storeName],
178
+ ['regular', 'store was changed']
179
+ ],
180
+ type: 'change'
181
+ }
182
+ if (changed) {
183
+ groupLog.message.push(
184
+ ['regular', 'in the'],
185
+ ['bold', changed],
186
+ ['regular', 'key']
187
+ )
188
+ }
189
+
190
+ let oldValue = isAtom(store) ? store.value : { ...store.value }
191
+ oldValue = isDeepMapKey(changed) ? structuredClone(oldValue) : oldValue
192
+ let unbindNotify = onNotify(store, () => {
193
+ let newValue = store.value
194
+ let valueMessage
195
+ if (changed && !isDeepMapKey(changed)) {
196
+ valueMessage = `${oldValue[changed]} → ${newValue[changed]}`
197
+ }
198
+
199
+ let run = () => {
200
+ group(groupLog)
201
+ if (valueMessage) {
202
+ log({
203
+ message: valueMessage,
204
+ type: 'value'
205
+ })
206
+ }
207
+ log({
208
+ type: 'new',
209
+ value: newValue
210
+ })
211
+ if (oldValue) {
212
+ log({
213
+ type: 'old',
214
+ value: oldValue
215
+ })
216
+ }
217
+ groupEnd()
218
+ }
219
+
220
+ if (currentActionId) {
221
+ queue[currentActionId].push(run)
222
+ } else {
223
+ run()
224
+ }
225
+ unbindNotify()
226
+ })
227
+ })
228
+ }
229
+
230
+ function createLogger(store, storeName, opts) {
231
+ let ignoreActions = opts.ignoreActions
232
+ let messages = opts.messages || {}
233
+ let unbind = []
234
+ let queue = {}
235
+
236
+ if (messages.mount !== false || messages.unmount !== false) {
237
+ unbind.push(handleMount(store, storeName, messages))
238
+ }
239
+
240
+ if (messages.action !== false) {
241
+ unbind.push(handleAction(store, storeName, queue, ignoreActions))
242
+ }
243
+
244
+ if (messages.change !== false) {
245
+ unbind.push(handleSet(store, storeName, queue, messages, ignoreActions))
246
+ }
247
+
248
+ return () => {
249
+ for (let i of unbind) i()
250
+ }
251
+ }
252
+
253
+ export function logger(stores, opts = {}) {
254
+ let unbind = Object.entries(stores).map(([storeName, store]) =>
255
+ createLogger(store, storeName, opts)
256
+ )
257
+ return () => {
258
+ for (let i of unbind) i()
259
+ }
260
+ }
package/package.json ADDED
@@ -0,0 +1,35 @@
1
+ {
2
+ "name": "@nanostores/logger",
3
+ "version": "0.1.0",
4
+ "description": "Logger of lifecycles, actions and changes for Nano Stores",
5
+ "keywords": [
6
+ "nanostores",
7
+ "devtools",
8
+ "logger",
9
+ "store",
10
+ "state",
11
+ "nano"
12
+ ],
13
+ "author": "Eduard Aksamitov <e@euaaaio.ru>",
14
+ "license": "MIT",
15
+ "repository": "nanostores/logger",
16
+ "sideEffects": false,
17
+ "type": "module",
18
+ "types": "./index.d.ts",
19
+ "exports": {
20
+ ".": "./index.js",
21
+ "./package.json": "./package.json"
22
+ },
23
+ "engines": {
24
+ "node": "^18.0.0 || >=20.0.0"
25
+ },
26
+ "peerDependencies": {
27
+ "nanostores": ">=0.9.2"
28
+ },
29
+ "nano-staged": {
30
+ "*.{js,ts}": [
31
+ "prettier --write",
32
+ "eslint --fix"
33
+ ]
34
+ }
35
+ }