dynamo-bao 0.8.2 → 0.10.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +169 -1
- package/README.md +32 -3
- package/bin/bao-create-table.js +0 -0
- package/bin/bao-rebuild-search-text.js +40 -14
- package/bin/dynamo-bao-update-table.js +20 -3
- package/bin/generators/manifest.js +1 -1
- package/bin/generators/model.js +7 -8
- package/bin/lib/confirm.js +24 -0
- package/bin/lib/process-models.js +73 -2
- package/package.json +17 -3
- package/src/config.js +21 -11
- package/src/constants.js +4 -0
- package/src/exceptions.js +17 -0
- package/src/fields.js +55 -1
- package/src/filter-expression.js +46 -17
- package/src/index.js +4 -3
- package/src/key-condition.js +2 -2
- package/src/mixins/batch-loading-mixin.js +8 -0
- package/src/mixins/mutation-mixin.js +80 -10
- package/src/mixins/query-mixin.js +4 -1
- package/src/mixins/unique-constraint-mixin.js +1 -1
- package/src/model-manager.js +33 -4
- package/src/model.js +107 -11
- package/src/remote/client.js +219 -0
- package/src/remote/codec.js +234 -0
- package/src/remote/context.js +299 -0
- package/src/remote/executor.js +400 -0
- package/src/remote/index.d.ts +413 -0
- package/src/remote/index.js +36 -0
- package/src/remote/json.js +104 -0
- package/src/remote/procedures.js +195 -0
- package/src/tenant-context.js +52 -26
- package/src/utils/search-text.js +1 -1
- package/bin/chokidar-test.js +0 -60
package/CHANGELOG.md
CHANGED
|
@@ -9,6 +9,172 @@ Each version heading links to the tag that was published to npm. Entries before
|
|
|
9
9
|
|
|
10
10
|
## [Unreleased]
|
|
11
11
|
|
|
12
|
+
## [0.10.0] - 2026-11-07
|
|
13
|
+
|
|
14
|
+
Semver minor (0.10.0). Adds the `dynamo-bao/remote` entry point; nothing
|
|
15
|
+
existing changes behavior.
|
|
16
|
+
|
|
17
|
+
**Key format: no key code changed.** Primary keys, GSI keys, unique
|
|
18
|
+
constraint keys, iteration keys and tenant prefixes are built exactly as in
|
|
19
|
+
0.9.0. Outside `src/remote/`, the only source changes are additions to
|
|
20
|
+
`src/model.js` (`fromRemote`, `isDetached`, and a guard at the top of
|
|
21
|
+
`save`, `loadRelatedData` and `getOrLoadRelatedField` that only fires on
|
|
22
|
+
instances `fromRemote` created) and one new exception class. The root
|
|
23
|
+
`dynamo-bao` entry exports the same names as before.
|
|
24
|
+
|
|
25
|
+
### Added
|
|
26
|
+
|
|
27
|
+
- **`dynamo-bao/remote`**, a new entry point (`require("dynamo-bao/remote")`
|
|
28
|
+
or `import ... from "dynamo-bao/remote"`) for running named, versioned
|
|
29
|
+
procedures next to DynamoDB and calling them from far away in one round
|
|
30
|
+
trip. See `tutorials/11-remote-procedures.md`, which freezes
|
|
31
|
+
`ProcedureContext`, `Actor`, the outcome tags (`ok` / `error` /
|
|
32
|
+
`unknown`) and the replay classes (`idempotent` / `conditional` /
|
|
33
|
+
`needs-ledger`). Exports:
|
|
34
|
+
- `defineProcedure`, `ProcedureRegistry` (with `get`, `has`, `versions`,
|
|
35
|
+
`latest`, `manifest`), `REPLAY_CLASSES`, `SCOPES`: registration by name,
|
|
36
|
+
version, scope and replay class. A procedure without a replay class or
|
|
37
|
+
scope is refused, and so is a version gap. Previous-version serving is
|
|
38
|
+
the application's obligation: the registry serves `@1` beside `@2` while
|
|
39
|
+
both descriptors are registered.
|
|
40
|
+
- `createContext`, `fresh`, `bindModelsToTenant`: the procedure context
|
|
41
|
+
(models, admin models bound to the resolver's admin partition, which is
|
|
42
|
+
required for `admin` and `both` scopes, tenant as
|
|
43
|
+
a value, actor passed through, request and operation ids, a logger bound
|
|
44
|
+
to request id and tenant, `now()`, `fresh` with capacity merge and
|
|
45
|
+
outer-cache priming, `waitUntil` with a 30 s cap, frozen config).
|
|
46
|
+
- `encodeValue`, `decodeRow`, `CodecError`: the wire codec, covering every
|
|
47
|
+
field type in `fields.js`. Dates and TTLs travel as epoch milliseconds,
|
|
48
|
+
`BinaryField` as `{ $binary }`, `StringSetField` as an array; any
|
|
49
|
+
non-JSON value is refused with its path.
|
|
50
|
+
- `createExecutor({ procedures, context, ingress, budget, region,
|
|
51
|
+
plainReturns })`: the fetch handler. Envelope validation, unknown
|
|
52
|
+
procedure and scope refusal, the actor check (the actor's `appId` must
|
|
53
|
+
equal the call tenant; no other actor field is read), concurrent and
|
|
54
|
+
isolated calls, tagged outcomes with capacity and duration, placement
|
|
55
|
+
echo, budget and ingress refusal, `drain()`. An error raised after `run`
|
|
56
|
+
returned (encoding its result, or `ResponseTooLarge`) carries
|
|
57
|
+
`executed: true`; an executor refusal carries `refused: true`.
|
|
58
|
+
- `remote(transport, { actor, retries, headers })` with `call` and
|
|
59
|
+
`batch`, and `inProcess(executor, { env, headers, ctx })`: `unknown` on
|
|
60
|
+
transport failure, no automatic resend of `needs-ledger` calls, reported
|
|
61
|
+
capacity added to the caller's batch context, and the executor's
|
|
62
|
+
`placement` (`{ colo, region }`) on each `ok` and `error` outcome.
|
|
63
|
+
- `DetachedInstanceError` (also in `exceptions`).
|
|
64
|
+
- **`Model.fromRemote(row)`** hydrates a detached, read-only instance from an
|
|
65
|
+
encoded row, and **`instance.isDetached()`** reports it. On a detached
|
|
66
|
+
instance `save`, `update`, `delete`, `loadRelatedData` and
|
|
67
|
+
`getOrLoadRelatedField` throw `DetachedInstanceError`.
|
|
68
|
+
- **TypeScript declarations** for the entry point in `src/remote/index.d.ts`
|
|
69
|
+
(`ProcedureContext`, `ContextResolver`, `Actor`, the descriptor, outcome
|
|
70
|
+
and replay types, and every export). A caller's `ok` is typed as it
|
|
71
|
+
arrives (`WireResult<Result>`: model instances as `EncodedRow`), and
|
|
72
|
+
`defineProcedure` is a type error when its result can hold a `Date`,
|
|
73
|
+
`Map`, `Set`, function or other non-JSON value. Resolvable with `moduleResolution`
|
|
74
|
+
`node`, `node16` and `bundler`. The package `exports` map gains
|
|
75
|
+
`./remote`, and `typesVersions` maps it for `moduleResolution: node`.
|
|
76
|
+
- **`examples/cloudflare-remote-executor/`**: a data worker with the
|
|
77
|
+
placement line, the `DATA` self-binding and the ingress secret, tested in
|
|
78
|
+
workerd with `@cloudflare/vitest-pool-workers` (`npm run test:workerd`).
|
|
79
|
+
- `tutorials/11-remote-procedures.md`.
|
|
80
|
+
|
|
81
|
+
### Codec refusals
|
|
82
|
+
|
|
83
|
+
The codec refuses one model shape: a **custom field whose stored value is
|
|
84
|
+
not JSON** (for example a custom field whose `toDy` returns a `Map`). Such a
|
|
85
|
+
row throws `CodecError` naming the model and field. Every built-in field
|
|
86
|
+
type encodes. A `Date` anywhere in a procedure result is refused; return
|
|
87
|
+
epoch milliseconds.
|
|
88
|
+
|
|
89
|
+
### For consumers adopting the executor
|
|
90
|
+
|
|
91
|
+
The Spike 6 audit's consumer-facing lists (the callers that cross the
|
|
92
|
+
boundary with a `Date` or a model instance, the memberships-cache
|
|
93
|
+
invalidation sites, and the activity-gate helpers) were handed over on
|
|
94
|
+
issue #18 on 2026-11-07:
|
|
95
|
+
https://github.com/aag1024/dynamo-bao/issues/18#issuecomment-6703195120
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
## [0.9.0] - 2026-10-28
|
|
99
|
+
|
|
100
|
+
### Security
|
|
101
|
+
|
|
102
|
+
- With tenancy enabled, an operation with no tenant in context now throws
|
|
103
|
+
`ConfigurationError`. It used to fall back to the tenant that was current
|
|
104
|
+
when `initModels()` ran, so a request that lost its tenant read and wrote
|
|
105
|
+
that tenant's data.
|
|
106
|
+
- `setCurrentTenant()` inside `runWithBatchContext()` now sets the tenant for
|
|
107
|
+
that context only. It used to set a process-wide tenant that concurrent
|
|
108
|
+
requests picked up. Registered resolvers now take precedence over the
|
|
109
|
+
process-wide tenant, `runWithTenant()` never sees it, and `clearTenant()`
|
|
110
|
+
inside a context clears only that context's tenant.
|
|
111
|
+
- Each distinct tenant id no longer adds a cached `ModelManager` that is
|
|
112
|
+
never freed. A caller sending random tenant ids could grow memory without
|
|
113
|
+
limit.
|
|
114
|
+
- Tenant ids containing `]` or `#`, which could produce another tenant's
|
|
115
|
+
keys, are rejected.
|
|
116
|
+
- A model with a field named like `n1` or `v1` could have that field's
|
|
117
|
+
placeholder overwritten by a write `condition`, writing the value into the
|
|
118
|
+
attribute the condition checked. Filter placeholders now use a reserved
|
|
119
|
+
prefix.
|
|
120
|
+
- `update()` rejects changes to primary key fields, and composite key values
|
|
121
|
+
can't contain the id separator `##__SK__##`. Either one could make an id
|
|
122
|
+
address a different record.
|
|
123
|
+
- `VersionField` is always generated on save and `CreateDateField` is set
|
|
124
|
+
only on create, so callers can't roll a version back to get around
|
|
125
|
+
optimistic locking.
|
|
126
|
+
- An `update()` that re-sends an unchanged unique value is now conditioned
|
|
127
|
+
on the stored value, so a concurrent change can't leave the value without
|
|
128
|
+
its constraint row for another record to claim.
|
|
129
|
+
- Codegen emits YAML values as literals and requires model, field, index
|
|
130
|
+
and constraint names to be JavaScript identifiers. Crafted YAML could
|
|
131
|
+
inject code into generated models or write files outside the output
|
|
132
|
+
directory.
|
|
133
|
+
|
|
134
|
+
### Added
|
|
135
|
+
|
|
136
|
+
- `allowedFilterFields` option on `queryByIndex()`, `iterateAll()` and
|
|
137
|
+
`searchAll()` (`allowedFields` on `FilterExpressionBuilder#build`) to limit
|
|
138
|
+
the fields a filter that comes from user input may reference.
|
|
139
|
+
- `TenantContext.setDefaultTenant()` sets the process-wide tenant
|
|
140
|
+
explicitly, for scripts and tests.
|
|
141
|
+
- `bao-rebuild-search-text --tenant <id>` for tenancy-enabled tables.
|
|
142
|
+
|
|
143
|
+
### Changed
|
|
144
|
+
|
|
145
|
+
- **Breaking:** importing the library no longer loads `.env` from the
|
|
146
|
+
working directory. Apps that relied on this should call
|
|
147
|
+
`require("dotenv").config()` themselves. The CLI tools still load `.env`.
|
|
148
|
+
- **Breaking:** config lookup no longer loads generic `config.js`,
|
|
149
|
+
`config.mjs` or `config.cjs` files, which could be an unrelated project's
|
|
150
|
+
config. It now refuses with a message saying to rename the file to
|
|
151
|
+
`dynamo-bao.config.js` or set `DYNAMO_BAO_CONFIG`.
|
|
152
|
+
- **Breaking:** `bao-update-table` and `bao-rebuild-search-text` ask before
|
|
153
|
+
changing the table. Pass `--yes` in scripts and CI.
|
|
154
|
+
- **Breaking:** field validation is stricter. `StringField` rejects objects,
|
|
155
|
+
arrays and booleans and now enforces `maxLength`. `IntegerField` rejects
|
|
156
|
+
non-integers and `FloatField` rejects non-numbers. Date fields reject
|
|
157
|
+
unparseable strings.
|
|
158
|
+
- `initModels()` no longer requires a tenant when tenancy is enabled.
|
|
159
|
+
- The `logging.level` passed to `initModels()` now takes effect
|
|
160
|
+
(`DYNAMO_BAO_LOG_LEVEL` still wins).
|
|
161
|
+
- Transactional writes send a `ClientRequestToken`, and updates that use
|
|
162
|
+
`ADD` (counters, set changes) are no longer retried, so a retry can't apply
|
|
163
|
+
a write twice.
|
|
164
|
+
|
|
165
|
+
### Fixed
|
|
166
|
+
|
|
167
|
+
- `$not` over more than one condition negated only the first one.
|
|
168
|
+
- Filter keys such as `constructor` or `toString` were looked up through the
|
|
169
|
+
prototype chain and either built an expression on a bogus attribute or
|
|
170
|
+
threw a `TypeError`. Filters are also limited to 16 levels of nesting.
|
|
171
|
+
- `CreateDateField` stored an ISO string as-is instead of converting it to a
|
|
172
|
+
timestamp.
|
|
173
|
+
- Model managers created for a tenant at runtime had no models, client or
|
|
174
|
+
config, so related-model lookups under that tenant could fail.
|
|
175
|
+
- A unique-constraint lookup error was logged with `console.error`,
|
|
176
|
+
bypassing the configured log level.
|
|
177
|
+
|
|
12
178
|
## [0.8.2] - 2026-10-27
|
|
13
179
|
|
|
14
180
|
### Fixed
|
|
@@ -487,7 +653,9 @@ Initial release: single-table models with fields, GSIs, unique constraints,
|
|
|
487
653
|
related fields, counters, TTL, filters, pagination, batch loading, hooks,
|
|
488
654
|
YAML codegen and a table creation tool.
|
|
489
655
|
|
|
490
|
-
[Unreleased]: https://github.com/aag1024/dynamo-bao/compare/v0.
|
|
656
|
+
[Unreleased]: https://github.com/aag1024/dynamo-bao/compare/v0.10.0...HEAD
|
|
657
|
+
[0.10.0]: https://github.com/aag1024/dynamo-bao/compare/v0.9.0...v0.10.0
|
|
658
|
+
[0.9.0]: https://github.com/aag1024/dynamo-bao/compare/v0.8.2...v0.9.0
|
|
491
659
|
[0.8.2]: https://github.com/aag1024/dynamo-bao/compare/v0.8.1...v0.8.2
|
|
492
660
|
[0.8.1]: https://github.com/aag1024/dynamo-bao/compare/v0.8.0...v0.8.1
|
|
493
661
|
[0.8.0]: https://github.com/aag1024/dynamo-bao/compare/v0.7.3...v0.8.0
|
package/README.md
CHANGED
|
@@ -190,6 +190,35 @@ export default {
|
|
|
190
190
|
|
|
191
191
|
For production Cloudflare Workers deployments, always use `runWithBatchContext` to get both safety and optimal performance.
|
|
192
192
|
|
|
193
|
+
### Remote Procedures (`dynamo-bao/remote`)
|
|
194
|
+
|
|
195
|
+
When code runs far from the table (Durable Objects near users, Workflows), each DynamoDB call pays a cross-region round trip. `dynamo-bao/remote` lets you register named, versioned procedures on a Worker placed next to DynamoDB and call them in one trip:
|
|
196
|
+
|
|
197
|
+
```javascript
|
|
198
|
+
const { defineProcedure, ProcedureRegistry, createExecutor, remote } = require("dynamo-bao/remote");
|
|
199
|
+
|
|
200
|
+
const getUser = defineProcedure({
|
|
201
|
+
name: "user.get", version: 1, scope: "app", replay: "idempotent",
|
|
202
|
+
async run(ctx, { userId }) {
|
|
203
|
+
const user = await ctx.models.User.find(userId);
|
|
204
|
+
return user.exists() ? { name: user.name } : null;
|
|
205
|
+
},
|
|
206
|
+
});
|
|
207
|
+
|
|
208
|
+
// Data worker, next to DynamoDB:
|
|
209
|
+
const executor = createExecutor({
|
|
210
|
+
procedures: new ProcedureRegistry([getUser]),
|
|
211
|
+
context: (call, env) => ({ models: getModels(env) }),
|
|
212
|
+
ingress: (request, env) => request.headers.get("x-data-binding") === env.DATA_BINDING_SECRET,
|
|
213
|
+
});
|
|
214
|
+
|
|
215
|
+
// Caller, anywhere:
|
|
216
|
+
const r = await remote(env.DATA, { actor, headers }).call(getUser, { userId }, { tenant: appId });
|
|
217
|
+
if ("ok" in r) console.log(r.ok.name);
|
|
218
|
+
```
|
|
219
|
+
|
|
220
|
+
See [tutorial 11](tutorials/11-remote-procedures.md) for the contract (context, actor, outcomes, replay classes) and [`examples/cloudflare-remote-executor/`](examples/cloudflare-remote-executor/) for a complete Worker. TypeScript declarations ship with the entry point.
|
|
221
|
+
|
|
193
222
|
### Batch Context Configuration
|
|
194
223
|
|
|
195
224
|
DynamoBao provides flexible batch context behavior that can be configured based on your application's needs:
|
|
@@ -457,7 +486,7 @@ Create a new Dynamo table for your project. You should have one table per projec
|
|
|
457
486
|
npx bao-init
|
|
458
487
|
```
|
|
459
488
|
|
|
460
|
-
This creates a `config.js` which contains settings for your project like AWS region and the table name.
|
|
489
|
+
This creates a `dynamo-bao.config.js` which contains settings for your project like AWS region and the table name.
|
|
461
490
|
|
|
462
491
|
It also creates a `models.yaml` file with a simple example model, and a `models` directory where
|
|
463
492
|
the generated models will be stored.
|
|
@@ -514,10 +543,10 @@ You should now have generated models in the `models` directory.
|
|
|
514
543
|
|
|
515
544
|
### ESM Support
|
|
516
545
|
|
|
517
|
-
DynamoBao supports generating models as ESM (ECMAScript Modules) for modern JavaScript projects. To enable ESM code generation, add the `codegen` configuration to your `config.js`:
|
|
546
|
+
DynamoBao supports generating models as ESM (ECMAScript Modules) for modern JavaScript projects. To enable ESM code generation, add the `codegen` configuration to your `dynamo-bao.config.js`:
|
|
518
547
|
|
|
519
548
|
```javascript
|
|
520
|
-
// config.js
|
|
549
|
+
// dynamo-bao.config.js
|
|
521
550
|
module.exports = {
|
|
522
551
|
aws: {
|
|
523
552
|
region: "us-west-2",
|
package/bin/bao-create-table.js
CHANGED
|
File without changes
|
|
@@ -6,12 +6,22 @@
|
|
|
6
6
|
// `searchable: true` on a model with existing data.
|
|
7
7
|
|
|
8
8
|
const resolve = require("./lib/resolve");
|
|
9
|
-
const {
|
|
9
|
+
const { confirm } = require("./lib/confirm");
|
|
10
|
+
const { initModels, runWithBatchContext, TenantContext } =
|
|
11
|
+
resolve("src/index.js");
|
|
10
12
|
const { initConfig } = resolve("src/config.js");
|
|
11
13
|
|
|
12
|
-
const
|
|
13
|
-
|
|
14
|
-
|
|
14
|
+
const args = process.argv.slice(2);
|
|
15
|
+
const tenantFlag = args.indexOf("--tenant");
|
|
16
|
+
const tenantId = tenantFlag === -1 ? null : args[tenantFlag + 1];
|
|
17
|
+
const modelName = args.find(
|
|
18
|
+
(arg, i) =>
|
|
19
|
+
!arg.startsWith("-") && (tenantFlag === -1 || i !== tenantFlag + 1),
|
|
20
|
+
);
|
|
21
|
+
if (!modelName || (tenantFlag !== -1 && !tenantId)) {
|
|
22
|
+
console.error(
|
|
23
|
+
"Usage: bao-rebuild-search-text <ModelName> [--tenant <tenantId>] [--yes]",
|
|
24
|
+
);
|
|
15
25
|
process.exit(1);
|
|
16
26
|
}
|
|
17
27
|
|
|
@@ -40,20 +50,36 @@ if (!modelName) {
|
|
|
40
50
|
process.exit(1);
|
|
41
51
|
}
|
|
42
52
|
|
|
43
|
-
|
|
53
|
+
if (config.tenancy?.enabled && !tenantId) {
|
|
54
|
+
console.error("Tenancy is enabled: pass --tenant <tenantId>.");
|
|
55
|
+
process.exit(1);
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
const scope = tenantId ? ` for tenant '${tenantId}'` : "";
|
|
59
|
+
if (
|
|
60
|
+
!(await confirm(
|
|
61
|
+
`Re-save every ${modelName} row${scope} in table '${config.db.tableName}'?`,
|
|
62
|
+
))
|
|
63
|
+
) {
|
|
64
|
+
process.exit(1);
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
console.log(`Rebuilding _searchText for ${modelName}${scope}...`);
|
|
44
68
|
let total = 0;
|
|
45
69
|
|
|
46
|
-
await
|
|
47
|
-
|
|
48
|
-
for (const
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
70
|
+
await TenantContext.runWithTenant(tenantId, () =>
|
|
71
|
+
runWithBatchContext(async () => {
|
|
72
|
+
for await (const batch of ModelClass.iterateAll({ batchSize: 50 })) {
|
|
73
|
+
for (const item of batch) {
|
|
74
|
+
await item.save({ forceReindex: true });
|
|
75
|
+
total++;
|
|
76
|
+
if (total % 100 === 0) {
|
|
77
|
+
console.log(` rebuilt ${total} so far...`);
|
|
78
|
+
}
|
|
53
79
|
}
|
|
54
80
|
}
|
|
55
|
-
}
|
|
56
|
-
|
|
81
|
+
}),
|
|
82
|
+
);
|
|
57
83
|
|
|
58
84
|
console.log(`Done. Rebuilt _searchText on ${total} ${modelName} item(s).`);
|
|
59
85
|
})().catch((err) => {
|
|
@@ -97,6 +97,7 @@ const ALL_ATTRIBUTE_DEFINITIONS = [
|
|
|
97
97
|
];
|
|
98
98
|
|
|
99
99
|
const { waitForTableActive } = require("./lib/create-table-params");
|
|
100
|
+
const { confirm } = require("./lib/confirm");
|
|
100
101
|
|
|
101
102
|
let client;
|
|
102
103
|
|
|
@@ -118,9 +119,16 @@ async function checkAndAddMissingGSIs(tableName) {
|
|
|
118
119
|
return;
|
|
119
120
|
}
|
|
120
121
|
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
122
|
+
const missingNames = missingGSIs.map((g) => g.IndexName).join(", ");
|
|
123
|
+
console.log(`Missing GSIs: ${missingNames}`);
|
|
124
|
+
if (
|
|
125
|
+
!(await confirm(
|
|
126
|
+
`Add GSIs ${missingNames} to table '${tableName}' (${client.region})?`,
|
|
127
|
+
))
|
|
128
|
+
) {
|
|
129
|
+
console.log("Skipped adding GSIs.");
|
|
130
|
+
return;
|
|
131
|
+
}
|
|
124
132
|
|
|
125
133
|
// DynamoDB only allows adding one GSI per UpdateTable call
|
|
126
134
|
for (const gsi of missingGSIs) {
|
|
@@ -181,6 +189,15 @@ async function checkAndEnableTTL(tableName) {
|
|
|
181
189
|
return;
|
|
182
190
|
}
|
|
183
191
|
|
|
192
|
+
if (
|
|
193
|
+
!(await confirm(
|
|
194
|
+
`Enable TTL on attribute 'ttl' for table '${tableName}' (${client.region})?`,
|
|
195
|
+
))
|
|
196
|
+
) {
|
|
197
|
+
console.log("Skipped enabling TTL.");
|
|
198
|
+
return;
|
|
199
|
+
}
|
|
200
|
+
|
|
184
201
|
console.log("Enabling TTL on attribute 'ttl'...");
|
|
185
202
|
await client.send(
|
|
186
203
|
new UpdateTimeToLiveCommand({
|
|
@@ -46,7 +46,7 @@ function generateManifestFile(modelsDir, manifestPath) {
|
|
|
46
46
|
const relativePath = path.relative(manifestDir, file).replace(/\\/g, "/");
|
|
47
47
|
// Ensure .js extension for ESM imports
|
|
48
48
|
const importPath = relativePath.endsWith('.js') ? relativePath : `${relativePath}.js`;
|
|
49
|
-
return `import * as model${index} from
|
|
49
|
+
return `import * as model${index} from ${JSON.stringify(importPath)};`;
|
|
50
50
|
})
|
|
51
51
|
.join("\n");
|
|
52
52
|
|
package/bin/generators/model.js
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
const path = require("path");
|
|
2
2
|
const fs = require("fs");
|
|
3
3
|
const { createLogger } = require("../utils/scriptLogger");
|
|
4
|
+
const { validateModelNames } = require("../lib/process-models");
|
|
4
5
|
|
|
5
6
|
// const __dirname = __dirname;
|
|
6
7
|
const logger = createLogger("ModelGen");
|
|
@@ -59,18 +60,14 @@ function generateModelClass(
|
|
|
59
60
|
}
|
|
60
61
|
|
|
61
62
|
if (fieldConfig.type === "RelatedField") {
|
|
62
|
-
return ` ${fieldName}: ${fieldConfig.type}(
|
|
63
|
+
return ` ${fieldName}: ${fieldConfig.type}(${JSON.stringify(fieldConfig.model)}, { required: ${!!fieldConfig.required} }),`;
|
|
63
64
|
}
|
|
64
65
|
|
|
65
66
|
// Build options object from all field config properties except 'type'
|
|
66
67
|
const options = Object.entries(fieldConfig)
|
|
67
68
|
.filter(([key]) => key !== "type")
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
if (typeof value === "string") return `${key}: '${value}'`;
|
|
71
|
-
if (Array.isArray(value)) return `${key}: ${JSON.stringify(value)}`;
|
|
72
|
-
return `${key}: ${value}`;
|
|
73
|
-
});
|
|
69
|
+
// Values are always emitted as literals, never as code.
|
|
70
|
+
.map(([key, value]) => `${key}: ${JSON.stringify(value)}`);
|
|
74
71
|
|
|
75
72
|
const optionsStr = options.length ? `{ ${options.join(", ")} }` : "";
|
|
76
73
|
return ` ${fieldName}: ${fieldConfig.type}(${optionsStr}),`;
|
|
@@ -244,7 +241,7 @@ ${customFieldImports ? customFieldImports + '\n' : ''}
|
|
|
244
241
|
${relatedModelImports ? relatedModelImports + '\n' : ''}
|
|
245
242
|
|
|
246
243
|
class ${modelName} extends BaoModel {
|
|
247
|
-
static modelPrefix =
|
|
244
|
+
static modelPrefix = ${JSON.stringify(modelConfig.modelPrefix)};
|
|
248
245
|
static iterable = ${iterable};
|
|
249
246
|
static iterationBuckets = ${iterationBuckets};
|
|
250
247
|
static searchable = ${searchable};
|
|
@@ -281,6 +278,8 @@ function generateUniqueConstraintMethods(modelConfig) {
|
|
|
281
278
|
}
|
|
282
279
|
|
|
283
280
|
function generateModelFiles(models, outputDir, fieldResolver, moduleSystem = 'commonjs') {
|
|
281
|
+
validateModelNames(models);
|
|
282
|
+
|
|
284
283
|
if (!fs.existsSync(outputDir)) {
|
|
285
284
|
fs.mkdirSync(outputDir, { recursive: true });
|
|
286
285
|
}
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
const readline = require("readline");
|
|
2
|
+
|
|
3
|
+
// Asks before a command changes a table. --yes (or -y) skips the prompt.
|
|
4
|
+
// With no terminal to ask on, the command refuses rather than proceeding.
|
|
5
|
+
async function confirm(message, argv = process.argv) {
|
|
6
|
+
if (argv.includes("--yes") || argv.includes("-y")) {
|
|
7
|
+
return true;
|
|
8
|
+
}
|
|
9
|
+
if (!process.stdin.isTTY) {
|
|
10
|
+
console.error(`${message}\nNo terminal to confirm on; re-run with --yes.`);
|
|
11
|
+
return false;
|
|
12
|
+
}
|
|
13
|
+
const rl = readline.createInterface({
|
|
14
|
+
input: process.stdin,
|
|
15
|
+
output: process.stdout,
|
|
16
|
+
});
|
|
17
|
+
const answer = await new Promise((resolve) =>
|
|
18
|
+
rl.question(`${message} [y/N] `, resolve),
|
|
19
|
+
);
|
|
20
|
+
rl.close();
|
|
21
|
+
return /^y(es)?$/i.test(answer.trim());
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
module.exports = { confirm };
|
|
@@ -77,7 +77,10 @@ function validateSearchable(modelName, modelDef) {
|
|
|
77
77
|
}
|
|
78
78
|
}
|
|
79
79
|
|
|
80
|
-
if (
|
|
80
|
+
if (
|
|
81
|
+
raw.caseSensitive !== undefined &&
|
|
82
|
+
typeof raw.caseSensitive !== "boolean"
|
|
83
|
+
) {
|
|
81
84
|
throw new Error(
|
|
82
85
|
`Model "${modelName}": \`searchable.caseSensitive\` must be a boolean.`,
|
|
83
86
|
);
|
|
@@ -130,4 +133,72 @@ function applyModelDefaults(models) {
|
|
|
130
133
|
return models;
|
|
131
134
|
}
|
|
132
135
|
|
|
133
|
-
|
|
136
|
+
// Names from model definitions become identifiers, string literals, file
|
|
137
|
+
// names and import paths in generated code, so they must be plain JavaScript
|
|
138
|
+
// identifiers. Anything else could inject code or write outside the output
|
|
139
|
+
// directory.
|
|
140
|
+
const IDENTIFIER = /^[A-Za-z_$][\w$]*$/;
|
|
141
|
+
|
|
142
|
+
function assertIdentifier(value, what) {
|
|
143
|
+
if (typeof value !== "string" || !IDENTIFIER.test(value)) {
|
|
144
|
+
throw new Error(
|
|
145
|
+
`Invalid ${what} ${JSON.stringify(value)}: must be a JavaScript identifier`,
|
|
146
|
+
);
|
|
147
|
+
}
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
function assertIdSuffix(value, what) {
|
|
151
|
+
if (typeof value !== "string" || !/\d$/.test(value)) {
|
|
152
|
+
throw new Error(`Invalid ${what} ${JSON.stringify(value)}`);
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
function validateModelNames(models) {
|
|
157
|
+
for (const [modelName, modelDef] of Object.entries(models)) {
|
|
158
|
+
assertIdentifier(modelName, "model name");
|
|
159
|
+
const where = (what) => `${what} in model ${modelName}`;
|
|
160
|
+
|
|
161
|
+
for (const [fieldName, fieldDef] of Object.entries(modelDef.fields || {})) {
|
|
162
|
+
assertIdentifier(fieldName, where("field name"));
|
|
163
|
+
if (fieldDef.type !== undefined) {
|
|
164
|
+
assertIdentifier(fieldDef.type, where(`type of field ${fieldName}`));
|
|
165
|
+
}
|
|
166
|
+
if (fieldDef.model !== undefined) {
|
|
167
|
+
assertIdentifier(fieldDef.model, where(`model of field ${fieldName}`));
|
|
168
|
+
}
|
|
169
|
+
for (const option of Object.keys(fieldDef)) {
|
|
170
|
+
assertIdentifier(option, where(`option of field ${fieldName}`));
|
|
171
|
+
}
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
const { partitionKey, sortKey } = modelDef.primaryKey || {};
|
|
175
|
+
assertIdentifier(partitionKey, where("primary partition key"));
|
|
176
|
+
if (sortKey !== undefined) {
|
|
177
|
+
assertIdentifier(sortKey, where("primary sort key"));
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
for (const [indexName, index] of Object.entries(modelDef.indexes || {})) {
|
|
181
|
+
assertIdentifier(indexName, where("index name"));
|
|
182
|
+
if (index === "primaryKey") continue;
|
|
183
|
+
assertIdentifier(
|
|
184
|
+
index.partitionKey,
|
|
185
|
+
where(`partition key of ${indexName}`),
|
|
186
|
+
);
|
|
187
|
+
assertIdentifier(index.sortKey, where(`sort key of ${indexName}`));
|
|
188
|
+
assertIdSuffix(index.indexId, where(`indexId of ${indexName}`));
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
for (const [name, constraint] of Object.entries(
|
|
192
|
+
modelDef.uniqueConstraints || {},
|
|
193
|
+
)) {
|
|
194
|
+
assertIdentifier(name, where("unique constraint name"));
|
|
195
|
+
assertIdentifier(constraint.field, where(`field of ${name}`));
|
|
196
|
+
assertIdSuffix(
|
|
197
|
+
constraint.uniqueConstraintId,
|
|
198
|
+
where(`uniqueConstraintId of ${name}`),
|
|
199
|
+
);
|
|
200
|
+
}
|
|
201
|
+
}
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
module.exports = { applyModelDefaults, validateModelNames };
|
package/package.json
CHANGED
|
@@ -1,22 +1,35 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "dynamo-bao",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.10.0",
|
|
4
4
|
"description": "Simple powerful data modeling primitives for DynamoDB in JavaScript.",
|
|
5
5
|
"main": "src/index.js",
|
|
6
6
|
"exports": {
|
|
7
7
|
".": "./src/index.js",
|
|
8
|
+
"./remote": {
|
|
9
|
+
"types": "./src/remote/index.d.ts",
|
|
10
|
+
"default": "./src/remote/index.js"
|
|
11
|
+
},
|
|
8
12
|
"./src/*": "./src/*",
|
|
9
13
|
"./package.json": "./package.json"
|
|
10
14
|
},
|
|
15
|
+
"typesVersions": {
|
|
16
|
+
"*": {
|
|
17
|
+
"remote": [
|
|
18
|
+
"src/remote/index.d.ts"
|
|
19
|
+
]
|
|
20
|
+
}
|
|
21
|
+
},
|
|
11
22
|
"scripts": {
|
|
12
23
|
"test": "LOG_LEVEL=OFF jest",
|
|
13
24
|
"test:debug": "LOG_LEVEL=DEBUG jest",
|
|
14
25
|
"create-table": "node bin/dynamo-bao-create-table.js",
|
|
15
26
|
"watch": "node bin/watch.js",
|
|
16
|
-
"docs": "jsdoc -c jsdoc.json --verbose"
|
|
27
|
+
"docs": "jsdoc -c jsdoc.json --verbose",
|
|
28
|
+
"test:workerd": "npm --prefix examples/cloudflare-remote-executor install --no-audit --no-fund && npm --prefix examples/cloudflare-remote-executor test"
|
|
17
29
|
},
|
|
18
30
|
"files": [
|
|
19
31
|
"bin/",
|
|
32
|
+
"!bin/chokidar-test.js",
|
|
20
33
|
"src/",
|
|
21
34
|
"README.md",
|
|
22
35
|
"CHANGELOG.md"
|
|
@@ -50,7 +63,8 @@
|
|
|
50
63
|
"gh-pages": "^6.2.0",
|
|
51
64
|
"jest": "^29.7.0",
|
|
52
65
|
"jsdoc": "^4.0.4",
|
|
53
|
-
"prettier": "3.4.2"
|
|
66
|
+
"prettier": "3.4.2",
|
|
67
|
+
"typescript": "^5.9.3"
|
|
54
68
|
},
|
|
55
69
|
"bin": {
|
|
56
70
|
"bao-init": "bin/dynamo-bao-create-table.js",
|
package/src/config.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
const fs = require("fs");
|
|
2
2
|
const path = require("path");
|
|
3
|
-
const
|
|
3
|
+
const { pathToFileURL } = require("url");
|
|
4
4
|
|
|
5
5
|
async function findConfig() {
|
|
6
6
|
// First check environment variable
|
|
@@ -22,10 +22,10 @@ async function findConfig() {
|
|
|
22
22
|
"dynamo-bao.config.cjs",
|
|
23
23
|
".dynamo-bao/config.js",
|
|
24
24
|
".dynamo-bao/config.mjs",
|
|
25
|
-
"config.js",
|
|
26
|
-
"config.mjs",
|
|
27
|
-
"config.cjs",
|
|
28
25
|
];
|
|
26
|
+
// Older versions also loaded these generic names, which meant running any
|
|
27
|
+
// project's config.js. Refuse them rather than silently using defaults.
|
|
28
|
+
const legacyNames = ["config.js", "config.mjs", "config.cjs"];
|
|
29
29
|
const searchPaths = [
|
|
30
30
|
process.cwd(), // Project root
|
|
31
31
|
];
|
|
@@ -40,10 +40,20 @@ async function findConfig() {
|
|
|
40
40
|
return normalizeConfig(rawConfig, configDir);
|
|
41
41
|
}
|
|
42
42
|
}
|
|
43
|
+
for (const name of legacyNames) {
|
|
44
|
+
if (fs.existsSync(path.join(searchPath, name))) {
|
|
45
|
+
throw new Error(
|
|
46
|
+
`Found ${name} but no dynamo-bao.config.js in ${searchPath}. ` +
|
|
47
|
+
"dynamo-bao no longer loads generic config file names: rename it " +
|
|
48
|
+
`to dynamo-bao.config.js, or set DYNAMO_BAO_CONFIG=${name}.`,
|
|
49
|
+
);
|
|
50
|
+
}
|
|
51
|
+
}
|
|
43
52
|
}
|
|
44
53
|
|
|
45
|
-
// If no config file found, create default config from env
|
|
46
|
-
|
|
54
|
+
// If no config file found, create default config from env. Only the CLI
|
|
55
|
+
// tools reach this, so loading .env here doesn't affect library users.
|
|
56
|
+
require("dotenv").config();
|
|
47
57
|
return {
|
|
48
58
|
aws: {
|
|
49
59
|
region: process.env.AWS_REGION || "us-west-2",
|
|
@@ -78,8 +88,7 @@ async function loadConfigFile(configPath) {
|
|
|
78
88
|
return require(configPath);
|
|
79
89
|
} else if (configPath.endsWith(".mjs") || configPath.endsWith(".js")) {
|
|
80
90
|
// Use dynamic import for ESM files
|
|
81
|
-
const
|
|
82
|
-
const module = await import(fileUrl);
|
|
91
|
+
const module = await import(pathToFileURL(configPath).href);
|
|
83
92
|
return module.default || module;
|
|
84
93
|
} else {
|
|
85
94
|
// Default to require for legacy files
|
|
@@ -142,10 +151,11 @@ async function initConfig() {
|
|
|
142
151
|
return config;
|
|
143
152
|
}
|
|
144
153
|
|
|
145
|
-
//
|
|
154
|
+
// Defaults read from the environment when the library is imported. This
|
|
155
|
+
// deliberately doesn't load .env: a library shouldn't change process.env, or
|
|
156
|
+
// pick its table and credentials from whatever .env is in the working
|
|
157
|
+
// directory. Apps that use .env should load it themselves.
|
|
146
158
|
try {
|
|
147
|
-
// For now, create a basic synchronous config
|
|
148
|
-
const dotenvResult = dotenv.config();
|
|
149
159
|
config = {
|
|
150
160
|
aws: {
|
|
151
161
|
region: process.env.AWS_REGION || "us-west-2",
|
package/src/constants.js
CHANGED
|
@@ -47,6 +47,9 @@ const SYSTEM_FIELDS = [
|
|
|
47
47
|
|
|
48
48
|
const UNIQUE_CONSTRAINT_KEY = "_raft_uc";
|
|
49
49
|
|
|
50
|
+
// Joins pk and sk in the string primary id of a composite-key model.
|
|
51
|
+
const GID_SEPARATOR = "##__SK__##";
|
|
52
|
+
|
|
50
53
|
module.exports = {
|
|
51
54
|
GSI_INDEX_ID1,
|
|
52
55
|
GSI_INDEX_ID2,
|
|
@@ -64,4 +67,5 @@ module.exports = {
|
|
|
64
67
|
UNIQUE_CONSTRAINT_ID3,
|
|
65
68
|
SYSTEM_FIELDS,
|
|
66
69
|
UNIQUE_CONSTRAINT_KEY,
|
|
70
|
+
GID_SEPARATOR,
|
|
67
71
|
};
|