@eliware/common 15.0.0 → 15.2.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.
Files changed (193) hide show
  1. package/AGENTS.md +7 -5
  2. package/README.md +12 -12
  3. package/RELEASE_NOTES.md +54 -0
  4. package/docs/README.md +10 -4
  5. package/docs/api.md +35 -164
  6. package/docs/logging.md +66 -0
  7. package/docs/package.md +44 -30
  8. package/docs/paths.md +57 -0
  9. package/docs/process-errors.md +62 -0
  10. package/docs/redaction.md +115 -0
  11. package/docs/signals.md +67 -0
  12. package/docs/snowflake-ids.md +77 -0
  13. package/docs/troubleshooting.md +33 -29
  14. package/docs/usage.md +42 -138
  15. package/package.json +28 -8
  16. package/specs/README.md +6 -0
  17. package/specs/directives.yaml +11 -6
  18. package/specs/errors.yaml +23 -0
  19. package/specs/log.yaml +19 -0
  20. package/specs/path.yaml +18 -0
  21. package/specs/redact.yaml +20 -0
  22. package/specs/signals.yaml +16 -0
  23. package/specs/snowflake.yaml +18 -0
  24. package/src/errors/cleanup/abort-listener.mjs +19 -0
  25. package/src/errors/cleanup/attached-handlers.mjs +30 -0
  26. package/src/errors/cleanup/detached-state.mjs +8 -0
  27. package/src/errors/cleanup/finalize.mjs +5 -0
  28. package/src/errors/cleanup/listener.mjs +27 -0
  29. package/src/errors/cleanup.mjs +43 -0
  30. package/src/errors/constants.mjs +1 -0
  31. package/src/errors/event/handler.mjs +38 -0
  32. package/src/errors/event/one-shot.mjs +37 -0
  33. package/src/errors/event-handlers.mjs +33 -0
  34. package/src/errors/failure.mjs +10 -0
  35. package/src/errors/finalize.mjs +27 -0
  36. package/src/errors/handler-removal.mjs +18 -0
  37. package/src/errors/index.d.mts +28 -0
  38. package/src/errors/index.d.ts +28 -0
  39. package/src/errors/index.mjs +6 -0
  40. package/src/errors/logging/diagnostic.mjs +9 -0
  41. package/src/errors/logging/error-diagnostic.mjs +5 -0
  42. package/src/errors/logging/value-diagnostic.mjs +5 -0
  43. package/src/errors/logging.mjs +10 -0
  44. package/src/errors/registration/events.mjs +9 -0
  45. package/src/errors/registration/lifecycle.mjs +18 -0
  46. package/src/errors/registration/registry.mjs +5 -0
  47. package/src/errors/registration/setup-state.mjs +20 -0
  48. package/src/errors/registration/state.mjs +28 -0
  49. package/src/errors/registration.mjs +80 -0
  50. package/src/errors/setup/installation.mjs +52 -0
  51. package/src/errors/setup/rollback.mjs +35 -0
  52. package/src/errors/setup.mjs +7 -0
  53. package/src/errors/validation/events.mjs +17 -0
  54. package/src/errors/validation/logger.mjs +8 -0
  55. package/src/errors/validation/process-object.mjs +11 -0
  56. package/src/errors/validation/signal.mjs +9 -0
  57. package/src/index.d.ts +14 -14
  58. package/src/index.mjs +9 -7
  59. package/src/log/child-logger.mjs +5 -0
  60. package/src/log/configuration/build-logger.mjs +13 -0
  61. package/src/log/configuration/default-options.mjs +5 -0
  62. package/src/log/configuration/normalize-options.mjs +14 -0
  63. package/src/log/configuration/validate-options.mjs +16 -0
  64. package/src/log/create-logger.mjs +18 -0
  65. package/src/log/formats/json-record.mjs +19 -0
  66. package/src/log/formats/json.mjs +38 -0
  67. package/src/log/formats/message.mjs +13 -0
  68. package/src/log/formats/text.mjs +21 -0
  69. package/src/log/index.d.mts +74 -0
  70. package/src/log/index.d.ts +74 -0
  71. package/src/log/index.mjs +15 -0
  72. package/src/log/logger-levels.mjs +37 -0
  73. package/src/path/base.mjs +17 -0
  74. package/src/path/conversions.mjs +7 -0
  75. package/src/path/create-path-helpers.mjs +58 -0
  76. package/src/path/current-path.mjs +13 -0
  77. package/src/path/file-url-to-path.mjs +5 -0
  78. package/src/path/index.d.mts +66 -0
  79. package/src/path/index.d.ts +66 -0
  80. package/src/path/index.mjs +12 -0
  81. package/src/path/input-classification.mjs +11 -0
  82. package/src/path/operation/failure.mjs +12 -0
  83. package/src/path/operation/logging.mjs +24 -0
  84. package/src/redact/headers/inspect-header-input.mjs +17 -0
  85. package/src/redact/headers/redact/entries.mjs +33 -0
  86. package/src/redact/headers/redact/headers.mjs +12 -0
  87. package/src/redact/headers/valid-entries.mjs +15 -0
  88. package/src/redact/index.d.mts +49 -0
  89. package/src/redact/index.d.ts +49 -0
  90. package/src/redact/index.mjs +7 -0
  91. package/src/redact/inspection/add-truncation-marker.mjs +13 -0
  92. package/src/redact/inspection/copy-error-fields.mjs +20 -0
  93. package/src/redact/inspection/inspect/entries.mjs +15 -0
  94. package/src/redact/inspection/inspect/error-fields.mjs +44 -0
  95. package/src/redact/inspection/safe-entries.mjs +7 -0
  96. package/src/redact/limits/default-limits.mjs +6 -0
  97. package/src/redact/limits/normalize/output-limit.mjs +8 -0
  98. package/src/redact/limits/normalize/traversal-limits.mjs +12 -0
  99. package/src/redact/markers/default-marker.mjs +1 -0
  100. package/src/redact/policy/create/policy.mjs +9 -0
  101. package/src/redact/policy/create/readonly-set.mjs +31 -0
  102. package/src/redact/policy/default/key-names.mjs +23 -0
  103. package/src/redact/policy/default/policy.mjs +9 -0
  104. package/src/redact/policy/normalize/keys.mjs +13 -0
  105. package/src/redact/policy/normalize-policy.mjs +14 -0
  106. package/src/redact/serialization/safe-serialize.mjs +34 -0
  107. package/src/redact/serialization/serialize/array.mjs +13 -0
  108. package/src/redact/serialization/serialize/buffer.mjs +5 -0
  109. package/src/redact/serialization/serialize/error.mjs +12 -0
  110. package/src/redact/serialization/serialize/object.mjs +22 -0
  111. package/src/redact/serialization/serialize/primitive.mjs +21 -0
  112. package/src/redact/structured/redact/array/attempt.mjs +9 -0
  113. package/src/redact/structured/redact/array/index-name.mjs +12 -0
  114. package/src/redact/structured/redact/array/indices.mjs +18 -0
  115. package/src/redact/structured/redact/array/properties.mjs +60 -0
  116. package/src/redact/structured/redact/array/result.mjs +11 -0
  117. package/src/redact/structured/redact/array.mjs +26 -0
  118. package/src/redact/structured/redact/classify.mjs +13 -0
  119. package/src/redact/structured/redact/error-fields.mjs +6 -0
  120. package/src/redact/structured/redact/error.mjs +14 -0
  121. package/src/redact/structured/redact/object.mjs +23 -0
  122. package/src/redact/structured/redact/value.mjs +49 -0
  123. package/src/redact/text/apply/configured/rules.mjs +9 -0
  124. package/src/redact/text/apply/configured/text-redactions.mjs +11 -0
  125. package/src/redact/text/apply/redactions.mjs +17 -0
  126. package/src/redact/text/apply/text-rules.mjs +8 -0
  127. package/src/redact/text/boundary/detect-jwt.mjs +18 -0
  128. package/src/redact/text/boundary/finish.mjs +15 -0
  129. package/src/redact/text/boundary/input.mjs +10 -0
  130. package/src/redact/text/boundary/jwt.mjs +22 -0
  131. package/src/redact/text/boundary/prepare.mjs +16 -0
  132. package/src/redact/text/boundary/process.mjs +9 -0
  133. package/src/redact/text/boundary/redaction.mjs +20 -0
  134. package/src/redact/text/boundary/secrets.mjs +21 -0
  135. package/src/redact/text/limit-output.mjs +12 -0
  136. package/src/redact/text/patterns/secret-key-patterns.mjs +2 -0
  137. package/src/redact/text/redact-text.mjs +8 -0
  138. package/src/redact/text/replace-literal/matches.mjs +39 -0
  139. package/src/redact/text/replace-literal/secret.mjs +6 -0
  140. package/src/redact/text/replace-literal/secrets.mjs +18 -0
  141. package/src/redact/text/replace-literal/trie.mjs +36 -0
  142. package/src/redact/text/rules/built-in.mjs +8 -0
  143. package/src/redact/text/rules/redact/authorization.mjs +12 -0
  144. package/src/redact/text/rules/redact/jwt/pattern.mjs +2 -0
  145. package/src/redact/text/rules/redact/jwt.mjs +10 -0
  146. package/src/redact/text/rules/redact/key/configured-values.mjs +25 -0
  147. package/src/redact/text/rules/redact/key/material.mjs +9 -0
  148. package/src/redact/text/rules/redact/key/values.mjs +16 -0
  149. package/src/redact/text/rules/redact/provider-token.mjs +9 -0
  150. package/src/signals/index.d.mts +29 -0
  151. package/src/signals/index.d.ts +29 -0
  152. package/src/signals/index.mjs +1 -0
  153. package/src/signals/lifecycle/abort/aggregate-cleanup.mjs +21 -0
  154. package/src/signals/lifecycle/abort/cleanup.mjs +9 -0
  155. package/src/signals/lifecycle/abort/listener-registration.mjs +14 -0
  156. package/src/signals/lifecycle/abort/listener.mjs +16 -0
  157. package/src/signals/lifecycle/abort/registration-cleanup.mjs +14 -0
  158. package/src/signals/lifecycle/abort/registration.mjs +19 -0
  159. package/src/signals/lifecycle/before/exit-registration.mjs +36 -0
  160. package/src/signals/lifecycle/before/exit.mjs +33 -0
  161. package/src/signals/lifecycle/cleanup/process-handlers.mjs +27 -0
  162. package/src/signals/lifecycle/cleanup/registration.mjs +5 -0
  163. package/src/signals/lifecycle/cleanup.mjs +17 -0
  164. package/src/signals/lifecycle/defaults.mjs +1 -0
  165. package/src/signals/lifecycle/exit-policy.mjs +17 -0
  166. package/src/signals/lifecycle/handlers/rollback.mjs +14 -0
  167. package/src/signals/lifecycle/handlers.mjs +35 -0
  168. package/src/signals/lifecycle/hooks.mjs +19 -0
  169. package/src/signals/lifecycle/logging.mjs +11 -0
  170. package/src/signals/lifecycle/registration-policy.mjs +29 -0
  171. package/src/signals/lifecycle/registration.mjs +7 -0
  172. package/src/signals/lifecycle/shutdown.mjs +75 -0
  173. package/src/signals/lifecycle/validation/lifecycle-options.mjs +8 -0
  174. package/src/signals/lifecycle/validation/logger.mjs +9 -0
  175. package/src/signals/lifecycle/validation/options.mjs +19 -0
  176. package/src/signals/lifecycle/validation/registration-options.mjs +36 -0
  177. package/src/signals/lifecycle/validation/signals.mjs +9 -0
  178. package/src/signals/register.mjs +76 -0
  179. package/src/snowflake/constants.mjs +15 -0
  180. package/src/snowflake/generator-options.mjs +27 -0
  181. package/src/snowflake/generator.mjs +82 -0
  182. package/src/snowflake/index.d.mts +24 -0
  183. package/src/snowflake/index.d.ts +24 -0
  184. package/src/snowflake/index.mjs +8 -0
  185. package/src/snowflake/log-generation-failure.mjs +9 -0
  186. package/src/snowflake/logger-validation.mjs +10 -0
  187. package/src/snowflake/validation.mjs +18 -0
  188. package/src/errors.d.mts +0 -9
  189. package/src/errors.mjs +0 -4
  190. package/src/fs.mjs +0 -4
  191. package/src/path.d.mts +0 -12
  192. package/src/path.mjs +0 -22
  193. package/src/signals.mjs +0 -4
@@ -0,0 +1,62 @@
1
+ # Process Error Handlers
2
+
3
+ Call `registerHandlers(options)` to listen for errors that escape application handlers, unhandled promise rejections, or warnings.
4
+ The function preserves unrelated listeners on the process-like object.
5
+ It does not stop the application or start it again.
6
+
7
+ ```js
8
+ import { registerHandlers } from "@eliware/common";
9
+
10
+ const handlers = registerHandlers({ events: ["warning"] });
11
+
12
+ // Remove handlers during application cleanup.
13
+ handlers.removeHandlers();
14
+ ```
15
+
16
+ The root package and `@eliware/common/errors` subpath export this API.
17
+
18
+ ## Options
19
+
20
+ | Option | Default | Purpose |
21
+ | ------------ | ----------------- | --------------------------------------------------------------- |
22
+ | `processObj` | Node.js `process` | Supply an event source for controlled use. |
23
+ | `log` | Package `log` | Supply a logger with `error`, `warn`, and `debug`. |
24
+ | `events` | `defaultEvents` | Select supported process events. |
25
+ | `once` | `false` | Process each selected event one time, then remove all handlers. |
26
+ | `signal` | None | Remove handlers when an `AbortSignal` aborts. |
27
+
28
+ `defaultEvents` contains `uncaughtException`, `unhandledRejection`, and `warning`.
29
+ The `events` option must be a non-empty array of supported names.
30
+ The function rejects unsupported values with an error.
31
+
32
+ Warnings use the logger's `warn()` method.
33
+ Unhandled rejections and uncaught exceptions use `error()`.
34
+ The handlers log value types and fixed error labels without forwarding raw event values.
35
+
36
+ ## Process-like objects
37
+
38
+ Pass an object with `on()`, `off()`, and `listeners()` methods.
39
+ The `once()` method is optional.
40
+ When `once` is true, the package uses `once()` when the object provides it.
41
+ If it lacks `once()`, the package uses `on()` and ignores later calls for events that fired.
42
+ Use this option for tests or a controlled event source.
43
+
44
+ ## Registration and cleanup
45
+
46
+ Each process object can have one active registration.
47
+ Repeated calls return that registration and ignore new options.
48
+ Pass an `AbortSignal` with `addEventListener()` and `removeEventListener()` when automatic cleanup is required.
49
+
50
+ Call `removeHandlers()` to remove the registered listeners.
51
+ The read-only `ready` property is true after handler setup ends.
52
+ The read-only `removed` property reports cleanup state.
53
+ The `removed` property stays false until cleanup removes every handler and abort listener.
54
+ If removal fails, the function throws and lets a later call retry failed cleanup.
55
+
56
+ The function returns logger and listener failures to the caller.
57
+ After an uncaught process error, apply the recovery or shutdown policy for your application.
58
+
59
+ ## TypeScript
60
+
61
+ Use `ProcessEvent`, `ProcessListener`, `Logger`, `ProcessLike`, `RegisterHandlersOptions`, and `RegisteredHandlers` from the package.
62
+ Read the [API reference](api.md) for the full export list.
@@ -0,0 +1,115 @@
1
+ # Redaction and Safe Serialization
2
+
3
+ Use redaction APIs to lower accidental disclosure in logs and diagnostics.
4
+ They provide best-effort filtering. They do not prove that a value is safe to share.
5
+
6
+ ## Select an API
7
+
8
+ | Function | Use |
9
+ | ---------------------------------------------- | ----------------------------------------------------------------------- |
10
+ | `createPolicy(options)` | Build a policy for repeated use with custom sensitive names or markers. |
11
+ | `redactValue(value, options)` | Copy an object or array and replace sensitive values. |
12
+ | `redactHeaders(headers, options)` | Replace sensitive values in common header input shapes. |
13
+ | `redactText(value, options)` | Filter known credential patterns and configured text values. |
14
+ | `replaceLiteralSecret(value, secret, marker?)` | Replace exact occurrences of one supplied secret. |
15
+ | `safeSerialize(value, options)` | Create a bounded representation for logs and diagnostics. |
16
+
17
+ The root package and the `@eliware/common/redact` subpath export these functions.
18
+
19
+ ## Set sensitive names
20
+
21
+ The default policy checks these names without regard to letter case:
22
+
23
+ ```text
24
+ token, accesstoken, authtoken, authorization, cookie, set-cookie,
25
+ proxy-authorization, password, passwd, secret, clientsecret, apikey,
26
+ api-key, accesskey, privatekey, passphrase, credential, webhook,
27
+ signature, tlskey, tlscert
28
+ ```
29
+
30
+ Pass `keys` or `redactKeys` to replace the default names.
31
+ Include `defaultPolicy.keys` when you want to add names.
32
+
33
+ ```js
34
+ import { createPolicy, defaultPolicy, redactValue } from "@eliware/common";
35
+
36
+ const policy = createPolicy({
37
+ keys: [...defaultPolicy.keys, "sessionId"],
38
+ marker: "[HIDDEN]",
39
+ });
40
+
41
+ const clean = redactValue({ sessionId: "example", status: 200 }, policy);
42
+ ```
43
+
44
+ The policy uses `[REDACTED]` as its default marker.
45
+ The `circularMarker` option applies to cycles in `redactValue`.
46
+
47
+ ## Redact structured values
48
+
49
+ `redactValue` returns a copy and leaves the input unchanged.
50
+ It checks property names and does not inspect text inside ordinary string values.
51
+ It supports objects, arrays, `Error` values, cycles, accessors, and hostile objects.
52
+
53
+ The traversal defaults to depth 20, 1,000 keys, and 1,000 array items.
54
+ Set `maxDepth`, `maxKeys`, and `maxArray` to change those limits.
55
+ Finite fractional limits are floored. Negative limits become zero.
56
+ Non-finite limits use their defaults.
57
+
58
+ The function replaces cycles with `[CIRCULAR]` by default.
59
+ It marks omitted object properties with `__truncated` and omitted array entries with `[TRUNCATED]`.
60
+ It chooses a numeric suffix when an object has a `__truncated` property.
61
+ It does not read values for sensitive array entries.
62
+
63
+ ## Redact headers
64
+
65
+ `redactHeaders` accepts a plain object, an array of name-value pairs, or an object with `entries()`.
66
+ Header names match without regard to case.
67
+
68
+ - Plain objects keep their header names and replace sensitive values.
69
+ - Pair arrays keep duplicate names and return an array.
70
+ - `entries()` inputs return lowercase names. The last value wins unless an earlier value was redacted.
71
+ - Malformed pairs are skipped while valid pairs remain.
72
+ - Unreadable iterables return an empty array.
73
+
74
+ ## Redact text
75
+
76
+ `redactText` checks authorization and bearer values, credential assignments, query values, provider tokens, JWT-like strings, and key blocks.
77
+ The function also checks names supplied through `keys` and literal values supplied through `secrets`.
78
+
79
+ ```js
80
+ import { redactText, replaceLiteralSecret } from "@eliware/common";
81
+
82
+ const message = redactText("sessionId=example-value", {
83
+ keys: ["sessionId"],
84
+ marker: "[HIDDEN]",
85
+ });
86
+ const clean = replaceLiteralSecret("token=example-secret", "example-secret");
87
+ ```
88
+
89
+ Literal matching is exact and case-sensitive.
90
+ Pass no more than 100 literal secrets with 10,000 characters total.
91
+ The function throws a `RangeError` when the secret limits are exceeded.
92
+ The default output limit is 10,000 characters.
93
+ Set `maxOutputLength` to change it.
94
+ The function limits input before applying rules and marks shortened output with `[TRUNCATED]`.
95
+
96
+ ## Serialize values safely
97
+
98
+ `safeSerialize` does not call `toJSON`.
99
+ It returns JSON-safe data for common values and text labels for special values.
100
+ The defaults limit depth to 20, keys to 1,000, array items to 1,000, and strings to 10,000 characters.
101
+
102
+ The serializer maps `undefined`, functions, symbols, BigInts, buffers, and cycles to bounded labels.
103
+ It omits enumerable symbol keys and custom array properties.
104
+ It preserves sparse array holes and own `__proto__` data without changing output prototypes.
105
+ Errors include bounded `name`, `message`, `stack`, and custom properties.
106
+
107
+ The output has no single total character limit.
108
+ Traversal limits do not replace secrecy rules.
109
+ Inspect output before sending it to a different system.
110
+
111
+ ## Limits
112
+
113
+ Redaction can miss unknown formats and can mark harmless text.
114
+ Add application-specific names and literal values when known.
115
+ Use access controls, encryption, and retention rules for data protection.
@@ -0,0 +1,67 @@
1
+ # Signal Handling and Shutdown
2
+
3
+ Call `registerSignals(options)` to run cleanup after process signals or `beforeExit`.
4
+ The default signals are `SIGTERM`, `SIGINT`, and `SIGHUP`.
5
+
6
+ ```js
7
+ import { registerSignals } from "@eliware/common";
8
+
9
+ const registration = registerSignals({
10
+ shutdownHook: async (label) => {
11
+ await closeConnections(label);
12
+ },
13
+ });
14
+ ```
15
+
16
+ The root package and `@eliware/common/signals` subpath export this API.
17
+
18
+ ## Options
19
+
20
+ | Option | Default | Purpose |
21
+ | -------------- | ----------------------------- | ----------------------------------------------------------------------- |
22
+ | `processObj` | Node.js `process` | Supply an event source with `on()`, `off()`, and `listeners()` methods. |
23
+ | `log` | Package `log` | Supply a logger with `debug`, `warn`, and `error`. |
24
+ | `signals` | `SIGTERM`, `SIGINT`, `SIGHUP` | Select signal names. |
25
+ | `shutdownHook` | None | Add synchronous or asynchronous cleanup. |
26
+ | `exitCode` | `0` | Set the process exit code after a signal. |
27
+ | `exit` | `true` | Allow or prevent process exit after signal cleanup. |
28
+ | `signal` | None | Remove or disable handlers when an `AbortSignal` aborts. |
29
+
30
+ Pass an empty `signals` array to disable signal listeners.
31
+ The package also registers `beforeExit` cleanup.
32
+ It removes duplicate signal names while keeping their first order.
33
+ If listener setup fails, the package removes any listeners from that setup.
34
+
35
+ ## Cleanup order
36
+
37
+ The package runs cleanup functions in registration order and waits for each function.
38
+ It continues after a cleanup function fails and logs a fixed error notice.
39
+ The notice omits the failed value, stack, and custom error fields.
40
+ The package also continues if its logger throws during cleanup.
41
+
42
+ The first shutdown request sets the label for all cleanup functions.
43
+ Later requests use the first shutdown promise.
44
+ Calls from inside a running cleanup function resolve immediately.
45
+ Only configured signal events trigger process exit.
46
+ Manual calls to `shutdown(label?)` do not trigger exit.
47
+
48
+ Node.js does not wait for asynchronous cleanup in its `exit` event.
49
+ The package uses `beforeExit` and keeps the event loop active while cleanup runs.
50
+ Keep cleanup tasks short so shutdown can complete promptly.
51
+
52
+ ## Repeated registration and cleanup
53
+
54
+ Each process object can have one active registration.
55
+ Call `registerSignals()` again with a `shutdownHook` to add cleanup before shutdown starts.
56
+ Keep lifecycle options the same across repeated calls.
57
+ Remove the active registration before you use different lifecycle options.
58
+
59
+ The registration provides `shutdown(label?)`, `getShuttingDown()`, `removeHandlers()`, and read-only `removed` members.
60
+ The `removed` property stays false until cleanup removes every listener.
61
+ The package checks `listeners()` after each `off()` call to confirm that the handler is gone.
62
+ If cleanup fails, call `removeHandlers()` again after the failing source can remove listeners.
63
+ Set `exit: false` when the application controls process exit.
64
+
65
+ ## TypeScript
66
+
67
+ Use `NodeSignal`, `SignalsLogger`, `SignalsProcessLike`, `RegisterSignalsOptions`, and `SignalsRegistration` from the package.
@@ -0,0 +1,77 @@
1
+ # Snowflake IDs
2
+
3
+ Call `createSnowflakeGenerator(options)` to make a generator.
4
+ Each generated ID is a decimal string.
5
+ Keep it as a string in JavaScript and JSON.
6
+
7
+ ```js
8
+ import { createSnowflakeGenerator } from "@eliware/common";
9
+
10
+ const createId = createSnowflakeGenerator({ workerId: 3, processId: 7 });
11
+ const id = createId();
12
+
13
+ console.log(id);
14
+ ```
15
+
16
+ The root package and `@eliware/common/snowflake` subpath export this API.
17
+
18
+ ## Options
19
+
20
+ | Option | Default | Purpose |
21
+ | ----------- | ------------------ | ---------------------------------------------- |
22
+ | `epoch` | `365662380000n` | Set the base Unix time in milliseconds. |
23
+ | `workerId` | `0` | Set a worker value from 0 through 31. |
24
+ | `processId` | `process.pid % 32` | Set a process value from 0 through 31. |
25
+ | `now` | `Date.now` | Supply a clock that returns Unix milliseconds. |
26
+ | `logger` | None | Record safe generator events. |
27
+
28
+ Pass a safe integer or `bigint` for the epoch and identity values.
29
+ The `now` function must return Unix milliseconds as a safe integer or `bigint`.
30
+ Set an epoch from zero through `(1n << 42n) - 1n`.
31
+ Give every active generator a unique worker and process pair.
32
+ The default process value can repeat across hosts.
33
+
34
+ ## ID layout
35
+
36
+ Each ID stores a 42-bit elapsed timestamp, a 5-bit worker value, a 5-bit process value, and a 12-bit sequence.
37
+ The package combines the fields as follows:
38
+
39
+ ```text
40
+ ((time - epoch) << 22) | (workerId << 17) | (processId << 12) | sequence
41
+ ```
42
+
43
+ Use the same epoch when you decode an ID.
44
+ Convert the decimal string to `BigInt` before reading its fields.
45
+
46
+ ```js
47
+ const value = BigInt(id);
48
+ const elapsed = value >> 22n;
49
+ const timestamp = new Date(Number(elapsed + 365662380000n));
50
+ ```
51
+
52
+ The package does not provide a decoder.
53
+ An ID exposes generation time and identity fields, so it is not a secret or access token.
54
+
55
+ ## Clock behavior and limits
56
+
57
+ The first clock value must be at or after the epoch.
58
+ If the clock later returns an earlier timestamp, the generator uses its last timestamp and advances the sequence.
59
+ Each generator can create 4,096 IDs at one millisecond.
60
+ The generator throws `RangeError` when the sequence or timestamp limit fails.
61
+ Retry sequence overflow after the clock advances.
62
+
63
+ ## Logging
64
+
65
+ Pass a logger with `error`, `warn`, `info`, and `debug` methods.
66
+ The generator logs creation, generated timestamps, clock rollback, and error types.
67
+ It does not include generated IDs, credentials, or error messages in those records.
68
+
69
+ ## Shared generator exports
70
+
71
+ `generate`, `snowflake`, and the default export use one shared generator.
72
+ Call `createSnowflakeGenerator()` for a separate epoch, clock, or identity.
73
+ The frozen `constants` export contains `epoch`, `sequenceBits`, `processBits`, and `workerBits` values.
74
+
75
+ ## TypeScript
76
+
77
+ Use `SnowflakeGeneratorOptions`, `SnowflakeConstants`, and `LoggerWithConfiguredLevels` from the package.
@@ -2,46 +2,50 @@
2
2
 
3
3
  ## Import errors
4
4
 
5
- Use Node.js 26 or later.
6
- Set the project to native ESM.
7
- Run `npm install @eliware/common` to install the package and its dependencies.
8
- Import from `@eliware/common`. Do not import private files under `src/`.
5
+ Use Node.js 26 or later and a native ESM project.
6
+ Install `@eliware/common` with npm.
7
+ Import public APIs from the package root or a documented subpath.
8
+ Do not import private files under `src/`.
9
9
 
10
10
  ## Type errors
11
11
 
12
- Use the package types that match the installed package version.
13
- Run `npm install` to update the lock file after a version change.
14
- Read the [API reference](api.md) and [declaration file](../src/index.d.ts).
12
+ Use declarations that match the installed package version.
13
+ Import types with the `type` modifier.
14
+ Read the [API reference](api.md) for public type names.
15
+ Run `npm install` after you change the package version in a project.
15
16
 
16
- ## Path errors
17
+ ## Redaction questions
17
18
 
18
- Pass `import.meta` or a directory string to a path helper.
19
- Pass a file URL to `fileUrlToPath`.
20
- Read the [path API section](api.md#path-helpers) for each helper's result.
19
+ Add application-specific names through `keys` or `redactKeys`.
20
+ Supply known literal secrets through `secrets` or `replaceLiteralSecret`.
21
+ Read [Redaction and safe serialization](redaction.md) for supported patterns and limits.
22
+ Inspect output before you send it to a different system.
21
23
 
22
24
  ## Logger errors
23
25
 
24
- Check the `level`, `transports`, and `format` options passed to `createLogger`.
25
- Pass a logger with `debug`, `info`, `warn`, and `error` methods where required.
26
- Remove secret values before you write metadata to logger output.
26
+ Check the `level`, `transports`, and `format` values passed to `createLogger`.
27
+ Use `text` or `json` as the format.
28
+ Pass logger metadata as the second argument.
29
+ Read [Logging](logging.md) for logger options and serialization behavior.
27
30
 
28
- ## Process handler errors
31
+ ## Path errors
29
32
 
30
- Keep each handler registration while it is required.
31
- Call `removeHandlers()` to remove error or signal handlers.
32
- Pass a valid process-like object and event names.
33
- Read the [API reference](api.md#error-handlers) and [shutdown handler guide](api.md#shutdown-handlers).
33
+ Pass `import.meta` or a directory string to a path helper.
34
+ Pass a file URL string or `URL` object to `fileUrlToPath`.
35
+ Use a directory string as the starting directory, not as a filename.
36
+ Read [Path utilities](paths.md) for helper results.
34
37
 
35
- ## Snowflake errors
38
+ ## Process handler errors
36
39
 
37
- Give each active generator a unique worker and process ID pair.
38
- Keep generated IDs as decimal strings. Do not convert them to `number`.
39
- Wait until the clock value changes after a sequence limit error.
40
- Check the epoch and clock when the generator reports a timestamp error.
41
- Read [Snowflake IDs](api.md#snowflake-ids) for limits and clock behavior.
40
+ Pass a process-like object with `on()`, `off()`, and `listeners()` methods.
41
+ Pass a logger with the methods required by the selected handler.
42
+ Call `removeHandlers()` when the registration ends.
43
+ Read [Process error handlers](process-errors.md) and [Signal handling](signals.md).
42
44
 
43
- ## Repository checks
45
+ ## Snowflake errors
44
46
 
45
- Run `npm ci` to install locked dependencies.
46
- Run `npm test` to check the repository.
47
- Repair the first reported error, then run `npm test` again.
47
+ Give each active generator a unique worker and process pair.
48
+ Keep generated IDs as decimal strings.
49
+ Check the configured epoch when the generator reports a timestamp error.
50
+ Wait for a later clock value after sequence overflow.
51
+ Read [Snowflake IDs](snowflake-ids.md) for field and clock limits.
package/docs/usage.md CHANGED
@@ -1,10 +1,10 @@
1
- # Setup and usage
1
+ # Setup and Usage
2
2
 
3
3
  ## Requirements
4
4
 
5
- Use Node.js 26 or later. Use a project that supports native ESM.
5
+ Use Node.js 26 or later. Use a project that supports native ECMAScript modules.
6
6
 
7
- ## Install
7
+ ## Install the package
8
8
 
9
9
  Install `@eliware/common` from npm.
10
10
 
@@ -12,180 +12,84 @@ Install `@eliware/common` from npm.
12
12
  npm install @eliware/common
13
13
  ```
14
14
 
15
- The package installs its Eliware runtime dependencies.
15
+ ## Import the APIs
16
16
 
17
- ## Read a file
18
-
19
- Use the Node.js `fs` namespace for file operations. This example reads a file as UTF-8 text.
20
-
21
- ```js
22
- import { fs } from "@eliware/common";
23
-
24
- const text = await fs.promises.readFile("./config.json", "utf8");
25
- const config = JSON.parse(text);
26
- ```
27
-
28
- Use Node.js `fs` documentation for available methods, options, and errors.
29
-
30
- ## Import public APIs
31
-
32
- Import the APIs that your app requires.
17
+ Import APIs from the package root when an application uses multiple library areas.
33
18
 
34
19
  ```js
35
20
  import {
21
+ createLogger,
36
22
  createSnowflakeGenerator,
37
23
  fs,
38
- log,
39
24
  path,
25
+ redactText,
40
26
  registerHandlers,
41
27
  registerSignals,
42
28
  } from "@eliware/common";
43
29
 
44
30
  const configFile = path(import.meta, "config.json");
45
- const createId = createSnowflakeGenerator({ workerId: 1, processId: 1 });
31
+ const createId = createSnowflakeGenerator({ workerId: 1, processId: 4 });
32
+ const logger = createLogger({ format: "json", keys: ["sessionId"] });
33
+ const cleanMessage = redactText("token=example-token");
46
34
 
47
- log.info("Read configuration", { configFile, id: createId() });
35
+ logger.info("Reading configuration", { configFile, id: createId(), cleanMessage });
48
36
  const handlers = registerHandlers();
49
- const keepAlive = setInterval(() => log.info("Waiting for SIGTERM or SIGINT."), 60_000);
50
-
51
- registerSignals({
52
- shutdownHook: () => {
53
- clearInterval(keepAlive);
54
- handlers.removeHandlers();
55
- },
37
+ const shutdown = registerSignals({
38
+ shutdownHook: () => handlers.removeHandlers(),
56
39
  });
57
40
 
58
- console.log(fs.existsSync(configFile));
59
- ```
60
-
61
- This code writes one Snowflake ID and checks one file. It stays active until a signal starts shutdown.
62
- The shutdown callback stops the timer and removes the error handlers.
63
-
64
- ## Use path helpers
65
-
66
- Pass `import.meta` to find paths from the current module.
67
-
68
- ```js
69
- import {
70
- fileUrlToPath,
71
- getCurrentDirname,
72
- path,
73
- pathUrl,
74
- relativePath,
75
- resolvePath,
76
- } from "@eliware/common";
77
-
78
- const directory = getCurrentDirname(import.meta);
79
- const file = path(import.meta, "data", "input.json");
80
- const url = pathUrl(import.meta, "data", "input.json");
81
- const absolute = resolvePath(import.meta, "data", "input.json");
82
- const relative = relativePath(import.meta, "data", "input.json");
83
- const localFile = fileUrlToPath(url);
84
- ```
85
-
86
- Pass a directory string when code does not have `import.meta`.
87
- Read the [API reference](api.md) for each path helper.
88
-
89
- Use `createPathHelpers` when your app must record path operations with a custom logger.
90
-
91
- ```js
92
- import { createPathHelpers } from "@eliware/common";
93
-
94
- const records = [];
95
- const helpers = createPathHelpers({ logger: { log: (record) => records.push(record) } });
96
- const file = helpers.path(import.meta, "data", "input.json");
41
+ console.log(fs.existsSync(configFile), shutdown.removed);
97
42
  ```
98
43
 
99
- The helper writes a debug record after it completes a path operation.
44
+ The example demonstrates the available APIs. Use cleanup callbacks that match the lifetime of your application.
100
45
 
101
- ## Use logger APIs
102
-
103
- Use the default `log` object or create a logger with `createLogger(options)`.
104
-
105
- ```js
106
- import { createLogger, safeSerialize } from "@eliware/common";
107
-
108
- const logger = createLogger({ format: "json", timestamp: true });
109
- logger.info("Request complete", safeSerialize({ requestId: "example" }));
110
- ```
46
+ ## Read a file
111
47
 
112
- Pass metadata as the second logger argument. Use `safeSerialize` to remove secret fields and limit nested values before you write records.
48
+ Use the `fs` export as the Node.js file system module.
113
49
 
114
50
  ```js
115
- import { createLogger, safeSerialize } from "@eliware/common";
51
+ import { fs } from "@eliware/common";
116
52
 
117
- const logger = createLogger({ format: "json" });
118
- logger.info("Request complete", safeSerialize({ token: "example", status: 200 }));
53
+ const text = await fs.promises.readFile("./config.json", "utf8");
54
+ const config = JSON.parse(text);
119
55
  ```
120
56
 
121
- The serializer returns a bounded representation. It does not guarantee that all sensitive data has been removed.
57
+ Read the [Node.js file system guide](https://nodejs.org/api/fs.html) for methods, options, and errors.
122
58
 
123
- ## Redact sensitive values
59
+ ## Use a focused import
124
60
 
125
- Use `redactText` to remove credentials from text before you write or store it.
61
+ Import a library area directly when an application uses one area by itself.
126
62
 
127
63
  ```js
128
- import { redactText, redactValue } from "@eliware/common";
129
-
130
- const message = redactText("Authorization: Bearer example-token");
131
- const record = redactValue({ user: "alex", token: "example-token" });
132
- console.log(message, record);
64
+ import { redactText, redactValue } from "@eliware/common/redact";
65
+ import { createLogger, log } from "@eliware/common/log";
66
+ import { createSnowflakeGenerator } from "@eliware/common/snowflake";
133
67
  ```
134
68
 
135
- `redactText` applies standard credential rules. Pass `secrets` to replace known literal values.
136
- `redactValue` returns a copy with sensitive property values replaced.
137
- Read the [Redaction APIs](api.md#redaction-apis) for policies, options, limits, and header handling.
138
-
139
- Use `redactHeaders` for HTTP header data. Use `createPolicy` to add a sensitive property name.
140
-
141
- ```js
142
- import { createPolicy, redactHeaders, redactValue } from "@eliware/common";
143
-
144
- const policy = createPolicy({ keys: ["token", "sessionId"] });
145
- const record = redactValue({ sessionId: "example", status: 200 }, policy);
146
- const headers = redactHeaders({ Authorization: "Bearer example", Accept: "application/json" });
147
- ```
69
+ The package also provides `/path`, `/errors`, and `/signals` subpaths.
70
+ All subpaths use the same implementation as the root exports.
148
71
 
149
- The policy replaces the default sensitive names with the names that you provide. Include the default names when you want to keep them.
72
+ ## Keep identifiers as strings
150
73
 
151
- ## Process errors and signals
74
+ Keep Snowflake IDs as decimal strings in JavaScript and JSON.
75
+ Convert an ID to `BigInt` only when exact integer math is required.
76
+ Read [Snowflake IDs](snowflake-ids.md) for identity and timestamp limits.
152
77
 
153
- Call `registerHandlers(options)` to add process error handlers.
154
- Call its `removeHandlers()` method when the handlers are no longer required.
155
- Call `registerSignals(options)` to add shutdown handlers.
156
- Pass `shutdownHook` to run cleanup.
157
- Read the [API reference](api.md) for defaults, options, return values, and dependency guides.
78
+ ## Read TypeScript types
158
79
 
159
- ## Create Snowflake IDs
160
-
161
- Create one generator with a unique worker and process ID pair.
162
-
163
- ```js
164
- import { createSnowflakeGenerator } from "@eliware/common";
165
-
166
- const createId = createSnowflakeGenerator({ workerId: 3, processId: 7 });
167
- console.log(createId());
168
- ```
169
-
170
- Each call returns a decimal string. Keep the ID as a string in JavaScript and JSON.
171
- Read the [Snowflake section in the API reference](api.md#snowflake-ids) for options and limits.
172
-
173
- ## TypeScript
174
-
175
- Import the types with a `type` modifier.
80
+ Import public types with a `type` modifier.
176
81
 
177
82
  ```ts
178
- import {
179
- createSnowflakeGenerator,
180
- registerSignals,
181
- type RegisterSignalsOptions,
182
- } from "@eliware/common";
83
+ import { createSnowflakeGenerator, registerSignals } from "@eliware/common";
84
+ import type { RegisterSignalsOptions, SnowflakeGeneratorOptions } from "@eliware/common";
85
+
86
+ const generatorOptions: SnowflakeGeneratorOptions = { workerId: 3, processId: 7 };
87
+ const signalOptions: RegisterSignalsOptions = { exit: false };
88
+ const createId = createSnowflakeGenerator(generatorOptions);
89
+ const registration = registerSignals(signalOptions);
183
90
 
184
- const options: RegisterSignalsOptions = { exit: false };
185
- const registration = registerSignals(options);
186
- const createId = createSnowflakeGenerator();
187
91
  console.log(createId());
188
92
  registration.removeHandlers();
189
93
  ```
190
94
 
191
- The package includes TypeScript declarations. Read [API types](api.md#typescript-types) for the exported type names.
95
+ Read the [API reference](api.md) for exported values and types.