@zyro-sec/util 1.0.0 → 1.0.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/docs/layer-node.md +155 -0
- package/package.json +12 -19
- package/script/build.ts +9 -0
- package/script/pack.ts +5 -0
- package/src/abort.test.ts +16 -0
- package/src/abort.ts +9 -0
- package/src/activity-calendar.test.ts +136 -0
- package/src/activity-calendar.ts +50 -0
- package/src/artifact.test.ts +29 -0
- package/src/artifact.ts +95 -0
- package/src/base64.test.ts +12 -0
- package/src/base64.ts +29 -0
- package/src/binary.test.ts +19 -0
- package/src/binary.ts +30 -0
- package/src/bom.test.ts +21 -0
- package/src/bom.ts +46 -0
- package/src/cross-spawn-spawner.ts +694 -0
- package/src/duration.ts +22 -0
- package/src/effect/app-node-platform.ts +40 -0
- package/src/effect/app-node.ts +14 -0
- package/src/effect/layer-node.ts +360 -0
- package/src/effect-flock.ts +313 -0
- package/src/encode.test.ts +32 -0
- package/src/encode.ts +39 -0
- package/src/execute-output.test.ts +36 -0
- package/src/execute-output.ts +23 -0
- package/src/flock.ts +346 -0
- package/src/fs-util.ts +271 -0
- package/src/glob.ts +38 -0
- package/src/global-roots.ts +19 -0
- package/src/global-roots.workerd.ts +16 -0
- package/src/global.ts +88 -0
- package/src/hash.ts +11 -0
- package/src/heap-snapshot.ts +44 -0
- package/src/no-timeout-fetch.test.ts +33 -0
- package/src/no-timeout-fetch.ts +5 -0
- package/src/npm-config.ts +41 -0
- package/src/npm.ts +557 -0
- package/src/observability/logging.ts +179 -0
- package/src/observability/otlp.ts +109 -0
- package/src/observability/shared.ts +8 -0
- package/src/observability.ts +60 -0
- package/src/open.test.ts +16 -0
- package/src/open.ts +12 -0
- package/src/patch.ts +382 -0
- package/src/path.test.ts +89 -0
- package/src/path.ts +149 -0
- package/src/process-signal.test.ts +38 -0
- package/src/process-signal.ts +23 -0
- package/src/process.ts +270 -0
- package/src/qr.ts +323 -0
- package/src/record.ts +3 -0
- package/src/retry.test.ts +87 -0
- package/src/retry.ts +51 -0
- package/src/runtime/import.bun.ts +10 -0
- package/src/runtime/import.node.ts +61 -0
- package/src/runtime/import.workerd.ts +9 -0
- package/src/runtime-import.ts +1 -0
- package/src/session-mention.test.ts +19 -0
- package/src/session-mention.ts +24 -0
- package/src/session-title-fallback.ts +36 -0
- package/src/session-turn.test.ts +131 -0
- package/src/session-turn.ts +82 -0
- package/src/teardown.ts +19 -0
- package/src/text-boundary.test.ts +39 -0
- package/src/text-boundary.ts +36 -0
- package/src/uuid.test.ts +80 -0
- package/src/uuid.ts +15 -0
- package/test/fixtures/qr.json +625 -0
- package/test/glob.test.ts +11 -0
- package/test/global-roots.test.ts +62 -0
- package/test/global.test.ts +99 -0
- package/test/observability-otlp.test.ts +45 -0
- package/test/qr.test.ts +113 -0
- package/test/session-title-fallback.test.ts +49 -0
- package/tsconfig.build.json +12 -0
- package/tsconfig.dist.json +10 -0
- package/tsconfig.json +14 -0
|
@@ -0,0 +1,155 @@
|
|
|
1
|
+
# Layer Graphs
|
|
2
|
+
|
|
3
|
+
`LayerNode` describes replaceable wiring for ordinary Effect Layers. Declarations
|
|
4
|
+
and compilation do not acquire resources. Effect still owns acquisition,
|
|
5
|
+
memoization, scopes, and finalization.
|
|
6
|
+
|
|
7
|
+
There are three values to compose:
|
|
8
|
+
|
|
9
|
+
- A **Node** is a replaceable declaration with a fixed output, error, and tag
|
|
10
|
+
contract. `make` supplies its default implementation; `unbound` leaves that
|
|
11
|
+
implementation for the caller to supply.
|
|
12
|
+
- A **Graph** is a node or an ordered `group` of graphs. Grouping exposes the
|
|
13
|
+
selected roots, not their transitive dependencies. Groups are not replacement
|
|
14
|
+
targets.
|
|
15
|
+
- A **Replacement** is a checked instruction made by `node.replace(...)`.
|
|
16
|
+
Replacement arrays can be stored and concatenated without losing their checks.
|
|
17
|
+
|
|
18
|
+
```ts
|
|
19
|
+
import { Context, Effect, Layer } from "effect"
|
|
20
|
+
import { LayerNode } from "@zyro-sec/util/effect/layer-node"
|
|
21
|
+
|
|
22
|
+
class Database extends Context.Service<Database, { readonly name: string }>()("example/Database") {}
|
|
23
|
+
class Users extends Context.Service<Users, { readonly name: string }>()("example/Users") {}
|
|
24
|
+
|
|
25
|
+
const tags = LayerNode.tags({ global: [], location: ["global"] })
|
|
26
|
+
const global = tags.make("global")
|
|
27
|
+
const location = tags.make("location")
|
|
28
|
+
|
|
29
|
+
const database = global({
|
|
30
|
+
service: Database,
|
|
31
|
+
layer: Layer.succeed(Database, { name: "live" }),
|
|
32
|
+
deps: [],
|
|
33
|
+
})
|
|
34
|
+
const users = location({
|
|
35
|
+
service: Users,
|
|
36
|
+
layer: Layer.effect(
|
|
37
|
+
Users,
|
|
38
|
+
Effect.map(Database, (db) => ({ name: db.name })),
|
|
39
|
+
),
|
|
40
|
+
deps: [database],
|
|
41
|
+
})
|
|
42
|
+
|
|
43
|
+
const replacements: LayerNode.Replacements = [database.replace(Layer.succeed(Database, { name: "test" }))]
|
|
44
|
+
|
|
45
|
+
const layer = LayerNode.compile(LayerNode.group([database, users]), {
|
|
46
|
+
replacements,
|
|
47
|
+
shared: tags.values.global,
|
|
48
|
+
})
|
|
49
|
+
// Layer<Database | Users>: both selected roots remain available.
|
|
50
|
+
```
|
|
51
|
+
|
|
52
|
+
## Substitution
|
|
53
|
+
|
|
54
|
+
Replacements target the exact declaration, not its display name or service key.
|
|
55
|
+
Two independently declared nodes can provide the same service in different
|
|
56
|
+
branches without capturing each other's overrides.
|
|
57
|
+
|
|
58
|
+
Keep the original declaration as the target when configuring a default:
|
|
59
|
+
|
|
60
|
+
```ts
|
|
61
|
+
const replacements = [Database.node.replace(Database.configured(options.database)), ...profile.replacements]
|
|
62
|
+
```
|
|
63
|
+
|
|
64
|
+
The replacement may be a closed Layer or another node. It must provide all the
|
|
65
|
+
source's outputs, may provide additional outputs, must not introduce new errors,
|
|
66
|
+
and must retain the source's tag. An open Layer must first be wired into a node.
|
|
67
|
+
Replacing a node prunes its original dependencies; replacing it with another node
|
|
68
|
+
uses that node's dependencies instead.
|
|
69
|
+
|
|
70
|
+
The rules are:
|
|
71
|
+
|
|
72
|
+
- The last replacement for the same source wins, before any traversal.
|
|
73
|
+
- Replacements also apply inside replacement dependency graphs and through
|
|
74
|
+
replacement chains.
|
|
75
|
+
- Replacing a node with itself is the identity operation.
|
|
76
|
+
- Unreachable replacements neither acquire resources nor traverse their graphs.
|
|
77
|
+
- Unbound nodes and cycles in the effective graph fail during compilation.
|
|
78
|
+
|
|
79
|
+
A node's contract is invariant. It cannot be widened or narrowed to authorize a
|
|
80
|
+
replacement that would violate another use of the original declaration. A graph
|
|
81
|
+
can forget outputs like an ordinary Layer, but cannot be used as a weaker
|
|
82
|
+
replacement handle.
|
|
83
|
+
|
|
84
|
+
Choice and composition are different: `group([a, b])` provides both roots, while
|
|
85
|
+
`group([condition ? a : b])` promises only outputs common to both alternatives.
|
|
86
|
+
The same rule applies to conditional implementation Layers. Use tuples for known
|
|
87
|
+
roots; a dynamic array can be empty and therefore guarantees no service outputs.
|
|
88
|
+
Every alternative of a conditional replacement must satisfy the source contract.
|
|
89
|
+
|
|
90
|
+
## Decoration
|
|
91
|
+
|
|
92
|
+
Use `mapLayer` to decorate a default implementation without duplicating or
|
|
93
|
+
inspecting its dependencies:
|
|
94
|
+
|
|
95
|
+
```ts
|
|
96
|
+
const observed = database.mapLayer((layer) => layer.pipe(Layer.tap(() => Effect.logDebug("database ready"))))
|
|
97
|
+
const replacements = [database.replace(observed)]
|
|
98
|
+
```
|
|
99
|
+
|
|
100
|
+
The callback is parametric in the Layer's requirements: it must preserve the
|
|
101
|
+
declared wiring and service/error contract. `mapLayer` returns a new node; it does
|
|
102
|
+
not mutate or automatically override the original. Only implemented nodes offer
|
|
103
|
+
this operation, not unbound slots or groups.
|
|
104
|
+
|
|
105
|
+
## Lifetimes
|
|
106
|
+
|
|
107
|
+
Without `shared`, compilation uses Effect's enclosing memo map throughout.
|
|
108
|
+
With `shared: tag`, matching nodes and their dependency subgraphs use that map;
|
|
109
|
+
remaining wiring uses one fresh map per build. A shared service's dependencies
|
|
110
|
+
must live at least as long as the service, including untagged helpers. This keeps application globals shared while isolating each
|
|
111
|
+
Location, without exposing incomplete graphs or losing shared root outputs.
|
|
112
|
+
|
|
113
|
+
The enclosing memo map remains ambient during construction, so a lazy LayerMap
|
|
114
|
+
captures the shared ancestry rather than a Location's private cache. Cache
|
|
115
|
+
selection is internal metadata, not an extra service output of each dependency.
|
|
116
|
+
|
|
117
|
+
Native Layer identity still controls acquisition within each memo map. Use a
|
|
118
|
+
distinct implementation Layer for differently wired definitions; compilation
|
|
119
|
+
rejects conflicting wiring of the same Layer within one graph's memo domain.
|
|
120
|
+
Compiled wiring is memoized once per build and memo domain, so a shared dependency
|
|
121
|
+
graph is not expanded into a tree during acquisition. Original Layer identities
|
|
122
|
+
still determine service sharing across separately compiled builds. An explicitly
|
|
123
|
+
fresh implementation refreshes its acquisition when its wiring is built.
|
|
124
|
+
|
|
125
|
+
Groups preserve root startup order and associate transparently. A node's
|
|
126
|
+
dependencies are built concurrently through native `Layer.provide`. Named
|
|
127
|
+
startup actions and Context references are supported even when their required
|
|
128
|
+
service output type is `never`.
|
|
129
|
+
|
|
130
|
+
## Migration
|
|
131
|
+
|
|
132
|
+
| Previous API | Current API |
|
|
133
|
+
| ------------------------------------------------ | ----------------------------------------------- |
|
|
134
|
+
| `[source, replacement]` | `source.replace(replacement)` |
|
|
135
|
+
| `compile(graph, replacements)` | `compile(graph, { replacements })` |
|
|
136
|
+
| `hoist`, compile both halves, `fresh`, `provide` | `compile(graph, { replacements, shared: tag })` |
|
|
137
|
+
| Spread a node and overwrite `implementation` | `node.mapLayer(transform)` |
|
|
138
|
+
| Generic root parameter `Node<A, E, any>` | `Graph<A, E>` |
|
|
139
|
+
|
|
140
|
+
An application can prepend a default binding and append caller overrides instead
|
|
141
|
+
of inspecting the original graph with `hasUnbound`. Unused defaults are pruned,
|
|
142
|
+
and defaults introduced as dependencies by an override are found naturally.
|
|
143
|
+
|
|
144
|
+
Code that reconstructed a replacement source by name must retain the original
|
|
145
|
+
declaration instead. Compiler representation fields are no longer public.
|
|
146
|
+
|
|
147
|
+
`PersistentPty.configured(options)` now returns a wired node, like the other Core
|
|
148
|
+
configuration factories. `PersistentPty.layer` remains the default raw Layer.
|
|
149
|
+
|
|
150
|
+
## Verification
|
|
151
|
+
|
|
152
|
+
Run `bun run typecheck:dist` in `packages/util` to build the package and check the
|
|
153
|
+
same positive and negative contract tests against its emitted declarations.
|
|
154
|
+
This ensures package consumers receive the same inference and replacement checks
|
|
155
|
+
as callers importing the source.
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"$schema": "https://json.schemastore.org/package.json",
|
|
3
3
|
"name": "@zyro-sec/util",
|
|
4
|
-
"version": "1.0.
|
|
4
|
+
"version": "1.0.1",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"license": "MIT",
|
|
7
7
|
"repository": {
|
|
@@ -12,13 +12,6 @@
|
|
|
12
12
|
"publishConfig": {
|
|
13
13
|
"access": "public"
|
|
14
14
|
},
|
|
15
|
-
"files": [
|
|
16
|
-
"dist"
|
|
17
|
-
],
|
|
18
|
-
"exports": {
|
|
19
|
-
"./effect/layer-node": "./src/effect/layer-node.ts",
|
|
20
|
-
"./*": "./src/*.ts"
|
|
21
|
-
},
|
|
22
15
|
"imports": {
|
|
23
16
|
"#global-roots": {
|
|
24
17
|
"workerd": "./src/global-roots.workerd.ts",
|
|
@@ -40,10 +33,10 @@
|
|
|
40
33
|
"typecheck:dist": "bun run build && bun typecheck --project tsconfig.dist.json"
|
|
41
34
|
},
|
|
42
35
|
"dependencies": {
|
|
43
|
-
"@effect/opentelemetry": "
|
|
44
|
-
"@effect/platform-node": "
|
|
45
|
-
"@effect/platform-node-shared": "
|
|
46
|
-
"@npmcli/arborist": "
|
|
36
|
+
"@effect/opentelemetry": "4.1.0",
|
|
37
|
+
"@effect/platform-node": "4.1.0",
|
|
38
|
+
"@effect/platform-node-shared": "4.1.0",
|
|
39
|
+
"@npmcli/arborist": "9.4.0",
|
|
47
40
|
"@npmcli/config": "10.8.1",
|
|
48
41
|
"@opentelemetry/api": "1.9.0",
|
|
49
42
|
"@opentelemetry/api-logs": "0.219.0",
|
|
@@ -54,8 +47,8 @@
|
|
|
54
47
|
"@opentelemetry/sdk-metrics": "2.8.0",
|
|
55
48
|
"@opentelemetry/sdk-trace-base": "2.8.0",
|
|
56
49
|
"@opentelemetry/sdk-trace-node": "2.8.0",
|
|
57
|
-
"cross-spawn": "
|
|
58
|
-
"effect": "
|
|
50
|
+
"cross-spawn": "7.0.6",
|
|
51
|
+
"effect": "4.1.0",
|
|
59
52
|
"glob": "13.0.5",
|
|
60
53
|
"mime-types": "3.0.2",
|
|
61
54
|
"minimatch": "10.2.5",
|
|
@@ -64,14 +57,14 @@
|
|
|
64
57
|
"pacote": "21.5.1"
|
|
65
58
|
},
|
|
66
59
|
"devDependencies": {
|
|
67
|
-
"@tsconfig/bun": "
|
|
68
|
-
"@types/bun": "
|
|
69
|
-
"@types/cross-spawn": "
|
|
70
|
-
"@types/node": "
|
|
60
|
+
"@tsconfig/bun": "1.0.9",
|
|
61
|
+
"@types/bun": "1.4.3",
|
|
62
|
+
"@types/cross-spawn": "6.0.6",
|
|
63
|
+
"@types/node": "24.12.2",
|
|
71
64
|
"@types/npm-package-arg": "6.1.4",
|
|
72
65
|
"@types/npmcli__arborist": "6.3.3",
|
|
73
66
|
"@types/pacote": "11.1.8",
|
|
74
|
-
"@typescript/native": "
|
|
67
|
+
"@typescript/native": "npm:typescript@7.1.0-beta",
|
|
75
68
|
"jsqr": "1.4.0"
|
|
76
69
|
}
|
|
77
70
|
}
|
package/script/build.ts
ADDED
package/script/pack.ts
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import { expect, test } from "bun:test"
|
|
2
|
+
import { abort } from "./abort.js"
|
|
3
|
+
|
|
4
|
+
test("aborts with an AbortError that does not record the caller's stack", () => {
|
|
5
|
+
const controller = new AbortController()
|
|
6
|
+
function disposeComponent() {
|
|
7
|
+
abort(controller)
|
|
8
|
+
}
|
|
9
|
+
|
|
10
|
+
disposeComponent()
|
|
11
|
+
|
|
12
|
+
expect(controller.signal.aborted).toBe(true)
|
|
13
|
+
expect(controller.signal.reason).toBeInstanceOf(DOMException)
|
|
14
|
+
expect(controller.signal.reason.name).toBe("AbortError")
|
|
15
|
+
expect(String(controller.signal.reason.stack)).not.toContain("disposeComponent")
|
|
16
|
+
})
|
package/src/abort.ts
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
// `controller.abort()` makes a new DOMException that records the caller's stack, and V8 keeps every frame's function
|
|
2
|
+
// and closure alive until something reads `.stack`. Aborting from a Solid cleanup or update then pins the whole batch
|
|
3
|
+
// it ran in, disposed computations and detached DOM included, for as long as the signal is reachable. This reason is
|
|
4
|
+
// made once, so its stack holds only this module's load.
|
|
5
|
+
const reason = new DOMException("signal is aborted without reason", "AbortError")
|
|
6
|
+
|
|
7
|
+
export function abort(controller: AbortController | undefined) {
|
|
8
|
+
controller?.abort(reason)
|
|
9
|
+
}
|
|
@@ -0,0 +1,136 @@
|
|
|
1
|
+
import { describe, expect, test } from "bun:test"
|
|
2
|
+
import { activityCalendar } from "./activity-calendar.js"
|
|
3
|
+
|
|
4
|
+
const input = {
|
|
5
|
+
from: new Date(2026, 0, 1).getTime(),
|
|
6
|
+
to: new Date(2026, 0, 8).getTime(),
|
|
7
|
+
maxWeeks: 53,
|
|
8
|
+
activity: [
|
|
9
|
+
{ date: "2026-01-01", steps: 1 },
|
|
10
|
+
{ date: "2026-01-02", steps: 50 },
|
|
11
|
+
],
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
describe("activity calendar", () => {
|
|
15
|
+
test("aligns Monday-first weeks and excludes cells outside the end-exclusive range", () => {
|
|
16
|
+
const calendar = activityCalendar(input)
|
|
17
|
+
expect(calendar.clipped).toBe(false)
|
|
18
|
+
expect(calendar.weeks).toHaveLength(2)
|
|
19
|
+
expect(calendar.weeks[0][0]).toEqual({ date: "2025-12-29", steps: 0, level: -1 })
|
|
20
|
+
expect(calendar.weeks[0][3]).toEqual({ date: "2026-01-01", steps: 1, level: 2 })
|
|
21
|
+
expect(calendar.weeks[0][4]).toEqual({ date: "2026-01-02", steps: 50, level: 4 })
|
|
22
|
+
expect(calendar.weeks[1][2]).toEqual({ date: "2026-01-07", steps: 0, level: 0 })
|
|
23
|
+
expect(calendar.weeks[1][3].level).toBe(-1)
|
|
24
|
+
expect(calendar.months).toEqual([{ week: 0, label: "Jan", span: 2 }])
|
|
25
|
+
})
|
|
26
|
+
|
|
27
|
+
test("clips to the latest weeks and keeps empty days distinct from out-of-range cells", () => {
|
|
28
|
+
const calendar = activityCalendar({ ...input, activity: [], maxWeeks: 1 })
|
|
29
|
+
expect(calendar.clipped).toBe(true)
|
|
30
|
+
expect(calendar.weeks).toHaveLength(1)
|
|
31
|
+
expect(calendar.weeks[0][0]).toEqual({ date: "2026-01-05", steps: 0, level: 0 })
|
|
32
|
+
expect(calendar.weeks[0][3].level).toBe(-1)
|
|
33
|
+
})
|
|
34
|
+
|
|
35
|
+
test("caps long histories at 53 weeks", () => {
|
|
36
|
+
const calendar = activityCalendar({ ...input, from: new Date(2020, 0, 1).getTime(), maxWeeks: 200 })
|
|
37
|
+
expect(calendar.clipped).toBe(true)
|
|
38
|
+
expect(calendar.weeks).toHaveLength(53)
|
|
39
|
+
expect(calendar.weeks.at(-1)?.[2].date).toBe("2026-01-07")
|
|
40
|
+
expect(calendar.months.reduce((sum, month) => sum + month.span, 0)).toBe(53)
|
|
41
|
+
})
|
|
42
|
+
|
|
43
|
+
test("returns month positions and spans for partial first and last months", () => {
|
|
44
|
+
const calendar = activityCalendar({
|
|
45
|
+
...input,
|
|
46
|
+
from: new Date(2026, 3, 29).getTime(),
|
|
47
|
+
to: new Date(2026, 4, 20).getTime(),
|
|
48
|
+
})
|
|
49
|
+
expect(calendar.months).toEqual([
|
|
50
|
+
{ week: 0, label: "Apr", span: 1 },
|
|
51
|
+
{ week: 1, label: "May", span: 3 },
|
|
52
|
+
])
|
|
53
|
+
const partial = activityCalendar({
|
|
54
|
+
...input,
|
|
55
|
+
from: new Date(2026, 3, 1).getTime(),
|
|
56
|
+
to: new Date(2026, 3, 2).getTime(),
|
|
57
|
+
})
|
|
58
|
+
expect(partial.months).toEqual([{ week: 0, label: "Apr", span: 1 }])
|
|
59
|
+
})
|
|
60
|
+
|
|
61
|
+
test("places month labels across a year boundary", () => {
|
|
62
|
+
const calendar = activityCalendar({
|
|
63
|
+
...input,
|
|
64
|
+
from: new Date(2025, 11, 22).getTime(),
|
|
65
|
+
to: new Date(2026, 0, 12).getTime(),
|
|
66
|
+
})
|
|
67
|
+
expect(calendar.months).toEqual([
|
|
68
|
+
{ week: 0, label: "Dec", span: 1 },
|
|
69
|
+
{ week: 1, label: "Jan", span: 2 },
|
|
70
|
+
])
|
|
71
|
+
})
|
|
72
|
+
|
|
73
|
+
test("keeps exactly seven distinct cells per week across DST and leap days", () => {
|
|
74
|
+
const calendar = activityCalendar({
|
|
75
|
+
from: new Date(2024, 1, 26).getTime(),
|
|
76
|
+
to: new Date(2024, 2, 12).getTime(),
|
|
77
|
+
maxWeeks: 53,
|
|
78
|
+
activity: [
|
|
79
|
+
{ date: "2024-02-29", steps: 1 },
|
|
80
|
+
{ date: "2024-03-10", steps: 1 },
|
|
81
|
+
],
|
|
82
|
+
})
|
|
83
|
+
expect(calendar.weeks).toHaveLength(3)
|
|
84
|
+
expect(
|
|
85
|
+
calendar.weeks
|
|
86
|
+
.flat()
|
|
87
|
+
.filter((day) => day.steps > 0)
|
|
88
|
+
.map((day) => day.date),
|
|
89
|
+
).toEqual(["2024-02-29", "2024-03-10"])
|
|
90
|
+
expect(new Set(calendar.weeks.flat().map((day) => day.date)).size).toBe(21)
|
|
91
|
+
})
|
|
92
|
+
|
|
93
|
+
test("uses the highest intensity for a single distinct positive count", () => {
|
|
94
|
+
const calendar = activityCalendar({ ...input, activity: input.activity.map((day) => ({ ...day, steps: 10 })) })
|
|
95
|
+
expect(
|
|
96
|
+
calendar.weeks
|
|
97
|
+
.flat()
|
|
98
|
+
.filter((day) => day.steps > 0)
|
|
99
|
+
.map((day) => day.level),
|
|
100
|
+
).toEqual([4, 4])
|
|
101
|
+
})
|
|
102
|
+
|
|
103
|
+
test("ranks distinct activity counts in four levels", () => {
|
|
104
|
+
const calendar = activityCalendar({
|
|
105
|
+
...input,
|
|
106
|
+
to: new Date(2026, 0, 10).getTime(),
|
|
107
|
+
activity: Array.from({ length: 8 }, (_, index) => ({ date: `2026-01-0${index + 1}`, steps: index + 1 })),
|
|
108
|
+
})
|
|
109
|
+
expect(
|
|
110
|
+
calendar.weeks
|
|
111
|
+
.flat()
|
|
112
|
+
.filter((day) => day.steps > 0)
|
|
113
|
+
.map((day) => day.level),
|
|
114
|
+
).toEqual([1, 1, 2, 2, 3, 3, 4, 4])
|
|
115
|
+
})
|
|
116
|
+
|
|
117
|
+
test("keeps intensity relative to the requested range when older weeks are clipped", () => {
|
|
118
|
+
const calendar = activityCalendar({
|
|
119
|
+
...input,
|
|
120
|
+
maxWeeks: 1,
|
|
121
|
+
activity: [
|
|
122
|
+
{ date: "2026-01-01", steps: 50 },
|
|
123
|
+
{ date: "2026-01-05", steps: 1 },
|
|
124
|
+
],
|
|
125
|
+
})
|
|
126
|
+
expect(calendar.weeks[0][0].level).toBe(2)
|
|
127
|
+
})
|
|
128
|
+
|
|
129
|
+
test("returns an empty calendar for an empty range", () => {
|
|
130
|
+
expect(activityCalendar({ ...input, to: input.from, activity: [] })).toEqual({
|
|
131
|
+
weeks: [],
|
|
132
|
+
months: [],
|
|
133
|
+
clipped: false,
|
|
134
|
+
})
|
|
135
|
+
})
|
|
136
|
+
})
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
export function activityCalendar(input: {
|
|
2
|
+
activity: readonly { date: string; steps: number }[]
|
|
3
|
+
from: number
|
|
4
|
+
to: number
|
|
5
|
+
maxWeeks: number
|
|
6
|
+
}) {
|
|
7
|
+
// Extract local dates first, then use UTC ordinals so DST cannot add or drop cells.
|
|
8
|
+
const ordinal = (time: number) => {
|
|
9
|
+
const date = new Date(time)
|
|
10
|
+
return Date.UTC(date.getFullYear(), date.getMonth(), date.getDate()) / 86_400_000
|
|
11
|
+
}
|
|
12
|
+
const from = ordinal(input.from)
|
|
13
|
+
const to = ordinal(input.to - 1)
|
|
14
|
+
const monday = from - ((new Date(from * 86_400_000).getUTCDay() + 6) % 7)
|
|
15
|
+
const total = input.to <= input.from ? 0 : Math.floor((to - monday) / 7) + 1
|
|
16
|
+
const count = Math.min(total, 53, Math.max(1, Math.floor(input.maxWeeks)))
|
|
17
|
+
const start = monday + Math.max(0, total - count) * 7
|
|
18
|
+
const values = new Map(input.activity.map((day) => [day.date, day.steps]))
|
|
19
|
+
const levels = [...new Set([...values.values()].filter((steps) => steps > 0))].sort((a, b) => a - b)
|
|
20
|
+
const weeks = Array.from({ length: count }, (_, week) =>
|
|
21
|
+
Array.from({ length: 7 }, (_, day) => {
|
|
22
|
+
const date = start + week * 7 + day
|
|
23
|
+
const key = new Date(date * 86_400_000).toISOString().slice(0, 10)
|
|
24
|
+
const steps = values.get(key) ?? 0
|
|
25
|
+
return {
|
|
26
|
+
date: key,
|
|
27
|
+
steps,
|
|
28
|
+
level:
|
|
29
|
+
date < from || date > to
|
|
30
|
+
? -1
|
|
31
|
+
: steps === 0
|
|
32
|
+
? 0
|
|
33
|
+
: Math.max(1, Math.ceil(((levels.indexOf(steps) + 1) / levels.length) * 4)),
|
|
34
|
+
}
|
|
35
|
+
}),
|
|
36
|
+
)
|
|
37
|
+
const formatter = new Intl.DateTimeFormat("en-US", { month: "short", timeZone: "UTC" })
|
|
38
|
+
// Thursday identifies the month owning most of a week; partial edge weeks stay inside the range.
|
|
39
|
+
const months = weeks
|
|
40
|
+
.map((_, week) => ({
|
|
41
|
+
week,
|
|
42
|
+
label: formatter.format(Math.min(to, Math.max(from, start + week * 7 + 3)) * 86_400_000),
|
|
43
|
+
}))
|
|
44
|
+
.filter((month, index, months) => index === 0 || month.label !== months[index - 1].label)
|
|
45
|
+
return {
|
|
46
|
+
weeks,
|
|
47
|
+
months: months.map((month, index) => ({ ...month, span: (months[index + 1]?.week ?? count) - month.week })),
|
|
48
|
+
clipped: count < total,
|
|
49
|
+
}
|
|
50
|
+
}
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
import { describe, expect, test } from "bun:test"
|
|
2
|
+
import { artifactKind } from "./artifact.js"
|
|
3
|
+
|
|
4
|
+
describe("artifactKind", () => {
|
|
5
|
+
test.each([
|
|
6
|
+
["shot.PNG", "image"],
|
|
7
|
+
["logo.svg", "svg"],
|
|
8
|
+
["song.mp3", "audio"],
|
|
9
|
+
["demo.mp4", "video"],
|
|
10
|
+
["clip.webm", "video"],
|
|
11
|
+
["paper.pdf", "pdf"],
|
|
12
|
+
["out/index.html", "html"],
|
|
13
|
+
["README.md", "markdown"],
|
|
14
|
+
["flow.mmd", "mermaid"],
|
|
15
|
+
["data.csv", "table"],
|
|
16
|
+
["data.tsv", "table"],
|
|
17
|
+
["Inter.woff2", "font"],
|
|
18
|
+
["report.docx", "document"],
|
|
19
|
+
["budget.XLSX", "spreadsheet"],
|
|
20
|
+
["deck.pptx", "presentation"],
|
|
21
|
+
["legacy.doc", "text"],
|
|
22
|
+
["src/app.ts", "text"],
|
|
23
|
+
["Makefile", "text"],
|
|
24
|
+
[".env", "text"],
|
|
25
|
+
["archive.tar.gz", "text"],
|
|
26
|
+
] as const)("classifies %s as %s", (path, kind) => {
|
|
27
|
+
expect(artifactKind(path)).toBe(kind)
|
|
28
|
+
})
|
|
29
|
+
})
|
package/src/artifact.ts
ADDED
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
/** How the app shows a file, from its extension. */
|
|
2
|
+
export type ArtifactKind =
|
|
3
|
+
| "image"
|
|
4
|
+
| "svg"
|
|
5
|
+
| "audio"
|
|
6
|
+
| "video"
|
|
7
|
+
| "pdf"
|
|
8
|
+
| "html"
|
|
9
|
+
| "markdown"
|
|
10
|
+
| "mermaid"
|
|
11
|
+
| "table"
|
|
12
|
+
| "font"
|
|
13
|
+
| "document"
|
|
14
|
+
| "spreadsheet"
|
|
15
|
+
| "presentation"
|
|
16
|
+
| "text"
|
|
17
|
+
|
|
18
|
+
const officeKinds = new Map<string, ArtifactKind>([
|
|
19
|
+
["application/vnd.openxmlformats-officedocument.wordprocessingml.document", "document"],
|
|
20
|
+
["application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", "spreadsheet"],
|
|
21
|
+
["application/vnd.openxmlformats-officedocument.presentationml.presentation", "presentation"],
|
|
22
|
+
])
|
|
23
|
+
|
|
24
|
+
const mimes = new Map([
|
|
25
|
+
["png", "image/png"],
|
|
26
|
+
["jpg", "image/jpeg"],
|
|
27
|
+
["jpeg", "image/jpeg"],
|
|
28
|
+
["gif", "image/gif"],
|
|
29
|
+
["webp", "image/webp"],
|
|
30
|
+
["avif", "image/avif"],
|
|
31
|
+
["bmp", "image/bmp"],
|
|
32
|
+
["ico", "image/x-icon"],
|
|
33
|
+
["tif", "image/tiff"],
|
|
34
|
+
["tiff", "image/tiff"],
|
|
35
|
+
["heic", "image/heic"],
|
|
36
|
+
["svg", "image/svg+xml"],
|
|
37
|
+
["mp3", "audio/mpeg"],
|
|
38
|
+
["wav", "audio/wav"],
|
|
39
|
+
["ogg", "audio/ogg"],
|
|
40
|
+
["oga", "audio/ogg"],
|
|
41
|
+
["m4a", "audio/mp4"],
|
|
42
|
+
["aac", "audio/aac"],
|
|
43
|
+
["flac", "audio/flac"],
|
|
44
|
+
["opus", "audio/ogg"],
|
|
45
|
+
["weba", "audio/webm"],
|
|
46
|
+
["mp4", "video/mp4"],
|
|
47
|
+
["m4v", "video/mp4"],
|
|
48
|
+
["webm", "video/webm"],
|
|
49
|
+
["mov", "video/quicktime"],
|
|
50
|
+
["ogv", "video/ogg"],
|
|
51
|
+
["mkv", "video/x-matroska"],
|
|
52
|
+
["pdf", "application/pdf"],
|
|
53
|
+
["html", "text/html"],
|
|
54
|
+
["htm", "text/html"],
|
|
55
|
+
["md", "text/markdown"],
|
|
56
|
+
["markdown", "text/markdown"],
|
|
57
|
+
["mdx", "text/markdown"],
|
|
58
|
+
["mmd", "text/vnd.mermaid"],
|
|
59
|
+
["mermaid", "text/vnd.mermaid"],
|
|
60
|
+
["csv", "text/csv"],
|
|
61
|
+
["tsv", "text/tab-separated-values"],
|
|
62
|
+
["ttf", "font/ttf"],
|
|
63
|
+
["otf", "font/otf"],
|
|
64
|
+
["woff", "font/woff"],
|
|
65
|
+
["woff2", "font/woff2"],
|
|
66
|
+
["docx", "application/vnd.openxmlformats-officedocument.wordprocessingml.document"],
|
|
67
|
+
["xlsx", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"],
|
|
68
|
+
["pptx", "application/vnd.openxmlformats-officedocument.presentationml.presentation"],
|
|
69
|
+
])
|
|
70
|
+
|
|
71
|
+
function artifactExtension(path: string) {
|
|
72
|
+
const name = path.split(/[\\/]/).pop() ?? ""
|
|
73
|
+
const index = name.lastIndexOf(".")
|
|
74
|
+
if (index <= 0) return ""
|
|
75
|
+
return name.slice(index + 1).toLowerCase()
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
export function artifactMime(path: string) {
|
|
79
|
+
return mimes.get(artifactExtension(path))
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
export function artifactKind(path: string): ArtifactKind {
|
|
83
|
+
const mime = artifactMime(path)
|
|
84
|
+
if (!mime) return "text"
|
|
85
|
+
if (mime === "image/svg+xml") return "svg"
|
|
86
|
+
if (mime === "application/pdf") return "pdf"
|
|
87
|
+
if (mime === "text/html") return "html"
|
|
88
|
+
if (mime === "text/markdown") return "markdown"
|
|
89
|
+
if (mime === "text/vnd.mermaid") return "mermaid"
|
|
90
|
+
if (mime === "text/csv" || mime === "text/tab-separated-values") return "table"
|
|
91
|
+
if (mime.startsWith("image/")) return "image"
|
|
92
|
+
if (mime.startsWith("audio/")) return "audio"
|
|
93
|
+
if (mime.startsWith("font/")) return "font"
|
|
94
|
+
return officeKinds.get(mime) ?? "video"
|
|
95
|
+
}
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import { describe, expect, test } from "bun:test"
|
|
2
|
+
import { base64ToBytes, bytesToBase64 } from "./base64.js"
|
|
3
|
+
|
|
4
|
+
describe("base64", () => {
|
|
5
|
+
test("encodes as standard base64 and decodes back to the same bytes", () => {
|
|
6
|
+
const bytes = Uint8Array.from({ length: 70_000 }, (_, index) => index % 256)
|
|
7
|
+
const encoded = bytesToBase64(bytes)
|
|
8
|
+
|
|
9
|
+
expect(encoded).toBe(Buffer.from(bytes).toString("base64"))
|
|
10
|
+
expect(base64ToBytes(encoded)).toEqual(bytes)
|
|
11
|
+
})
|
|
12
|
+
})
|
package/src/base64.ts
ADDED
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
// The native codecs (Chromium 140, Firefox 133, Safari 18.2) run about 100 times faster than a string round trip. The
|
|
2
|
+
// type libraries declare them, but older web browsers lack them, so each is read as possibly missing first.
|
|
3
|
+
const nativeEncode: (() => string) | undefined = Uint8Array.prototype.toBase64
|
|
4
|
+
const nativeDecode: ((value: string) => Uint8Array) | undefined = Uint8Array.fromBase64
|
|
5
|
+
|
|
6
|
+
/** Encodes bytes as standard base64. */
|
|
7
|
+
export function bytesToBase64(bytes: Uint8Array) {
|
|
8
|
+
if (nativeEncode) return bytes.toBase64()
|
|
9
|
+
|
|
10
|
+
const parts: string[] = []
|
|
11
|
+
|
|
12
|
+
for (let index = 0; index < bytes.length; index += 0x8000) {
|
|
13
|
+
parts.push(String.fromCharCode(...bytes.subarray(index, index + 0x8000)))
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
return btoa(parts.join(""))
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
/** Decodes standard base64 into bytes. */
|
|
20
|
+
export function base64ToBytes(value: string) {
|
|
21
|
+
if (nativeDecode) return Uint8Array.fromBase64(value)
|
|
22
|
+
|
|
23
|
+
const binary = atob(value)
|
|
24
|
+
const bytes = new Uint8Array(binary.length)
|
|
25
|
+
|
|
26
|
+
for (let index = 0; index < binary.length; index++) bytes[index] = binary.charCodeAt(index)
|
|
27
|
+
|
|
28
|
+
return bytes
|
|
29
|
+
}
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
import { describe, expect, test } from "bun:test"
|
|
2
|
+
import { Binary } from "./binary.js"
|
|
3
|
+
|
|
4
|
+
describe("binary search", () => {
|
|
5
|
+
test("finds sorted values and their insertion points", () => {
|
|
6
|
+
const values = [{ id: "a" }, { id: "c" }, { id: "e" }]
|
|
7
|
+
expect(Binary.search(values, "c", (item) => item.id)).toEqual({ found: true, index: 1 })
|
|
8
|
+
expect(Binary.search(values, "d", (item) => item.id)).toEqual({ found: false, index: 2 })
|
|
9
|
+
expect(Binary.search(values, "0", (item) => item.id)).toEqual({ found: false, index: 0 })
|
|
10
|
+
})
|
|
11
|
+
|
|
12
|
+
test("inserts before the first matching sorted value", () => {
|
|
13
|
+
const values = [{ id: "a" }, { id: "c" }, { id: "c" }, { id: "e" }]
|
|
14
|
+
const item = { id: "c" }
|
|
15
|
+
|
|
16
|
+
expect(Binary.insert(values, item, (value) => value.id)).toBe(values)
|
|
17
|
+
expect(values).toEqual([{ id: "a" }, item, { id: "c" }, { id: "c" }, { id: "e" }])
|
|
18
|
+
})
|
|
19
|
+
})
|
package/src/binary.ts
ADDED
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
export namespace Binary {
|
|
2
|
+
export function search<T>(array: T[], id: string, compare: (item: T) => string) {
|
|
3
|
+
let left = 0
|
|
4
|
+
let right = array.length - 1
|
|
5
|
+
|
|
6
|
+
while (left <= right) {
|
|
7
|
+
const middle = Math.floor((left + right) / 2)
|
|
8
|
+
const value = compare(array[middle])
|
|
9
|
+
if (value === id) return { found: true, index: middle }
|
|
10
|
+
if (value < id) left = middle + 1
|
|
11
|
+
else right = middle - 1
|
|
12
|
+
}
|
|
13
|
+
return { found: false, index: left }
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
export function insert<T>(array: T[], item: T, compare: (item: T) => string) {
|
|
17
|
+
const id = compare(item)
|
|
18
|
+
let left = 0
|
|
19
|
+
let right = array.length
|
|
20
|
+
|
|
21
|
+
while (left < right) {
|
|
22
|
+
const middle = Math.floor((left + right) / 2)
|
|
23
|
+
if (compare(array[middle]) < id) left = middle + 1
|
|
24
|
+
else right = middle
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
array.splice(left, 0, item)
|
|
28
|
+
return array
|
|
29
|
+
}
|
|
30
|
+
}
|