@voxgig/sdkgen 3.0.0 → 3.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (40) hide show
  1. package/dist/action/doctor.js +65 -10
  2. package/dist/action/doctor.js.map +1 -1
  3. package/dist/cmp/ExternalTarget.d.ts +2 -0
  4. package/dist/cmp/ExternalTarget.js +104 -0
  5. package/dist/cmp/ExternalTarget.js.map +1 -0
  6. package/dist/helpers/packageMeta.d.ts +9 -1
  7. package/dist/helpers/packageMeta.js +40 -0
  8. package/dist/helpers/packageMeta.js.map +1 -1
  9. package/dist/sdkgen.d.ts +2 -2
  10. package/dist/sdkgen.js +229 -2
  11. package/dist/sdkgen.js.map +1 -1
  12. package/dist/tsconfig.tsbuildinfo +1 -1
  13. package/dist/types.d.ts +12 -0
  14. package/dist/utility.js +10 -1
  15. package/dist/utility.js.map +1 -1
  16. package/model/sdkgen.aontu +120 -0
  17. package/package.json +1 -1
  18. package/project/.sdk/model/target/go-cli.aontu +0 -1
  19. package/project/.sdk/model/target/go-mcp.aontu +0 -1
  20. package/project/.sdk/model/target/java.aontu +0 -1
  21. package/project/.sdk/model/target/kotlin.aontu +0 -1
  22. package/project/.sdk/model/target/lean.aontu +0 -1
  23. package/project/.sdk/model/target/py-data.aontu +0 -1
  24. package/project/.sdk/model/target/scala.aontu +0 -1
  25. package/project/.sdk/model/target/seneca-provider.aontu +118 -0
  26. package/project/.sdk/model/target/zig.aontu +0 -1
  27. package/project/.sdk/src/cmp/seneca-provider/Extras_seneca-provider.ts +3915 -0
  28. package/project/.sdk/src/cmp/seneca-provider/Main_seneca-provider.ts +960 -0
  29. package/project/.sdk/tm/seneca-provider/CODE_OF_CONDUCT.md +132 -0
  30. package/project/.sdk/tm/seneca-provider/LICENSE +21 -0
  31. package/project/.sdk/tm/seneca-provider/Makefile +15 -0
  32. package/project/.sdk/tm/seneca-provider/src/tsconfig.json +18 -0
  33. package/project/.sdk/tm/seneca-provider/test/tsconfig.json +16 -0
  34. package/project/.sdk/tm/seneca-provider/tsfmt.json +3 -0
  35. package/src/action/doctor.ts +77 -12
  36. package/src/cmp/ExternalTarget.ts +125 -0
  37. package/src/helpers/packageMeta.ts +48 -0
  38. package/src/sdkgen.ts +280 -1
  39. package/src/types.ts +24 -1
  40. package/src/utility.ts +10 -1
@@ -0,0 +1,3915 @@
1
+ import {
2
+ cmp, each,
3
+ File, Content, Folder,
4
+ jsKey, jsProp,
5
+ } from '@voxgig/sdkgen'
6
+
7
+
8
+ // The rest of the seneca-provider package: its test suite, CI workflow and
9
+ // README. Split out of Main only for size — everything here is driven by the
10
+ // same `provider` shape Main builds from the model.
11
+ //
12
+ // The tests are the reason this target is worth generating at all. A provider
13
+ // is thin, and the thin part is exactly where the mistakes are: a cmd that
14
+ // forgets a parent path param, an entity that comes back under the wrong
15
+ // canon, a 404 that should have been `null` and instead threw. All three are
16
+ // checked below, offline, against the SDK's own mock transport — so a
17
+ // generated provider is verified without a server.
18
+
19
+
20
+ // The name of the entity a parent path param addresses, or '' when the model
21
+ // has none of that name.
22
+ //
23
+ // From `e.parentOf`, which Main derives PER KEY. `e.parentEntity` describes
24
+ // only the FIRST parent, so an entity nested two levels deep had every one of
25
+ // its parents resolved to the innermost one — addressing the wrong record, or
26
+ // none.
27
+ function parentName(e: any, key: string): string {
28
+ const byKey = (e.parentOf || {})[key]
29
+ if (null != byKey && '' !== byKey) {
30
+ return String(byKey)
31
+ }
32
+
33
+ const f = (e.fields || []).find((f: any) => f.name === key)
34
+ return (f && f.parentEntity) || ''
35
+ }
36
+
37
+
38
+ // The seeded id of the record a parent path param points at.
39
+ function parentSeed(e: any, key: string): string {
40
+ const pe = parentName(e, key)
41
+
42
+ // A key naming no entity in the model still has to seed SOMETHING the
43
+ // guard accepts; strip the `_id` suffix and use that.
44
+ return '' !== pe ? `${pe}0` : `${key.replace(/_id$/, '')}0`
45
+ }
46
+
47
+
48
+ // `key: 'value', ` pairs for an entity's parent path params, ready to splice
49
+ // into an object literal. Empty for a top-level entity, so the same emitter
50
+ // serves both.
51
+ //
52
+ // OFFLINE the value is the seeded parent id, which exists because the seed put
53
+ // it there. LIVE it is a local VARIABLE, emitted as ES shorthand: a real server
54
+ // holds whatever records it holds, and a fixture id written into a live test is
55
+ // a 404 waiting to happen. That is not hypothetical — seeding the live nested
56
+ // create is exactly how the first version of this failed, with
57
+ // `create: request: 404` against a parent that only ever existed in the mock.
58
+ function parentPairs(e: any, live: boolean): string {
59
+ return e.parents
60
+ .map((p: string) => live ? `${p}, ` : `${p}: '${parentSeed(e, p)}', `)
61
+ .join('')
62
+ }
63
+
64
+
65
+ // The entity a parent path param addresses, or null when the model has none of
66
+ // that name.
67
+ function parentEntityFor(provider: any, e: any, key: string): any {
68
+ const name = parentName(e, key)
69
+
70
+ return '' === name ? null :
71
+ provider.entities.find((pe: any) => pe.name === name) || null
72
+ }
73
+
74
+
75
+ // Can a LIVE round-trip get hold of this entity's parent ids at all? Every
76
+ // parent key must name an entity in the model, and that entity must be
77
+ // listable — otherwise there is no honest way to obtain an id the server will
78
+ // accept, and the test is not emitted rather than emitted and skipped.
79
+ function liveParentsResolvable(provider: any, e: any): boolean {
80
+ return e.parents.every((p: string) => {
81
+ const pe = parentEntityFor(provider, e, p)
82
+ return null != pe && pe.cmds.includes('list')
83
+ })
84
+ }
85
+
86
+
87
+ // The lines that fetch a live parent id per parent key, plus the guard that
88
+ // skips when the server has no parent record to attach to. Empty for a
89
+ // top-level entity.
90
+ function liveParentSetup(provider: any, e: any, ind: string): string {
91
+ if (0 === e.parents.length) {
92
+ return ''
93
+ }
94
+
95
+ return e.parents.map((p: string) => {
96
+ const pe = parentEntityFor(provider, e, p)
97
+ const pv = `${pe.name}Records`
98
+
99
+ return `${ind} // ${e.name} records hang off ${pe.name} records, so the ${p} has to
100
+ ${ind} // come FROM THE SERVER. This database is not ours to seed.
101
+ ${ind} const ${pv} = await seneca
102
+ ${ind} .entity('provider/${provider.lower}/${pe.name}')
103
+ ${ind} .list\$()
104
+
105
+ ${ind} if (0 === ${pv}.length) return t.skip('no ${pe.name} to attach a ${e.name} to')
106
+
107
+ ${ind} const ${p} = ${pv}[0].${pe.idf || 'id'}
108
+
109
+ `
110
+ }).join('')
111
+ }
112
+
113
+
114
+ // A field a round-trip test can CHANGE and then assert on: the first string
115
+ // field that is neither the id nor a parent path param. Without one there is
116
+ // nothing an update could alter that an assertion could see, so the update leg
117
+ // is dropped rather than asserted vacuously.
118
+ function mutableField(e: any): string {
119
+ const f = (e.fields || []).find((f: any) =>
120
+ f.name !== e.idf && 'id' !== f.name &&
121
+ !e.parents.includes(f.name) && 'string' === f.kind)
122
+
123
+ return f ? f.name : ''
124
+ }
125
+
126
+
127
+ // A create -> load -> update -> remove round-trip for one entity.
128
+ //
129
+ // Emitted for any entity declaring BOTH save and remove, in both modes: once
130
+ // offline against the SDK's mock transport, once live behind the server probe.
131
+ // The write path is where a provider actually breaks — a save that forgets a
132
+ // parent key, an update that creates a second record instead of amending the
133
+ // first — and it was covered by nothing until this existed. The hand-written
134
+ // provider this target was modelled on had exactly these tests, live; dropping
135
+ // them on the first regeneration left every cmd.save and cmd.remove action in
136
+ // the generated plugin unexecuted by its own suite.
137
+ //
138
+ // The created id is never asserted to a VALUE: both the mock and a real API
139
+ // assign it themselves and ignore any the SDK sends.
140
+ function crudTest(provider: any, e: any, mode: 'offline' | 'live'): string {
141
+ const live = 'live' === mode
142
+ const pairs = parentPairs(e, live)
143
+ // Seneca's key, not the API's: this test drives seneca.entity(...), whose
144
+ // query and entity always spell the id `id`. The provider translates to
145
+ // whatever the API calls it.
146
+ const idf = 'id'
147
+ const mut = mutableField(e)
148
+
149
+ const ind = live ? ' ' : ' '
150
+ const mk = live ? 'makeSeneca(liveOpts())' : 'makeSeneca()'
151
+ const setup = live ? liveParentSetup(provider, e, ind) : ''
152
+
153
+ const made = 0 < e.fields.filter((f: any) =>
154
+ f.name !== idf && 'id' !== f.name && !e.parents.includes(f.name)).length ?
155
+ seedLiteral(e, 'crud') : ''
156
+
157
+ return `${ind}it('${e.name}-crud', async (${live ? 't' : ''}) => {
158
+ ${live ? `${ind} if (!live) return t.skip(noServer())\n` : ''}${ind} const seneca = await ${mk}
159
+ ${ind} const ent = seneca.entity('provider/${provider.lower}/${e.name}')
160
+
161
+ ${setup}${ind} // Seneca's convention: an entity WITHOUT an id is a create. The API
162
+ ${ind} // assigns the id itself, so the saved record comes back with one it chose.
163
+ ${ind} const made = await ent.make$({ ${pairs}${made} }).save$()
164
+
165
+ ${ind} assert.ok(null != made.${idf})
166
+ ${ind} assert.equal(
167
+ ${ind} made.canon\$({ string: true }),
168
+ ${ind} 'provider/${provider.lower}/${e.name}',
169
+ ${ind} )
170
+
171
+ ${ind} const id = made.${idf}
172
+
173
+ ${ind} try {
174
+ ${ind} const loaded = await ent.load\$({ ${pairs}${idf}: id })
175
+ ${ind} assert.equal(loaded.${idf}, id)
176
+ ${
177
+ '' === mut ? '' :
178
+ `
179
+ ${ind} // An entity CARRYING an id is an update, not a second create.
180
+ ${ind} loaded.${mut} = 'crud-${mut}-2'
181
+ ${ind} const updated = await loaded.save\$()
182
+
183
+ ${ind} assert.equal(updated.${idf}, id)
184
+ ${ind} assert.equal(updated.${mut}, 'crud-${mut}-2')
185
+
186
+ ${ind} const reloaded = await ent.load\$({ ${pairs}${idf}: id })
187
+ ${ind} assert.equal(reloaded.${mut}, 'crud-${mut}-2')
188
+ `}${ind} }
189
+ ${ind} finally {
190
+ ${ind} // Always clean up. The mock and the server both hold data for the
191
+ ${ind} // process lifetime, so a leaked record changes what later tests see.
192
+ ${ind} await ent.remove\$({ ${pairs}${idf}: id })
193
+ ${ind} }
194
+
195
+ ${ind} // remove is real: the record is gone, and reading it is an ordinary
196
+ ${ind} // not-found rather than an error.
197
+ ${ind} assert.equal(await ent.load\$({ ${pairs}${idf}: id }), null)
198
+ ${ind}})
199
+
200
+ `
201
+ }
202
+
203
+
204
+ // A source literal for one field, by kind.
205
+ //
206
+ // `$ARRAY` and `$OBJECT` are in the model's sentinel vocabulary and used to
207
+ // fall through to the string branch, so a list field came out as
208
+ // `tags: 'quick-tags'` — a type-incorrect body that a validating server
209
+ // rejects, and a fixture that quietly stopped exercising non-scalar payloads.
210
+ function fieldLiteral(f: any, tag: string): string {
211
+ switch (f.kind) {
212
+ case 'number': return '12345'
213
+ case 'boolean': return 'true'
214
+ case 'array': return '[]'
215
+ case 'object': return '{}'
216
+ default: return `'${tag}-${f.name}'`
217
+ }
218
+ }
219
+
220
+
221
+ // `name: 'value'` pairs for an entity's own (non-id, non-parent) required
222
+ // fields, tagged with `tag` so a test record is recognisable in a store it
223
+ // shares with the seed.
224
+ function seedLiteral(e: any, tag: string): string {
225
+ return (e.fields || [])
226
+ .filter((f: any) =>
227
+ f.name !== e.idf && 'id' !== f.name && !e.parents.includes(f.name))
228
+ .map((f: any) => `${jsKey(f.name)}: ${fieldLiteral(f, tag)}`)
229
+ .join(', ')
230
+ }
231
+
232
+
233
+ // A plausible seed record for an entity: its required fields, given values
234
+ // that read as data rather than as `string`.
235
+ function seedRecord(e: any, idx: number): Record<string, any> {
236
+ const out: Record<string, any> = {}
237
+
238
+ for (const f of e.fields) {
239
+ if ('id' === f.name || f.name === e.idf) {
240
+ out[f.name] = `${e.name}${idx}`
241
+ }
242
+ else if (e.parents.includes(f.name)) {
243
+ // A nested entity's parent id must match a record the parent seeds, or
244
+ // the offline store answers nothing and every nested test reads as a
245
+ // false pass.
246
+ out[f.name] = `${f.parentEntity}0`
247
+ }
248
+ else if ('number' === f.kind) {
249
+ out[f.name] = 100 * (idx + 1)
250
+ }
251
+ else if ('boolean' === f.kind) {
252
+ out[f.name] = false
253
+ }
254
+ else if ('array' === f.kind) {
255
+ out[f.name] = []
256
+ }
257
+ else if ('object' === f.kind) {
258
+ out[f.name] = {}
259
+ }
260
+ else {
261
+ out[f.name] = `${f.name}${idx}`
262
+ }
263
+ }
264
+
265
+ return out
266
+ }
267
+
268
+
269
+ const Tests = cmp(function Tests(props: any) {
270
+ const { provider } = props
271
+
272
+ // The entity the suite exercises hardest: prefer one with no parent keys
273
+ // (nothing to arrange) and the most cmds.
274
+ const subject = [...provider.entities]
275
+ .sort((a: any, b: any) =>
276
+ (a.parents.length - b.parents.length) || (b.cmds.length - a.cmds.length))[0]
277
+
278
+ const nested = provider.entities.filter((e: any) => 0 < e.parents.length)
279
+
280
+ Folder({ name: 'test' }, () => {
281
+
282
+ // The seed the offline mock transport is loaded with. Generated from the
283
+ // model so it matches the shape the SDK will actually return.
284
+ File({ name: 'seed.js' }, () => {
285
+ Content(`/* Generated by @voxgig/sdkgen. Do not edit. */
286
+ 'use strict'
287
+
288
+ // Seed data for the SDK's offline mock transport, so the entity tests
289
+ // exercise real code paths without a server.
290
+ const SEED = {
291
+ entity: {
292
+ `)
293
+ each(provider.entities, (e: any) => {
294
+ Content(` ${e.name}: {
295
+ `)
296
+ each([0, 1], (i: any) => {
297
+ const idx = Number(i.val$ ?? i)
298
+ const rec = seedRecord(e, idx)
299
+ Content(` ${e.name}${idx}: ${JSON.stringify(rec)},
300
+ `)
301
+ })
302
+ Content(` },
303
+ `)
304
+ })
305
+ Content(` },
306
+ }
307
+
308
+ module.exports = { SEED }
309
+ `)
310
+ })
311
+
312
+
313
+ // The message-level spec seneca-msg-test drives. TypeScript, compiled to
314
+ // dist-test by test/tsconfig.json — which is also why it must exist: the
315
+ // shipped tsconfig has `include: ["**/*.ts"]` and tsc fails outright on a
316
+ // config that matches no input.
317
+ File({ name: 'basic.messages.ts' }, () => {
318
+ Content(`/* Generated by @voxgig/sdkgen. Do not edit. */
319
+
320
+ const Pkg = require('../package.json')
321
+
322
+ const messages = {
323
+ print: false,
324
+ pattern: 'sys:provider,provider:${provider.lower}',
325
+ allow: { missing: true },
326
+
327
+ calls: [
328
+ {
329
+ pattern: 'get:info',
330
+ out: {
331
+ ok: true,
332
+ name: '${provider.lower}',
333
+ version: Pkg.version,
334
+ },
335
+ },
336
+ ],
337
+ }
338
+
339
+ export default messages
340
+
341
+ if ('undefined' !== typeof module) {
342
+ module.exports = messages
343
+ }
344
+ `)
345
+ })
346
+
347
+
348
+ File({ name: `${provider.fileBase}.test.js` }, () => {
349
+ Content(`/* Generated by @voxgig/sdkgen. Do not edit. */
350
+ 'use strict'
351
+
352
+ const { describe, it, before } = require('node:test')
353
+ const assert = require('node:assert')
354
+
355
+ const Seneca = require('seneca')
356
+
357
+ const ${provider.pluginName} = require('../dist/${provider.fileBase}')
358
+ const ${provider.pluginName}Doc = require('../dist/${provider.pluginName}-doc')
359
+
360
+ const SenecaMsgTest = require('seneca-msg-test')
361
+ const { Maintain } = require('@seneca/maintain')
362
+
363
+ const { SEED } = require('./seed')
364
+
365
+ const BasicMessages = require('../dist-test/basic.messages')
366
+ ${'' === provider.liveBase ? '' : `
367
+ // The live tests run against the companion test server in the SDK repo
368
+ // (\`app/\`), which serves this by default. Start it with:
369
+ // cd ${provider.sdkrel}/app && npm start
370
+ const LIVE_BASE = process.env.${provider.ENV}_TEST_BASE || '${provider.liveBase}'
371
+ `}
372
+
373
+ describe('${provider.fileBase}', () => {
374
+
375
+ it('happy', async () => {
376
+ assert.notEqual(${provider.pluginName}, undefined)
377
+ assert.notEqual(${provider.pluginName}Doc, undefined)
378
+
379
+ const seneca = await makeSeneca()
380
+
381
+ assert.partialDeepStrictEqual(
382
+ await seneca.post('sys:provider,provider:${provider.lower},get:info'),
383
+ {
384
+ ok: true,
385
+ name: '${provider.lower}',
386
+ },
387
+ )
388
+ })
389
+
390
+
391
+ it('messages', async () => {
392
+ const seneca = await makeSeneca()
393
+ await SenecaMsgTest(seneca, BasicMessages)()
394
+ })
395
+
396
+
397
+ it('sdk-export', async () => {
398
+ const seneca = await makeSeneca()
399
+ const sdk = seneca.export('${provider.pluginName}/sdk')()
400
+
401
+ `)
402
+ each(provider.entities, (e: any) => {
403
+ Content(` assert.equal(typeof sdk.${e.acc}, 'function')
404
+ `)
405
+ })
406
+ Content(` })
407
+
408
+ `)
409
+
410
+ if (subject.cmds.includes('list')) {
411
+ Content(`
412
+ it('${subject.name}-list', async () => {
413
+ const seneca = await makeSeneca()
414
+ const list = await seneca.entity('provider/${provider.lower}/${subject.name}').list$()
415
+
416
+ assert.equal(list.length, 2)
417
+
418
+ // Entities must come back as Seneca entities under this plugin's canon.
419
+ // The SDK tags its own results with its entity marker, which must not
420
+ // survive into the Seneca entity.
421
+ assert.equal(
422
+ list[0].canon$({ string: true }),
423
+ 'provider/${provider.lower}/${subject.name}',
424
+ )
425
+ })
426
+
427
+ `)
428
+ }
429
+
430
+ if (subject.cmds.includes('load')) {
431
+ Content(`
432
+ it('${subject.name}-load', async () => {
433
+ const seneca = await makeSeneca()
434
+ const found = await seneca
435
+ .entity('provider/${provider.lower}/${subject.name}')
436
+ .load$('${subject.name}0')
437
+
438
+ assert.equal(found.${subject.idf || 'id'}, '${subject.name}0')
439
+ assert.equal(
440
+ found.canon$({ string: true }),
441
+ 'provider/${provider.lower}/${subject.name}',
442
+ )
443
+ })
444
+
445
+
446
+ // A 404 from a single-item read is an ordinary "not found" answer, not a
447
+ // failure: the provider turns it into null rather than letting the SDK
448
+ // throw.
449
+ it('${subject.name}-load-missing', async () => {
450
+ const seneca = await makeSeneca()
451
+ const missing = await seneca
452
+ .entity('provider/${provider.lower}/${subject.name}')
453
+ .load$('nosuch${subject.name}')
454
+
455
+ assert.equal(missing, null)
456
+ })
457
+
458
+ `)
459
+ }
460
+
461
+ // A nested entity cannot build its path without the parent id. That is
462
+ // the mistake this target exists to make impossible, so pin it.
463
+ each(nested, (e: any) => {
464
+ // EVERY parent key, not just the first. An entity nested two levels
465
+ // deep is guarded on both, so a test supplying only the alphabetically
466
+ // first tripped the second guard and failed on the code it was meant
467
+ // to be exercising.
468
+ const key = e.parents[0]
469
+ const pairs = e.parents
470
+ .map((k: string) => `${k}: '${parentSeed(e, k)}'`).join(', ')
471
+
472
+ Content(`
473
+ it('${e.name}-needs-${key}', async () => {
474
+ const seneca = await makeSeneca()
475
+
476
+ await assert.rejects(
477
+ () => seneca.entity('provider/${provider.lower}/${e.name}').list$({}),
478
+ /${key} is required/,
479
+ )
480
+ })
481
+
482
+ `)
483
+ if (e.cmds.includes('list')) {
484
+ // Assert on the SEEDED RECORDS, not merely that an array came back.
485
+ // `Array.isArray` is true of the empty array, so the nested-list
486
+ // test passed while proving nothing: the seed puts both of this
487
+ // entity's records under the same parent, so both must come back,
488
+ // under this plugin's canon, still carrying the parent key that
489
+ // addressed them.
490
+ Content(`
491
+ it('${e.name}-list', async () => {
492
+ const seneca = await makeSeneca()
493
+ const list = await seneca
494
+ .entity('provider/${provider.lower}/${e.name}')
495
+ .list$({ ${pairs} })
496
+
497
+ assert.equal(list.length, 2)
498
+ assert.equal(
499
+ list[0].canon$({ string: true }),
500
+ 'provider/${provider.lower}/${e.name}',
501
+ )
502
+ assert.equal(list[0].${key}, '${parentSeed(e, key)}')
503
+ })
504
+
505
+ `)
506
+ }
507
+
508
+ // Reading ONE nested record is the path that has to thread both the
509
+ // parent id and the entity id through to the SDK, so cover it
510
+ // separately from list.
511
+ if (e.cmds.includes('load')) {
512
+ Content(`
513
+ it('${e.name}-load', async () => {
514
+ const seneca = await makeSeneca()
515
+ const found = await seneca
516
+ .entity('provider/${provider.lower}/${e.name}')
517
+ .load$({ ${pairs}, id: '${e.name}0' })
518
+
519
+ assert.equal(found.id, '${e.name}0')
520
+ assert.equal(
521
+ found.canon$({ string: true }),
522
+ 'provider/${provider.lower}/${e.name}',
523
+ )
524
+ })
525
+
526
+
527
+ it('${e.name}-load-missing', async () => {
528
+ const seneca = await makeSeneca()
529
+ const missing = await seneca
530
+ .entity('provider/${provider.lower}/${e.name}')
531
+ .load$({ ${pairs}, id: 'nosuch${e.name}' })
532
+
533
+ assert.equal(missing, null)
534
+ })
535
+
536
+ `)
537
+ }
538
+ })
539
+
540
+ // The WRITE path, offline. Reads were covered and writes were not, so
541
+ // every generated `cmd.save` and `cmd.remove` action shipped without its
542
+ // own suite ever running it — including the parent-key guard on a nested
543
+ // save, which is the one this target exists to get right. The mock
544
+ // transport implements create/update/remove, so this needs no server.
545
+ each(provider.entities, (e: any) => {
546
+ if (e.cmds.includes('save') && e.cmds.includes('remove')) {
547
+ Content(`
548
+ ` + crudTest(provider, e, 'offline'))
549
+ }
550
+ })
551
+
552
+ // Live tests, against the companion server in the SDK repo's `app/`.
553
+ // They PROBE first and skip when nothing is listening, so the suite is
554
+ // green on a machine that has never started it — a live suite that
555
+ // fails when the server is absent is one nobody runs.
556
+ if ('' !== provider.liveBase) {
557
+ Content(`
558
+ describe('live', () => {
559
+ let live = false
560
+
561
+ before(async () => {
562
+ live = await serverUp(LIVE_BASE)
563
+ })
564
+
565
+ `)
566
+ if (subject.cmds.includes('list')) {
567
+ Content(` it('${subject.name}-list', async (t) => {
568
+ if (!live) return t.skip(noServer())
569
+ const seneca = await makeSeneca(liveOpts())
570
+
571
+ const list = await seneca.entity('provider/${provider.lower}/${subject.name}').list$()
572
+
573
+ assert.ok(Array.isArray(list))
574
+ if (0 < list.length) {
575
+ assert.equal(
576
+ list[0].canon$({ string: true }),
577
+ 'provider/${provider.lower}/${subject.name}',
578
+ )
579
+ }
580
+ })
581
+
582
+ `)
583
+ }
584
+ if (subject.cmds.includes('load')) {
585
+ Content(` // A read of something that is not there is \`null\`, live as well as
586
+ // offline: the provider's 404 handling is the same code path either way.
587
+ it('${subject.name}-load-missing', async (t) => {
588
+ if (!live) return t.skip(noServer())
589
+ const seneca = await makeSeneca(liveOpts())
590
+
591
+ assert.equal(
592
+ await seneca
593
+ .entity('provider/${provider.lower}/${subject.name}')
594
+ .load$('nosuch${subject.name}'),
595
+ null,
596
+ )
597
+ })
598
+
599
+ `)
600
+ }
601
+
602
+ // The write path against a REAL server. The mock answers the shape the
603
+ // SDK expects by construction; only a live run proves the request the
604
+ // provider builds is one the API actually accepts — which for a nested
605
+ // entity means the parent id reached the URL rather than the body.
606
+ //
607
+ // Emitted only when a live parent id is OBTAINABLE (see
608
+ // liveParentsResolvable): against a real server the parent has to be
609
+ // looked up, and an entity whose parent cannot be listed offers no
610
+ // honest way to get one.
611
+ each(provider.entities, (e: any) => {
612
+ if (e.cmds.includes('save') && e.cmds.includes('remove') &&
613
+ liveParentsResolvable(provider, e)) {
614
+ Content(crudTest(provider, e, 'live'))
615
+ }
616
+ })
617
+
618
+ Content(` })
619
+
620
+ `)
621
+ }
622
+
623
+ // Repository hygiene, from the @seneca/maintain dependency this package
624
+ // declares. Two of its checks report a fault that is not there, because
625
+ // of WHERE they run rather than what they find, so each is excluded
626
+ // only in the environment that breaks it.
627
+ Content(`
628
+ it('maintain', async () => {
629
+ const exclude = []
630
+
631
+ // check_default proves the default branch is main by looking for
632
+ // [branch "main"] in .git/config. A pull_request build checks out the
633
+ // merge ref, which records no such section.
634
+ if ('pull_request' === process.env.GITHUB_EVENT_NAME) {
635
+ exclude.push('check_default')
636
+ }
637
+
638
+ // url_pkgjson locates package.json by comparing process.cwd() + '/package.json'
639
+ // against a path found with Filehound. On Windows those are the same file
640
+ // spelt with different separators, so the url is never read.
641
+ if ('win32' === process.platform) {
642
+ exclude.push('url_pkgjson')
643
+ }
644
+
645
+ await Maintain({ exclude })
646
+ })
647
+
648
+ `)
649
+
650
+ Content(`})
651
+
652
+ `)
653
+
654
+ if ('' !== provider.liveBase) {
655
+ Content(`
656
+ function noServer() {
657
+ return 'no ${provider.lower} server at ' + LIVE_BASE
658
+ }
659
+
660
+
661
+ function liveOpts() {
662
+ return { sdk: { base: LIVE_BASE } }
663
+ }
664
+
665
+
666
+ // Probe the companion test server so live tests skip cleanly when it is not
667
+ // running, rather than failing the suite.
668
+ async function serverUp(base) {
669
+ try {
670
+ const res = await fetch(base + '${provider.probePath}', {
671
+ signal: AbortSignal.timeout(2000),
672
+ })
673
+ return res.ok
674
+ }
675
+ catch (e) {
676
+ return false
677
+ }
678
+ }
679
+
680
+ `)
681
+ }
682
+
683
+ Content(`
684
+ // Default to the SDK's offline mock transport, seeded from ./seed.
685
+ async function makeSeneca(pluginopts) {
686
+ pluginopts = pluginopts || { test: true, testopts: SEED }
687
+
688
+ const seneca = Seneca({ legacy: false })
689
+ .test()
690
+ .use('promisify')
691
+ .use('entity')
692
+ .use('env', {
693
+ // Declared so the provider convention is exercised, and defaulted so
694
+ // the suite runs with nothing configured.
695
+ var: {
696
+ $${provider.ENV}_APIKEY: '',
697
+ },
698
+ })
699
+ .use('provider', {
700
+ provider: {
701
+ ${provider.lower}: {
702
+ keys: {
703
+ apikey: { value: '$${provider.ENV}_APIKEY' },
704
+ },
705
+ },
706
+ },
707
+ })
708
+ .use(${provider.pluginName}, pluginopts)
709
+
710
+ return seneca.ready()
711
+ }
712
+ `)
713
+ })
714
+ })
715
+ })
716
+
717
+
718
+ // --- test/live.js, test/quick.js --------------------------------------------
719
+ //
720
+ // Manual scripts, not part of `npm test`: they need the companion server in
721
+ // the SDK repo's `app/`, which is not published. Generated because the path
722
+ // to that server is knowable — it is the inverse of this target's own
723
+ // `output: path` — so the instruction can be exact rather than "start the
724
+ // server somehow".
725
+
726
+ const Scripts = cmp(function Scripts(props: any) {
727
+ const { provider } = props
728
+
729
+ // Nothing to point at without a declared server.
730
+ if ('' === provider.liveBase) {
731
+ return
732
+ }
733
+
734
+ const subject = [...provider.entities]
735
+ .sort((a: any, b: any) =>
736
+ (a.parents.length - b.parents.length) || (b.cmds.length - a.cmds.length))[0]
737
+
738
+ const senecaSetup = `const Seneca = require('seneca')
739
+
740
+ const BASE = process.env.${provider.ENV}_TEST_BASE || '${provider.liveBase}'
741
+
742
+ async function makeSeneca() {
743
+ return Seneca({ legacy: false })
744
+ .test()
745
+ .use('promisify')
746
+ .use('entity')
747
+ .use('provider', {
748
+ provider: {
749
+ ${provider.lower}: {
750
+ keys: {
751
+ apikey: { value: '' },
752
+ },
753
+ },
754
+ },
755
+ })
756
+ .use('..', { sdk: { base: BASE } })
757
+ .ready()
758
+ }
759
+ `
760
+
761
+ Folder({ name: 'test' }, () => {
762
+
763
+ File({ name: 'live.js' }, () => {
764
+ Content(`/* Manual script: read from a running ${provider.api} server.
765
+ *
766
+ * Start the companion test server from the SDK repo first:
767
+ * cd ${provider.sdkrel}/app && npm start
768
+ *
769
+ * Then: node test/live.js
770
+ */
771
+
772
+ ${senecaSetup}
773
+
774
+ run()
775
+
776
+ async function run() {
777
+ const seneca = await makeSeneca()
778
+
779
+ `)
780
+ // A nested entity's list needs its parent's id, so LOOK ONE UP rather
781
+ // than emitting a placeholder: a script that 404s on first run teaches
782
+ // nothing and reads as a broken provider.
783
+ each(provider.entities.filter((e: any) => e.cmds.includes('list')), (e: any) => {
784
+ if (0 === e.parents.length) {
785
+ Content(` console.log('${e.name.toUpperCase()}', await seneca
786
+ .entity('provider/${provider.lower}/${e.name}')
787
+ .list$())
788
+
789
+ `)
790
+ return
791
+ }
792
+
793
+ const parent = provider.entities
794
+ .find((p: any) => p.name === e.parentEntity && p.cmds.includes('list'))
795
+ if (null == parent) {
796
+ // Nothing to derive the parent id from. Say so in the script
797
+ // rather than emitting a call that cannot work.
798
+ Content(` // ${e.name}: needs ${e.parents.join(', ')}; no listable parent to take
799
+ // one from, so supply it yourself:
800
+ // await seneca.entity('provider/${provider.lower}/${e.name}')
801
+ // .list$({ ${e.parents.map((k: string) => `${k}: '...'`).join(', ')} })
802
+
803
+ `)
804
+ return
805
+ }
806
+
807
+ const key = e.parents[0]
808
+ Content(` const ${parent.name}s = await seneca
809
+ .entity('provider/${provider.lower}/${parent.name}')
810
+ .list$()
811
+
812
+ if (0 < ${parent.name}s.length) {
813
+ console.log('${e.name.toUpperCase()}', await seneca
814
+ .entity('provider/${provider.lower}/${e.name}')
815
+ .list$({ ${key}: ${parent.name}s[0].${parent.idf || 'id'} }))
816
+ }
817
+
818
+ `)
819
+ })
820
+ Content(`}
821
+ `)
822
+ })
823
+
824
+
825
+ // The write cycle, kept separate: it MUTATES the server, so it is not
826
+ // something to run by reflex. It cleans up after itself.
827
+ if (subject.cmds.includes('save') && subject.cmds.includes('remove')) {
828
+ const idf = subject.idf || 'id'
829
+ const writable = subject.fields
830
+ .filter((f: any) => f.name !== idf && f.name !== 'id')
831
+ .filter((f: any) => !subject.parents.includes(f.name))
832
+
833
+ const make = writable
834
+ .map((f: any) => `${jsKey(f.name)}: ${fieldLiteral(f, 'quick')}`)
835
+ .join(', ')
836
+
837
+ File({ name: 'quick.js' }, () => {
838
+ Content(`/* Manual script: exercise the full CRUD cycle against a running server.
839
+ *
840
+ * Start the companion test server from the SDK repo first:
841
+ * cd ${provider.sdkrel}/app && npm start
842
+ *
843
+ * Then: node test/quick.js
844
+ *
845
+ * Creates and then removes a ${subject.name}, so the server is left as found.
846
+ */
847
+
848
+ ${senecaSetup}
849
+
850
+ run()
851
+
852
+ async function run() {
853
+ const seneca = await makeSeneca()
854
+
855
+ // Create: the API assigns the id, so none is supplied here.
856
+ let ${subject.name} = await seneca
857
+ .entity('provider/${provider.lower}/${subject.name}')
858
+ .make$({ ${make} })
859
+ .save$()
860
+ console.log('CREATED', ${subject.name})
861
+
862
+ const id = ${subject.name}.${idf}
863
+
864
+ try {
865
+ `)
866
+ // Change something an assertion could SEE. A container field would be
867
+ // rewritten to the same empty literal, which demonstrates nothing.
868
+ const upd = writable.find((f: any) =>
869
+ 'string' === f.kind || 'number' === f.kind) || null
870
+
871
+ if (subject.ops.includes('update') && null != upd) {
872
+ const f = upd
873
+ const v = 'number' === f.kind ? '4321' : `'quick-${f.name}-2'`
874
+ Content(` // Update: an entity carrying an id is an update.
875
+ ${jsProp(subject.name, f.name)} = ${v}
876
+ console.log('UPDATED', await ${subject.name}.save$())
877
+
878
+ `)
879
+ }
880
+ if (subject.cmds.includes('load')) {
881
+ Content(` console.log(
882
+ 'LOADED',
883
+ await seneca.entity('provider/${provider.lower}/${subject.name}').load$(id)
884
+ )
885
+
886
+ `)
887
+ }
888
+
889
+ // The NESTED write, which is the leg worth having a manual script
890
+ // for: it is the one where the parent id has to reach the URL rather
891
+ // than the body, and where a provider that forgets it reports an
892
+ // opaque 404 instead of saying what is missing.
893
+ //
894
+ // Only for a child of the record just created — then the parent id is
895
+ // `id`, already in hand, and removing the child leaves the server
896
+ // exactly as found. A child of anything else would need its own
897
+ // lookup, which belongs in the test suite rather than in a script
898
+ // whose whole point is to be readable.
899
+ const child = provider.entities.find((e: any) =>
900
+ 1 === e.parents.length &&
901
+ e.parentEntity === subject.name &&
902
+ e.cmds.includes('save') && e.cmds.includes('remove'))
903
+
904
+ if (null != child) {
905
+ const ckey = child.parents[0]
906
+ const cidf = child.idf || 'id'
907
+ const cmake = (child.fields || [])
908
+ .filter((f: any) =>
909
+ f.name !== cidf && 'id' !== f.name && !child.parents.includes(f.name))
910
+ .map((f: any) => `${jsKey(f.name)}: ${fieldLiteral(f, 'quick')}`)
911
+ .join(', ')
912
+
913
+ Content(` // ${child.name} records hang off ${subject.name} records, so this one
914
+ // goes under the ${subject.name} just created — and comes back off again.
915
+ const ${child.name} = await seneca
916
+ .entity('provider/${provider.lower}/${child.name}')
917
+ .make$({ ${ckey}: id${'' === cmake ? '' : ', ' + cmake} })
918
+ .save$()
919
+ console.log('${child.name.toUpperCase()} CREATED', ${child.name})
920
+
921
+ await seneca
922
+ .entity('provider/${provider.lower}/${child.name}')
923
+ .remove$({ ${ckey}: id, ${cidf}: ${child.name}.${cidf} })
924
+ console.log('${child.name.toUpperCase()} REMOVED')
925
+
926
+ `)
927
+ }
928
+
929
+ Content(` }
930
+ finally {
931
+ await seneca.entity('provider/${provider.lower}/${subject.name}').remove$(id)
932
+ console.log('REMOVED', id)
933
+ }
934
+ `)
935
+ if (subject.cmds.includes('load')) {
936
+ Content(`
937
+ console.log(
938
+ 'AFTER REMOVE (expect null)',
939
+ await seneca.entity('provider/${provider.lower}/${subject.name}').load$(id)
940
+ )
941
+ `)
942
+ }
943
+ Content(`}
944
+ `)
945
+ })
946
+ }
947
+ })
948
+ })
949
+
950
+
951
+ // --- .github/workflows/build.yml --------------------------------------------
952
+
953
+ const Workflow = cmp(function Workflow(props: any) {
954
+ const { provider } = props
955
+
956
+ Folder({ name: '.github' }, () => {
957
+ Folder({ name: 'workflows' }, () => {
958
+ File({ name: 'build.yml' }, () => {
959
+ Content(`# Generated by @voxgig/sdkgen. Do not edit.
960
+ #
961
+ # The ${provider.api} SDK is a normal published dependency, so \`npm install\`
962
+ # is all that is needed to build and run the offline tests on every platform.
963
+ ${!provider.liveApp ? '' : `#
964
+ # The live tests additionally need the companion server, which is only
965
+ # distributed in the SDK's source repository (it is not published). That repo
966
+ # is cloned and started on Linux only, because backgrounding the server
967
+ # assumes a POSIX shell. The live tests probe for the server and skip cleanly
968
+ # when it is absent, so on Windows and macOS they simply skip.`}
969
+
970
+ name: build
971
+
972
+ on:
973
+ push:
974
+ branches: [main]
975
+ pull_request:
976
+ branches: [main]
977
+
978
+ jobs:
979
+ build:
980
+ timeout-minutes: 10
981
+
982
+ strategy:
983
+ fail-fast: false
984
+ matrix:
985
+ os: [ubuntu-latest, windows-latest, macos-latest]
986
+ node-version: [24.x]
987
+
988
+ runs-on: \${{ matrix.os }}
989
+
990
+ steps:
991
+ - uses: actions/checkout@v7
992
+
993
+ - name: Use Node.js \${{ matrix.node-version }}
994
+ uses: actions/setup-node@v7
995
+ with:
996
+ node-version: \${{ matrix.node-version }}
997
+
998
+ ${!provider.liveApp ? '' : `
999
+ # Live-test target. Failure to start degrades coverage (the live tests
1000
+ # probe first and skip) rather than failing the build — which is what
1001
+ # continue-on-error is for, and what its absence undid: GitHub runs a
1002
+ # run: block under bash -e, so a repo whose app/ has no build script,
1003
+ # or no app/ at all, went red on its first push with the comment
1004
+ # above still claiming otherwise.
1005
+ - name: Start the ${provider.api} test server
1006
+ if: runner.os == 'Linux'
1007
+ continue-on-error: true
1008
+ run: |
1009
+ git clone --depth 1 \\
1010
+ ${provider.sdkRepoUrl}.git \\
1011
+ "$RUNNER_TEMP/sdk"
1012
+ cd "$RUNNER_TEMP/sdk/app"
1013
+ npm install
1014
+ npm run build
1015
+ npm start &
1016
+ for i in $(seq 1 30); do
1017
+ if curl -sf ${provider.liveBase}${provider.probePath} > /dev/null; then
1018
+ echo "server up"
1019
+ exit 0
1020
+ fi
1021
+ sleep 1
1022
+ done
1023
+ echo "server did not start; live tests will skip"
1024
+ `}
1025
+ - run: npm install
1026
+ - run: npm i seneca seneca-entity seneca-promisify @seneca/provider @seneca/env
1027
+ - run: npm run build --if-present
1028
+ - run: npm test
1029
+ `)
1030
+ })
1031
+ })
1032
+ })
1033
+ })
1034
+
1035
+
1036
+ // --- README.md ---------------------------------------------------------------
1037
+ //
1038
+ // The heading set is NOT free: @seneca/maintain checks a Seneca plugin README
1039
+ // for "Quick Example", "More Examples", "Motivation", "Support", "API",
1040
+ // "Contributing" and "Background", and the generated `maintain` test fails
1041
+ // without them. That check is the reason to generate this file rather than
1042
+ // leave it to a maintainer.
1043
+
1044
+ const Readme = cmp(function Readme(props: any) {
1045
+ const { provider } = props
1046
+
1047
+ const subject = [...provider.entities]
1048
+ .sort((a: any, b: any) =>
1049
+ (a.parents.length - b.parents.length) || (b.cmds.length - a.cmds.length))[0]
1050
+
1051
+ const nested = provider.entities.filter((e: any) => 0 < e.parents.length)
1052
+
1053
+ File({ name: 'README.md' }, () => {
1054
+ Content(`![Seneca ${provider.Name}-Provider](http://senecajs.org/files/assets/seneca-logo.png)
1055
+
1056
+ > _Seneca ${provider.Name}-Provider_ is a plugin for [Seneca](http://senecajs.org)
1057
+
1058
+ Provides access to the ${provider.api} API using the Seneca _provider_
1059
+ convention. ${provider.api} entities are represented as Seneca entities so that
1060
+ they can be accessed using the Seneca entity API and messages.
1061
+
1062
+ Requests are handled by the [${provider.api} SDK](${provider.sdkRepoUrl}),
1063
+ which is generated from the API's OpenAPI specification. This plugin is
1064
+ generated from the same specification by
1065
+ [@voxgig/sdkgen](https://github.com/voxgig/sdkgen) — do not edit it by hand,
1066
+ change the model and regenerate.
1067
+
1068
+ See [seneca-entity](https://github.com/senecajs/seneca-entity) and the [Seneca Data
1069
+ Entities
1070
+ Tutorial](https://senecajs.org/docs/tutorials/understanding-data-entities.html)
1071
+ for more details on the Seneca entity API.
1072
+
1073
+ [![build](${provider.repoUrl}/actions/workflows/build.yml/badge.svg)](${provider.repoUrl}/actions/workflows/build.yml)
1074
+
1075
+ | This open source module is sponsored and supported by [${provider.publisher}](${provider.publisherUrl}). |
1076
+ | --- |
1077
+
1078
+
1079
+ <!--START:SECTION:intro-->
1080
+ <!--END:SECTION:intro-->
1081
+
1082
+
1083
+ ## Documentation
1084
+
1085
+ Full documentation lives in [\`doc/\`](doc/README.md) and follows the
1086
+ [Diátaxis](https://diataxis.fr) framework:
1087
+
1088
+ | Document | Purpose |
1089
+ | -------- | ------- |
1090
+ | [Tutorial](doc/tutorial.md) | Start here. Build a working script from an empty folder. |
1091
+ | [How-to guides](doc/how-to.md) | Recipes for specific tasks. |
1092
+ | [Reference](doc/reference.md) | Every pattern, entity, option and export. |
1093
+ | [Explanation](doc/explanation.md) | Why the plugin is designed this way. |
1094
+
1095
+
1096
+ ## Quick Example
1097
+
1098
+ \`\`\`js
1099
+ const Seneca = require('seneca')
1100
+
1101
+ const seneca = Seneca()
1102
+ .use('promisify')
1103
+ .use('entity')
1104
+ .use('env', { var: { $${provider.ENV}_APIKEY: '' } })
1105
+ .use('provider', {
1106
+ provider: {
1107
+ ${provider.lower}: {
1108
+ keys: { apikey: { value: '$${provider.ENV}_APIKEY' } },
1109
+ },
1110
+ },
1111
+ })
1112
+ .use('${provider.pkgName}')
1113
+
1114
+ await seneca.ready()
1115
+
1116
+ `)
1117
+ if (subject.cmds.includes('list')) {
1118
+ Content(`const ${subject.name}s = await seneca
1119
+ .entity('provider/${provider.lower}/${subject.name}').list$()
1120
+ `)
1121
+ }
1122
+ if (subject.cmds.includes('load')) {
1123
+ Content(`const ${subject.name} = await seneca
1124
+ .entity('provider/${provider.lower}/${subject.name}').load$('some-id')
1125
+ `)
1126
+ }
1127
+ Content(`\`\`\`
1128
+
1129
+
1130
+ ## Install
1131
+
1132
+ \`\`\`sh
1133
+ npm install ${provider.pkgName}
1134
+ \`\`\`
1135
+
1136
+ This plugin expects the Seneca host framework to be present:
1137
+
1138
+ \`\`\`sh
1139
+ npm install seneca seneca-entity seneca-promisify @seneca/provider @seneca/env
1140
+ \`\`\`
1141
+
1142
+
1143
+ ## Options
1144
+
1145
+ | Option | Type | Description |
1146
+ | --- | --- | --- |
1147
+ | \`sdk\` | object | Passed straight to the \`${provider.sdkClass}\` constructor. Most usefully \`base\`, to point at a server. |
1148
+ | \`test\` | boolean | Run the SDK in offline test mode (in-memory mock transport). |
1149
+ | \`testopts\` | object | Seed and options for the mock, used only when \`test\` is true. |
1150
+
1151
+
1152
+ ## Entities
1153
+
1154
+ Each API entity is exposed as a Seneca entity under
1155
+ \`provider/${provider.lower}/<entity>\`.
1156
+
1157
+ | Seneca entity | Commands | Fields |
1158
+ | --- | --- | --- |
1159
+ `)
1160
+ // Fields as well as commands: a reader deciding whether this plugin
1161
+ // covers what they need has to know what a record CONTAINS, and the
1162
+ // table used to answer only half the question.
1163
+ each(provider.entities, (e: any) => {
1164
+ const fields = 0 === e.fields.length ? '—' :
1165
+ e.fields.map((f: any) => '`' + f.name + '`').join(', ')
1166
+ Content(`| \`provider/${provider.lower}/${e.name}\` | ${e.cmds.map((c: string) => '`' + c + '$`').join(', ')} | ${fields} |
1167
+ `)
1168
+ })
1169
+
1170
+ if (0 < nested.length) {
1171
+ Content(`
1172
+ ### Nested entities
1173
+
1174
+ Some entities live under a parent in the API path, so every command needs the
1175
+ parent's id in the query. Leaving it out throws with a message naming the
1176
+ missing key, rather than failing as an opaque 404 from a half-built URL.
1177
+
1178
+ `)
1179
+ each(nested, (e: any) => {
1180
+ Content(`- \`${e.name}\` requires \`${e.parents.join('`, `')}\`
1181
+ `)
1182
+ })
1183
+ }
1184
+
1185
+ Content(`
1186
+
1187
+ ## Action Patterns
1188
+
1189
+ Every message pattern this plugin registers. The entity actions are the ones
1190
+ \`seneca-entity\` dispatches to when you call \`list$\` / \`load$\` / \`save$\` /
1191
+ \`remove$\` on a canon below — you rarely post them by hand, but they are what
1192
+ appears in a Seneca log, and a plugin that documents one of nine is a plugin
1193
+ whose logs cannot be read.
1194
+
1195
+ | Pattern | Description |
1196
+ | --- | --- |
1197
+ | \`sys:provider,provider:${provider.lower},get:info\` | Plugin and SDK version information. |
1198
+ `)
1199
+
1200
+ const CMD_DESC: Record<string, string> = {
1201
+ list: 'List records',
1202
+ load: 'Load one record',
1203
+ save: 'Create or update a record',
1204
+ remove: 'Remove a record',
1205
+ }
1206
+
1207
+ each(provider.entities, (e: any) => {
1208
+ each(e.cmds, (cmd: any) => {
1209
+ const c = String(cmd.val$ ?? cmd)
1210
+ Content(`| \`sys:entity,cmd:${c},zone:provider,base:${provider.lower},name:${e.name}\` | ${CMD_DESC[c]}. |
1211
+ `)
1212
+ })
1213
+ })
1214
+
1215
+ Content(`
1216
+
1217
+
1218
+ ## More Examples
1219
+
1220
+ ### Offline testing
1221
+
1222
+ The SDK ships an in-memory mock transport, so this plugin can be exercised
1223
+ with no server:
1224
+
1225
+ \`\`\`js
1226
+ .use('${provider.pkgName}', { test: true, testopts: { entity: { ... } } })
1227
+ \`\`\`
1228
+
1229
+ \`testopts\` is passed straight to the SDK's test constructor; \`entity\`
1230
+ seeds the mock store. See \`test/seed.js\` for the shape.
1231
+
1232
+ `)
1233
+ if ('' !== provider.liveBase) {
1234
+ Content(`### Running against a server
1235
+
1236
+ \`\`\`js
1237
+ .use('${provider.pkgName}', { sdk: { base: '${provider.liveBase}' } })
1238
+ \`\`\`
1239
+
1240
+ The companion test server is distributed in the SDK's source repository
1241
+ only. From a checkout beside this one:
1242
+
1243
+ \`\`\`sh
1244
+ cd ${provider.sdkrel}/app && npm start
1245
+ \`\`\`
1246
+
1247
+ Then \`node test/live.js\` reads from it, and \`node test/quick.js\` runs a
1248
+ full create/update/load/remove cycle.
1249
+
1250
+ `)
1251
+ }
1252
+
1253
+ Content(`
1254
+ ## Motivation
1255
+
1256
+ Applications rarely talk to one external service, and each service usually
1257
+ arrives with its own client library, authentication style and error
1258
+ conventions. That variety leaks into application code and makes it harder to
1259
+ test.
1260
+
1261
+ The Seneca provider convention removes the variety: every external service
1262
+ becomes a Seneca entity reached with \`list$\`, \`load$\`, \`save$\` and
1263
+ \`remove$\`, so application code has one shape regardless of what it talks to.
1264
+
1265
+ The SDK underneath arrives at a similar conclusion from the other side — it
1266
+ deliberately exposes entities rather than HTTP routes. This plugin is the
1267
+ short bridge between the two.
1268
+
1269
+
1270
+ ## Support
1271
+
1272
+ - Issues and bugs: [GitHub issues](${provider.repoUrl}/issues)
1273
+ - Seneca community: [senecajs.org](http://senecajs.org)
1274
+
1275
+
1276
+ ## API
1277
+
1278
+ ### Plugin export: \`${provider.pluginName}/sdk\`
1279
+
1280
+ Returns the configured \`${provider.sdkClass}\` instance, for the operations
1281
+ the entity API does not cover:
1282
+
1283
+ \`\`\`js
1284
+ const sdk = seneca.export('${provider.pluginName}/sdk')()
1285
+ \`\`\`
1286
+
1287
+
1288
+ ## Contributing
1289
+
1290
+ This plugin is GENERATED. Changes belong in the SDK project's model and
1291
+ components, not here — anything edited in this repository is overwritten by
1292
+ the next generation run.
1293
+
1294
+ The [Senecajs org](http://senecajs.org) encourages open participation. If you
1295
+ feel you can help in any way, be it with bug reporting, documentation,
1296
+ examples, extra testing, or new features, please get in touch.
1297
+
1298
+
1299
+ ## Background
1300
+
1301
+ Generated by [@voxgig/sdkgen](https://github.com/voxgig/sdkgen) from the
1302
+ ${provider.api} API definition, against the
1303
+ [${provider.sdkPkg}](https://www.npmjs.com/package/${provider.sdkPkg}) SDK.
1304
+ `)
1305
+ })
1306
+ })
1307
+
1308
+
1309
+ // --- doc/tutorial.md ---------------------------------------------------------
1310
+ //
1311
+ // The Diataxis TUTORIAL: an empty folder to a working script in about fifteen
1312
+ // minutes. It teaches, so it is deliberately narrower than the other three
1313
+ // documents — one path, no alternatives, and no decisions asked of the
1314
+ // reader.
1315
+ //
1316
+ // Two decisions shape this component.
1317
+ //
1318
+ // FIRST, a tutorial must never ask the reader to invent a value. Every id in
1319
+ // the script is therefore either seeded here (offline) or read back from a
1320
+ // list call (live) — never a literal that only happens to exist on the
1321
+ // author's machine. That is also why a declared server is not by itself
1322
+ // enough to choose the live lesson: the primary entity must be listable, and
1323
+ // a nested primary entity must have a listable parent, or there is no honest
1324
+ // way to come by the first id. Failing that the offline lesson runs, which is
1325
+ // a complete tutorial in its own right rather than an apology for a missing
1326
+ // server.
1327
+ //
1328
+ // SECOND, the step numbers are computed rather than written, because which
1329
+ // steps exist depends on which cmds the model declares. `step()` counts as it
1330
+ // emits, and the prose refers to what a step did rather than to a number that
1331
+ // may not be there.
1332
+ //
1333
+ // The offline seed reuses seedRecord() — the same function behind
1334
+ // test/seed.js — so what the reader is told to paste has the shape the SDK
1335
+ // really answers with.
1336
+
1337
+ const DocTutorial = cmp(function DocTutorial(props: any) {
1338
+ const { provider } = props
1339
+
1340
+ // Entity and field names come from an API definition, so they cannot be
1341
+ // assumed to be legal JavaScript identifiers.
1342
+ const ident = (s: string) => String(s).replace(/[^A-Za-z0-9_$]/g, '_')
1343
+ const qkey = (k: string) =>
1344
+ /^[A-Za-z_$][A-Za-z0-9_$]*$/.test(String(k)) ? String(k) : `'${k}'`
1345
+ const plural = (n: string) =>
1346
+ n.endsWith('s') ? `${ident(n)}List` : `${ident(n)}s`
1347
+ const canon = (n: string) => `provider/${provider.lower}/${n}`
1348
+ const entOf = (name: string) =>
1349
+ provider.entities.find((e: any) => e.name === name) || null
1350
+
1351
+ // The entity the lesson is built on: fewest parent keys to arrange, then
1352
+ // most cmds to show. The same choice the tests and the README make, so all
1353
+ // three talk about the same thing.
1354
+ const subject = [...provider.entities]
1355
+ .sort((a: any, b: any) =>
1356
+ (a.parents.length - b.parents.length) || (b.cmds.length - a.cmds.length))[0]
1357
+
1358
+ const idf = subject.idf || 'id'
1359
+ const subjParent = 0 < subject.parents.length ?
1360
+ entOf(subject.parentEntity) : null
1361
+
1362
+ const hasServer = '' !== provider.liveBase
1363
+
1364
+ // Can the live lesson actually be written? It needs a server AND a first id
1365
+ // the script can discover for itself.
1366
+ const live = hasServer &&
1367
+ subject.cmds.includes('list') &&
1368
+ (0 === subject.parents.length ||
1369
+ (1 === subject.parents.length &&
1370
+ null != subjParent && subjParent.cmds.includes('list')))
1371
+
1372
+ const offline = !live
1373
+
1374
+ // The nested entity the lesson finishes on. Prefer one hanging off the
1375
+ // subject, so the reader recognises the parent id when it turns up.
1376
+ const readable = (e: any) => e.cmds.includes('list') || e.cmds.includes('load')
1377
+ const nested = provider.entities
1378
+ .filter((e: any) => 0 < e.parents.length && e.name !== subject.name)
1379
+ .filter(readable)
1380
+ // Live, the parent id has to come from somewhere: exactly one parent key,
1381
+ // and a parent that can be listed.
1382
+ .filter((e: any) => offline ||
1383
+ (1 === e.parents.length && null != entOf(e.parentEntity) &&
1384
+ entOf(e.parentEntity).cmds.includes('list')))
1385
+ const child = nested.find((e: any) => e.parentEntity === subject.name) ||
1386
+ nested.find((e: any) => null != entOf(e.parentEntity)) ||
1387
+ nested[0] || null
1388
+ const childParent = null == child ? null : entOf(child.parentEntity)
1389
+
1390
+ // The value seedRecord() gives a parent key, so a query written here finds
1391
+ // the seeded record instead of quietly matching nothing.
1392
+ const seedParentVal = (e: any, k: string) => {
1393
+ const f = (e.fields || []).find((f: any) => f.name === k)
1394
+ const pe = (null != f && '' !== f.parentEntity) ? f.parentEntity :
1395
+ (k === e.parents[0] ? (e.parentEntity || '') : '')
1396
+ return `${pe}0`
1397
+ }
1398
+
1399
+ // A seed record guaranteed to carry its id and its parent keys.
1400
+ // seedRecord() emits only the fields the model marks required, and a record
1401
+ // missing its parent key is invisible to the very query this lesson makes.
1402
+ const demoRecord = (e: any, idx: number) => {
1403
+ const rec: any = seedRecord(e, idx)
1404
+ const eidf = e.idf || 'id'
1405
+ if (null == rec[eidf]) {
1406
+ rec[eidf] = `${e.name}${idx}`
1407
+ }
1408
+ for (const k of e.parents) {
1409
+ if (null == rec[k]) {
1410
+ rec[k] = seedParentVal(e, k)
1411
+ }
1412
+ }
1413
+ return rec
1414
+ }
1415
+
1416
+ // Only the entities the lesson touches, in model order.
1417
+ const seedNames = [subject.name]
1418
+ if (null != subjParent) seedNames.push(subjParent.name)
1419
+ if (null != child) seedNames.push(child.name)
1420
+ if (null != childParent) seedNames.push(childParent.name)
1421
+
1422
+ const seedLiteral = provider.entities
1423
+ .filter((e: any) => seedNames.includes(e.name))
1424
+ .map((e: any) =>
1425
+ ` ${qkey(e.name)}: {\n` +
1426
+ [0, 1].map((idx: number) =>
1427
+ ` ${qkey(e.name + idx)}: ${JSON.stringify(demoRecord(e, idx))},\n`)
1428
+ .join('') +
1429
+ ` },\n`)
1430
+ .join('')
1431
+
1432
+ // Every call on the subject carries its parent keys, if it has any: live
1433
+ // they come from a lookup, offline from the seed.
1434
+ const subjKeys = subject.parents.map((k: string) =>
1435
+ `${qkey(k)}: ${offline ? `'${seedParentVal(subject, k)}'` : ident(k)}`)
1436
+ const listArg = 0 === subjKeys.length ? '' : `{ ${subjKeys.join(', ')} }`
1437
+ const oneArg = (id: string) => 0 === subjKeys.length ? id :
1438
+ `{ ${subjKeys.concat([`${qkey(idf)}: ${id}`]).join(', ')} }`
1439
+
1440
+ const subjVar = plural(subject.name)
1441
+ const subjOne = ident(subject.name)
1442
+
1443
+ // Live, the first id is whatever the server answered with; offline it is
1444
+ // seeded above.
1445
+ const firstId = offline ? `'${subject.name}0'` : `${subjVar}[0].${idf}`
1446
+
1447
+ // A nested subject needs its parent's id before anything else can run.
1448
+ const subjPre = (live && null != subjParent) ?
1449
+ ` // ${subject.name} records live under ${subjParent.name} records in the API,
1450
+ // so every ${subject.name} call needs a ${subject.parents[0]}.
1451
+ const ${plural(subjParent.name)} = await seneca
1452
+ .entity('${canon(subjParent.name)}')
1453
+ .list$()
1454
+ const ${ident(subject.parents[0])} = ${plural(subjParent.name)}[0].${subjParent.idf || 'id'}
1455
+
1456
+ ` : ''
1457
+
1458
+ // Fields worth printing, and worth writing: not the id, not a parent key.
1459
+ const plainFields = subject.fields.filter((f: any) =>
1460
+ f.name !== idf && 'id' !== f.name && !subject.parents.includes(f.name))
1461
+ const shown = plainFields.slice(0, 2)
1462
+ const litval = (f: any, alt: boolean) =>
1463
+ 'number' === f.kind ? (alt ? '4321' : '1234') :
1464
+ 'boolean' === f.kind ? (alt ? 'true' : 'false') :
1465
+ `'tutorial-${f.name}${alt ? '-2' : ''}'`
1466
+
1467
+ const makeFields = subject.parents
1468
+ .map((k: string) =>
1469
+ `${qkey(k)}: ${offline ? `'${seedParentVal(subject, k)}'` : ident(k)}`)
1470
+ .concat(plainFields.map((f: any) => `${qkey(f.name)}: ${litval(f, false)}`))
1471
+
1472
+ const hasRead = subject.cmds.includes('list') || subject.cmds.includes('load')
1473
+ // Creating a record with nothing in it teaches nothing, so the write step
1474
+ // needs at least one field the caller actually supplies.
1475
+ const canWrite = subject.cmds.includes('save') && 0 < plainFields.length
1476
+ const canUpdate = canWrite && subject.ops.includes('update')
1477
+ const canRemove = canWrite && subject.cmds.includes('remove')
1478
+
1479
+ const cmdList = subject.cmds.map((c: string) => '`' + c + '$`').join(', ')
1480
+
1481
+ // Entity names are lowercase, and some of them have to start a sentence.
1482
+ const cap = (s: string) => s.charAt(0).toUpperCase() + s.slice(1)
1483
+
1484
+ // A nested SUBJECT would otherwise carry an unexplained parent key through
1485
+ // every example in the lesson. Said once, before the first call.
1486
+ const nestedNote = 0 === subject.parents.length ? '' :
1487
+ `${cap(subject.name)} records live inside ${'' === subject.parentEntity ?
1488
+ 'a parent record' : `${subject.parentEntity} records`} in the API,
1489
+ and the route says so:
1490
+
1491
+ \`${subject.path}\`
1492
+
1493
+ The parent id there is not optional, so every ${subject.name} call
1494
+ carries ${subject.parents.map((k: string) => '`' + k + '`').join(' and ')} in its query. Leave it out and the provider
1495
+ names the key you missed, rather than letting a half-built URL come
1496
+ back as a puzzling 404.
1497
+
1498
+ `
1499
+
1500
+ // The clone lands in a directory named for the repository, so the cd that
1501
+ // follows can be exact rather than "wherever you put it". With no repo url
1502
+ // to clone from, the only path anyone can be told is the relative one back
1503
+ // to the SDK project.
1504
+ const sdkRepo = String(provider.sdkRepoUrl || '')
1505
+ const sdkDir = sdkRepo.replace(/\/+$/, '').split('/').pop() || 'sdk'
1506
+ const appDir = '' === sdkRepo ? `${provider.sdkrel}/app` : `${sdkDir}/app`
1507
+
1508
+ const getServer = '' === sdkRepo ?
1509
+ `You also need a server to talk to. The SDK itself installs from npm,
1510
+ but its test server does not — it ships only in the SDK's source
1511
+ project, in its \`app\` folder, which is at \`${provider.sdkrel}\`
1512
+ relative to this one.
1513
+ ` :
1514
+ `You also need a server to talk to. The SDK itself installs from npm,
1515
+ but its test server does not — it ships only in the SDK's source
1516
+ repository, so clone that:
1517
+
1518
+ \`\`\`sh
1519
+ $ git clone ${sdkRepo}.git
1520
+ \`\`\`
1521
+
1522
+ If you already have that checkout beside this plugin, it is at
1523
+ \`${provider.sdkrel}\`, and you can skip the clone.
1524
+ `
1525
+
1526
+ // What a bare GET on the probe route answers with, when the model has one.
1527
+ const probeEnt = '' === provider.probePath ? null :
1528
+ provider.entities.find((e: any) => e.path === provider.probePath)
1529
+
1530
+ // Who assigns ids and holds the data, in prose.
1531
+ const source = live ? 'server' : 'store'
1532
+
1533
+ // Where the nested-subject note lands: the first step that shows a call.
1534
+ const noteAt = subject.cmds.includes('list') ? 'list' :
1535
+ subject.cmds.includes('load') ? 'load' : 'write'
1536
+
1537
+ let stepno = 0
1538
+ const step = (title: string) => `## Step ${++stepno}: ${title}`
1539
+
1540
+ File({ name: 'tutorial.md' }, () => {
1541
+
1542
+ Content(`# Tutorial: your first ${provider.Name} query
1543
+
1544
+ This tutorial takes you from an empty folder to a script that
1545
+ ${canWrite ? 'reads and writes' : 'reads'} ${provider.api} data through
1546
+ Seneca entities. It should take about fifteen minutes.
1547
+
1548
+ You will build one script and add to it as you go.`)
1549
+
1550
+ if (live) {
1551
+ Content(` Everything runs
1552
+ locally against a test server you start yourself, so nothing here can
1553
+ affect anything outside your machine.
1554
+
1555
+ You need [Node.js](https://nodejs.org) 24 or later.
1556
+
1557
+ ${getServer}
1558
+ ${step('Start the test server')}
1559
+
1560
+ That server implements the ${provider.api} API. Build and start it:
1561
+
1562
+ \`\`\`sh
1563
+ $ cd ${appDir}
1564
+ $ npm install
1565
+ $ npm run build
1566
+ $ npm start
1567
+ \`\`\`
1568
+
1569
+ It listens on \`${provider.liveBase}\`. Check it from another terminal:
1570
+
1571
+ \`\`\`sh
1572
+ $ curl ${provider.liveBase}${provider.probePath}
1573
+ \`\`\`
1574
+
1575
+ `)
1576
+ Content(null == probeEnt ?
1577
+ `You should get a JSON answer rather than a refused connection.
1578
+ Leave the server running.
1579
+
1580
+ ` :
1581
+ `You should see a JSON array of ${probeEnt.name} records.
1582
+ Leave the server running.
1583
+
1584
+ `)
1585
+ }
1586
+ else {
1587
+ Content(` Everything runs in
1588
+ memory: the SDK ships an offline mode backed by a small in-memory
1589
+ store, and you supply that store's contents yourself. No request leaves
1590
+ your machine, so nothing here can affect anything outside it.
1591
+
1592
+ You need [Node.js](https://nodejs.org) 24 or later. You do not need a
1593
+ server, a network connection, or credentials.
1594
+
1595
+ `)
1596
+ }
1597
+
1598
+ Content(`${step('Create the project')}
1599
+
1600
+ `)
1601
+ if (live) {
1602
+ Content(`In a new terminal:
1603
+
1604
+ `)
1605
+ }
1606
+ Content(`\`\`\`sh
1607
+ $ mkdir ${provider.lower}-demo
1608
+ $ cd ${provider.lower}-demo
1609
+ $ npm init -y
1610
+ $ npm install seneca seneca-entity seneca-promisify @seneca/provider ${provider.pkgName}
1611
+ \`\`\`
1612
+
1613
+ The first four are the Seneca host: the framework itself, the entity
1614
+ API, the promise wrapper that makes calls awaitable, and the shared
1615
+ machinery every Seneca provider is built on. The last is this plugin,
1616
+ which brings the ${provider.api} SDK with it.
1617
+
1618
+ ${step('Connect')}
1619
+
1620
+ Create \`demo.js\`:
1621
+
1622
+ \`\`\`js
1623
+ const Seneca = require('seneca')
1624
+
1625
+ `)
1626
+
1627
+ if (offline) {
1628
+ Content(`// The offline store. Each key under an entity name is that record's
1629
+ // id, and each record is what the API would have answered with.
1630
+ const SEED = {
1631
+ entity: {
1632
+ ${seedLiteral} },
1633
+ }
1634
+
1635
+ `)
1636
+ }
1637
+
1638
+ Content(`async function main() {
1639
+ const seneca = await Seneca({ legacy: false })
1640
+ .use('promisify')
1641
+ .use('entity')
1642
+ .use('provider', {
1643
+ provider: {
1644
+ ${qkey(provider.lower)}: {
1645
+ keys: {
1646
+ apikey: { value: '' },
1647
+ },
1648
+ },
1649
+ },
1650
+ })
1651
+ `)
1652
+ Content(live ?
1653
+ ` .use('${provider.pkgName}', {
1654
+ sdk: { base: '${provider.liveBase}' },
1655
+ })
1656
+ ` :
1657
+ ` .use('${provider.pkgName}', {
1658
+ test: true,
1659
+ testopts: SEED,
1660
+ })
1661
+ `)
1662
+ Content(` .ready()
1663
+
1664
+ const info = await seneca.post('sys:provider,provider:${provider.lower},get:info')
1665
+ console.log(info)
1666
+ }
1667
+
1668
+ main()
1669
+ \`\`\`
1670
+
1671
+ Run it:
1672
+
1673
+ \`\`\`sh
1674
+ $ node demo.js
1675
+ \`\`\`
1676
+
1677
+ You should see:
1678
+
1679
+ \`\`\`js
1680
+ {
1681
+ ok: true,
1682
+ name: '${provider.lower}',
1683
+ version: '${provider.version}',
1684
+ sdk: { name: '${provider.sdkPkg}', version: '${provider.sdkVersion}' },
1685
+ }
1686
+ \`\`\`
1687
+
1688
+ Two details of that configuration are worth a moment. The \`apikey\` is
1689
+ declared even though nothing here asks for credentials — an empty
1690
+ value simply means no \`authorization\` header is sent. Every Seneca
1691
+ provider is configured the same way, so an application that later moves
1692
+ to an authenticated service changes one value rather than its shape.
1693
+ And \`get:info\` is answered by the plugin itself, without calling the
1694
+ API, so a reply tells you the plugin loaded and initialised before any
1695
+ request goes anywhere.
1696
+
1697
+ `)
1698
+
1699
+ if (subject.cmds.includes('list')) {
1700
+ Content(`${step(`List the ${subject.name} records`)}
1701
+
1702
+ ${'list' === noteAt ? nestedNote : ''}Replace the \`console.log(info)\` line with:
1703
+
1704
+ \`\`\`js
1705
+ ${subjPre} const ${subjVar} = await seneca
1706
+ .entity('${canon(subject.name)}')
1707
+ .list$(${listArg})
1708
+
1709
+ console.log('Found ' + ${subjVar}.length + ' ${subject.name} record(s):')
1710
+ ${subjVar}.forEach((r) => {
1711
+ console.log(' ' + r.${idf}${shown.map((f: any) => ` + ' ' + r.${f.name}`).join('')})
1712
+ })
1713
+ \`\`\`
1714
+
1715
+ `)
1716
+ Content(offline ?
1717
+ `Run it again and you will see the two ${subject.name}
1718
+ records you seeded, under the ids they are filed by.
1719
+
1720
+ ` :
1721
+ `Run it again and you will see every ${subject.name}
1722
+ record the server holds.
1723
+
1724
+ `)
1725
+ Content(`No URL, no HTTP verb, no JSON parsing. You asked a Seneca entity for
1726
+ a list, the provider turned that into an SDK call, and the SDK turned
1727
+ it into a request. These are ordinary Seneca entities, so everything
1728
+ you already know about the entity API applies to them.
1729
+
1730
+ `)
1731
+ }
1732
+
1733
+ if (subject.cmds.includes('load')) {
1734
+ Content(`${step(`Load one ${subject.name}`)}
1735
+
1736
+ ${'load' === noteAt ? nestedNote : ''}Add:
1737
+
1738
+ \`\`\`js
1739
+ const one = await seneca
1740
+ .entity('${canon(subject.name)}')
1741
+ .load$(${oneArg(firstId)})
1742
+
1743
+ console.log('loaded', one.${idf}${0 < shown.length ? `, one.${shown[0].name}` : ''})
1744
+ \`\`\`
1745
+
1746
+ `)
1747
+ Content(subject.cmds.includes('list') ?
1748
+ `\`list$\` gives you many, \`load$\` gives you one. Now ask for
1749
+ something that is not there:
1750
+
1751
+ ` :
1752
+ `\`load$\` gives you one record by its id. Now ask for something
1753
+ that is not there:
1754
+
1755
+ `)
1756
+ Content(`\`\`\`js
1757
+ const missing = await seneca
1758
+ .entity('${canon(subject.name)}')
1759
+ .load$(${oneArg(`'nosuch${subject.name}'`)})
1760
+
1761
+ console.log('missing =', missing) // null
1762
+ \`\`\`
1763
+
1764
+ You get \`null\`, not an exception. "There is no such
1765
+ ${subject.name}" is an ordinary answer to a lookup, so it does not
1766
+ interrupt your code.
1767
+
1768
+ `)
1769
+ }
1770
+
1771
+ if (canWrite) {
1772
+ Content(`${step('Create, change and remove')}
1773
+
1774
+ ${'write' === noteAt ? nestedNote : ''}`)
1775
+ Content(hasRead ?
1776
+ `Everything so far has been reading. This entity accepts writes too,
1777
+ so add:
1778
+
1779
+ ` :
1780
+ `Now write one. Add:
1781
+
1782
+ `)
1783
+ Content(`\`\`\`js
1784
+ // Create: make$ builds an entity, save$ persists it.
1785
+ let ${subjOne} = await seneca
1786
+ .entity('${canon(subject.name)}')
1787
+ .make$({ ${makeFields.join(', ')} })
1788
+ .save$()
1789
+
1790
+ console.log('created with id', ${subjOne}.${idf})
1791
+ \`\`\`
1792
+
1793
+ Run it, and note the id printed. It is **not** one you chose — the
1794
+ ${source} assigns ids itself and ignores any you send. That is worth
1795
+ knowing before you write code that assumes otherwise.
1796
+
1797
+ `)
1798
+
1799
+ if (canUpdate) {
1800
+ Content(`Now change it. An entity that already carries an id is an update
1801
+ rather than a create, and \`save$\` decides between the two on exactly
1802
+ that:
1803
+
1804
+ \`\`\`js
1805
+ ${subjOne}.${plainFields[0].name} = ${litval(plainFields[0], true)}
1806
+ ${subjOne} = await ${subjOne}.save$()
1807
+
1808
+ console.log('updated:', ${subjOne}.${plainFields[0].name})
1809
+ \`\`\`
1810
+
1811
+ `)
1812
+ }
1813
+
1814
+ if (canRemove) {
1815
+ Content(`And remove it, leaving the ${source} as you found it:
1816
+
1817
+ \`\`\`js
1818
+ await seneca
1819
+ .entity('${canon(subject.name)}')
1820
+ .remove$(${oneArg(`${subjOne}.${idf}`)})
1821
+ \`\`\`
1822
+
1823
+ `)
1824
+ if (subject.cmds.includes('load')) {
1825
+ Content(`Load it once more and, as before, you get \`null\`:
1826
+
1827
+ \`\`\`js
1828
+ console.log(
1829
+ 'after remove:',
1830
+ await seneca
1831
+ .entity('${canon(subject.name)}')
1832
+ .load$(${oneArg(`${subjOne}.${idf}`)})
1833
+ ) // null
1834
+ \`\`\`
1835
+
1836
+ `)
1837
+ }
1838
+ }
1839
+ else {
1840
+ Content(`This entity declares no remove operation, so the record you have just
1841
+ created stays where it is.
1842
+
1843
+ `)
1844
+ }
1845
+
1846
+ Content(`Those are the only methods there are:
1847
+
1848
+ ${cmdList}
1849
+
1850
+ They behave the same way on every entity this plugin exposes.
1851
+
1852
+ `)
1853
+ }
1854
+
1855
+ if (null != child) {
1856
+ const ckey = child.parents[0]
1857
+ const cidf = child.idf || 'id'
1858
+ const cparent = null == childParent ? 'their parent' :
1859
+ `${childParent.name} records`
1860
+ const cop = child.cmds.includes('list') ? 'list' : 'load'
1861
+
1862
+ // Live, the parent id comes from a list; offline it is seeded, so a
1863
+ // literal is both shorter and exactly reproducible.
1864
+ const reuse = `${subjVar}[0].${idf}`
1865
+ const cval = offline ? `'${seedParentVal(child, ckey)}'` :
1866
+ (null != childParent && childParent.name === subject.name &&
1867
+ subject.cmds.includes('list') && 0 === subject.parents.length) ?
1868
+ reuse : ident(ckey)
1869
+
1870
+ const cpre = (live && reuse !== cval) ?
1871
+ ` const ${plural(childParent.name)} = await seneca
1872
+ .entity('${canon(childParent.name)}')
1873
+ .list$()
1874
+ const ${ident(ckey)} = ${plural(childParent.name)}[0].${childParent.idf || 'id'}
1875
+
1876
+ ` : ''
1877
+
1878
+ const cargs = child.parents.map((k: string) => k === ckey ?
1879
+ `${qkey(k)}: ${cval}` : `${qkey(k)}: '${seedParentVal(child, k)}'`)
1880
+
1881
+ Content(`${step(`Reach the ${child.name} records`)}
1882
+
1883
+ ${cap(child.name)} records live inside ${cparent}, and the API route
1884
+ says so:
1885
+
1886
+ \`${child.path}\`
1887
+
1888
+ The parent id in that path is not optional, so every ${child.name}
1889
+ call needs a \`${ckey}\` in its query:
1890
+
1891
+ \`\`\`js
1892
+ `)
1893
+
1894
+ if (child.cmds.includes('list')) {
1895
+ Content(`${cpre} const ${plural(child.name)} = await seneca
1896
+ .entity('${canon(child.name)}')
1897
+ .list$({ ${cargs.join(', ')} })
1898
+
1899
+ console.log('found ' + ${plural(child.name)}.length + ' ${child.name} record(s)')
1900
+ `)
1901
+ }
1902
+ else {
1903
+ Content(`${cpre} const found = await seneca
1904
+ .entity('${canon(child.name)}')
1905
+ .load$({ ${cargs.concat([`${qkey(cidf)}: '${child.name}0'`]).join(', ')} })
1906
+
1907
+ console.log('found', found.${cidf})
1908
+ `)
1909
+ }
1910
+
1911
+ Content(`\`\`\`
1912
+
1913
+ Leave the \`${ckey}\` out and the call throws at once, naming the key it
1914
+ needed, rather than letting a half-built URL come back as a puzzling
1915
+ 404:
1916
+
1917
+ \`\`\`js
1918
+ // throws: ${provider.pkgName}: ${child.name} ${cop}: ${ckey} is required
1919
+ await seneca
1920
+ .entity('${canon(child.name)}')
1921
+ .${'list' === cop ? 'list$()' : `load$('${child.name}0')`}
1922
+ \`\`\`
1923
+
1924
+ `)
1925
+ }
1926
+
1927
+ if (offline) {
1928
+ Content(`## Talking to a real server
1929
+
1930
+ The script you have just written never touched the network. To point it
1931
+ at a running ${provider.api} server instead, replace the \`test\` and
1932
+ \`testopts\` options with that server's base URL:
1933
+
1934
+ \`\`\`js
1935
+ .use('${provider.pkgName}', {
1936
+ sdk: { base: '${hasServer ? provider.liveBase : 'https://api.example.com'}' },
1937
+ })
1938
+ \`\`\`
1939
+
1940
+ Nothing else in the script changes — the entity calls are the same
1941
+ calls. Your seeded ids will not exist there, so read the ids you need
1942
+ from a \`list$\` first.
1943
+
1944
+ `)
1945
+ if (hasServer && '' !== sdkRepo) {
1946
+ Content(`A test server that answers on that address is distributed in the SDK's
1947
+ source repository, which is the only place it ships. Clone
1948
+ \`${sdkRepo}\`, then run \`npm install\`, \`npm run build\` and
1949
+ \`npm start\` in its \`app\` folder.
1950
+
1951
+ `)
1952
+ }
1953
+ }
1954
+
1955
+ Content(`## What you have learned
1956
+
1957
+ You built a script that ${canWrite ? 'reads and writes' : 'reads'}
1958
+ ${provider.api} data through Seneca entities,
1959
+ ${live ? 'against a real server' : 'with no server involved'}. Along
1960
+ the way you saw:
1961
+
1962
+ - Provider configuration has the same shape even when no credentials
1963
+ are needed.
1964
+ - API resources are Seneca entities under \`provider/${provider.lower}/\`,
1965
+ reached with the entity API you already know.
1966
+ `)
1967
+ if (null != child || 0 < subject.parents.length) {
1968
+ Content(`- A resource nested under another in the API needs its parent's id in
1969
+ every query, and says which key is missing when you forget.
1970
+ `)
1971
+ }
1972
+ if (subject.cmds.includes('load')) {
1973
+ Content(`- \`load$\` answers \`null\` for something that is not there, rather
1974
+ than throwing.
1975
+ `)
1976
+ }
1977
+ if (canWrite) {
1978
+ Content(`- \`save$\` creates without an id and updates with one, and the
1979
+ ${source} chooses the id.
1980
+ `)
1981
+ }
1982
+ if (offline) {
1983
+ Content(`- The offline store makes all of this runnable with nothing installed
1984
+ but npm packages, which is also how you test your own code.
1985
+ `)
1986
+ }
1987
+
1988
+ Content(`
1989
+ ## Where to go next
1990
+
1991
+ - To do a specific job — ${live ? 'run without a server' : 'point at a real server'}, reach the raw SDK,
1992
+ test your own code — see the [how-to guides](how-to.md).
1993
+ - To look up an exact pattern, field or option, see the
1994
+ [reference](reference.md).
1995
+ - To understand why the plugin is built this way — why entities rather
1996
+ than one message per route, and what it does with the SDK's answers
1997
+ — see the [explanation](explanation.md).
1998
+ - For what each of these documents is for, see the
1999
+ [documentation index](README.md).
2000
+ `)
2001
+ })
2002
+ })
2003
+
2004
+
2005
+ // --- doc/how-to.md ----------------------------------------------------------
2006
+ //
2007
+ // The task-oriented quadrant of the Diataxis set: one problem per section, for
2008
+ // a reader who already has the plugin loaded. It instructs and does not
2009
+ // explain — anything that starts justifying a design choice belongs in
2010
+ // explanation.md and is linked to instead.
2011
+ //
2012
+ // Two decisions worth naming. First, the section list is built as data before
2013
+ // anything is emitted, so the table of contents and the sections themselves
2014
+ // are produced from the SAME guards and cannot drift: a recipe that is
2015
+ // suppressed because no entity declares the cmd also loses its TOC entry.
2016
+ // Second, every example id is the one `seedRecord` gives that entity, so the
2017
+ // examples here and the seed in test/seed.js agree — the offline recipe can
2018
+ // then be copied verbatim and the ids used in every other recipe will
2019
+ // actually resolve.
2020
+
2021
+ const DocHowto = cmp(function DocHowto(props: any) {
2022
+ const { provider } = props
2023
+
2024
+ const ents = provider.entities
2025
+ const nested = ents.filter((e: any) => 0 < e.parents.length)
2026
+
2027
+ // The model gives '' when the API definition declares no server. Normalise
2028
+ // an absent value to the same thing, so a missing base is treated as absent
2029
+ // rather than printed as a default nobody can use.
2030
+ const liveBase = provider.liveBase || ''
2031
+
2032
+ // The same choice the tests and the manual scripts make: fewest parent keys
2033
+ // (nothing to arrange), then most cmds. Recipes prefer it, so one entity
2034
+ // carries the reader through the document wherever it can.
2035
+ const subject = [...ents]
2036
+ .sort((a: any, b: any) =>
2037
+ (a.parents.length - b.parents.length) || (b.cmds.length - a.cmds.length))[0]
2038
+
2039
+ const forCmd = (cmd: string) => {
2040
+ const able = ents.filter((e: any) => e.cmds.includes(cmd))
2041
+ return able.find((e: any) => e === subject) ||
2042
+ able.find((e: any) => 0 === e.parents.length) ||
2043
+ able[0] || null
2044
+ }
2045
+
2046
+ const canon = (e: any) => `provider/${provider.lower}/${e.name}`
2047
+ const idf = (e: any) => e.idf || 'id'
2048
+
2049
+ // A parent key's example value. This MIRRORS seedRecord rather than
2050
+ // inventing something more readable: the offline recipe below seeds with
2051
+ // seedRecord, and an example id that does not match what was seeded turns
2052
+ // every other recipe into a lookup that answers null.
2053
+ const parentVal = (e: any, k: string) => {
2054
+ const f = e.fields.find((f: any) => f.name === k)
2055
+ return null == f ? `${k.replace(/_id$/, '')}0` : `${f.parentEntity}0`
2056
+ }
2057
+
2058
+ const parentArgs = (e: any) =>
2059
+ e.parents.map((k: string) => `${k}: '${parentVal(e, k)}'`).join(', ')
2060
+
2061
+ // A query naming ONE record. A top-level entity takes the bare id string;
2062
+ // a nested one cannot, because it is identified by the whole set of keys.
2063
+ const oneArgs = (e: any) => 0 === e.parents.length ?
2064
+ `'${e.name}0'` : `{ ${parentArgs(e)}, ${idf(e)}: '${e.name}0' }`
2065
+
2066
+ const listArgs = (e: any) =>
2067
+ 0 === e.parents.length ? '' : `{ ${parentArgs(e)} }`
2068
+
2069
+ // The SDK's own entity ops always take an object, even for a bare id.
2070
+ const sdkLoadArgs = (e: any) => 0 === e.parents.length ?
2071
+ `{ ${idf(e)}: '${e.name}0' }` :
2072
+ `{ ${parentArgs(e)}, ${idf(e)}: '${e.name}0' }`
2073
+
2074
+ const key = (k: string) => /^[A-Za-z_$][A-Za-z0-9_$]*$/.test(k) ? k : `'${k}'`
2075
+
2076
+ const literal = (rec: Record<string, any>) => {
2077
+ const names = Object.keys(rec)
2078
+ if (0 === names.length) {
2079
+ return '{}'
2080
+ }
2081
+ return '{ ' + names
2082
+ .map((k) => `${key(k)}: ` +
2083
+ ('string' === typeof rec[k] ? `'${rec[k]}'` : String(rec[k])))
2084
+ .join(', ') + ' }'
2085
+ }
2086
+
2087
+ // What a create sends: the seeded record without its id, because the id is
2088
+ // the API's to assign. Parent keys stay — a nested write carries them in
2089
+ // the data rather than the query.
2090
+ const createData = (e: any) => {
2091
+ const rec = seedRecord(e, 0)
2092
+ delete rec[idf(e)]
2093
+ delete rec.id
2094
+ return rec
2095
+ }
2096
+
2097
+ const changeable = (e: any) => e.fields.find((f: any) =>
2098
+ f.name !== idf(e) && 'id' !== f.name && !e.parents.includes(f.name))
2099
+
2100
+ const newValue = (f: any) => 'number' === f.kind ? '999' :
2101
+ 'boolean' === f.kind ? 'true' : `'${f.name}-changed'`
2102
+
2103
+ const pathParams = (p: string) =>
2104
+ (String(p).match(/\{([^}]+)\}/g) || []).map((s: string) => s.slice(1, -1))
2105
+
2106
+ const eList = forCmd('list')
2107
+ const eLoad = forCmd('load')
2108
+ const eSave = forCmd('save')
2109
+ const eRemove = forCmd('remove')
2110
+
2111
+ // Sections as data, so the contents list and the sections cannot disagree.
2112
+ const sections: any[] = []
2113
+ const sec = (title: string, body: string) => sections.push({ title, body })
2114
+
2115
+ // GitHub's heading anchors: lowercased, punctuation dropped, spaces
2116
+ // hyphenated. Section titles avoid backticks and full stops so this stays
2117
+ // a faithful reproduction rather than an approximation.
2118
+ const anchor = (title: string) => '#' + title.toLowerCase()
2119
+ .replace(/[^a-z0-9 _-]/g, '').trim().replace(/ +/g, '-')
2120
+
2121
+ const NESTED_TITLE = 'Work with nested entities'
2122
+ const OFFLINE_TITLE = 'Run offline, without a server'
2123
+
2124
+
2125
+ if (null != eList) {
2126
+ sec('List the records of an entity', `Every resource this plugin covers is a Seneca entity under
2127
+ \`provider/${provider.lower}/\`, so listing one is \`list$\`:
2128
+
2129
+ \`\`\`js
2130
+ const ${eList.name}s = await seneca
2131
+ .entity('${canon(eList)}')
2132
+ .list$(${listArgs(eList)})
2133
+ \`\`\`
2134
+
2135
+ You get an ordinary array of Seneca entities back, so \`length\`, \`map\`
2136
+ and \`data$()\` behave exactly as they do for any other store.
2137
+
2138
+ Fields in the query travel to the API as match criteria. Seneca's own
2139
+ directives — \`sort$\`, \`limit$\` and the rest — are stripped before the
2140
+ call, because they are features of a database store and not of an HTTP
2141
+ API. If you need ordering or paging, ask the API for it using fields it
2142
+ recognises, or sort the returned array yourself.${0 < nested.length ? `
2143
+
2144
+ An entity nested under a parent in the API path cannot be listed without
2145
+ the parent's id; see [${NESTED_TITLE}](${anchor(NESTED_TITLE)}).` : ''}`)
2146
+ }
2147
+
2148
+
2149
+ if (null != eLoad) {
2150
+ sec('Read one record by id', `\`load$\` answers a single record:
2151
+
2152
+ \`\`\`js
2153
+ const ${eLoad.name} = await seneca
2154
+ .entity('${canon(eLoad)}')
2155
+ .load$(${oneArgs(eLoad)})
2156
+ \`\`\`
2157
+ ${'id' === idf(eLoad) ? '' : `
2158
+ The id field for \`${eLoad.name}\` is \`${idf(eLoad)}\`, so that is the
2159
+ key to supply.
2160
+ `}
2161
+ A record that is not there comes back as \`null\`. It is not an error and
2162
+ it does not throw, so test the value rather than wrapping the call:
2163
+
2164
+ \`\`\`js
2165
+ const missing = await seneca
2166
+ .entity('${canon(eLoad)}')
2167
+ .load$(${0 === eLoad.parents.length ? `'nosuch'` :
2168
+ `{ ${parentArgs(eLoad)}, ${idf(eLoad)}: 'nosuch' }`})
2169
+
2170
+ if (null == missing) {
2171
+ // no such ${eLoad.name}
2172
+ }
2173
+ \`\`\`
2174
+
2175
+ Everything else that can go wrong — a network failure, a 5xx, a rejected
2176
+ key — does throw, so an unhandled rejection still means something is
2177
+ genuinely wrong.`)
2178
+ }
2179
+
2180
+
2181
+ if (null != eSave) {
2182
+ const created = literal(createData(eSave))
2183
+
2184
+ sec('Create a record', `\`make$\` builds an entity and \`save$\` writes it. An entity with no id
2185
+ is a create:
2186
+
2187
+ \`\`\`js
2188
+ const ${eSave.name} = await seneca
2189
+ .entity('${canon(eSave)}')
2190
+ .make$(${created})
2191
+ .save$()
2192
+
2193
+ console.log(${eSave.name}.${idf(eSave)})
2194
+ \`\`\`
2195
+ ${0 === eSave.parents.length ? '' : `
2196
+ Note that \`${eSave.parents.join('`, `')}\` travels in the DATA for a write,
2197
+ not in a query: a \`${eSave.name}\` is created inside its parent.
2198
+ `}
2199
+ \`save$\` resolves to the record as the API returned it, which is the only
2200
+ reliable source of the id. Read it from there rather than predicting it:
2201
+ what an API does with an id you supply on create is its own business, and
2202
+ several ignore it entirely.`)
2203
+
2204
+ const f = changeable(eSave)
2205
+
2206
+ sec('Update a record', `The same call updates. \`save$\` dispatches on the id: an entity carrying
2207
+ one is an update, an entity without one is a create. So the safe shape is
2208
+ load, change, save:
2209
+
2210
+ \`\`\`js${eSave.cmds.includes('load') ? `
2211
+ const ${eSave.name} = await seneca
2212
+ .entity('${canon(eSave)}')
2213
+ .load$(${oneArgs(eSave)})
2214
+ ` : `
2215
+ const ${eSave.name} = seneca
2216
+ .entity('${canon(eSave)}')
2217
+ .make$(${literal(0 === eSave.parents.length ?
2218
+ { [idf(eSave)]: `${eSave.name}0` } :
2219
+ { ...Object.fromEntries(eSave.parents.map(
2220
+ (k: string) => [k, parentVal(eSave, k)])),
2221
+ [idf(eSave)]: `${eSave.name}0` })})
2222
+ `}${null == f ? `
2223
+ // change the fields you need
2224
+ ` : `
2225
+ ${eSave.name}.${f.name} = ${newValue(f)}
2226
+ `}
2227
+ await ${eSave.name}.save$()
2228
+ \`\`\`
2229
+
2230
+ Mutating the record you loaded sends it as it stood plus your change, so
2231
+ you do not depend on how the API treats a request that omits fields —
2232
+ some merge, some replace.`)
2233
+ }
2234
+
2235
+
2236
+ if (null != eRemove) {
2237
+ sec('Remove a record', `\`\`\`js
2238
+ await seneca
2239
+ .entity('${canon(eRemove)}')
2240
+ .remove$(${oneArgs(eRemove)})
2241
+ \`\`\`
2242
+ ${0 === eRemove.parents.length ? '' : `
2243
+ As with a read, the parent keys are part of naming the record, so they go
2244
+ in the query object alongside the id.
2245
+ `}${eRemove.cmds.includes('load') ? `
2246
+ A \`load$\` of the same id afterwards answers \`null\`.` :
2247
+ `
2248
+ \`remove$\` resolves once the API has accepted the removal.`}`)
2249
+ }
2250
+
2251
+
2252
+ if (0 < nested.length) {
2253
+ // A nested entity that declares no cmds has nothing to demonstrate, so
2254
+ // prefer one that does; the error example needs a command that exists.
2255
+ const n = nested.find((e: any) => 0 < e.cmds.length) || nested[0]
2256
+ const firstCmd = n.cmds[0] || 'list'
2257
+
2258
+ sec(NESTED_TITLE, `Some resources live inside a parent, and the API path says so — the
2259
+ route for \`${n.name}\` is:
2260
+
2261
+ \`\`\`
2262
+ ${n.path}
2263
+ \`\`\`
2264
+
2265
+ So a \`${n.name}\` cannot be addressed at all without its parent's id, and
2266
+ the provider requires those keys on every command.
2267
+
2268
+ ${nested.map((e: any) =>
2269
+ `- \`${e.name}\` requires \`${e.parents.join('`, `')}\``).join('\n')}
2270
+
2271
+ For reads the keys go in the query; for writes they go in the data:
2272
+
2273
+ \`\`\`js${n.cmds.includes('list') ? `
2274
+ await seneca.entity('${canon(n)}').list$({ ${parentArgs(n)} })
2275
+ ` : ''}${n.cmds.includes('load') ? `
2276
+ await seneca.entity('${canon(n)}')
2277
+ .load$({ ${parentArgs(n)}, ${idf(n)}: '${n.name}0' })
2278
+ ` : ''}${n.cmds.includes('save') ? `
2279
+ await seneca.entity('${canon(n)}')
2280
+ .make$(${literal(createData(n))})
2281
+ .save$()
2282
+ ` : ''}${n.cmds.includes('remove') ? `
2283
+ await seneca.entity('${canon(n)}')
2284
+ .remove$({ ${parentArgs(n)}, ${idf(n)}: '${n.name}0' })
2285
+ ` : ''}\`\`\`
2286
+
2287
+ Leave a key out and the call throws at once, naming what is missing:
2288
+
2289
+ \`\`\`
2290
+ ${provider.pkgName}: ${n.name} ${firstCmd}: ${n.parents[0]} is required
2291
+ \`\`\`
2292
+
2293
+ That is deliberate: without it the SDK would build half a URL and the
2294
+ server would answer 404, which is a much harder message to act on. The
2295
+ [explanation](explanation.md) covers why this is a guard rather than a
2296
+ silent default.`)
2297
+ }
2298
+
2299
+
2300
+ {
2301
+ // Seed the entity the recipes use, plus the first nested entity AND its
2302
+ // parent — a child seeded under a parent that is not there lists as
2303
+ // empty, which reads as a passing test that proves nothing.
2304
+ const seeded: any[] = []
2305
+ const add = (e: any) => {
2306
+ if (null != e && !seeded.includes(e)) {
2307
+ seeded.push(e)
2308
+ }
2309
+ }
2310
+ const child = 0 < nested.length ? nested[0] : null
2311
+ const parent = null == child ? null :
2312
+ ents.find((p: any) => p.name === child.parentEntity)
2313
+
2314
+ add(subject)
2315
+ if (null != child) {
2316
+ add(parent)
2317
+ add(child)
2318
+ }
2319
+ seeded.sort((a: any, b: any) => ents.indexOf(a) - ents.indexOf(b))
2320
+
2321
+ const seed = seeded.map((e: any) => ` ${e.name}: {
2322
+ ` + [0, 1].map((i: number) =>
2323
+ ` ${e.name}${i}: ${literal(seedRecord(e, i))},`).join('\n') + `
2324
+ },`).join('\n')
2325
+
2326
+ sec(OFFLINE_TITLE, `The SDK ships an in-memory mock transport. Turn it on with \`test\` and
2327
+ seed it with \`testopts\`:
2328
+
2329
+ \`\`\`js
2330
+ .use('${provider.pkgName}', {
2331
+ test: true,
2332
+ testopts: {
2333
+ entity: {
2334
+ ${seed}
2335
+ },
2336
+ },
2337
+ })
2338
+ \`\`\`
2339
+
2340
+ Records are keyed by id under their entity name, and the id inside the
2341
+ record has to match the key it is filed under. Every command then works
2342
+ offline, not-found included: an id you did not seed answers \`null\`,
2343
+ exactly as it would against a real server.${null == parent || null == child ? '' : `
2344
+
2345
+ A nested record has to point at a parent that is actually seeded: each
2346
+ \`${child.name}\` above carries \`${child.parents[0]}: '${parentVal(child, child.parents[0])}'\`, and
2347
+ that is a \`${parent.name}\` the seed contains. Seed a child under a parent
2348
+ that is not there and its list comes back empty rather than failing —
2349
+ which, in a test, reads as a pass that proves nothing.`}
2350
+
2351
+ This is how this plugin's own suite runs, and it is the recommended way
2352
+ to test application code that uses the provider: no server, no network,
2353
+ and the same code path as production. See \`test/seed.js\`, which seeds
2354
+ every entity this way.`)
2355
+ }
2356
+
2357
+
2358
+ sec('Point at a different server', `The \`sdk\` option is passed straight to the \`${provider.sdkClass}\`
2359
+ constructor, so \`base\` chooses the host:
2360
+
2361
+ \`\`\`js
2362
+ .use('${provider.pkgName}', {
2363
+ sdk: { base: 'https://${provider.lower}.example.com' },
2364
+ })
2365
+ \`\`\`
2366
+
2367
+ ${'' === liveBase ?
2368
+ `The API definition declares no server, so there is no default worth
2369
+ relying on: set \`base\` explicitly, or run against the mock instead (see
2370
+ [${OFFLINE_TITLE}](${anchor(OFFLINE_TITLE)})).` :
2371
+ `The SDK's own default is \`${liveBase}\`, which is where the
2372
+ companion test server listens, so local development usually needs no
2373
+ \`base\` at all.`}`)
2374
+
2375
+
2376
+ sec('Send an API key', `Credentials are not a plugin option: they come through the provider
2377
+ convention, so that every provider in an application is configured the
2378
+ same way. Declare the variable with \`env\` and set the key under this
2379
+ provider's name:
2380
+
2381
+ \`\`\`js
2382
+ .use('env', {
2383
+ var: { $${provider.ENV}_APIKEY: String },
2384
+ })
2385
+ .use('provider', {
2386
+ provider: {
2387
+ ${provider.lower}: {
2388
+ keys: {
2389
+ apikey: { value: '$${provider.ENV}_APIKEY' },
2390
+ },
2391
+ },
2392
+ },
2393
+ })
2394
+ \`\`\`
2395
+
2396
+ Every request then carries \`authorization: Bearer <apikey>\`. An absent
2397
+ or empty key adds no header at all, so an API that needs no credentials
2398
+ is configured in exactly the same shape with an empty value — which is
2399
+ why it is worth writing even when there is nothing to send. An
2400
+ application that later moves to an authenticated service then changes one
2401
+ value rather than its structure.
2402
+
2403
+ For a different scheme, set the header yourself. Headers supplied through
2404
+ \`sdk\` win over the one the key would have set:
2405
+
2406
+ \`\`\`js
2407
+ .use('${provider.pkgName}', {
2408
+ sdk: { headers: { 'x-api-key': process.env.${provider.ENV}_APIKEY } },
2409
+ })
2410
+ \`\`\``)
2411
+
2412
+
2413
+ sec('Check which plugin and SDK are running', `One message, and the thing to reach for when a deployment is behaving
2414
+ unexpectedly:
2415
+
2416
+ \`\`\`js
2417
+ const info = await seneca.post(
2418
+ 'sys:provider,provider:${provider.lower},get:info')
2419
+ \`\`\`
2420
+
2421
+ \`\`\`js
2422
+ {
2423
+ ok: true,
2424
+ name: '${provider.lower}',
2425
+ version: '${provider.version}',
2426
+ sdk: { name: '${provider.sdkPkg}', version: '${provider.sdkVersion}' },
2427
+ }
2428
+ \`\`\`
2429
+
2430
+ \`version\` is this plugin's; \`sdk.version\` is the SDK it is running
2431
+ against. That pair is what to quote in a bug report, because the two are
2432
+ released separately and most surprises live in the gap between them.`)
2433
+
2434
+
2435
+ {
2436
+ const dpe = eList || subject
2437
+ const dpath = dpe.path || provider.probePath || '/'
2438
+ const dparams = pathParams(dpath)
2439
+ const dval = (k: string) => (k === idf(dpe) || 'id' === k) ?
2440
+ `${dpe.name}0` : `${k.replace(/_id$/, '')}0`
2441
+
2442
+ sec('Reach the SDK directly', `The entity API covers the operations the API model declares. For
2443
+ anything else — an endpoint with no entity behind it, a response header
2444
+ you need to read — take the configured SDK client out of the plugin's
2445
+ exports:
2446
+
2447
+ \`\`\`js
2448
+ const sdk = seneca.export('${provider.pluginName}/sdk')()
2449
+ \`\`\`
2450
+
2451
+ The export is a function, so call it, and it only answers after
2452
+ \`seneca.ready()\` — that is when the plugin builds the client with the
2453
+ resolved key.
2454
+
2455
+ SDK operations resolve to SDK ENTITY instances rather than plain data, so
2456
+ read the record out with \`.data()\`. The provider does this for you; here
2457
+ you do it yourself:
2458
+
2459
+ \`\`\`js${dpe.cmds.includes('list') ? `
2460
+ const ${dpe.name}s = (await sdk.${dpe.acc}().list(${listArgs(dpe)}))
2461
+ .map((r) => r.data())
2462
+ ` : ''}${dpe.cmds.includes('load') ? `
2463
+ const one = (await sdk.${dpe.acc}().load(${sdkLoadArgs(dpe)})).data()
2464
+ ` : ''}\`\`\`
2465
+
2466
+ For a route the entity model does not cover at all, \`direct\` sends a
2467
+ request and hands back the raw response:
2468
+
2469
+ \`\`\`js
2470
+ const res = await sdk.direct({
2471
+ path: '${dpath}',
2472
+ method: 'GET',${0 === dparams.length ? '' : `
2473
+ params: { ${dparams.map((k: string) => `${key(k)}: '${dval(k)}'`).join(', ')} },`}
2474
+ })
2475
+
2476
+ if (res instanceof Error) throw res
2477
+ if (!res.ok) throw (res.err || new Error('status ' + res.status))
2478
+
2479
+ console.log(res.data)
2480
+ \`\`\`
2481
+
2482
+ \`prepare()\` builds the same request without sending it, which is the
2483
+ quickest way to see what the SDK would actually do — url, method, headers
2484
+ and body, before anything leaves the process.
2485
+
2486
+ Raw data becomes a Seneca entity again through \`data$\`:
2487
+
2488
+ \`\`\`js
2489
+ const ent = seneca.entity('${canon(dpe)}').data$(res.data)
2490
+ \`\`\``)
2491
+ }
2492
+
2493
+
2494
+ sec('Develop against a local SDK checkout', `The SDK is an ordinary published dependency, so normal use needs nothing
2495
+ special:
2496
+
2497
+ \`\`\`sh
2498
+ $ npm install
2499
+ \`\`\`
2500
+
2501
+ If you are changing the SDK and this plugin together, point npm at a
2502
+ local checkout instead. Clone the SDK beside this repository, at the path
2503
+ this project expects, and build it — it does not commit its build output:
2504
+
2505
+ \`\`\`sh
2506
+ $ git clone ${provider.sdkRepoUrl}.git \\
2507
+ ${provider.sdkrel}
2508
+ $ cd ${provider.sdkrel}/ts
2509
+ $ npm install && npm run build
2510
+ \`\`\`
2511
+
2512
+ Then link it in, without committing the change to \`package.json\`:
2513
+
2514
+ \`\`\`sh
2515
+ $ npm install --no-save ${provider.sdkrel}/ts
2516
+ \`\`\`
2517
+
2518
+ npm creates a symlink, so a rebuild of the SDK is picked up here with no
2519
+ reinstall:
2520
+
2521
+ \`\`\`sh
2522
+ $ ls -l node_modules/${provider.sdkPkg}
2523
+ \`\`\`
2524
+
2525
+ To go back to the published SDK:
2526
+
2527
+ \`\`\`sh
2528
+ $ rm -rf node_modules/${provider.sdkPkg} package-lock.json && npm install
2529
+ \`\`\`
2530
+
2531
+ Removing the lockfile matters. npm will happily keep resolving to the
2532
+ link if the lockfile still records it and the local version satisfies the
2533
+ range.`)
2534
+
2535
+
2536
+ {
2537
+ const pattern = subject.cmds.includes('load') ? `${subject.name}-load` :
2538
+ subject.cmds.includes('list') ? `${subject.name}-list` : 'happy'
2539
+ const skipped = subject.cmds.includes('list') ?
2540
+ `${subject.name}-list` : `${subject.name}-load-missing`
2541
+
2542
+ sec('Run the test suite', `\`\`\`sh
2543
+ $ npm run build
2544
+ $ npm test
2545
+ \`\`\`
2546
+
2547
+ The build comes first: the suite runs against \`dist\`, so an unbuilt
2548
+ change is not the change you are testing.
2549
+
2550
+ The offline tests use the SDK mock and always run.${'' === liveBase ? '' : ` The live tests
2551
+ probe for a server first and skip cleanly when there is none, so a clean
2552
+ checkout is green on a machine that has never started one:
2553
+
2554
+ \`\`\`
2555
+ ﹣ ${skipped} # no ${provider.lower} server at ${liveBase}
2556
+ \`\`\``}
2557
+
2558
+ Coverage, and a single test by name:
2559
+
2560
+ \`\`\`sh
2561
+ $ npm run test-coverage
2562
+ $ TEST_PATTERN=${pattern} npm run test-some
2563
+ \`\`\``)
2564
+ }
2565
+
2566
+
2567
+ if ('' !== liveBase) {
2568
+ sec('Run the live tests against a server', `The companion test server ships only in the SDK's source repository, not
2569
+ in the published package. From the checkout beside this one:
2570
+
2571
+ \`\`\`sh
2572
+ $ cd ${provider.sdkrel}/app
2573
+ $ npm install && npm run build && npm start
2574
+ \`\`\`
2575
+
2576
+ Then run the suite as usual: the live tests find the server and activate
2577
+ themselves.
2578
+
2579
+ \`\`\`sh
2580
+ $ npm test
2581
+ \`\`\`
2582
+
2583
+ To target a server somewhere else:
2584
+
2585
+ \`\`\`sh
2586
+ $ ${provider.ENV}_TEST_BASE=http://localhost:9000 npm test
2587
+ \`\`\`
2588
+
2589
+ The generated live tests only read, so a run leaves the server exactly as
2590
+ it found it.${subject.cmds.includes('save') && subject.cmds.includes('remove') ? `
2591
+
2592
+ Two manual scripts are there for poking at a running server by hand:
2593
+
2594
+ \`\`\`sh
2595
+ $ node test/live.js # read from each entity
2596
+ $ node test/quick.js # a full write cycle, cleaning up after itself
2597
+ \`\`\`` : `
2598
+
2599
+ \`node test/live.js\` reads from each entity, for poking at a running
2600
+ server by hand.`}`)
2601
+ }
2602
+
2603
+
2604
+ sec('Build and release', `\`\`\`sh
2605
+ $ npm run build # tsc --build src test
2606
+ $ npm run watch # the same, in watch mode
2607
+ $ npm run reset # clean, install, build, test
2608
+ \`\`\`
2609
+
2610
+ Releasing follows the Seneca convention, in one command — clean, install,
2611
+ build, test, tag from \`package.json\`, publish:
2612
+
2613
+ \`\`\`sh
2614
+ $ npm run repo-publish
2615
+ \`\`\`
2616
+
2617
+ Only \`dist\`, the TypeScript sources and the licence file are published;
2618
+ the test suite and its build output stay in the repository.
2619
+
2620
+ Before publishing, check that \`package.json\` still depends on the
2621
+ published SDK by version range and not on a local path: a \`file:\`
2622
+ dependency left behind from local development installs perfectly on your
2623
+ own machine and cannot be resolved by anybody else.
2624
+
2625
+ One last thing: this repository is GENERATED from the ${provider.api} API
2626
+ model by [@voxgig/sdkgen](https://github.com/voxgig/sdkgen). An edit made
2627
+ here survives exactly as long as the next generation run. Change the
2628
+ model, or the components that build this target, and regenerate.`)
2629
+
2630
+
2631
+ File({ name: 'how-to.md' }, () => {
2632
+ Content(`# How-to guides
2633
+
2634
+ Each guide here solves one problem, and assumes you already have a
2635
+ working Seneca instance with this plugin loaded. If you do not, work
2636
+ through the [tutorial](tutorial.md) first.
2637
+
2638
+ These guides show what to do and leave out the reasoning — that is in the
2639
+ [explanation](explanation.md), and the exact patterns, fields and options
2640
+ are listed in the [reference](reference.md).
2641
+
2642
+ `)
2643
+
2644
+ each(sections, (s: any) => {
2645
+ Content(`- [${s.title}](${anchor(s.title)})
2646
+ `)
2647
+ })
2648
+
2649
+ each(sections, (s: any) => {
2650
+ Content(`
2651
+ ## ${s.title}
2652
+
2653
+ ${s.body}
2654
+ `)
2655
+ })
2656
+ })
2657
+ })
2658
+
2659
+
2660
+ // --- doc/reference.md ---------------------------------------------------------
2661
+ //
2662
+ // The Diátaxis reference: information-oriented, complete, and never teaching.
2663
+ // Everything a caller can reach — options, canons, fields, patterns, exports,
2664
+ // errors, environment variables, scripts — stated once, in tables, with the
2665
+ // exact strings the generated source actually emits.
2666
+ //
2667
+ // Three facts here are easy to get wrong by copying a hand-written original.
2668
+ // The guard message carries the PUBLISHED package name, because that is what
2669
+ // Main interpolates (`${provider.pkgName}: <entity> <cmd>: <key> is required`).
2670
+ // The `sdk` block of the get:info response carries the SDK's PACKAGE name, not
2671
+ // its slug. And an entity whose id field is not literally `id` cannot be read
2672
+ // with the `load$('x')` short form at all — Seneca turns that into `{id: 'x'}`,
2673
+ // which the generated action does not look at — so the object form is
2674
+ // documented for those entities instead of the string form.
2675
+ //
2676
+ // Nothing here assumes CRUD: every table row is conditional on the cmds and
2677
+ // ops the model actually declares, so an API offering only create, or only
2678
+ // reads, documents only what it has.
2679
+
2680
+ const DocReference = cmp(function DocReference(props: any) {
2681
+ const { provider } = props
2682
+
2683
+ // The entity used for worked examples: the same choice the tests and README
2684
+ // make, so all three documents show the same entity.
2685
+ const subject = [...provider.entities]
2686
+ .sort((a: any, b: any) =>
2687
+ (a.parents.length - b.parents.length) || (b.cmds.length - a.cmds.length))[0]
2688
+
2689
+ const nested = provider.entities.filter((e: any) => 0 < e.parents.length)
2690
+ const saving = provider.entities.filter((e: any) => e.cmds.includes('save'))
2691
+
2692
+ // Entities whose API offers BOTH create and update: only for those does
2693
+ // `save$` dispatch on the id. Where it offers one, saying otherwise is wrong.
2694
+ const dispatch = saving.filter((e: any) =>
2695
+ e.ops.includes('create') && e.ops.includes('update'))
2696
+ const oneway = saving.filter((e: any) => !dispatch.includes(e))
2697
+
2698
+ const anyCmd = (c: string) => provider.entities.some((e: any) => e.cmds.includes(c))
2699
+ const anyOp = (o: string) => saving.some((e: any) => e.ops.includes(o))
2700
+
2701
+ const live = '' !== provider.liveBase
2702
+
2703
+ // test/quick.js is emitted only when the subject entity can be created and
2704
+ // removed again — see the Scripts cmp — so only document it when it exists.
2705
+ const quick = live && subject.cmds.includes('save') && subject.cmds.includes('remove')
2706
+
2707
+ const canon = (e: any) => `provider/${provider.lower}/${e.name}`
2708
+
2709
+ const cmdList = (e: any) => e.cmds.map((c: string) => '`' + c + '$`').join(', ')
2710
+
2711
+ const keys = (list: string[]) => '`' + list.join('`, `') + '`'
2712
+
2713
+ // The same list as prose: `a`, `b` and `c`.
2714
+ const keysAnd = (list: string[]) => 1 === list.length ? keys(list) :
2715
+ `${keys(list.slice(0, -1))} and \`${list[list.length - 1]}\``
2716
+
2717
+ // A query literal for the docs: parent keys first, then whatever else the
2718
+ // command needs.
2719
+ const query = (e: any, extra: string[]) =>
2720
+ `{ ${[...e.parents, ...extra].map((k: string) => `${k}: '...'`).join(', ')} }`
2721
+
2722
+ // How a single record is addressed. The `load$('x')` short form only works
2723
+ // when the id field is literally `id`.
2724
+ const oneArg = (e: any) => 0 < e.parents.length ? query(e, [e.idf]) :
2725
+ 'id' === e.idf ? `'...'` : query(e, [e.idf])
2726
+
2727
+ // The required-key phrasing, which has to read correctly for one key as
2728
+ // well as several.
2729
+ const reqd = (list: string[]) =>
2730
+ 1 === list.length ? `${keys(list)} **required**` :
2731
+ 2 === list.length ? `\`${list[0]}\` and \`${list[1]}\`, both **required**` :
2732
+ `${keys(list)}, all **required**`
2733
+
2734
+ // The example used in the error block: whichever command the subject has.
2735
+ const errCall = subject.cmds.includes('list') ?
2736
+ `list$(${0 < subject.parents.length ? query(subject, []) : ''})` :
2737
+ subject.cmds.includes('load') ? `load$(${oneArg(subject)})` :
2738
+ subject.cmds.includes('remove') ? `remove$(${oneArg(subject)})` :
2739
+ 'make$({ ... }).save$()'
2740
+
2741
+ File({ name: 'reference.md' }, () => {
2742
+ Content(`# Reference
2743
+
2744
+ Complete description of the interface exposed by
2745
+ \`${provider.pkgName}\` version ${provider.version}.
2746
+
2747
+ This document describes the machinery and assumes you know what you are
2748
+ looking for. To learn the plugin, start with the [tutorial](tutorial.md);
2749
+ for recipes, see the [how-to guides](how-to.md); for the reasoning behind
2750
+ the design, see the [explanation](explanation.md). The package overview is
2751
+ the [README](../README.md), and the document index is [here](README.md).
2752
+
2753
+ - [Requirements](#requirements)
2754
+ - [Registration](#registration)
2755
+ - [Options](#options)
2756
+ - [Entities](#entities)
2757
+ - [Action patterns](#action-patterns)
2758
+ - [Plugin exports](#plugin-exports)
2759
+ - [Errors](#errors)
2760
+ - [Authentication keys](#authentication-keys)
2761
+ - [Environment variables](#environment-variables)
2762
+ - [Package scripts](#package-scripts)
2763
+
2764
+ ## Requirements
2765
+
2766
+ | Item | Value |
2767
+ | ---- | ----- |
2768
+ | Node.js | \`>=24\` |
2769
+ | Module format | CommonJS |
2770
+ | SDK | [\`${provider.sdkPkg}\`](https://www.npmjs.com/package/${provider.sdkPkg}) \`^${provider.sdkVersion}\` |
2771
+
2772
+ The SDK is an ordinary published dependency, installed by \`npm install\`
2773
+ like any other.
2774
+ `)
2775
+
2776
+ if (live) {
2777
+ Content(`
2778
+ The companion **test server** used by the live tests is a separate matter:
2779
+ it ships only in the SDK's [source repository](${provider.sdkRepoUrl}) under
2780
+ \`app/\`, and is not published. It is needed only to run the live tests —
2781
+ see the [how-to guides](how-to.md).
2782
+ `)
2783
+ }
2784
+
2785
+ Content(`
2786
+ ### Peer dependencies
2787
+
2788
+ All must be present in the host application. The accepted version ranges are
2789
+ declared in this package's \`package.json\`.
2790
+
2791
+ | Package | Purpose |
2792
+ | ------- | ------- |
2793
+ | \`seneca\` | The host framework. The plugin runs inside the host's instance, never its own. |
2794
+ | \`seneca-entity\` | The entity API the canons below are served through. |
2795
+ | \`seneca-promisify\` | The promise-returning message API. |
2796
+ | \`@seneca/provider\` | The provider convention, including \`provider/entityBuilder\`. |
2797
+ | \`@seneca/env\` | Resolves \`$\`-prefixed key values from the environment. |
2798
+
2799
+ ## Registration
2800
+
2801
+ The plugin name is \`${provider.pluginName}\`. It must be registered after
2802
+ \`entity\`, \`promisify\` and \`provider\`:
2803
+
2804
+ \`\`\`js
2805
+ Seneca({ legacy: false })
2806
+ .use('promisify')
2807
+ .use('entity')
2808
+ .use('provider', { ... })
2809
+ `)
2810
+
2811
+ if (live) {
2812
+ Content(` .use('${provider.pkgName}', { sdk: { base: '${provider.liveBase}' } })
2813
+ \`\`\`
2814
+ `)
2815
+ }
2816
+ else {
2817
+ Content(` .use('${provider.pkgName}', { sdk: { base: BASE } })
2818
+ \`\`\`
2819
+
2820
+ The ${provider.api} definition declares no server, so there is no default
2821
+ base URL: \`BASE\` is the URL of the API you are talking to, and it must be
2822
+ supplied through the \`sdk\` option.
2823
+ `)
2824
+ }
2825
+
2826
+ Content(`
2827
+ The SDK client is constructed during plugin startup and is not available
2828
+ until \`seneca.ready()\` resolves.
2829
+
2830
+ ## Options
2831
+
2832
+ | Option | Type | Default | Effect |
2833
+ | ------ | ---- | ------- | ------ |
2834
+ | \`sdk\` | object | \`{}\` | Passed straight to the \`${provider.sdkClass}\` constructor. Most usefully \`base\`. |
2835
+ | \`test\` | boolean | \`false\` | Run the SDK against its in-memory mock transport instead of HTTP. |
2836
+ | \`testopts\` | object | \`{}\` | Test-feature options, used only when \`test\` is true. \`{entity: {...}}\` seeds the mock. |
2837
+
2838
+ ### \`sdk\`
2839
+
2840
+ Any option the \`${provider.sdkClass}\` constructor accepts:
2841
+
2842
+ | Key | Effect |
2843
+ | --- | ------ |
2844
+ | \`base\` | Base URL for API requests. ${live ?
2845
+ `The SDK's own default is \`${provider.liveBase}\`.` :
2846
+ 'There is no default: this API declares no server, so it must be set.'} |
2847
+ | \`prefix\` / \`suffix\` | URL fragments placed around the path. |
2848
+ | \`headers\` | Headers sent on every request. These win over the \`authorization\` header the provider adds from a configured key. |
2849
+ | \`system\` | System overrides, e.g. a custom \`fetch\`. |
2850
+
2851
+ ### \`test\` and \`testopts\`
2852
+
2853
+ \`\`\`js
2854
+ .use('${provider.pkgName}', {
2855
+ test: true,
2856
+ testopts: {
2857
+ entity: {
2858
+ `)
2859
+ each(provider.entities, (e: any) => {
2860
+ Content(` ${e.name}: { ${e.name}0: ${JSON.stringify(seedRecord(e, 0))} },
2861
+ `)
2862
+ })
2863
+ Content(` },
2864
+ },
2865
+ })
2866
+ \`\`\`
2867
+
2868
+ Mock records are keyed by id under their entity name. In this mode no
2869
+ network calls are made, and an unseeded id produces the same not-found
2870
+ behaviour as a live server. This package's own \`test/seed.js\` is generated
2871
+ in exactly this shape.
2872
+ `)
2873
+
2874
+ if (0 < nested.length) {
2875
+ Content(`
2876
+ A nested record's parent key must name a record the parent entity also
2877
+ seeds: the mock resolves the path literally, so an unmatched parent id
2878
+ yields nothing rather than an error.
2879
+ `)
2880
+ }
2881
+
2882
+ Content(`
2883
+ ## Entities
2884
+
2885
+ The plugin registers ${1 === provider.entities.length ?
2886
+ 'one entity canon' : `${provider.entities.length} entity canons`}.
2887
+ A canon carries only the commands its API operations support — an entity the
2888
+ API offers no delete for has no \`remove$\` — so the tables below are the
2889
+ whole of what each one answers.
2890
+
2891
+ | Seneca canon | SDK accessor | Route | Id field | Parent keys | Commands |
2892
+ | ------------ | ------------ | ----- | -------- | ----------- | -------- |
2893
+ `)
2894
+ each(provider.entities, (e: any) => {
2895
+ Content(`| \`${canon(e)}\` | \`sdk.${e.acc}()\` | \`${e.path}\` | \`${e.idf}\` | ${0 < e.parents.length ?
2896
+ keys(e.parents) : '—'} | ${cmdList(e)} |
2897
+ `)
2898
+ })
2899
+
2900
+ each(provider.entities, (e: any) => {
2901
+ const hasCreate = e.ops.includes('create')
2902
+ const hasUpdate = e.ops.includes('update')
2903
+
2904
+ Content(`
2905
+ ### \`${canon(e)}\`
2906
+
2907
+ Backed by \`sdk.${e.acc}()\`, whose results are \`${e.cls}\` instances; the
2908
+ provider hands Seneca the plain record from \`.data()\`.
2909
+ `)
2910
+
2911
+ if (0 < e.parents.length) {
2912
+ Content(`
2913
+ \`${e.name}\` is nested under \`${e.path}\` in the API, so **every**
2914
+ \`${e.name}\` command requires ${keysAnd(e.parents)}. Omitting one throws —
2915
+ \`${provider.pkgName}: ${e.name} <cmd>: ${e.parents[0]} is required\` —
2916
+ before any request is made, rather than issuing one that would 404.
2917
+ `)
2918
+ }
2919
+
2920
+ Content(`
2921
+ | Command | Query / data | Returns |
2922
+ | ------- | ------------ | ------- |
2923
+ `)
2924
+ if (e.cmds.includes('list')) {
2925
+ Content(`| \`list$(q)\` | ${0 < e.parents.length ?
2926
+ `${reqd(e.parents)}, plus optional match fields` :
2927
+ 'optional match fields'} | Array of \`${e.name}\` entities. |
2928
+ `)
2929
+ }
2930
+ if (e.cmds.includes('load')) {
2931
+ Content(`| \`load$(q)\` | ${reqd([...e.parents, e.idf])} | One \`${e.name}\`, or \`null\` if not found. |
2932
+ `)
2933
+ }
2934
+ if (e.cmds.includes('save')) {
2935
+ Content(`| \`save$()\` | entity data${0 < e.parents.length ?
2936
+ `, including ${keysAnd(e.parents)}` : ''} | ${hasCreate && hasUpdate ?
2937
+ `Created or updated \`${e.name}\`.` : hasCreate ?
2938
+ `Created \`${e.name}\`; the API declares no update operation.` :
2939
+ `Updated \`${e.name}\`; the API declares no create operation.`} |
2940
+ `)
2941
+ }
2942
+ if (e.cmds.includes('remove')) {
2943
+ Content(`| \`remove$(q)\` | ${reqd([...e.parents, e.idf])} | \`null\`. |
2944
+ `)
2945
+ }
2946
+
2947
+ // The `load$('x')` short form sets `id`, which an entity keyed by
2948
+ // anything else never reads. Nested entities need the object form for
2949
+ // their parent keys anyway, so this only needs saying for top-level ones.
2950
+ const shortForm = 0 === e.parents.length && 'id' !== e.idf ?
2951
+ e.cmds.filter((c: string) => 'load' === c || 'remove' === c) : []
2952
+
2953
+ if (0 < shortForm.length) {
2954
+ Content(`
2955
+ This entity is keyed by \`${e.idf}\` rather than \`id\`, so the short
2956
+ ${1 === shortForm.length ? 'form' : 'forms'} ${shortForm
2957
+ .map((c: string) => `\`${c}$('...')\``).join(' and ')} ${1 === shortForm.length ?
2958
+ 'does' : 'do'} not address it: Seneca reads a bare string as
2959
+ \`{id: '...'}\`, which is not a key this entity uses. Pass
2960
+ \`{ ${e.idf}: '...' }\` instead.
2961
+ `)
2962
+ }
2963
+
2964
+ if (0 === e.fields.length) {
2965
+ Content(`
2966
+ The API definition declares no required fields for this entity; whatever it
2967
+ returns is passed through unchanged.
2968
+ `)
2969
+ }
2970
+ else {
2971
+ Content(`
2972
+ Required fields, as declared by the API definition. Optional fields the API
2973
+ also defines are passed through unchanged in both directions.
2974
+
2975
+ | Field | Type | Notes |
2976
+ | ----- | ---- | ----- |
2977
+ `)
2978
+ each(e.fields, (f: any) => {
2979
+ Content(`| \`${f.name}\` | ${f.kind} | ${f.name === e.idf ? 'Id field.' :
2980
+ e.parents.includes(f.name) ? ('' === f.parentEntity ?
2981
+ 'Parent key. Required by every command.' :
2982
+ `Parent key: the id of a \`${f.parentEntity}\`. Required by every command.`) : ''} |
2983
+ `)
2984
+ })
2985
+ }
2986
+
2987
+ if (e.cmds.includes('list') || e.cmds.includes('load')) {
2988
+ Content(`
2989
+ \`\`\`js
2990
+ `)
2991
+ if (e.cmds.includes('list')) {
2992
+ Content(`const ${e.name}s = await seneca
2993
+ .entity('${canon(e)}')
2994
+ .list$(${0 < e.parents.length ? query(e, []) : ''})
2995
+ `)
2996
+ }
2997
+ if (e.cmds.includes('load')) {
2998
+ Content(`const ${e.name} = await seneca
2999
+ .entity('${canon(e)}')
3000
+ .load$(${oneArg(e)})
3001
+ `)
3002
+ }
3003
+ Content(`\`\`\`
3004
+ `)
3005
+ }
3006
+ })
3007
+
3008
+ if (0 < dispatch.length) {
3009
+ // The dispatching entity to show it with: the subject when it qualifies,
3010
+ // otherwise the first that does.
3011
+ const s = dispatch.includes(subject) ? subject : dispatch[0]
3012
+ const writable = s.fields
3013
+ .filter((f: any) => f.name !== s.idf && f.name !== 'id')
3014
+ .filter((f: any) => !s.parents.includes(f.name))
3015
+ const value = (f: any, alt: boolean) => 'number' === f.kind ?
3016
+ (alt ? '4321' : '1234') : 'boolean' === f.kind ?
3017
+ (alt ? 'true' : 'false') : `'${f.name}${alt ? '-changed' : '-value'}'`
3018
+ const make = [
3019
+ ...s.parents.map((k: string) => `${k}: '...'`),
3020
+ ...writable.map((f: any) => `${f.name}: ${value(f, false)}`),
3021
+ ].join(', ')
3022
+
3023
+ Content(`
3024
+ ### Create versus update
3025
+
3026
+ \`save$\` follows the Seneca convention: an entity **without** an id is
3027
+ created, an entity **with** one is updated. The provider dispatches on the
3028
+ id field, so the same call does both.
3029
+
3030
+ \`\`\`js
3031
+ // Create — no ${s.idf}.
3032
+ const ${s.name} = await seneca
3033
+ .entity('${canon(s)}')
3034
+ .make$({ ${make} })
3035
+ .save$()
3036
+
3037
+ // Update — ${s.idf} present.
3038
+ ${0 < writable.length ? `${s.name}.${writable[0].name} = ${value(writable[0], true)}
3039
+ ` : ''}await ${s.name}.save$()
3040
+ \`\`\`
3041
+
3042
+ Whether a client-supplied id survives a create is a property of the API, not
3043
+ of this plugin: many assign the id themselves and ignore the one sent. Read
3044
+ the id back off the returned entity rather than assuming the one you set.
3045
+ `)
3046
+ }
3047
+
3048
+ if (0 < oneway.length) {
3049
+ if (0 === dispatch.length) {
3050
+ Content(`
3051
+ ### Create versus update
3052
+
3053
+ \`save$\` normally dispatches on the id: an entity without one is created,
3054
+ an entity with one is updated.
3055
+ `)
3056
+ }
3057
+
3058
+ Content(`
3059
+ ${1 === oneway.length ?
3060
+ 'This entity supports only one half of that pair, so `save$` does not' :
3061
+ 'These entities support only one half of that pair, so `save$` does not'}
3062
+ dispatch for ${1 === oneway.length ? 'it' : 'them'}:
3063
+
3064
+ | Canon | Behaviour of \`save$\` |
3065
+ | ----- | -------------------- |
3066
+ `)
3067
+ each(oneway, (e: any) => {
3068
+ Content(`| \`${canon(e)}\` | Always ${e.ops.includes('create') ? 'creates' : 'updates'}; the API declares no ${e.ops.includes('create') ? 'update' : 'create'} operation. |
3069
+ `)
3070
+ })
3071
+ }
3072
+
3073
+ Content(`
3074
+ ### Command to SDK operation
3075
+
3076
+ | Seneca command | SDK call | Notes |
3077
+ | -------------- | -------- | ----- |
3078
+ `)
3079
+ if (anyCmd('list')) {
3080
+ Content(`| \`list$(q)\` | \`.list(q)\` | Query keys are passed through as match fields. |
3081
+ `)
3082
+ }
3083
+ if (anyCmd('load')) {
3084
+ Content(`| \`load$(q)\` | \`.load({ ...keys })\` | Only the keys the route needs are sent. |
3085
+ `)
3086
+ }
3087
+ if (anyOp('create')) {
3088
+ Content(`| \`save$()\` on an entity with no id | \`.create(data)\` | Data is the entity's own fields, without Seneca metadata. |
3089
+ `)
3090
+ }
3091
+ if (anyOp('update')) {
3092
+ Content(`| \`save$()\` on an entity with an id | \`.update(data)\` | |
3093
+ `)
3094
+ }
3095
+ if (anyCmd('remove')) {
3096
+ Content(`| \`remove$(q)\` | \`.remove({ ...keys })\` | Resolves to \`null\` whatever the API returns. |
3097
+ `)
3098
+ }
3099
+
3100
+ Content(`
3101
+ Every SDK operation resolves to an SDK entity instance, or a list of them,
3102
+ rather than raw data. The provider calls \`.data()\` on each and hands the
3103
+ plain record to \`entize\`, so what comes back is an ordinary Seneca entity
3104
+ under this plugin's canon, carrying none of the SDK's own markers.
3105
+
3106
+ ### Query fields
3107
+
3108
+ Seneca query directives — any key ending in \`$\`, such as \`sort$\` or
3109
+ \`limit$\` — are stripped before the query reaches the SDK. They are
3110
+ instructions to a store, not match fields for the API, and are not
3111
+ otherwise supported.
3112
+
3113
+ ## Action patterns
3114
+
3115
+ ### \`sys:provider,provider:${provider.lower},get:info\`
3116
+
3117
+ Returns metadata about the plugin and SDK. Answered locally; makes no API
3118
+ call.
3119
+
3120
+ \`\`\`js
3121
+ await seneca.post('sys:provider,provider:${provider.lower},get:info')
3122
+ \`\`\`
3123
+
3124
+ \`\`\`js
3125
+ {
3126
+ ok: true,
3127
+ name: '${provider.lower}',
3128
+ version: '${provider.version}',
3129
+ sdk: {
3130
+ name: '${provider.sdkPkg}',
3131
+ version: '${provider.sdkVersion}',
3132
+ },
3133
+ }
3134
+ \`\`\`
3135
+
3136
+ Both versions are read at runtime from the respective \`package.json\`, so
3137
+ they describe what is installed rather than what was generated.
3138
+
3139
+ ### Entity patterns
3140
+
3141
+ Registered by \`@seneca/provider\`. Normally reached through the entity API
3142
+ rather than posted directly.
3143
+
3144
+ | Pattern |
3145
+ | ------- |
3146
+ `)
3147
+ each(provider.entities, (e: any) => {
3148
+ Content(e.cmds
3149
+ .map((c: string) =>
3150
+ `| \`sys:entity,zone:provider,base:${provider.lower},name:${e.name},cmd:${c}\` |\n`)
3151
+ .join(''))
3152
+ })
3153
+
3154
+ Content(`
3155
+ ### Inherited from \`@seneca/provider\`
3156
+
3157
+ | Pattern | Purpose |
3158
+ | ------- | ------- |
3159
+ | \`sys:provider,get:key\` | Fetch one named key for a provider. |
3160
+ | \`sys:provider,get:keymap\` | Fetch all keys for a provider. |
3161
+ | \`sys:provider,list:provider\` | List registered providers and their key names. |
3162
+
3163
+ ## Plugin exports
3164
+
3165
+ ### \`${provider.pluginName}/sdk\`
3166
+
3167
+ A function returning the configured \`${provider.sdkClass}\` instance.
3168
+
3169
+ \`\`\`js
3170
+ const sdk = seneca.export('${provider.pluginName}/sdk')()
3171
+ `)
3172
+ if (subject.ops.includes('list')) {
3173
+ Content(`
3174
+ // Every SDK operation resolves to an SDK entity (or a list of them),
3175
+ // not raw data; \`.data()\` gives the plain record.
3176
+ const ${subject.name}s = (await sdk.${subject.acc}().list()).map((e) => e.data())
3177
+ `)
3178
+ }
3179
+ if ('' !== provider.probePath) {
3180
+ Content(`
3181
+ // \`direct\` reaches endpoints outside the entity model.
3182
+ const res = await sdk.direct({ path: '${provider.probePath}', method: 'GET' })
3183
+ `)
3184
+ }
3185
+ Content(`\`\`\`
3186
+
3187
+ Available only after \`seneca.ready()\`. Use it for SDK features the entity
3188
+ API does not surface — notably \`direct()\` and \`prepare()\` for endpoints
3189
+ the entity model does not cover.
3190
+
3191
+ ## Errors
3192
+
3193
+ | Situation | Behaviour |
3194
+ | --------- | --------- |
3195
+ `)
3196
+ if (anyCmd('load')) {
3197
+ Content(`| \`load$\` for a non-existent id | Resolves to \`null\`. |
3198
+ `)
3199
+ }
3200
+ if (anyCmd('remove')) {
3201
+ Content(`| \`remove$\` for a non-existent id | Resolves to \`null\`; not an error. |
3202
+ `)
3203
+ }
3204
+ if (0 < nested.length) {
3205
+ Content(`| A nested entity command missing a parent key | Throws before any request is made. |
3206
+ `)
3207
+ }
3208
+ if (anyCmd('list') || anyCmd('save')) {
3209
+ Content(`| A 404 from \`${[anyCmd('list') ? 'list$' : '', anyCmd('save') ? 'save$' : ''].filter((s: string) => '' !== s).join('` or `')}\` | Thrown. Only single-record reads and removes map a 404 to \`null\`. |
3210
+ `)
3211
+ }
3212
+ Content(`| Any other non-2xx response | Thrown as raised by the SDK. |
3213
+ | A request that never got a response | Thrown, with \`status\` \`-1\`. |
3214
+
3215
+ SDK errors are \`${provider.Name}Error\` instances carrying
3216
+ \`is${provider.Name}Error: true\`, a \`code\` (e.g. \`request_status\`), the
3217
+ HTTP \`status\` at the top level (\`-1\` when the request never got a
3218
+ response), a \`notFound\` flag, and a \`ctx\` holding the request context and
3219
+ its \`result\` — \`status\`, \`statusText\`, \`headers\` and \`body\`. The
3220
+ \`null\`-on-missing behaviour is triggered by \`err.notFound\`, not by
3221
+ inspecting the status at the call site.
3222
+
3223
+ \`\`\`js
3224
+ try {
3225
+ await seneca.entity('${canon(subject)}').${errCall}
3226
+ }
3227
+ catch (err) {
3228
+ console.error(err.code, err.status, err.notFound)
3229
+ }
3230
+ \`\`\`
3231
+ `)
3232
+
3233
+ if (0 < nested.length) {
3234
+ Content(`
3235
+ The missing-parent-key guard is this plugin's own, thrown before the SDK is
3236
+ called at all. Its message names the entity, the command and the key:
3237
+
3238
+ | Entity | Message |
3239
+ | ------ | ------- |
3240
+ `)
3241
+ each(nested, (e: any) => {
3242
+ Content(e.parents
3243
+ .map((k: string) =>
3244
+ `| \`${e.name}\` | \`${provider.pkgName}: ${e.name} <cmd>: ${k} is required\` |\n`)
3245
+ .join(''))
3246
+ })
3247
+ Content(`
3248
+ where \`<cmd>\` is the command that was called. A key counts as missing if
3249
+ it is absent, \`null\` or the empty string.
3250
+ `)
3251
+ }
3252
+
3253
+ Content(`
3254
+ ## Authentication keys
3255
+
3256
+ The plugin follows the provider convention: if an \`apikey\` key is
3257
+ configured and non-empty, it is sent as \`authorization: Bearer <apikey>\`
3258
+ on every request. If the provider is not registered, or the key is absent or
3259
+ empty, no header is added and startup proceeds normally — an API that needs
3260
+ no credential exercises the same path.
3261
+
3262
+ \`\`\`js
3263
+ .use('provider', {
3264
+ provider: {
3265
+ ${provider.lower}: {
3266
+ keys: {
3267
+ apikey: { value: '$${provider.ENV}_APIKEY' },
3268
+ },
3269
+ },
3270
+ },
3271
+ })
3272
+ \`\`\`
3273
+
3274
+ The key is read once, during \`seneca.prepare()\`, by posting
3275
+ \`sys:provider,get:keymap,provider:${provider.lower}\`. An \`authorization\`
3276
+ header supplied through the \`sdk.headers\` option takes precedence over it.
3277
+
3278
+ ## Environment variables
3279
+
3280
+ The plugin never reads the environment itself. These are the variables the
3281
+ surrounding convention and tooling resolve:
3282
+
3283
+ | Variable | Read by | Purpose |
3284
+ | -------- | ------- | ------- |
3285
+ | \`$${provider.ENV}_APIKEY\` | \`@seneca/env\` | Supplies the \`apikey\` value when the key is declared as \`'$${provider.ENV}_APIKEY'\`, as above. |
3286
+ `)
3287
+ if (live) {
3288
+ Content(`| \`$${provider.ENV}_TEST_BASE\` | The test suite and the manual scripts | Base URL for the live tests. Defaults to \`${provider.liveBase}\`. |
3289
+ `)
3290
+ }
3291
+
3292
+ Content(`
3293
+ ## Package scripts
3294
+
3295
+ | Script | Action |
3296
+ | ------ | ------ |
3297
+ | \`npm run build\` | \`tsc --build src test\` — compiles to \`dist\` and \`dist-test\`. |
3298
+ | \`npm run watch\` | The same, in watch mode. |
3299
+ | \`npm test\` | Runs the \`node:test\` suite. |
3300
+ | \`npm run test-some\` | Runs tests matching \`$TEST_PATTERN\`. |
3301
+ | \`npm run test-watch\` | Test suite in watch mode. |
3302
+ | \`npm run test-coverage\` | Test suite with Node's built-in coverage. |
3303
+ | \`npm run clean\` | Removes \`node_modules\`, \`dist\`, \`dist-test\`, \`.tsbuildinfo\`, lockfiles. |
3304
+ | \`npm run reset\` | \`clean\`, then install, build and test. |
3305
+ | \`npm run repo-tag\` | Commits, tags and pushes \`v<version>\` taken from \`package.json\`. |
3306
+ | \`npm run repo-publish\` | Clean install, then \`repo-publish-quick\`. |
3307
+ | \`npm run repo-publish-quick\` | Build, test, tag, and publish to npm. |
3308
+
3309
+ ### Repository layout
3310
+
3311
+ | Path | Contents |
3312
+ | ---- | -------- |
3313
+ | \`src/\` | TypeScript source, with its own \`tsconfig.json\`. |
3314
+ | \`test/\` | Test suite (\`.js\`, run by \`node:test\`) and TypeScript fixtures. |
3315
+ | \`dist/\` | Compiled source. Committed; published. |
3316
+ | \`dist-test/\` | Compiled test fixtures. Committed; **not** published. |
3317
+ | \`.tsbuildinfo/\` | Incremental build cache. Not committed. |
3318
+ | \`doc/\` | This documentation. |
3319
+
3320
+ This repository is generated by
3321
+ [@voxgig/sdkgen](https://github.com/voxgig/sdkgen) from the ${provider.api}
3322
+ API definition. Anything edited here is overwritten by the next generation
3323
+ run; changes belong in the model.
3324
+ `)
3325
+
3326
+ if (live) {
3327
+ const listable = provider.entities
3328
+ .filter((e: any) => e.cmds.includes('list'))
3329
+ .map((e: any) => e.name)
3330
+
3331
+ Content(`
3332
+ ### Manual scripts
3333
+
3334
+ Not part of \`npm test\`: they need the companion test server, which is
3335
+ distributed only in the SDK's source repository.
3336
+
3337
+ | Script | Purpose |
3338
+ | ------ | ------ |
3339
+ `)
3340
+ Content(`| \`node test/live.js\` | ${0 < listable.length ?
3341
+ `Read ${listable.join(', ')} from a running server.` :
3342
+ 'Reads from a running server; no entity here supports `list$`, so it does nothing.'} |
3343
+ `)
3344
+ if (quick) {
3345
+ Content(`| \`node test/quick.js\` | Exercise the full write cycle on \`${subject.name}\`, cleaning up after itself. |
3346
+ `)
3347
+ }
3348
+ Content(`
3349
+ ${quick ? 'Both scripts target' : 'It targets'} \`$${provider.ENV}_TEST_BASE\`, defaulting to
3350
+ \`${provider.liveBase}\`.
3351
+ `)
3352
+ }
3353
+ })
3354
+ })
3355
+
3356
+
3357
+ // --- doc/explanation.md ------------------------------------------------------
3358
+ //
3359
+ // The understanding-oriented corner of the Diátaxis set: the document someone
3360
+ // opens when the plugin surprised them. It DISCUSSES and never instructs, so
3361
+ // nothing here is a step and nothing here is a table — those belong in
3362
+ // tutorial.md, how-to.md and reference.md.
3363
+ //
3364
+ // The hard part of generating this one is that its subject is design reasoning,
3365
+ // most of which is true of EVERY provider this target emits (the entityBuilder
3366
+ // convention, the four-cmds-to-five-ops join, the .data() hop, the 404
3367
+ // translation) and only some of which depends on the model (whether any entity
3368
+ // is nested, whether writes exist at all, whether the API declares a server).
3369
+ // So the invariant prose is written once and the model-dependent sections are
3370
+ // guarded — an API with no nesting gets no nesting section rather than a
3371
+ // section explaining that it has none.
3372
+
3373
+ const DocExplanation = cmp(function DocExplanation(props: any) {
3374
+ const { provider } = props
3375
+
3376
+ // The entity used as the worked example throughout: fewest parent keys
3377
+ // (nothing to arrange around it) and the most cmds. Same choice the Tests
3378
+ // and Readme cmps make, so the documents agree on what they talk about.
3379
+ const subject = [...provider.entities]
3380
+ .sort((a: any, b: any) =>
3381
+ (a.parents.length - b.parents.length) || (b.cmds.length - a.cmds.length))[0]
3382
+
3383
+ const nested = provider.entities.filter((e: any) => 0 < e.parents.length)
3384
+ const writable = provider.entities.filter((e: any) => e.cmds.includes('save'))
3385
+ const loadable = provider.entities.filter((e: any) => e.cmds.includes('load'))
3386
+ const removable = provider.entities.filter((e: any) => e.cmds.includes('remove'))
3387
+
3388
+ // Entities where `save` has nothing to dispatch on, because the API offers
3389
+ // only one of create/update. Worth naming: their `save$` ignores the id
3390
+ // rule the rest of this document explains.
3391
+ const onesided = writable.filter((e: any) =>
3392
+ !(e.ops.includes('create') && e.ops.includes('update')))
3393
+
3394
+ const code = (s: string) => '`' + s + '`'
3395
+ const list = (names: string[]) => names.map(code).join(', ')
3396
+
3397
+ // What the offline suite actually covers, so the prose does not claim a
3398
+ // `load` test for an entity that has no load.
3399
+ const covered: string[] = []
3400
+ if (subject.cmds.includes('list')) covered.push('list')
3401
+ if (subject.cmds.includes('load')) covered.push('load', 'the not-found answer')
3402
+ if (0 < nested.length) covered.push('the nested-entity rules')
3403
+ const coveredPhrase = 0 < covered.length ? ` — ${covered.join(', ')} —` : ''
3404
+
3405
+ const othersSentence = 1 < provider.entities.length ?
3406
+ 'The other entities carry whatever their own operations support; the\n' +
3407
+ '[reference](reference.md) lists them all.' :
3408
+ 'It is the only entity this API declares, and the\n' +
3409
+ '[reference](reference.md) spells its commands out.'
3410
+
3411
+ // The nesting section names the parent entity when the model knows it, and
3412
+ // falls back to the path params when a parent key points at nothing declared.
3413
+ const n = nested[0]
3414
+ const nestLead = null == n ? '' :
3415
+ '' !== n.parentEntity ?
3416
+ `The API nests ${code(n.name)} under ${code(n.parentEntity)}: a ` +
3417
+ `${code(n.name)}'s URL contains its ${code(n.parentEntity)}.` :
3418
+ `The API nests ${code(n.name)} under a parent resource: a ` +
3419
+ `${code(n.name)}'s URL contains ${list(n.parents)}.`
3420
+
3421
+ File({ name: 'explanation.md' }, () => {
3422
+ Content(`# Explanation
3423
+
3424
+ This document discusses why \`${provider.pkgName}\` is built the way it is.
3425
+ It does not tell you how to do anything — for that see the
3426
+ [tutorial](tutorial.md) and the [how-to guides](how-to.md), and for the exact
3427
+ patterns, entities and options, the [reference](reference.md). The whole set is
3428
+ indexed in [doc/README.md](README.md).
3429
+
3430
+
3431
+ ## The provider convention
3432
+
3433
+ Seneca applications talk to the outside world through *providers*. A provider
3434
+ is a plugin that makes a third-party API look like a Seneca data source, so
3435
+ application code uses the entity API it already knows instead of learning a
3436
+ client library per service.
3437
+
3438
+ The payoff is uniformity. An application reading from ${provider.api}, a
3439
+ payment processor and a CRM uses one access pattern for all three:
3440
+
3441
+ \`\`\`js
3442
+ await seneca.entity('provider/${provider.lower}/${subject.name}').list$()
3443
+ await seneca.entity('provider/stripe/charge').list$()
3444
+ \`\`\`
3445
+
3446
+ Because these are ordinary Seneca entities, everything built on the entity API
3447
+ — logging, tracing, message interception, test doubles — applies to remote
3448
+ calls without any special support for HTTP.
3449
+
3450
+
3451
+ ## What entityBuilder buys
3452
+
3453
+ The convention is more than a naming scheme. \`@seneca/provider\` exports
3454
+ \`provider/entityBuilder\`, and this plugin hands it exactly one thing: a map
3455
+ from entity name to a small set of cmd actions. Recognising the
3456
+ \`provider/${provider.lower}/\` canon, registering the \`role:entity\` messages
3457
+ that sit behind \`list$\`, \`load$\`, \`save$\` and \`remove$\`, and turning
3458
+ whatever an action returns into an entity of the right canon — none of that is
3459
+ written here. It arrives with the convention.
3460
+
3461
+ What remains is a handful of async functions, each a few lines long, whose
3462
+ whole job is to call the SDK and hand the result back through the \`entize\`
3463
+ function entityBuilder supplies. That thinness is the point rather than an
3464
+ accident of effort: a provider that is nearly all glue can be read at a glance,
3465
+ generated in full, and regenerated when the API moves. Cleverness added here is
3466
+ cleverness that has to be maintained against a moving target.
3467
+
3468
+
3469
+ ## Two layers of the same idea
3470
+
3471
+ This provider is unusual among Seneca providers in that the thing it wraps is
3472
+ *already* entity-shaped. The ${provider.api} SDK exposes accessors like
3473
+ \`client.${subject.acc}()\` — carrying
3474
+ ${list(subject.ops)} —
3475
+ rather than raw HTTP routes, for much the same reason Seneca does. A small,
3476
+ uniform surface is easier for people and for agents to reason about than a set
3477
+ of URL templates.
3478
+
3479
+ So the provider is mostly a translation between two entity models that already
3480
+ agree on the important things. Where they *disagree* is where this plugin has
3481
+ to do real work, and each disagreement is discussed below.
3482
+
3483
+
3484
+ ## Where the SDK and Seneca disagree
3485
+
3486
+ ### Four commands, five operations
3487
+
3488
+ Seneca's store commands are \`list\`, \`load\`, \`save\` and \`remove\`. The
3489
+ SDK's operations are \`list\`, \`load\`, \`create\`, \`update\` and \`remove\`.
3490
+ Four of the five line up. \`save\` is the join, and it dispatches on the id: an
3491
+ entity carrying one is an update, an entity without one is a create.
3492
+
3493
+ `)
3494
+
3495
+ if (0 < writable.length) {
3496
+ Content(`That is Seneca's convention rather than this plugin's invention, and it is a
3497
+ good one. Exposing create and update separately would push the HTTP verb back
3498
+ into application code — the caller who loaded a record, changed a field and
3499
+ called \`save$\` would have to know whether that becomes a POST or a PUT. The
3500
+ presence of the id already answers the question. Asking the caller to answer it
3501
+ again only adds a way to be wrong.
3502
+
3503
+ `)
3504
+ }
3505
+
3506
+ Content(`Which commands exist at all is decided per entity, from the operations the API
3507
+ declares, rather than from an assumption that everything is CRUD.
3508
+ \`${subject.name}\` carries
3509
+ ${list(subject.cmds.map((c: string) => c + '$'))}.
3510
+ ${othersSentence}
3511
+ An entity whose API has no create and no update simply has no \`save$\`, which
3512
+ is a better answer than a \`save$\` that exists and then fails at the HTTP
3513
+ layer.
3514
+
3515
+ `)
3516
+
3517
+ if (0 < onesided.length) {
3518
+ Content(`Where an entity declares only one of create and update there is nothing to
3519
+ dispatch on, and \`save$\` means that operation whether an id is present or not:
3520
+
3521
+ `)
3522
+ each(onesided, (e: any) => {
3523
+ Content(`- \`${e.name}\`: \`save$\` always ${e.ops.includes('create') ? 'creates' : 'updates'}
3524
+ `)
3525
+ })
3526
+ Content(`
3527
+ `)
3528
+ }
3529
+
3530
+ Content(`### Entity instances versus plain data
3531
+
3532
+ Every SDK operation resolves to an SDK entity instance, never to raw data:
3533
+ \`list\` to a list of them, and each single-record operation to one. The record
3534
+ is absorbed into the instance and read back through \`.data()\`.${0 < removable.length ?
3535
+ ` A removed\nentity is the same instance, marked deleted, still holding what it held.` : ''}
3536
+
3537
+ Seneca's \`entize\` wants plain data, so the provider takes the \`.data()\` hop
3538
+ on everything the SDK hands back, before it goes anywhere near an entity. That
3539
+ is the whole of the \`plain\` helper in the source, and it is the only place in
3540
+ the plugin that knows the SDK deals in instances at all.
3541
+
3542
+ The hop earns its keep for a second reason. An SDK instance carries its own
3543
+ serialisation marker, and that marker must not survive into a Seneca entity:
3544
+ Seneca reads \`entity$\` on a data object as the *canon*. A marker landing on
3545
+ that key would be taken as a canon, and the record would come back under the
3546
+ wrong one — or under none. The SDK namespaces its marker so the collision
3547
+ cannot happen by accident, but normalising at this boundary is still the right
3548
+ call. It is what makes the data plain, and it keeps the provider independent of
3549
+ whatever the SDK decides to carry alongside a record.
3550
+
3551
+ `)
3552
+
3553
+ if (0 < loadable.length) {
3554
+ Content(`### Missing things
3555
+
3556
+ \`load$\` for an id that does not exist resolves to \`null\`. Only a 404 is
3557
+ translated this way; every other failure propagates.
3558
+
3559
+ "This thing does not exist" is an ordinary answer to a lookup, not a failure of
3560
+ the lookup. It is usually a branch in the caller's logic, and forcing every call
3561
+ site into a \`try\`/\`catch\` to express that branch makes the common path noisy.
3562
+ A malformed request, a rejected credential or an unreachable server means
3563
+ something else entirely: the question could not be asked, and that should
3564
+ interrupt rather than quietly look like an empty result.
3565
+
3566
+ The SDK does not draw this line — it throws for any non-2xx — so the provider
3567
+ asks the thrown error, which reports \`notFound\` and the HTTP \`status\` at the
3568
+ top level. That coupling to the SDK's error shape is a deliberate and narrow
3569
+ one, and it is why the shape is written down in the
3570
+ [reference](reference.md).
3571
+
3572
+ `)
3573
+
3574
+ if (0 < removable.length) {
3575
+ Content(`\`remove$\` is treated the same way and for the same reason: removing something
3576
+ that is already gone leaves the caller with what the caller wanted.
3577
+
3578
+ `)
3579
+ }
3580
+ }
3581
+ else if (0 < removable.length) {
3582
+ Content(`### Missing things
3583
+
3584
+ Nothing here reads a single record by id, but \`remove$\` still has to decide
3585
+ what "it was not there" means, and it treats a 404 as an ordinary outcome rather
3586
+ than a failure: the record is gone, which is what the caller asked for. Every
3587
+ other failure — a malformed request, a rejected credential, an unreachable
3588
+ server — means the question could not be asked at all, and propagates.
3589
+
3590
+ The SDK does not draw that line; it throws for any non-2xx. So the provider asks
3591
+ the thrown error, which reports \`notFound\` and the HTTP \`status\` at the top
3592
+ level. That coupling to the SDK's error shape is a deliberate and narrow one,
3593
+ and it is why the shape is written down in the [reference](reference.md).
3594
+
3595
+ `)
3596
+ }
3597
+
3598
+ if (0 < nested.length) {
3599
+ Content(`### Nesting
3600
+
3601
+ ${nestLead}
3602
+ Seneca's entity model is flat — a canon has no notion of a parent.
3603
+
3604
+ The gap is bridged by putting the parent id in the query, which is why
3605
+ \`${n.parents[0]}\` is required on every \`${n.name}\` command${n.cmds.includes('load') ?
3606
+ `, and why\n\`${n.name}\` \`load$\` takes an object rather than a bare id string` : ''}.
3607
+ This is inherited from the API's URL structure — \`${n.path}\` — rather than
3608
+ chosen here.
3609
+
3610
+ The provider checks for \`${n.parents[0]}\` itself and throws a named error
3611
+ rather than letting the request go out. Without the check, the SDK builds a URL
3612
+ with a missing segment and the server answers 404${n.cmds.includes('load') ?
3613
+ `, and that 404 is\nindistinguishable from "that ${n.name} does not exist" — which the provider\nwould then dutifully translate to \`null\`. A forgotten argument would look\nexactly like an empty result` :
3614
+ ` — an opaque failure that says\nnothing about the argument that was left out`}. Failing early turns a confusing
3615
+ wrong answer into an obvious mistake.
3616
+
3617
+ `)
3618
+ if (1 < nested.length) {
3619
+ Content(`The same applies to every nested entity here —
3620
+ ${list(nested.map((e: any) => e.name))} — each guarded on its own keys.
3621
+
3622
+ `)
3623
+ }
3624
+ }
3625
+
3626
+ Content(`### Query directives
3627
+
3628
+ Seneca store queries can carry directives such as \`sort$\` and \`limit$\`.
3629
+ These are instructions to a *store*, and the API has no equivalent, so the
3630
+ provider strips any key ending in \`$\` before the query becomes an API match.
3631
+
3632
+ Passing them through would be worse than dropping them: the SDK would forward
3633
+ them as ordinary match fields, and the API would either ignore them or reject
3634
+ the request outright. Dropping them is imperfect too — a caller who writes
3635
+ \`list$({ sort$: 'name' })\` gets unsorted results and no complaint — but it is
3636
+ the behaviour least likely to produce a wrong answer, and the limitation is
3637
+ documented rather than hidden. Sorting and limiting belong on the caller's
3638
+ side, or in the API's own query fields where it has them.
3639
+
3640
+
3641
+ `)
3642
+
3643
+ if (0 < writable.length) {
3644
+ Content(`## Why writes are supported here
3645
+
3646
+ The read-only question is worth asking of every provider, and the answer here
3647
+ follows from the API rather than from taste.
3648
+
3649
+ Writes map cleanly onto entities only when the API's notion of "save" is
3650
+ unambiguous. For a CMS with draft states, localised fields and a separate
3651
+ publish step, \`save$\` would have to pick one interpretation and would mislead
3652
+ whoever guessed differently. Here the write operations are plain whole-record
3653
+ ones, so \`save$\` can mean exactly one thing for each of
3654
+ ${list(writable.map((e: any) => e.name))}, and the store surface those
3655
+ operations support is implemented in full.
3656
+
3657
+ One wrinkle does not map cleanly. Seneca's model lets a caller choose an id;
3658
+ many APIs assign ids themselves and ignore any id sent on create. The provider
3659
+ does not try to paper over that, because it cannot make a server honour an id
3660
+ it did not issue. Code that predicts the id of a record it is about to create
3661
+ will be wrong on such an API, and the remedy is to read the id back from what
3662
+ \`save$\` returns rather than to guess it beforehand.
3663
+
3664
+
3665
+ `)
3666
+ }
3667
+ else {
3668
+ Content(`## Why this provider only reads
3669
+
3670
+ Every entity here exposes reads alone. That is not a policy decision taken in
3671
+ the plugin: the cmd map is built from the operations the API declares, and none
3672
+ of these entities declares a create or an update. A \`save$\` that existed only
3673
+ to fail at the HTTP layer would be worse than no \`save$\` at all — the absence
3674
+ is the honest signal, and it appears in the entity table in the
3675
+ [reference](reference.md).
3676
+
3677
+ If the API grows write operations, they arrive here by regeneration rather than
3678
+ by hand. Nothing about the mapping is waiting to be written.
3679
+
3680
+
3681
+ `)
3682
+ }
3683
+
3684
+ Content(`## Credentials, whether or not the API needs them
3685
+
3686
+ At startup the plugin asks \`@seneca/provider\` for the keymap of
3687
+ \`${provider.lower}\` and sends the \`apikey\` as a bearer token when one is
3688
+ configured.
3689
+
3690
+ The key is *optional*. Absent, unconfigured and empty all mean "send no
3691
+ header", and none of them is an error. For an API that needs no credential this
3692
+ looks like ceremony, and it is worth keeping anyway: the shape of a Seneca
3693
+ application should not depend on whether a particular service happens to need a
3694
+ key. An application that moves from an open endpoint to an authenticated
3695
+ deployment then changes one configuration value rather than restructuring how
3696
+ the plugin loads — and a provider that demanded a key from an API that has none
3697
+ would force every user to invent a fake one.
3698
+
3699
+
3700
+ ## Depending on a published SDK
3701
+
3702
+ The SDK is an ordinary published dependency: \`${provider.sdkPkg}\` at
3703
+ \`^${provider.sdkVersion}\`, resolved by npm like anything else.
3704
+
3705
+ The alternative is vendoring — copying the generated client into this
3706
+ repository. That is tempting, since both artefacts come from the same model and
3707
+ change together. It is also wrong. It makes a second copy of something that is
3708
+ regenerated whenever the API moves, and it puts this plugin's release cycle in
3709
+ charge of the API's. As a dependency, the SDK carries its own semantic version:
3710
+ when the API changes, the SDK is versioned, and this plugin either follows the
3711
+ range or pins until it is ready. Keeping them separable also matters to the
3712
+ people who use the SDK with no Seneca anywhere in sight.
3713
+
3714
+ One consequence of depending on generated code is worth stating plainly. The
3715
+ SDK is regenerated as the API model changes, so its surface can shift in ways a
3716
+ hand-written library's would not. That argues for keeping this plugin thin, and
3717
+ for pinning behaviour in tests. Everything this plugin knows about the SDK's
3718
+ shapes is concentrated in three small functions — the \`.data()\` hop, the query
3719
+ cleaner and the not-found translation — plus the construction of the client, so
3720
+ an SDK change is absorbed in one place and surfaces as a failing offline test
3721
+ rather than as a surprise in production.
3722
+
3723
+ `)
3724
+
3725
+ if ('' === provider.liveBase) {
3726
+ Content(`The API definition declares no server, so this plugin has no default host: the
3727
+ base URL arrives through the \`sdk.base\` option, supplied by whoever configures
3728
+ the plugin for a particular deployment. The tests therefore run entirely
3729
+ against the SDK's mock transport, which is the one host that is always
3730
+ available.
3731
+
3732
+
3733
+ `)
3734
+ }
3735
+ else {
3736
+ Content(`The distinction that does survive is between the SDK and its **test server**.
3737
+ The SDK is published; the server is not, and ships only in
3738
+ [the SDK's source repository](${provider.sdkRepoUrl}). So the offline tests need
3739
+ nothing but \`npm install\`, while the live tests need a clone. That asymmetry
3740
+ is why the live tests probe for the server and skip rather than fail: the common
3741
+ case is a contributor who has the dependency but not the repository.
3742
+
3743
+
3744
+ `)
3745
+ }
3746
+
3747
+ Content(`## A generated plugin
3748
+
3749
+ Nothing in this repository is hand-written. The plugin source, its tests, its CI
3750
+ workflow, its manifest and these documents are all emitted by
3751
+ [@voxgig/sdkgen](https://github.com/voxgig/sdkgen) from the ${provider.api} API
3752
+ model — the same model the SDK is generated from, which is why the two cannot
3753
+ disagree about entity names, id fields, or which operations exist.
3754
+
3755
+ There is one blunt consequence for anyone reading the code and reaching for an
3756
+ edit: the edit will not survive. The next generation run overwrites this
3757
+ repository, without a merge and without a warning. A fix applied here is a fix
3758
+ that has to be applied again, silently, forever.
3759
+
3760
+ The source of truth is the SDK project's model — \`${provider.sdkrel}\` from
3761
+ here, if both are checked out — together with the sdkgen component that emits
3762
+ this target. A change to *what* the API offers belongs in the model; a change to
3763
+ *how* the provider expresses it belongs in the component. Both are versioned,
3764
+ both regenerate every provider built this way rather than just this one, and
3765
+ both are where a fix is worth making. See
3766
+ [Contributing](../README.md#contributing).
3767
+
3768
+
3769
+ ## How the tests are arranged
3770
+
3771
+ The suite runs offline by default. It needs no credentials and no network.
3772
+
3773
+ The **offline** tests use the SDK's own mock transport, reached through this
3774
+ plugin's own options:
3775
+
3776
+ \`\`\`js
3777
+ .use('${provider.pkgName}', {
3778
+ test: true,
3779
+ testopts: { entity: { ${subject.name}: { '${subject.name}0': { ... } } } },
3780
+ })
3781
+ \`\`\`
3782
+
3783
+ This is better than the usual provider-testing compromise. Rather than checking
3784
+ only that the plugin loads and answers
3785
+ \`sys:provider,provider:${provider.lower},get:info\`, the tests exercise the
3786
+ entity commands themselves${coveredPhrase}
3787
+ through the real code path, from a Seneca entity call down to the transport and
3788
+ back. The only thing replaced is the socket. And because the mock belongs to the
3789
+ SDK, it stays honest as the SDK changes: a regeneration that alters a return
3790
+ shape breaks a test here rather than someone's production run.
3791
+
3792
+ Seeding the mock is not decoration either. The seed is generated from the same
3793
+ model as the entities, so the records the tests read carry the fields the API
3794
+ would really return${0 < nested.length ? `, and a nested record's parent id
3795
+ names a parent record that exists — otherwise the nested tests would read an
3796
+ empty store and pass without proving anything` : ''}.
3797
+
3798
+ `)
3799
+
3800
+ if ('' !== provider.liveBase) {
3801
+ Content(`The **live** tests point at the companion server in the SDK repository and probe
3802
+ it before running, skipping with a stated reason when nothing answers. So a
3803
+ contributor who has just cloned this repository gets a meaningful result
3804
+ immediately, and a more thorough one after starting the server.
3805
+
3806
+ Skipping is deliberate, and preferred over quietly returning early. An early
3807
+ \`return\` reports a test as *passed*, which makes an unconfigured checkout look
3808
+ as though it verified the integration when it verified nothing at all. A skip is
3809
+ honest about coverage, and the summary count shows how much did not run.
3810
+
3811
+ `)
3812
+
3813
+ if (subject.cmds.includes('save') && subject.cmds.includes('remove')) {
3814
+ Content(`The manual scripts in \`test/\` that write to a live server remove what they
3815
+ create, in a \`finally\` block, so the server is left as it was found. A run that
3816
+ leaks a record changes the result of the next one, which is how a suite becomes
3817
+ order-dependent and then flaky.
3818
+ `)
3819
+ }
3820
+ }
3821
+ })
3822
+ })
3823
+
3824
+
3825
+ // --- doc/ --------------------------------------------------------------------
3826
+ //
3827
+ // The Diátaxis documentation set: an index plus the four quadrants.
3828
+ //
3829
+ // WHY THIS IS GENERATED AT ALL. Every other sdkgen target emits a single
3830
+ // README, and for a language SDK that is the right amount: the SDK's real
3831
+ // reference is its types. A Seneca provider has no types a reader can browse —
3832
+ // its whole interface is message patterns and entity canons, which exist only
3833
+ // in prose. The provider this target was modelled on carried 1100 lines of
3834
+ // hand-written documentation for exactly that reason, and the first
3835
+ // regeneration left all of it orphaned: the README's link table was gone and
3836
+ // nothing emitted the files it had pointed at.
3837
+ //
3838
+ // Everything here is derived from the same `provider` shape the source and the
3839
+ // tests are built from, so the docs cannot describe an entity the plugin does
3840
+ // not expose, or a cmd it does not implement — the drift that makes
3841
+ // hand-written provider docs untrustworthy after the second API change.
3842
+
3843
+ const DocIndex = cmp(function DocIndex(props: any) {
3844
+ const { provider } = props
3845
+
3846
+ File({ name: 'README.md' }, () => {
3847
+ Content(`# Documentation
3848
+
3849
+ The documentation for \`${provider.pkgName}\` follows the
3850
+ [Diátaxis](https://diataxis.fr) framework. Each document serves one purpose,
3851
+ and that purpose decides what belongs in it. If you are unsure where to look,
3852
+ use the table below.
3853
+
3854
+ | Document | Purpose | Read it when |
3855
+ | -------- | ------- | ------------ |
3856
+ | [Tutorial](tutorial.md) | Learning-oriented. A lesson that takes you from nothing to a working script. | You have never used this plugin and want to see it work. |
3857
+ | [How-to guides](how-to.md) | Task-oriented. Recipes that solve one problem each. | You know what you want to do and need the steps. |
3858
+ | [Reference](reference.md) | Information-oriented. A complete, factual description of the interface. | You need to look up a message pattern, entity field, or option. |
3859
+ | [Explanation](explanation.md) | Understanding-oriented. The reasoning behind the design. | You want to know *why* it works this way, or you are debugging something surprising. |
3860
+
3861
+ ## The distinction that matters most
3862
+
3863
+ The tutorial and the how-to guides look alike — both are sequences of steps —
3864
+ but they are not interchangeable.
3865
+
3866
+ The **tutorial** is a lesson. It is safe to follow, it produces a result you
3867
+ can see, and it asks you to make no decisions. Its job is to build confidence,
3868
+ so it deliberately avoids alternatives and edge cases.
3869
+
3870
+ A **how-to guide** assumes competence. It answers "how do I list every record
3871
+ of a collection?", and it assumes you already have a working Seneca instance.
3872
+ Its job is to get a task done, so it omits the explanation.
3873
+
3874
+ Likewise **reference** describes the machinery and nothing else — it never
3875
+ teaches. **Explanation** discusses and gives context — it never instructs.
3876
+
3877
+ ## These documents are generated
3878
+
3879
+ This plugin, and this documentation with it, is generated by
3880
+ [@voxgig/sdkgen](https://github.com/voxgig/sdkgen) from the ${provider.api} API
3881
+ definition held in the [SDK project](${provider.sdkRepoUrl}). An edit made here
3882
+ is lost on the next regeneration.
3883
+
3884
+ Something genuinely specific to this API — a quirk of its authentication, a
3885
+ rate limit worth warning about — belongs in the model the generator reads, not
3886
+ in the output it writes. Everything else belongs in the generator's own
3887
+ components, where fixing it once fixes every provider.
3888
+ `)
3889
+ })
3890
+ })
3891
+
3892
+
3893
+ // The whole `doc/` folder. One cmp so Main names the documentation once, and
3894
+ // so the folder is opened in a single place — the four quadrant components
3895
+ // emit a File each and know nothing about where they sit.
3896
+ const Docs = cmp(function Docs(props: any) {
3897
+ const { provider } = props
3898
+
3899
+ Folder({ name: 'doc' }, () => {
3900
+ DocIndex({ provider })
3901
+ DocTutorial({ provider })
3902
+ DocHowto({ provider })
3903
+ DocReference({ provider })
3904
+ DocExplanation({ provider })
3905
+ })
3906
+ })
3907
+
3908
+
3909
+ export {
3910
+ Tests,
3911
+ Scripts,
3912
+ Workflow,
3913
+ Readme,
3914
+ Docs,
3915
+ }