@dxos/effect 0.8.4-main.406dc2a → 0.8.4-main.59c2e9b

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 (54) hide show
  1. package/dist/lib/browser/chunk-CGS2ULMK.mjs +11 -0
  2. package/dist/lib/browser/chunk-CGS2ULMK.mjs.map +7 -0
  3. package/dist/lib/browser/index.mjs +351 -225
  4. package/dist/lib/browser/index.mjs.map +4 -4
  5. package/dist/lib/browser/meta.json +1 -1
  6. package/dist/lib/browser/testing.mjs +38 -0
  7. package/dist/lib/browser/testing.mjs.map +7 -0
  8. package/dist/lib/node-esm/chunk-HSLMI22Q.mjs +11 -0
  9. package/dist/lib/node-esm/chunk-HSLMI22Q.mjs.map +7 -0
  10. package/dist/lib/node-esm/index.mjs +351 -225
  11. package/dist/lib/node-esm/index.mjs.map +4 -4
  12. package/dist/lib/node-esm/meta.json +1 -1
  13. package/dist/lib/node-esm/testing.mjs +38 -0
  14. package/dist/lib/node-esm/testing.mjs.map +7 -0
  15. package/dist/types/src/RuntimeProvider.d.ts +21 -0
  16. package/dist/types/src/RuntimeProvider.d.ts.map +1 -0
  17. package/dist/types/src/ast.d.ts +34 -21
  18. package/dist/types/src/ast.d.ts.map +1 -1
  19. package/dist/types/src/atom-kvs.d.ts +19 -0
  20. package/dist/types/src/atom-kvs.d.ts.map +1 -0
  21. package/dist/types/src/dynamic-runtime.d.ts +56 -0
  22. package/dist/types/src/dynamic-runtime.d.ts.map +1 -0
  23. package/dist/types/src/dynamic-runtime.test.d.ts +2 -0
  24. package/dist/types/src/dynamic-runtime.test.d.ts.map +1 -0
  25. package/dist/types/src/errors.d.ts +4 -0
  26. package/dist/types/src/errors.d.ts.map +1 -1
  27. package/dist/types/src/index.d.ts +5 -3
  28. package/dist/types/src/index.d.ts.map +1 -1
  29. package/dist/types/src/{jsonPath.d.ts → json-path.d.ts} +11 -3
  30. package/dist/types/src/json-path.d.ts.map +1 -0
  31. package/dist/types/src/json-path.test.d.ts +2 -0
  32. package/dist/types/src/json-path.test.d.ts.map +1 -0
  33. package/dist/types/src/resource.d.ts +5 -1
  34. package/dist/types/src/resource.d.ts.map +1 -1
  35. package/dist/types/tsconfig.tsbuildinfo +1 -1
  36. package/package.json +26 -10
  37. package/src/RuntimeProvider.ts +35 -0
  38. package/src/ast.test.ts +10 -8
  39. package/src/ast.ts +99 -85
  40. package/src/atom-kvs.ts +35 -0
  41. package/src/dynamic-runtime.test.ts +465 -0
  42. package/src/dynamic-runtime.ts +195 -0
  43. package/src/errors.ts +17 -2
  44. package/src/index.ts +5 -3
  45. package/src/interrupt.test.ts +3 -1
  46. package/src/{jsonPath.test.ts → json-path.test.ts} +47 -8
  47. package/src/{jsonPath.ts → json-path.ts} +27 -3
  48. package/src/layers.test.ts +4 -2
  49. package/src/otel.test.ts +1 -0
  50. package/src/resource.ts +9 -4
  51. package/src/sanity.test.ts +24 -10
  52. package/dist/types/src/jsonPath.d.ts.map +0 -1
  53. package/dist/types/src/jsonPath.test.d.ts +0 -2
  54. package/dist/types/src/jsonPath.test.d.ts.map +0 -1
package/src/errors.ts CHANGED
@@ -8,6 +8,7 @@ import * as Effect from 'effect/Effect';
8
8
  import * as Exit from 'effect/Exit';
9
9
  import * as GlobalValue from 'effect/GlobalValue';
10
10
  import * as Option from 'effect/Option';
11
+ import * as Runtime from 'effect/Runtime';
11
12
  import type * as Tracer from 'effect/Tracer';
12
13
 
13
14
  const spanSymbol = Symbol.for('effect/SpanAnnotation');
@@ -21,6 +22,10 @@ const locationRegex = /\((.*)\)/g;
21
22
  * Unwraps error proxy.
22
23
  */
23
24
  const prettyErrorStack = (error: any, appendStacks: string[] = []): any => {
25
+ if (typeof error !== 'object' || error === null) {
26
+ return error;
27
+ }
28
+
24
29
  const span = error[spanSymbol];
25
30
 
26
31
  const lines = typeof error.stack === 'string' ? error.stack.split('\n') : [];
@@ -118,9 +123,10 @@ export const causeToError = (cause: Cause.Cause<any>): Error => {
118
123
  const errors = [...Chunk.toArray(Cause.failures(cause)), ...Chunk.toArray(Cause.defects(cause))];
119
124
 
120
125
  const getStackFrames = (): string[] => {
121
- const o: { stack: string } = {} as any;
126
+ // Bun requies the target object for `captureStackTrace` to be an Error.
127
+ const o = new Error();
122
128
  Error.captureStackTrace(o, getStackFrames);
123
- return o.stack.split('\n').slice(1);
129
+ return o.stack!.split('\n').slice(1);
124
130
  };
125
131
 
126
132
  const stackFrames = getStackFrames();
@@ -174,6 +180,15 @@ export const runAndForwardErrors = async <A, E>(
174
180
  return unwrapExit(exit);
175
181
  };
176
182
 
183
+ export const runInRuntime = async <A, E, R>(
184
+ runtime: Runtime.Runtime<R>,
185
+ effect: Effect.Effect<A, E, R>,
186
+ options?: { signal?: AbortSignal },
187
+ ): Promise<A> => {
188
+ const exit = await Runtime.runPromiseExit(runtime, effect, options);
189
+ return unwrapExit(exit);
190
+ };
191
+
177
192
  /**
178
193
  * Like `Effect.promise` but also caputes spans for defects.
179
194
  * Workaround for: https://github.com/Effect-TS/effect/issues/5436
package/src/index.ts CHANGED
@@ -3,9 +3,11 @@
3
3
  //
4
4
 
5
5
  export * from './ast';
6
- export * from './jsonPath';
7
- export * from './url';
6
+ export * from './atom-kvs';
8
7
  export * from './context';
8
+ export * as DynamicRuntime from './dynamic-runtime';
9
9
  export * from './errors';
10
- export * from './testing';
10
+ export * from './json-path';
11
11
  export * from './resource';
12
+ export * from './url';
13
+ export * as RuntimeProvider from './RuntimeProvider';
@@ -7,6 +7,8 @@ import * as Cause from 'effect/Cause';
7
7
  import * as Effect from 'effect/Effect';
8
8
  import * as Fiber from 'effect/Fiber';
9
9
 
10
+ import { runAndForwardErrors } from './errors';
11
+
10
12
  const doWork = Effect.fn('doWork')(function* () {
11
13
  yield* Effect.sleep('1 minute');
12
14
  return 'work done';
@@ -18,7 +20,7 @@ it.effect.skip(
18
20
  function* (_) {
19
21
  const resultFiber = yield* doWork().pipe(Effect.fork);
20
22
  setTimeout(() => {
21
- void Effect.runPromise(Fiber.interrupt(resultFiber));
23
+ void runAndForwardErrors(Fiber.interrupt(resultFiber));
22
24
  }, 2_000);
23
25
 
24
26
  const result = yield* resultFiber;
@@ -4,7 +4,7 @@
4
4
 
5
5
  import { describe, expect, test } from 'vitest';
6
6
 
7
- import { type JsonPath, createJsonPath, getField, isJsonPath, splitJsonPath } from './jsonPath';
7
+ import { type JsonPath, createJsonPath, getField, getValue, isJsonPath, setValue, splitJsonPath } from './json-path';
8
8
 
9
9
  describe('createJsonPath', () => {
10
10
  test('supported path subset', () => {
@@ -32,9 +32,9 @@ describe('createJsonPath', () => {
32
32
 
33
33
  test('path splitting', () => {
34
34
  const cases = [
35
- ['foo.bar[0].baz', ['foo', 'bar', '0', 'baz']],
36
- ['users[1].name', ['users', '1', 'name']],
37
- ['data[0][1]', ['data', '0', '1']],
35
+ ['foo.bar[0].baz', ['foo', 'bar', 0, 'baz']],
36
+ ['users[1].name', ['users', 1, 'name']],
37
+ ['data[0][1]', ['data', 0, 1]],
38
38
  ['simple.path', ['simple', 'path']],
39
39
  ['root', ['root']],
40
40
  ] as const;
@@ -47,15 +47,15 @@ describe('createJsonPath', () => {
47
47
  test('path splitting - extended cases', () => {
48
48
  const cases = [
49
49
  // Multiple consecutive array indices.
50
- ['matrix[0][1][2]', ['matrix', '0', '1', '2']],
50
+ ['matrix[0][1][2]', ['matrix', 0, 1, 2]],
51
51
  // Properties with underscores and $.
52
52
  ['$_foo.bar_baz', ['$_foo', 'bar_baz']],
53
53
  // Deep nesting.
54
- ['very.deep.nested[0].property.path[5]', ['very', 'deep', 'nested', '0', 'property', 'path', '5']],
54
+ ['very.deep.nested[0].property.path[5]', ['very', 'deep', 'nested', 0, 'property', 'path', 5]],
55
55
  // Single character properties.
56
- ['a[0].b.c', ['a', '0', 'b', 'c']],
56
+ ['a[0].b.c', ['a', 0, 'b', 'c']],
57
57
  // Properties containing numbers.
58
- ['prop123.item456[7]', ['prop123', 'item456', '7']],
58
+ ['prop123.item456[7]', ['prop123', 'item456', 7]],
59
59
  ] as const;
60
60
 
61
61
  cases.forEach(([input, expected]) => {
@@ -99,3 +99,42 @@ describe('createJsonPath', () => {
99
99
  expect(getField({ a: 'foo' }, 'a' as JsonPath)).toBe('foo');
100
100
  });
101
101
  });
102
+
103
+ describe('Types', () => {
104
+ test('checks sanity', async ({ expect }) => {
105
+ const obj = {};
106
+ expect(obj).to.exist;
107
+ });
108
+ });
109
+
110
+ describe('get/set deep', () => {
111
+ test('get/set operations', ({ expect }) => {
112
+ const obj = {
113
+ name: 'test',
114
+ items: ['a', 'b', 'c'],
115
+ nested: {
116
+ prop: 'value',
117
+ arr: [1, 2, 3],
118
+ },
119
+ };
120
+
121
+ // Basic property access.
122
+ expect(getValue(obj, 'name' as JsonPath)).toBe('test');
123
+
124
+ // Array index access.
125
+ expect(getValue(obj, 'items[1]' as JsonPath)).toBe('b');
126
+
127
+ // Nested property access.
128
+ expect(getValue(obj, 'nested.prop' as JsonPath)).toBe('value');
129
+
130
+ // Nested array access.
131
+ expect(getValue(obj, 'nested.arr[2]' as JsonPath)).toBe(3);
132
+
133
+ // Setting values.
134
+ const updated1 = setValue(obj, 'items[1]' as JsonPath, 'x');
135
+ expect(updated1.items[1]).toBe('x');
136
+
137
+ const updated2 = setValue(obj, 'nested.arr[0]' as JsonPath, 99);
138
+ expect(updated2.nested.arr[0]).toBe(99);
139
+ });
140
+ });
@@ -7,16 +7,21 @@ import * as Schema from 'effect/Schema';
7
7
  import { JSONPath } from 'jsonpath-plus';
8
8
 
9
9
  import { invariant } from '@dxos/invariant';
10
+ import { getDeep, setDeep } from '@dxos/util';
10
11
 
11
12
  export type JsonProp = string & { __JsonPath: true; __JsonProp: true };
12
13
  export type JsonPath = string & { __JsonPath: true };
13
14
 
15
+ // TODO(burdon): Start with "$."?
16
+
14
17
  const PATH_REGEX = /^($|[a-zA-Z_$][\w$]*(?:\.[a-zA-Z_$][\w$]*|\[\d+\](?:\.)?)*$)/;
18
+
15
19
  const PROP_REGEX = /^\w+$/;
16
20
 
17
21
  /**
18
22
  * https://www.ietf.org/archive/id/draft-goessner-dispatch-jsonpath-00.html
19
23
  */
24
+ // TODO(burdon): Keys could be arbitrary strings.
20
25
  export const JsonPath = Schema.String.pipe(Schema.pattern(PATH_REGEX)).annotations({
21
26
  title: 'JSON path',
22
27
  description: 'JSON path to a property',
@@ -50,7 +55,7 @@ export const isJsonPath = (value: unknown): value is JsonPath => {
50
55
  * @param path Array of string or number segments
51
56
  * @returns Valid JsonPath or undefined if invalid
52
57
  */
53
- export const createJsonPath = (path: (string | number)[]): JsonPath => {
58
+ export const createJsonPath = (path: readonly (string | number)[]): JsonPath => {
54
59
  const candidatePath = path
55
60
  .map((p, i) => {
56
61
  if (typeof p === 'number') {
@@ -80,7 +85,7 @@ export const fromEffectValidationPath = (effectPath: string): JsonPath => {
80
85
  * Splits a JsonPath into its constituent parts.
81
86
  * Handles property access and array indexing.
82
87
  */
83
- export const splitJsonPath = (path: JsonPath): string[] => {
88
+ export const splitJsonPath = (path: JsonPath): (string | number)[] => {
84
89
  if (!isJsonPath(path)) {
85
90
  return [];
86
91
  }
@@ -88,14 +93,33 @@ export const splitJsonPath = (path: JsonPath): string[] => {
88
93
  return (
89
94
  path
90
95
  .match(/[a-zA-Z_$][\w$]*|\[\d+\]/g)
91
- ?.map((part) => (part.startsWith('[') ? part.replace(/[[\]]/g, '') : part)) ?? []
96
+ ?.map((part) => part.replace(/[[\]]/g, ''))
97
+ .map((part) => {
98
+ const parsed = Number.parseInt(part, 10);
99
+ return Number.isNaN(parsed) ? part : parsed;
100
+ }) ?? []
92
101
  );
93
102
  };
94
103
 
95
104
  /**
96
105
  * Applies a JsonPath to an object.
97
106
  */
107
+ // TODO(burdon): Reconcile with getValue.
98
108
  export const getField = (object: any, path: JsonPath): any => {
99
109
  // By default, JSONPath returns an array of results.
100
110
  return JSONPath({ path, json: object })[0];
101
111
  };
112
+
113
+ /**
114
+ * Get value from object using JsonPath.
115
+ */
116
+ export const getValue = <T extends object>(obj: T, path: JsonPath): any => {
117
+ return getDeep(obj, splitJsonPath(path));
118
+ };
119
+
120
+ /**
121
+ * Set value on object using JsonPath.
122
+ */
123
+ export const setValue = <T extends object>(obj: T, path: JsonPath, value: any): T => {
124
+ return setDeep(obj, splitJsonPath(path), value);
125
+ };
@@ -10,6 +10,8 @@ import * as Layer from 'effect/Layer';
10
10
  import * as ManagedRuntime from 'effect/ManagedRuntime';
11
11
  import { test } from 'vitest';
12
12
 
13
+ import { runAndForwardErrors } from './errors';
14
+
13
15
  class ClientConfig extends Context.Tag('ClientConfig')<ClientConfig, { endpoint: string }>() {}
14
16
 
15
17
  class Client extends Context.Tag('Client')<Client, { call: () => Effect.Effect<void> }>() {
@@ -76,7 +78,7 @@ class ClientPlugin {
76
78
  async run() {
77
79
  const layer = Layer.provide(Client.layer, this._serverPlugin.clientConfigLayer);
78
80
 
79
- await Effect.runPromise(
81
+ await runAndForwardErrors(
80
82
  Effect.gen(function* () {
81
83
  const client = yield* Client;
82
84
  yield* client.call();
@@ -89,7 +91,7 @@ test.skip('plugins', async () => {
89
91
  const serverPlugin = new ServerPlugin();
90
92
  console.log('ServerPlugin created');
91
93
 
92
- await Effect.runPromise(Effect.sleep(Duration.millis(500)));
94
+ await runAndForwardErrors(Effect.sleep(Duration.millis(500)));
93
95
  console.log('wake up');
94
96
 
95
97
  {
package/src/otel.test.ts CHANGED
@@ -76,6 +76,7 @@ const makeOtelLogProcessor = (logger: Logger): LogProcessor => {
76
76
  });
77
77
  };
78
78
  };
79
+
79
80
  log.addProcessor(makeOtelLogProcessor(logger));
80
81
 
81
82
  beforeAll(() => {
package/src/resource.ts CHANGED
@@ -3,23 +3,28 @@
3
3
  //
4
4
 
5
5
  import * as Effect from 'effect/Effect';
6
+ import type * as Scope from 'effect/Scope';
6
7
 
7
8
  import type { Lifecycle } from '@dxos/context';
8
9
 
9
- // TODO(dmaretskyi): Extract to effect-utils.
10
- export const acquireReleaseResource = <T extends Lifecycle>(getResource: () => T) =>
10
+ /**
11
+ * Acquires a resource and releases it when the scope is closed.
12
+ */
13
+ export const acquireReleaseResource = <T extends Lifecycle>(
14
+ getResource: () => T,
15
+ ): Effect.Effect<T, never, Scope.Scope> =>
11
16
  Effect.acquireRelease(
12
17
  Effect.gen(function* () {
13
18
  const resource = getResource();
14
19
  yield* Effect.promise(async () => {
15
- resource.open?.();
20
+ await resource.open?.();
16
21
  return undefined;
17
22
  });
18
23
  return resource;
19
24
  }),
20
25
  (resource) =>
21
26
  Effect.promise(async () => {
22
- resource.close?.();
27
+ await resource.close?.();
23
28
  return undefined;
24
29
  }),
25
30
  );
@@ -8,6 +8,8 @@ import { describe, test } from 'vitest';
8
8
 
9
9
  import { log } from '@dxos/log';
10
10
 
11
+ import { runAndForwardErrors } from './errors';
12
+
11
13
  describe('sanity tests', () => {
12
14
  test('function pipeline', async ({ expect }) => {
13
15
  const result = Function.pipe(
@@ -19,35 +21,47 @@ describe('sanity tests', () => {
19
21
  });
20
22
 
21
23
  test('effect pipeline (mixing types)', async ({ expect }) => {
22
- const result = await Effect.runPromise(
24
+ const result = await runAndForwardErrors(
23
25
  Function.pipe(
24
26
  Effect.promise(() => Promise.resolve(100)),
25
- Effect.tap((value) => log('tap', { value })),
27
+ Effect.tap((value) => {
28
+ log('tap', { value });
29
+ }),
26
30
  Effect.map((value: number) => String(value)),
27
- Effect.tap((value) => log('tap', { value })),
31
+ Effect.tap((value) => {
32
+ log('tap', { value });
33
+ }),
28
34
  Effect.map((value: string) => value.length),
29
- Effect.tap((value) => log('tap', { value })),
35
+ Effect.tap((value) => {
36
+ log('tap', { value });
37
+ }),
30
38
  ),
31
39
  );
32
40
  expect(result).to.eq(3);
33
41
  });
34
42
 
35
43
  test('effect pipeline (mixing sync/async)', async ({ expect }) => {
36
- const result = await Effect.runPromise(
44
+ const result = await runAndForwardErrors(
37
45
  Function.pipe(
38
46
  Effect.succeed(100),
39
- Effect.tap((value) => log('tap', { value })),
47
+ Effect.tap((value) => {
48
+ log('tap', { value });
49
+ }),
40
50
  Effect.flatMap((value) => Effect.promise(() => Promise.resolve(String(value)))),
41
- Effect.tap((value) => log('tap', { value })),
51
+ Effect.tap((value) => {
52
+ log('tap', { value });
53
+ }),
42
54
  Effect.map((value) => value.length),
43
- Effect.tap((value) => log('tap', { value })),
55
+ Effect.tap((value) => {
56
+ log('tap', { value });
57
+ }),
44
58
  ),
45
59
  );
46
60
  expect(result).to.eq(3);
47
61
  });
48
62
 
49
63
  test('error handling', async ({ expect }) => {
50
- Effect.runPromise(
64
+ runAndForwardErrors(
51
65
  Function.pipe(
52
66
  Effect.succeed(10),
53
67
  Effect.map((value) => value * 2),
@@ -63,7 +77,7 @@ describe('sanity tests', () => {
63
77
  ),
64
78
  )
65
79
  .then(() => expect.fail())
66
- .catch((error) => {
80
+ .catch((error: any) => {
67
81
  expect(error).to.be.instanceOf(Error);
68
82
  });
69
83
  });
@@ -1 +0,0 @@
1
- {"version":3,"file":"jsonPath.d.ts","sourceRoot":"","sources":["../../../src/jsonPath.ts"],"names":[],"mappings":"AAKA,OAAO,KAAK,MAAM,MAAM,eAAe,CAAC;AAKxC,MAAM,MAAM,QAAQ,GAAG,MAAM,GAAG;IAAE,UAAU,EAAE,IAAI,CAAC;IAAC,UAAU,EAAE,IAAI,CAAA;CAAE,CAAC;AACvE,MAAM,MAAM,QAAQ,GAAG,MAAM,GAAG;IAAE,UAAU,EAAE,IAAI,CAAA;CAAE,CAAC;AAKrD;;GAEG;AACH,eAAO,MAAM,QAAQ,EAGR,MAAM,CAAC,MAAM,CAAC,QAAQ,CAAC,CAAC;AACrC,eAAO,MAAM,QAAQ,EAIT,MAAM,CAAC,MAAM,CAAC,QAAQ,CAAC,CAAC;AAEpC,eAAO,MAAM,UAAU,GAAI,OAAO,OAAO,KAAG,KAAK,IAAI,QAEpD,CAAC;AAEF;;;;;;;;;;;;;;;;;;GAkBG;AACH,eAAO,MAAM,cAAc,GAAI,MAAM,CAAC,MAAM,GAAG,MAAM,CAAC,EAAE,KAAG,QAa1D,CAAC;AAEF;;;GAGG;AACH,eAAO,MAAM,wBAAwB,GAAI,YAAY,MAAM,KAAG,QAK7D,CAAC;AAEF;;;GAGG;AACH,eAAO,MAAM,aAAa,GAAI,MAAM,QAAQ,KAAG,MAAM,EAUpD,CAAC;AAEF;;GAEG;AACH,eAAO,MAAM,QAAQ,GAAI,QAAQ,GAAG,EAAE,MAAM,QAAQ,KAAG,GAGtD,CAAC"}
@@ -1,2 +0,0 @@
1
- export {};
2
- //# sourceMappingURL=jsonPath.test.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"jsonPath.test.d.ts","sourceRoot":"","sources":["../../../src/jsonPath.test.ts"],"names":[],"mappings":""}