@akterjs/sdk 0.0.0-stage → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (37) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +105 -2
  3. package/dist/actor/json-document.schema.d.mts +14 -0
  4. package/dist/actor/json-document.schema.mjs +177 -0
  5. package/dist/actor/plain-actor.contract.d.mts +3 -0
  6. package/dist/actor/plain-actor.contract.mjs +63 -0
  7. package/dist/actor/plain-compile.contract.d.mts +100 -0
  8. package/dist/actor/plain-compile.contract.mjs +267 -0
  9. package/dist/actor/plain-definition.errors.d.mts +12 -0
  10. package/dist/actor/plain-definition.errors.mjs +10 -0
  11. package/dist/actor/plain-error.schema.d.mts +25 -0
  12. package/dist/actor/plain-error.schema.mjs +90 -0
  13. package/dist/actor/plain-handlers.contract.d.mts +87 -0
  14. package/dist/actor/plain-handlers.contract.mjs +94 -0
  15. package/dist/actor/plain-implement.contract.d.mts +27 -0
  16. package/dist/actor/plain-implement.contract.mjs +184 -0
  17. package/dist/actor/plain-types.contract.d.mts +316 -0
  18. package/dist/actor/plain-types.contract.mjs +1 -0
  19. package/dist/actor/plain-values.contract.d.mts +11 -0
  20. package/dist/actor/plain-values.contract.mjs +1 -0
  21. package/dist/actor/resource/plain-computers.contract.d.mts +89 -0
  22. package/dist/actor/resource/plain-computers.contract.mjs +34 -0
  23. package/dist/actor/resource/plain-file-access.contract.d.mts +38 -0
  24. package/dist/actor/resource/plain-file-access.contract.mjs +23 -0
  25. package/dist/actor/resource/plain-files.contract.d.mts +53 -0
  26. package/dist/actor/resource/plain-files.contract.mjs +47 -0
  27. package/dist/actor/standard-schema.schema.d.mts +76 -0
  28. package/dist/actor/standard-schema.schema.mjs +113 -0
  29. package/dist/local-server.adapter.d.mts +23 -0
  30. package/dist/local-server.adapter.mjs +43 -0
  31. package/dist/plain-client.adapter.d.mts +60 -0
  32. package/dist/plain-client.adapter.mjs +12 -0
  33. package/dist/plain-engine.layer.d.mts +9 -0
  34. package/dist/plain-engine.layer.mjs +10 -0
  35. package/dist/plain-sdk.contract.d.mts +7 -0
  36. package/dist/plain-sdk.contract.mjs +1 -0
  37. package/package.json +67 -3
package/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/README.md CHANGED
@@ -1,3 +1,106 @@
1
- # Temporary Holding Version
1
+ # @akterjs/sdk
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ The plain TypeScript SDK, for teams that don't write Effect: declare actors with Standard Schema validators, write handlers as plain functions, and call actors through a Promise client that rejects with the declared error classes. It compiles every declaration to `Akter.make` from `@akterjs/effect`, so both SDKs run on the same engine and pass the same engine conformance (ADR 0005, ADR 0015). No Effect type appears in its public surface.
4
+
5
+ ```sh
6
+ npm install @akterjs/sdk
7
+ npm install -D @akterjs/cli
8
+ ```
9
+
10
+ Docs: https://docs.akter.dev. Pricing: https://docs.akter.dev/pricing.
11
+
12
+ ```ts
13
+ import { z } from "zod";
14
+ import { Akter } from "@akterjs/sdk";
15
+
16
+ export const OverdrawnError = Akter.error("OverdrawnError", z.object({ balance: z.number().int() }));
17
+
18
+ export const Account = Akter.make("Account", {
19
+ commands: {
20
+ deposit: Akter.command({ payload: z.object({ amount: z.number().int() }), success: z.number().int() }),
21
+ withdraw: Akter.command({ errors: [OverdrawnError], payload: z.object({ amount: z.number().int() }) }),
22
+ },
23
+ create: z.object({ owner: z.string() }),
24
+ key: z.string(),
25
+ queries: { balance: Akter.query({ success: z.number().int() }) },
26
+ state: z.object({ balance: z.number().int(), owner: z.string() }),
27
+ });
28
+
29
+ export const AccountLive = Account.implement({
30
+ commands: {
31
+ deposit: (ctx, { amount }) => {
32
+ ctx.update({ balance: ctx.state.balance + amount });
33
+
34
+ return ctx.state.balance + amount;
35
+ },
36
+ withdraw: (ctx, { amount }) => {
37
+ if (amount > ctx.state.balance) {
38
+ throw new OverdrawnError({ balance: ctx.state.balance - amount });
39
+ }
40
+
41
+ ctx.update({ balance: ctx.state.balance - amount });
42
+ },
43
+ },
44
+ create: (_ctx, { owner }) => ({ balance: 0, owner }),
45
+ queries: { balance: (ctx) => ctx.state.balance },
46
+ });
47
+
48
+ export const app = Akter.app([AccountLive]);
49
+ ```
50
+
51
+ ## Entry points
52
+
53
+ | Import | What it holds |
54
+ | ---------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
55
+ | `@akterjs/sdk` | `Akter.make`, `command`, `query`, `job`, `error`, `app`, the `Principal` and `ActorPrincipal` validators, and the plain types |
56
+ | `@akterjs/sdk/client` | `createClient({ actors, url, headers })`: `client.Account("acct-1").deposit({ amount: 5 })`, `create`, `ensure`, `warm`, and `subscribe` on queries and state |
57
+ | `@akterjs/sdk/testing` | `serveLocal({ app })`: the local engine in this process, resolving to `{ url, close, erase }`, for tests and scripts |
58
+ | `@akterjs/sdk/engine` | `engineOf(app)`: the Effect actors and layer an app serves, for engines and `@akterjs/conformance`, not for apps. It is the one entry point whose types come from Effect |
59
+
60
+ `akter dev` and `akter deploy` load `app` from the app module as they do for an Effect app: both read its `actors` and `layer`.
61
+
62
+ ## What a declaration may hold
63
+
64
+ A validator implements both Standard Schema and Standard JSON Schema, such as Zod 4, ArkType, Valibot through `toStandardJsonSchema`, or Effect Schema through `Schema.toStandardJSONSchemaV1(Schema.toStandardSchemaV1(schema))` (ADR 0015). `Akter.make` exports each declaration's input and output JSON Schema (draft 2020-12) and throws a `PlainDefinitionError`, naming the actor, the member, the part and the reasons, when:
65
+
66
+ - the validator has no JSON Schema export, or its export throws, as Zod's does for `z.date()`
67
+ - a declaration refers to itself (a recursive `$ref`)
68
+ - a value position accepts anything (`z.unknown()`, `{}`, `true`). `additionalProperties: true` beside declared properties, as Effect Schema exports every struct, is allowed
69
+ - an error class was not made by `Akter.error`, or the actor declares both `initial` and `create`, or neither
70
+
71
+ At run time, every payload, reply, error, key, principal and state value passes the validator and must come out as JSON, so a validator that returns a `Date` for a string-shaped export fails the call, and the command changes nothing. The captured documents are on `actor.contract`, keyed by member, for history and devtools.
72
+
73
+ ## Handlers
74
+
75
+ Command, query, create and result handlers are synchronous. They get `ctx` with the actor's `state`, `key`, `principal` and `sql` (a tagged template over the actor's own SQLite database that runs now and returns rows), and a command also gets `update`, `id`, `now`, `send`, `schedule`, `cancel`, `start` and `signal`. A handler that throws a declared error class fails the call with that error and rolls back every write. Anything else it throws, or a Promise it returns, is a defect: I/O belongs in a job (ADR 0007).
76
+
77
+ A job handler is `async (payload, steps) => value`. `steps.run(name, (step) => ...)` records the step's JSON result (any JSON-safe value, interfaces included; a function, `Date`, `bigint`, symbol or `undefined` field is a type error naming it, such as `NotJson<"a Date">`), and `step.key` is its idempotency key: the same each time this job runs this step, distinct from every other step and job, and `steps.sleep(name, "2 hours")` is a durable timer, so a job that resumes after a restart skips the steps it recorded. `steps.waitFor(name)` waits until a command of the same actor calls `ctx.signal(id, name, value)` with the job's id and resolves to the JSON `value`, recorded like a step, as an approval does. The signal is stored in the command's transaction and wakes the job once it commits, so a command that throws signals nothing and a retried one signals once; a job that has finished or was never started ignores it. Approve another actor's job by sending that actor a command that signals it. A job declared with `patches: ["review-first"]` asks `steps.patched("review-first")`, which is `true` only when the code that started the job declared that patch, so a job in flight keeps its old path across a deploy that changes its steps. The actor's result handler for that job receives `ctx`, the result (`{ outcome: "success", value }`, `{ outcome: "failure", error }` or `{ outcome: "defect", defect }`) and the job, `{ id }`, where `id` is what `ctx.start` returned.
78
+
79
+ ## Parity with the Effect SDK
80
+
81
+ Built and tested: actors with `initial` or `create`, commands, queries, declared caller kinds, error classes, jobs with recorded steps, durable sleep and signals (`ctx.signal`, `steps.waitFor`), result handlers, `send`, `schedule`, SQL migrations, live queries and state subscriptions, files, computers in jobs, and the captured contract. `@akterjs/conformance` runs every engine guarantee against a plain Ledger with the Effect Ledger's wire contract. Built without a test of their own yet: `cancel` and state upgrades (`state: { from, upgrade }`).
82
+
83
+ Files: a client uploads bytes with `client.Account(key).files.upload(bytes)` and gets a receipt; a command binds it with `ctx.files.attach(path, receipt)` or drops one with `ctx.files.remove(path)`, both in the command's transaction, so a command that then throws attaches nothing. `ctx.files.list({ prefix?, limit?, cursor? })` and `ctx.files.usage(...)` work in commands, result handlers and queries. Bytes never pass through a handler (ADR 0007): clients read them with `files.download(path, range?)`. A file failure inside a handler, such as an unknown receipt, is thrown as the engine's tagged error (`_tag: "FileNotFoundError"`), and fails the call as a defect unless the handler catches it.
84
+
85
+ Computers: in a job, `steps.computer(Task, key)` is that actor's computers, the plain face of the Effect `Task.computer(key)`: `ensure`, `get`, `list`, `pause`, `resume`, `stop`, `remove`, `fork` and `exec`, each returning a Promise. Call them inside `steps.run`, and key each exec step with its step's key, as in `steps.run("test", (step) => computers.exec("web", { command: "pnpm test", key: step.key }))`, so a step that runs again reads the recorded outcome back instead of running twice. A failure rejects with the engine's tagged error (`_tag: "ComputerHeldError"`), and a spec or exec request past the limits rejects with `InvalidRequestError` before it reaches a provider. Computers are for jobs only: a command or query does no I/O (ADR 0007). Tested against a recording provider; no engine provides computers until Phase 6 does, so until then every call rejects with `ComputersUnavailableError`.
86
+
87
+ Fork from the client: `client.Task(key).fork(into)` copies the actor into `into` and resolves with the copy's handle, typed like the original; the copy starts quiet (ADR 0017). It admits only an app's operators, the `user` and `apiKey` kinds. `akter dev` forks. Akter Cloud refuses the fork RPC for every caller by design (`InvalidRequestError`): a fork there is an operator action on the Cloud API (decision 5), made with `akter actors fork`, the `actors_fork` MCP tool or `actorForks.create`. `examples/best-of-n-agent` runs one attempt per fork with it.
88
+
89
+ Not built yet, each waiting on its engine phase (`../akter-cloud/docs/release-matrix.md` lists their state): fork from a handler or job, branch, snapshot and restore of actors (Phase 7). Each joins `ctx` and the client the way `send` and `start` do here: a method on the erased context in `src/actor/plain-handlers.contract.ts`, typed per actor in `src/actor/plain-types.contract.ts`.
90
+
91
+ Known limits:
92
+
93
+ - A handler that catches a step's rejection while its job is being suspended still ends interrupted; the step replays when the job resumes.
94
+ - `serveLocal` runs on the real clock. Drive durable time in tests with `Story` from `@akterjs/effect/testing`, as `tests/actor/plain-actor.contract.test.ts` does.
95
+
96
+ Local administration: `server.erase({ actor, key })` stops the actor's jobs and removes its computers, file claims and
97
+ database. It is idempotent; a durable marker reserves the erased key in that store and resumes interrupted cleanup
98
+ on restart. It is an explicit in-process method, never an app RPC or a bypass of Cloud's per-target erase approval.
99
+ `serveLocal({ app, computers: true })` opts into local computers for that server; `false` disables them and omitting
100
+ the option keeps `AKTER_LOCAL_COMPUTERS`. These run ordinary local processes, not isolated virtual machines.
101
+
102
+ ## Package
103
+
104
+ - Depends on: `@akterjs/client` and `@standard-schema/spec` (types only); peers `@akterjs/effect`, `effect` and `@effect/platform-node` (for `serveLocal`). `@akterjs/effect` is a peer so the app, this SDK and the CLI share one copy: `akter dev`, `history` and `migrate` import it from the app's folder to run the actors `Akter.app` compiled, and a second copy would not match them. Install it beside the SDK: `npm install @akterjs/sdk @akterjs/effect effect`.
105
+ - Must not depend on: any private package.
106
+ - `pnpm test` and `pnpm test:bun` run the tests on Node and Bun. `tests/plain-sdk.contract.types.test.ts` compiles a consumer against the built `dist` and fails if its emitted declarations import Effect.
@@ -0,0 +1,14 @@
1
+ import { Record, Schema } from "effect";
2
+ import { StandardJSONSchemaV1 } from "@standard-schema/spec";
3
+ type JsonNode = Record.ReadonlyRecord<string, Schema.Json>;
4
+ interface CheckedDocument {
5
+ readonly document: JsonNode;
6
+ readonly refusals: readonly string[];
7
+ }
8
+ interface Exporting {
9
+ readonly converter: StandardJSONSchemaV1.Converter;
10
+ readonly side: "input" | "output";
11
+ }
12
+ /** Exports one side of a validator's JSON Schema as draft 2020-12 and checks that Akter can store what it describes. */
13
+ declare const exportDocument: ({ converter, side }: Exporting) => CheckedDocument;
14
+ export { type CheckedDocument, type JsonNode, exportDocument };
@@ -0,0 +1,177 @@
1
+ import { Array, Option, Predicate, Record, Result, Schema, String as String$1, pipe } from "effect";
2
+ // src/actor/json-document.schema.ts
3
+ const definitionPrefix = "#/$defs/";
4
+ const rootReference = "#";
5
+ const annotationKeys = [
6
+ "$comment",
7
+ "$id",
8
+ "$schema",
9
+ "default",
10
+ "deprecated",
11
+ "description",
12
+ "examples",
13
+ "readOnly",
14
+ "title",
15
+ "writeOnly"
16
+ ];
17
+ const dataKeys = [
18
+ "const",
19
+ "default",
20
+ "enum",
21
+ "examples"
22
+ ];
23
+ const schemaListKeys = [
24
+ "allOf",
25
+ "anyOf",
26
+ "oneOf",
27
+ "prefixItems"
28
+ ];
29
+ const schemaKeys = [
30
+ "additionalProperties",
31
+ "contains",
32
+ "else",
33
+ "if",
34
+ "items",
35
+ "not",
36
+ "propertyNames",
37
+ "then",
38
+ "unevaluatedItems",
39
+ "unevaluatedProperties"
40
+ ];
41
+ /** Keys whose `true` opens an object to extra properties beside the declared ones, as Effect Schema exports every struct. The extras are still checked as JSON when stored. */
42
+ const openingKeys = ["additionalProperties", "unevaluatedProperties"];
43
+ /** Whether a keyword's value constrains nothing on purpose: `false` forbids, and `true` on an opening key allows extras. */
44
+ const isDeliberate = (key, value) => value === false || value === true && Array.contains(openingKeys, key);
45
+ const schemaMapKeys = [
46
+ "dependentSchemas",
47
+ "patternProperties",
48
+ "properties"
49
+ ];
50
+ const isJsonObject = Schema.is(Schema.JsonObject);
51
+ const isJsonArray = Schema.is(Schema.Array(Schema.Json));
52
+ /** Reads an exporter's document, which a validator library hands back untyped. */
53
+ const jsonObjectOf = Schema.decodeUnknownOption(Schema.JsonObject);
54
+ const objectOf = (node) => Option.liftPredicate(node, isJsonObject);
55
+ const placeOf = (path) => Option.getOrElse(Option.liftPredicate(path, String$1.isNonEmpty), () => "the root");
56
+ const refusal = (path, reason) => `${placeOf(path)} ${reason}`;
57
+ const childPath = (path, key) => Option.match(Option.liftPredicate(path, String$1.isNonEmpty), {
58
+ onNone: () => key,
59
+ onSome: (parent) => `${parent}.${key}`
60
+ });
61
+ const definitionName = (reference) => Option.map(Option.liftPredicate(reference, String$1.startsWith(definitionPrefix)), String$1.slice(8));
62
+ /** Finds the definition a `$ref` names, or the reason it cannot be inlined. */
63
+ const expansionOf = (reference, inlining) => {
64
+ const name = definitionName(reference);
65
+ if (reference === rootReference || Option.exists(name, (found) => Array.contains(inlining.expanding, found))) return Result.fail(refusal(inlining.path, `refers to itself (${reference}); recursive declarations are not supported`));
66
+ return Result.fromOption(Option.flatMap(name, (found) => Option.map(Record.get(inlining.definitions, found), (definition) => ({
67
+ definition,
68
+ name: found
69
+ }))), () => refusal(inlining.path, `refers to ${reference}, which the document does not define`));
70
+ };
71
+ const withSiblings = (node, expanded) => Option.match(objectOf(expanded.node), {
72
+ onNone: () => expanded,
73
+ onSome: (object) => ({
74
+ node: {
75
+ ...object,
76
+ ...Record.remove(node, "$ref")
77
+ },
78
+ refusals: expanded.refusals
79
+ })
80
+ });
81
+ const isData = (key) => Array.contains(dataKeys, key) || key === "$defs";
82
+ const joined = (entries) => ({
83
+ node: Record.fromEntries(Array.map(entries, ([key, inlined]) => [key, inlined.node])),
84
+ refusals: Array.flatMap(entries, ([, inlined]) => inlined.refusals)
85
+ });
86
+ const referenceOf = (node) => Option.filter(Record.get(node, "$ref"), Predicate.isString);
87
+ const inlineNode = (node, inlining) => {
88
+ if (isJsonArray(node)) {
89
+ const items = Array.map(node, (item, index) => inlineNode(item, {
90
+ ...inlining,
91
+ path: childPath(inlining.path, String(index))
92
+ }));
93
+ return {
94
+ node: Array.map(items, (item) => item.node),
95
+ refusals: Array.flatMap(items, (item) => item.refusals)
96
+ };
97
+ }
98
+ const inlineObject = (object) => Option.match(referenceOf(object), {
99
+ onNone: () => joined(Array.map(Record.toEntries(object), ([key, value]) => {
100
+ if (isData(key)) return [key, {
101
+ node: value,
102
+ refusals: []
103
+ }];
104
+ return [key, inlineNode(value, {
105
+ ...inlining,
106
+ path: childPath(inlining.path, key)
107
+ })];
108
+ })),
109
+ onSome: (reference) => Result.match(expansionOf(reference, inlining), {
110
+ onFailure: (reason) => ({
111
+ node: object,
112
+ refusals: [reason]
113
+ }),
114
+ onSuccess: ({ definition, name }) => withSiblings(object, inlineNode(definition, {
115
+ ...inlining,
116
+ expanding: [...inlining.expanding, name]
117
+ }))
118
+ })
119
+ });
120
+ return Option.match(objectOf(node), {
121
+ onNone: () => ({
122
+ node,
123
+ refusals: []
124
+ }),
125
+ onSome: inlineObject
126
+ });
127
+ };
128
+ const isUnconstrained = (node) => node === true || Option.exists(objectOf(node), (object) => Array.every(Record.keys(object), (key) => Array.contains(annotationKeys, key)));
129
+ const subschemas = (node, path) => [
130
+ ...Array.flatMap(schemaKeys, (key) => pipe(Record.get(node, key), Option.filter((value) => !isDeliberate(key, value)), Option.match({
131
+ onNone: () => [],
132
+ onSome: (value) => [[childPath(path, key), value]]
133
+ }))),
134
+ ...Array.flatMap(schemaListKeys, (key) => pipe(Record.get(node, key), Option.filter(isJsonArray), Option.match({
135
+ onNone: () => [],
136
+ onSome: (values) => Array.map(values, (value, index) => [childPath(path, `${key}.${String(index)}`), value])
137
+ }))),
138
+ ...Array.flatMap(schemaMapKeys, (key) => pipe(Record.get(node, key), Option.flatMap(objectOf), Option.match({
139
+ onNone: () => [],
140
+ onSome: (values) => Array.map(Record.toEntries(values), ([name, value]) => [childPath(path, name), value])
141
+ })))
142
+ ];
143
+ const unconstrainedAt = (node, path) => {
144
+ if (isUnconstrained(node)) return [refusal(path, "accepts any value; declare its shape")];
145
+ return Option.match(objectOf(node), {
146
+ onNone: () => [],
147
+ onSome: (object) => Array.flatMap(subschemas(object, path), ([child, value]) => unconstrainedAt(value, child))
148
+ });
149
+ };
150
+ const checkObject = (document) => {
151
+ const definitions = pipe(Record.get(document, "$defs"), Option.flatMap(objectOf), Option.getOrElse(() => ({})));
152
+ const body = Record.remove(Record.remove(document, "$schema"), "$defs");
153
+ const inlined = inlineNode(body, {
154
+ definitions,
155
+ expanding: [],
156
+ path: ""
157
+ });
158
+ const flat = Option.getOrElse(objectOf(inlined.node), () => ({}));
159
+ if (Array.isReadonlyArrayEmpty(inlined.refusals)) return {
160
+ document: flat,
161
+ refusals: unconstrainedAt(flat, "")
162
+ };
163
+ return {
164
+ document: flat,
165
+ refusals: inlined.refusals
166
+ };
167
+ };
168
+ const draft = { target: "draft-2020-12" };
169
+ /** Exports one side of a validator's JSON Schema as draft 2020-12 and checks that Akter can store what it describes. */
170
+ const exportDocument = ({ converter, side }) => Option.match(jsonObjectOf(converter[side](draft)), {
171
+ onNone: () => ({
172
+ document: {},
173
+ refusals: ["the exporter returned a document that is not JSON"]
174
+ }),
175
+ onSome: checkObject
176
+ });
177
+ export { exportDocument };
@@ -0,0 +1,3 @@
1
+ import { PlainAkter } from "./plain-types.contract.mjs";
2
+ /** The plain SDK: define actors with Standard Schema validators and plain functions, served by the same engine as the Effect SDK. */
3
+ export declare const Akter: PlainAkter;
@@ -0,0 +1,63 @@
1
+ import { PlainCompiler } from "./plain-compile.contract.mjs";
2
+ import { PlainErrors } from "./plain-error.schema.mjs";
3
+ import { PlainImplement } from "./plain-implement.contract.mjs";
4
+ import { PlainFileAccesses } from "./resource/plain-file-access.contract.mjs";
5
+ import { actorPrincipal, principal } from "./standard-schema.schema.mjs";
6
+ // src/actor/plain-actor.contract.ts
7
+ function make(name, options) {
8
+ const compilation = PlainCompiler.compile({
9
+ name,
10
+ options
11
+ });
12
+ const refs = PlainCompiler.refsOf(() => compilation, {
13
+ name,
14
+ options
15
+ });
16
+ const implement = (handlers) => {
17
+ const implementation = { actor: name };
18
+ PlainImplement.register(implementation, {
19
+ actor: compilation.compiled.actor,
20
+ layer: PlainImplement.implement(compilation, handlers)
21
+ });
22
+ return implementation;
23
+ };
24
+ const actor = {
25
+ commands: refs.commands,
26
+ contract: compilation.contract,
27
+ implement,
28
+ jobs: refs.jobs,
29
+ name
30
+ };
31
+ PlainCompiler.register(actor, compilation);
32
+ return actor;
33
+ }
34
+ function command(options = {}) {
35
+ return {
36
+ kind: "command",
37
+ options
38
+ };
39
+ }
40
+ function query(options = {}) {
41
+ return {
42
+ kind: "query",
43
+ options
44
+ };
45
+ }
46
+ const job = (options) => ({
47
+ kind: "job",
48
+ options
49
+ });
50
+ const app = (declared) => PlainImplement.app(declared);
51
+ /** The plain SDK: define actors with Standard Schema validators and plain functions, served by the same engine as the Effect SDK. */
52
+ const Akter = {
53
+ ActorPrincipal: actorPrincipal,
54
+ Principal: principal,
55
+ app,
56
+ command,
57
+ error: PlainErrors.error,
58
+ fileAccess: PlainFileAccesses.fileAccess,
59
+ job,
60
+ make,
61
+ query
62
+ };
63
+ export { Akter };