@servable/tools 1.6.6 → 2.0.0-unischema.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -3,7 +3,7 @@
3
3
  "type": "module",
4
4
  "source": "src/index.js",
5
5
  "main": "src/index.js",
6
- "version": "1.6.6",
6
+ "version": "2.0.0-unischema.2",
7
7
  "description": "Servable tools is a utility that builds a protocol's manifest and documents it.",
8
8
  "author": "Servable Community",
9
9
  "license": "ISC",
@@ -2,13 +2,18 @@ import importJSONAsync from "../../../lib/importJSONAsync.js"
2
2
 
3
3
 
4
4
  export default async ({ path, cache, cacheKey }) => {
5
+ // importJSONAsync returns null (no throw) when the file simply doesn't exist - so anything
6
+ // that reaches this catch is a file that DOES exist but failed to read/parse (e.g. invalid
7
+ // JSON - a real incident: activitable's schema.json had a trailing comma that had silently
8
+ // never parsed successfully in production, see .docs/technical/unischema-plan.md). Swallowing
9
+ // that to `null` here made it indistinguishable from "this protocol has no schema.json at
10
+ // all" to every caller (schemaRaw() et al.) - a broken schema.json silently produced a build
11
+ // with that protocol's classes/fields/indexes just missing, no error anywhere but a buried
12
+ // console line. Rethrow with the path instead, so `schema build`/`plan`/`apply` fails loudly
13
+ // and names the exact file.
5
14
  try {
6
- // console.log("[Servable]", `importJSONDefault for path ${path}`)
7
- const data = await importJSONAsync(path)
8
- // console.log("[Servable]", `importJSONDefault for path ${path} successful`)
9
- return data
15
+ return await importJSONAsync(path)
10
16
  } catch (e) {
11
- console.error("[Servable]", `importJSONDefault for path ${path}:`, e)
17
+ throw new Error(`Failed to parse ${path}: ${e.message}`)
12
18
  }
13
- return null
14
19
  }
@@ -1,6 +1,5 @@
1
1
  import BaseClass from './base.js'
2
2
 
3
- import directories from '../../lib/directories.js'
4
3
  import cleanProtocols from '../../lib/cleanProtocols.js'
5
4
  import mergeClassProtocols from './lib/mergeClassProtocols.js'
6
5
 
@@ -9,7 +8,6 @@ import directoryGlob from '../../lib/directoryGlob.js'
9
8
 
10
9
  import checkFileExists from '../../lib/checkFileExists.js'
11
10
  import directoryFilesRecursive from '../../lib/directoryFilesRecursive.js'
12
- import { ProtocolEnum } from '../../manifest/data/1.0.0/enums.js'
13
11
 
14
12
  import triggerItems from './lib/triggerItems.js'
15
13
  import fs from 'fs'
@@ -499,193 +497,59 @@ export default class ProtocolLoaderV1_0_0 extends BaseClass {
499
497
 
500
498
 
501
499
  //#region schema
500
+ // unischema: a protocol's schema is one flat, unversioned file at its root -
501
+ // `${this.path}/schema.json` - see v1.1.0.js's identical region for the full rationale and
502
+ // .docs/technical/unischema-plan.md for the wider context.
502
503
 
503
504
  async classesSchemas(props) {
504
- // if (this.valueInCache('classes')) {
505
- // return this.valueInCache('classes')
506
- // }
507
-
508
505
  const schema = await this.schemaRaw(props)
509
506
  if (schema && schema.managed) {
510
507
  return schema.managed.classes
511
508
  }
512
-
513
- const schemaPath = await this._schemaPath()
514
- let path = `${schemaPath}/classes.js`
515
-
516
- if ((await checkFileExists(path))) {
517
- const classes = await (await import(path)).default({ protocol: this.protocolInstance })
518
- // this.cache['classes'] = classes
519
- return classes
520
- }
521
-
522
- path = `${schemaPath}/classes.json`
523
- if (!(await checkFileExists(path))) {
524
- return []
525
- }
526
-
527
- const classes = await importJSONAsync(path)
528
- // this.cache['classes'] = classes
529
- return classes
509
+ return []
530
510
  }
531
511
 
532
512
  async schemaFields(props) {
533
- // const cacheKey = 'schemaFields'
534
- // if (this.valueInCache(cacheKey)) {
535
- // return this.valueInCache(cacheKey)
536
- // }
537
513
  const schema = await this.schemaRaw(props)
538
514
  if (schema && schema.target) {
539
515
  return schema.target.fields
540
516
  }
541
-
542
- const schemaPath = await this._schemaPath()
543
- const path = `${schemaPath}/fields.json`
544
- if (!(await checkFileExists(path))) {
545
- return null
546
- }
547
-
548
- return this._importJSONDefault({ path, })
517
+ return null
549
518
  }
550
519
 
551
520
  async schemaIndexes(props) {
552
- // const cacheKey = 'schemaIndexes'
553
- // if (this.valueInCache(cacheKey)) {
554
- // return this.valueInCache(cacheKey)
555
- // }
556
521
  const schema = await this.schemaRaw(props)
557
522
  if (schema && schema.target) {
558
523
  return schema.target.indexes
559
524
  }
560
-
561
- const schemaPath = await this._schemaPath()
562
- const path = `${schemaPath}/indexes.json`
563
-
564
- if (!(await checkFileExists(path))) {
565
- return null
566
- }
567
-
568
- return this._importJSONDefault({ path, })
525
+ return null
569
526
  }
570
527
 
571
528
  async schemaRaw(props = {}) {
572
- const { ad } = props
573
- const a = await this._accessManifestItem({
574
- item: ProtocolEnum.Schema,
575
- })
576
- // const cacheKey = 'schemaIndexes'
577
- // if (this.valueInCache(cacheKey)) {
578
- // return this.valueInCache(cacheKey)
579
- // }
580
-
581
- const schemaPath = await this._schemaPath()
582
-
583
- //#TODO: A dynamic schema needs protocols to be instantiated per class as to avoid class defintion collusions and edge case.
584
- // let path = `${schemaPath}/index.js`
585
-
586
- // if ((await checkFileExists(path))) {
587
- // let data = (await import(path)).default
588
- // //#TODO: don't use up protocol params
589
- // data = await data({ ...props, params: this.protocolInstance.params })
590
- // return data
591
- // }
592
-
593
- let path = `${schemaPath}/index.json`
529
+ // Memoized for the same reason v1.1.0.js's does - schemaFields()/schemaIndexes()/
530
+ // schemaClassLevelPermissions() each call this independently for every protocol attached to
531
+ // every class.
532
+ const cacheKey = 'schemaRaw'
533
+ if (this._valueInCache(cacheKey)) {
534
+ return this._valueInCache(cacheKey)
535
+ }
594
536
 
537
+ const path = `${this.path}/schema.json`
595
538
  if (!(await checkFileExists(path))) {
596
539
  return null
597
540
  }
598
541
 
599
542
  const b = await this._importJSONDefault({ path, })
543
+ this.cache[cacheKey] = b
600
544
  return b
601
545
  }
602
546
 
603
547
  async schemaClassLevelPermissions(props) {
604
- // const cacheKey = 'schemaClassLevelPermissions'
605
- // if (this.valueInCache(cacheKey)) {
606
- // return this.valueInCache(cacheKey)
607
- // }
608
-
609
548
  const schema = await this.schemaRaw(props)
610
549
  if (schema && schema.target) {
611
550
  return schema.target.classLevelPermissions
612
551
  }
613
-
614
- const schemaPath = await this._schemaPath()
615
- const path = `${schemaPath}/classlevelpermissions.json`
616
-
617
- if (!(await checkFileExists(path))) {
618
- return null
619
- }
620
-
621
- return this._importJSONDefault({ path, })
622
- }
623
-
624
- async _schemaPath() {
625
- //let version = this.currentProtocolVersion ? this.currentProtocolVersion : this.protocolInstanceVersion
626
- let version = this.protocolInstance.version
627
- let versions = await this.schemaVersions()
628
-
629
- if (!version) {
630
- return `${this.path}/schema`
631
- }
632
-
633
- if (!versions
634
- || !versions.length) {
635
- return `${this.path}/schema`
636
- }
637
-
638
- if (versions
639
- && versions.length
640
- && !versions.includes(version)) {
641
- return `${this.path}/schema`
642
- }
643
-
644
- if (versions
645
- && versions.length
646
- && version === 'latest') {
647
- version = versions[versions.length - 1] //#TODO: sort by semver
648
- }
649
-
650
- const path = `${this.path}/schema/${version}`
651
- return path
652
- }
653
-
654
-
655
- async schemaVersions() {
656
- const cacheKey = '_schemaVersions'
657
- if (this._valueInCache(cacheKey)) {
658
- return this._valueInCache(cacheKey)
659
- }
660
- const items = await directories({ path: `${this.path}/schema` })
661
- if (!items || !items.length) {
662
- return null
663
- }
664
- let data = items.map(i => i.name)
665
- data = data.sort()
666
- this.cache[cacheKey] = data
667
- return data
668
- }
669
-
670
- async schemaVersionOf({ version, subPath }) {
671
- const cacheKey = `_schemaVersionOf${subPath}`
672
- if (this._valueInCache(cacheKey)) {
673
- return this._valueInCache(cacheKey)
674
- }
675
-
676
- const versions = await this.schemaVersions()
677
- if (!versions || !versions.includes(version)) {
678
- return null
679
- }
680
-
681
- const path = `${this.path}/schema/${version}/migration/${subPath}/index.js`
682
- if (!(await checkFileExists(path))) {
683
- return null
684
- }
685
-
686
- const data = await import(path)
687
- this.cache[cacheKey] = data
688
- return data
552
+ return null
689
553
  }
690
554
 
691
555
  //#endregion
@@ -1,6 +1,5 @@
1
1
  import BaseClass from './base.js'
2
2
 
3
- import directories from '../../lib/directories.js'
4
3
  import cleanProtocols from '../../lib/cleanProtocols.js'
5
4
  import mergeClassProtocols from './lib/mergeClassProtocols.js'
6
5
 
@@ -486,99 +485,53 @@ export default class ProtocolLoaderV1_1_0 extends BaseClass {
486
485
 
487
486
 
488
487
  //#region schema
488
+ // unischema: a protocol's schema is one flat, unversioned file at its root -
489
+ // `${this.path}/schema.json` - replacing the old `schema/<semver>/index.json` snapshot-per-
490
+ // version convention entirely. No version-path resolution, no schema/ directory, no up/down
491
+ // scripts. See .docs/technical/unischema-plan.md for why.
492
+ //
493
+ // The split-file convention some protocols used (classes.json/fields.json/indexes.json/
494
+ // classlevelpermissions.json as separate files instead of one merged index.json) is not
495
+ // supported here going forward - it was folded into the single `{ managed, target }` shape by
496
+ // the one-time migration (see backend/main's migrate-protocol-schemas script), same as the
497
+ // versioned-directory convention was. This loader only ever reads one shape, one file.
489
498
 
490
499
  async classesSchemas(props) {
491
- // if (this.valueInCache('classes')) {
492
- // return this.valueInCache('classes')
493
- // }
494
-
495
500
  const schema = await this.schemaRaw(props)
496
501
  if (schema && schema.managed) {
497
502
  return schema.managed.classes
498
503
  }
499
-
500
- const schemaPath = await this._schemaPath()
501
- let path = `${schemaPath}/classes.js`
502
-
503
- if ((await checkFileExists(path))) {
504
- const classes = await (await import(path)).default({ protocol: this.protocolInstance })
505
- // this.cache['classes'] = classes
506
- return classes
507
- }
508
-
509
- path = `${schemaPath}/classes.json`
510
- if (!(await checkFileExists(path))) {
511
- return []
512
- }
513
-
514
- const classes = await importJSONAsync(path)
515
- // this.cache['classes'] = classes
516
- return classes
504
+ return []
517
505
  }
518
506
 
519
507
  async schemaFields(props) {
520
- // const cacheKey = 'schemaFields'
521
- // if (this.valueInCache(cacheKey)) {
522
- // return this.valueInCache(cacheKey)
523
- // }
524
508
  const schema = await this.schemaRaw(props)
525
509
  if (schema && schema.target) {
526
510
  return schema.target.fields
527
511
  }
528
-
529
- const schemaPath = await this._schemaPath()
530
- const path = `${schemaPath}/fields.json`
531
- if (!(await checkFileExists(path))) {
532
- return null
533
- }
534
-
535
- return this._importJSONDefault({ path, })
512
+ return null
536
513
  }
537
514
 
538
515
  async schemaIndexes(props) {
539
- // const cacheKey = 'schemaIndexes'
540
- // if (this.valueInCache(cacheKey)) {
541
- // return this.valueInCache(cacheKey)
542
- // }
543
516
  const schema = await this.schemaRaw(props)
544
517
  if (schema && schema.target) {
545
518
  return schema.target.indexes
546
519
  }
547
-
548
- const schemaPath = await this._schemaPath()
549
- const path = `${schemaPath}/indexes.json`
550
-
551
- if (!(await checkFileExists(path))) {
552
- return null
553
- }
554
-
555
- return this._importJSONDefault({ path, })
520
+ return null
556
521
  }
557
522
 
558
523
  async schemaRaw(props = {}) {
559
- // schemaFields()/schemaIndexes()/schemaClassLevelPermissions() each call
560
- // this independently for every protocol attached to every class, so
561
- // without caching the same schema/<version>/index.json gets read and
562
- // JSON.parse'd up to 3x per class-protocol edge across the whole build.
524
+ // Memoized: schemaFields()/schemaIndexes()/schemaClassLevelPermissions() each call this
525
+ // independently for every protocol attached to every class, so without caching the same
526
+ // schema.json gets read and JSON.parse'd up to 3x per class-protocol edge across the whole
527
+ // build (see servable_launch_perf_audit memory - this memoization predates unischema and is
528
+ // kept unchanged here).
563
529
  const cacheKey = 'schemaRaw'
564
530
  if (this._valueInCache(cacheKey)) {
565
531
  return this._valueInCache(cacheKey)
566
532
  }
567
533
 
568
- const schemaPath = await this._schemaPath()
569
-
570
- //#TODO: A dynamic schema needs protocols to be instantiated per class as to avoid class defintion collusions and edge case.
571
- // let path = `${schemaPath}/index.js`
572
-
573
- // if ((await checkFileExists(path))) {
574
- // let data = (await import(path)).default
575
- // //#TODO: don't use up protocol params
576
- // data = await data({ ...props, params: this.protocolInstance.params })
577
- // return data
578
- // }
579
-
580
- let path = `${schemaPath}/index.json`
581
-
534
+ const path = `${this.path}/schema.json`
582
535
  if (!(await checkFileExists(path))) {
583
536
  return null
584
537
  }
@@ -589,91 +542,11 @@ export default class ProtocolLoaderV1_1_0 extends BaseClass {
589
542
  }
590
543
 
591
544
  async schemaClassLevelPermissions(props) {
592
- // const cacheKey = 'schemaClassLevelPermissions'
593
- // if (this.valueInCache(cacheKey)) {
594
- // return this.valueInCache(cacheKey)
595
- // }
596
-
597
545
  const schema = await this.schemaRaw(props)
598
546
  if (schema && schema.target) {
599
547
  return schema.target.classLevelPermissions
600
548
  }
601
-
602
- const schemaPath = await this._schemaPath()
603
- const path = `${schemaPath}/classlevelpermissions.json`
604
-
605
- if (!(await checkFileExists(path))) {
606
- return null
607
- }
608
-
609
- return this._importJSONDefault({ path, })
610
- }
611
-
612
- async _schemaPath() {
613
- //let version = this.currentProtocolVersion ? this.currentProtocolVersion : this.protocolInstanceVersion
614
- let version = this.protocolInstance.version
615
- let versions = await this.schemaVersions()
616
-
617
- if (!version) {
618
- return `${this.path}/schema`
619
- }
620
-
621
- if (!versions
622
- || !versions.length) {
623
- return `${this.path}/schema`
624
- }
625
-
626
- if (versions
627
- && versions.length
628
- && !versions.includes(version)) {
629
- return `${this.path}/schema`
630
- }
631
-
632
- if (versions
633
- && versions.length
634
- && version === 'latest') {
635
- version = versions[versions.length - 1] //#TODO: sort by semver
636
- }
637
-
638
- const path = `${this.path}/schema/${version}`
639
- return path
640
- }
641
-
642
-
643
- async schemaVersions() {
644
- const cacheKey = '_schemaVersions'
645
- if (this._valueInCache(cacheKey)) {
646
- return this._valueInCache(cacheKey)
647
- }
648
- const items = await directories({ path: `${this.path}/schema` })
649
- if (!items || !items.length) {
650
- return null
651
- }
652
- let data = items.map(i => i.name)
653
- data = data.sort()
654
- this.cache[cacheKey] = data
655
- return data
656
- }
657
-
658
- async schemaVersionOf({ version, subPath }) {
659
- const cacheKey = `_schemaVersionOf${subPath}`
660
- if (this._valueInCache(cacheKey)) {
661
- return this._valueInCache(cacheKey)
662
- }
663
-
664
- const versions = await this.schemaVersions()
665
- if (!versions || !versions.includes(version)) {
666
- return null
667
- }
668
-
669
- const path = `${this.path}/schema/${version}/${subPath}.js`
670
- if (!(await checkFileExists(path))) {
671
- return null
672
- }
673
-
674
- const data = await import(path)
675
- this.cache[cacheKey] = data
676
- return data
549
+ return null
677
550
  }
678
551
 
679
552
  //#endregion
package/src/index.js CHANGED
@@ -5,6 +5,8 @@ import * as ManifestEnumsV1_1_0 from './manifest/data/1.0.0/enums.js'
5
5
 
6
6
  import buildSchema from './schema/build/index.js'
7
7
  import validateSchema from './schema/validate/index.js'
8
+ import compileArtifact, { hashOf as artifactHashOf, normalizeArtifact } from './schema/artifact/index.js'
9
+ import plan from './schema/plan/index.js'
8
10
  // import validateProtocol from './lib/config/validate/protocol/index.js'
9
11
  import cleanProtocols from './lib/cleanProtocols.js'
10
12
 
@@ -23,6 +25,10 @@ export {
23
25
  ManifestEnumsV1_1_0,
24
26
  buildSchema,
25
27
  validateSchema,
28
+ compileArtifact,
29
+ artifactHashOf,
30
+ normalizeArtifact,
31
+ plan,
26
32
  cleanProtocols,
27
33
  generateGithubReadme,
28
34
  Domain
@@ -0,0 +1,19 @@
1
+ // Deterministic JSON.stringify - object keys sorted recursively, so two structurally-identical
2
+ // schemas always hash to the same string regardless of the order protocols happened to
3
+ // contribute their fields in. Arrays keep their order (field/index order within an object does
4
+ // not matter for schema equivalence, but array element order - e.g. protocol ids - might).
5
+ const sortValue = (value) => {
6
+ if (Array.isArray(value)) {
7
+ return value.map(sortValue)
8
+ }
9
+ if (value && typeof value === 'object' && !(value instanceof Date)) {
10
+ const sorted = {}
11
+ Object.keys(value).sort().forEach(key => {
12
+ sorted[key] = sortValue(value[key])
13
+ })
14
+ return sorted
15
+ }
16
+ return value
17
+ }
18
+
19
+ export default (value) => JSON.stringify(sortValue(value))
@@ -0,0 +1,112 @@
1
+ // unischema's compiled schema artifact - see .docs/technical/unischema-plan.md decision #3.
2
+ //
3
+ // `buildSchema()` returns a rich object graph (protocol instances, loaders, caches) meant for
4
+ // driving the launch process, not for committing to git or hashing. This module extracts the
5
+ // one thing that actually matters for drift-detection and PR review: the fully-resolved,
6
+ // per-class schema every protocol's contributions have already been merged into
7
+ // (`appProtocol.schema.classes.all` - built by schema/build/buildProtocol/index.js, each entry
8
+ // already passed through classStruct/protocolInClassClassSchema for every contributing
9
+ // protocol). That merged view, not any single protocol's own schema.json, is what Parse actually
10
+ // receives at launch - so it's what should be reviewed and diffed.
11
+ import buildSchema from '../build/index.js'
12
+ import stableStringify from '../../lib/stableStringify.js'
13
+ import crypto from 'crypto'
14
+
15
+ const ARTIFACT_VERSION = 1
16
+
17
+ const normalizeClass = (classSchema) => {
18
+ const {
19
+ className,
20
+ fields = {},
21
+ indexes = {},
22
+ classLevelPermissions = {},
23
+ } = classSchema || {}
24
+
25
+ return {
26
+ className,
27
+ fields,
28
+ indexes,
29
+ classLevelPermissions,
30
+ }
31
+ }
32
+
33
+ // buildSchema()'s protocol graph carries version and dependency info per protocol instance -
34
+ // pulled out separately from the class data above because it answers a different question
35
+ // (validateSchema's protocol-compatibility check, decision #10) than the schema content does.
36
+ const extractProtocolVersions = (protocols) => {
37
+ const seen = new Map()
38
+ ;(protocols || []).forEach(protocol => {
39
+ const { instances } = protocol || {}
40
+ ;(instances || []).forEach(instance => {
41
+ if (!instance || !instance.id) {
42
+ return
43
+ }
44
+ seen.set(`${instance.id}@${instance.version}`, {
45
+ id: instance.id,
46
+ version: instance.version,
47
+ minimumCompatibleVersion: instance.minimumCompatibleVersion,
48
+ })
49
+ })
50
+ })
51
+ return [...seen.values()].sort((a, b) => a.id.localeCompare(b.id) || a.version.localeCompare(b.version))
52
+ }
53
+
54
+ // Pure - no I/O, takes a buildSchema() result it did not itself produce. Split out from
55
+ // compileArtifact() specifically so a caller that already has a buildSchema() result (launch/
56
+ // index.js always does - it's already the slow, once-per-boot step) never has to pay for a
57
+ // second one just to get an artifact. Only the CLI (which never has one lying around) goes
58
+ // through compileArtifact() below.
59
+ export const normalizeArtifact = ({ appProtocol, protocols }) => {
60
+ const classes = (appProtocol?.schema?.classes?.all || [])
61
+ .map(normalizeClass)
62
+ .filter(c => c.className)
63
+ .sort((a, b) => a.className.localeCompare(b.className))
64
+
65
+ const protocolVersions = extractProtocolVersions(protocols)
66
+
67
+ // Hash covers `classes` ONLY, not protocolVersions - confirmed live during testing that which
68
+ // protocol instances buildProtocol()'s recursive protocolFactory()/protocolsCache resolves
69
+ // (and therefore what ends up in protocolVersions) is resolution-order-dependent for any
70
+ // protocol that gets referenced from more than one place, independent of unischema's own
71
+ // changes and independent of any actual schema content - two builds from byte-identical
72
+ // protocol sources produced identical `classes` but different `protocolVersions` depending on
73
+ // incidental import-order effects elsewhere (which class.js files happened to import
74
+ // successfully). That makes protocolVersions unsuitable for hash-based drift detection
75
+ // (decision #4) - it would false-positive on every deploy for reasons unrelated to any real
76
+ // schema change. `classes` is what Parse actually receives and is what proved stable across
77
+ // both runs, so it's the only thing this artifact's identity is defined by. protocolVersions
78
+ // is still recorded (validateSchema's compatibility check, decision #10, and it's genuinely
79
+ // useful in a `schema plan` diff) - just not part of `hash`.
80
+ const hash = crypto.createHash('sha256').update(stableStringify({ classes })).digest('hex')
81
+
82
+ return {
83
+ artifactVersion: ARTIFACT_VERSION,
84
+ generatedAt: new Date().toISOString(),
85
+ hash,
86
+ classes,
87
+ protocolVersions,
88
+ }
89
+ }
90
+
91
+ // Convenience wrapper for a caller with no buildSchema() result already in hand (the CLI, always
92
+ // - see schema/build.js, plan.js, apply.js, contract.js). Also used, deliberately, to detect
93
+ // drift at boot (decision #4): the server calls normalizeArtifact() on the result of its own
94
+ // buildSchema() run to hash "what the sources say right now," rather than calling this and
95
+ // re-running buildSchema() a second time.
96
+ export const compileArtifact = async ({ servableConfig }) => {
97
+ const result = await buildSchema({ servableConfig })
98
+ return normalizeArtifact(result)
99
+ }
100
+
101
+ // Content-only equality - ignores generatedAt, so re-running the build with no real schema
102
+ // change produces the same hash. Used both to build the artifact's own `hash` field and, at
103
+ // boot, to compare a freshly-compiled artifact against the one committed to git.
104
+ export const hashOf = (artifact) => {
105
+ if (!artifact) {
106
+ return null
107
+ }
108
+ const { classes = [] } = artifact
109
+ return crypto.createHash('sha256').update(stableStringify({ classes })).digest('hex')
110
+ }
111
+
112
+ export default compileArtifact
@@ -15,6 +15,22 @@ export default async ({
15
15
  protocolPayload,
16
16
  instancesPathId
17
17
  })
18
+
19
+ // A protocol can declare a dependency-of-a-dependency (ownProtocols()) that isn't actually
20
+ // vendored locally - confirmed live while testing unischema's migration against backend/main:
21
+ // disposableorphansable, disposablechildrenable and servableconfigurable are all referenced
22
+ // this way by at least one protocol but don't exist under protocols/. protocolFactory()
23
+ // returns null in that case (protocolPath() found nowhere to load from) rather than
24
+ // throwing, so this was always reachable - it just hadn't been hit before. Previously this
25
+ // crashed the entire schema build (`protocol.loader` on null) for every class, not just the
26
+ // one missing protocol; skipping the missing dependency and continuing is what the rest of
27
+ // this loop already assumes is possible (see the `a && a.length` check right below, which
28
+ // already tolerates a protocol contributing nothing).
29
+ if (!protocol) {
30
+ console.warn(`[@servable/tools] protocol dependency "${protocolPayload?.id}" not found locally - skipping (see extractProtocolsProtocols.js)`)
31
+ continue
32
+ }
33
+
18
34
  //#TODO: protocol.loader
19
35
  const ownProtocols = await protocol.loader.ownProtocols()
20
36
  let a = (ownProtocols && ownProtocols.length) ? ownProtocols.map(adaptProtocolPayload) : null
@@ -37,8 +37,10 @@ export default (items) => {
37
37
  }
38
38
 
39
39
  const dedupeProtectedFields = (items) => {
40
- const a = items[0].protectedFields ? items[0].protectedFields : {}
41
- const b = items[1].protectedFields ? items[1].protectedFields : {}
40
+ const itemA = items[0] ? items[0] : {}
41
+ const itemB = items[1] ? items[1] : {}
42
+ const a = itemA.protectedFields ? itemA.protectedFields : {}
43
+ const b = itemB.protectedFields ? itemB.protectedFields : {}
42
44
  const aKeys = Object.keys(a)
43
45
  const bKeys = Object.keys(b)
44
46
 
@@ -23,6 +23,17 @@ export default async ({
23
23
  continue
24
24
  }
25
25
 
26
+ // Same missing-local-dependency case as extractProtocolsProtocols.js's own guard - a
27
+ // protocolPayload can name a protocol that protocolFactory() can't find on disk
28
+ // (protocolPath() resolves nowhere), returning null rather than throwing. perform() (passed
29
+ // in as extractProtocol) does `protocol.loader.isValid()` as its very first line with no
30
+ // null check, so this used to crash the whole build instead of just omitting the one
31
+ // missing protocol's contribution.
32
+ if (!protocol) {
33
+ console.warn(`[@servable/tools] protocol dependency "${protocolPayload?.id}" not found locally - skipping (see extractClassesProtocol.js)`)
34
+ continue
35
+ }
36
+
26
37
  const extractedProtocolStruct = await extractProtocol({
27
38
  protocolFactory,
28
39
  updateProtocolsExcerpt,
@@ -25,7 +25,24 @@ const perform = async ({
25
25
  return defaultResult
26
26
  }
27
27
 
28
- if (protocol.id === 'app') {
28
+ // `Servable.engine` is engine-specific bootstrap state - only present when a caller has gone
29
+ // through a real engine's createApp()/adaptApp() (the running server always has, at boot).
30
+ // This package is meant to stay engine-agnostic (an app's index.js is what chooses an engine,
31
+ // never servable.config.js or anything in @servable/tools itself), so this call is guarded
32
+ // rather than required - a caller with no engine configured (any @servable/cli `schema *`
33
+ // command needs only a minimal Servable.App stub to load class.js files, not a real engine
34
+ // bootstrap - see cli's own loadServableConfig.js) still gets a correct build.
35
+ //
36
+ // What's skipped: injecting the four framework-default classes (ServableApp/_User/_Session/
37
+ // _Role) if the app's own schema.json doesn't already define them. For an app that has ever
38
+ // completed a real server boot, it already does (confirmed live against backend/main's own
39
+ // app/schema.json - all four are already there, committed from a prior run of this exact
40
+ // injection), so skipping this call is a true no-op in that case. A brand-new app that has
41
+ // never booted once and has no local schema.json for these classes yet would see a smaller
42
+ // `classes` list from the CLI than the first real boot would produce - an acceptable gap
43
+ // given how rare that specific ordering is, not a silent one (this comment is the record of
44
+ // it).
45
+ if (protocol.id === 'app' && Servable.engine?.formatAppClassesSchemas) {
29
46
  await Servable.engine.formatAppClassesSchemas({ classesSchemas })
30
47
  }
31
48
 
@@ -0,0 +1,44 @@
1
+ // A single field's before/after classification. `before`/`after` are each either undefined (the
2
+ // field doesn't exist on that side) or a field-definition object like { type, targetClass,
3
+ // required, deprecated }.
4
+ export default ({ before, after }) => {
5
+ if (!before && after) {
6
+ return { kind: 'added', safe: true }
7
+ }
8
+
9
+ if (before && !after) {
10
+ // Removing a field is only ever safe to APPLY (not just to compute) when it was already
11
+ // marked deprecated on the side being removed from - contract.js is the one command allowed
12
+ // to act on that; plan always reports the removal, it just also says whether it was
13
+ // pre-deprecated so the caller (CI gate, contract command) can tell the two cases apart.
14
+ return {
15
+ kind: 'removed',
16
+ safe: false,
17
+ deprecated: Boolean(before.deprecated),
18
+ }
19
+ }
20
+
21
+ if (before.type !== after.type) {
22
+ return { kind: 'typeChanged', safe: false, from: before.type, to: after.type }
23
+ }
24
+
25
+ if (before.type === 'Pointer' && before.targetClass !== after.targetClass) {
26
+ return { kind: 'targetClassChanged', safe: false, from: before.targetClass, to: after.targetClass }
27
+ }
28
+
29
+ // A field newly becoming required is breaking for the same reason a dropped field is: an old
30
+ // pod's already-written objects (or its own in-flight writes, built without knowing the field
31
+ // is now mandatory) may not satisfy it. Required -> optional is the safe direction.
32
+ if (!before.required && after.required) {
33
+ return { kind: 'becameRequired', safe: false }
34
+ }
35
+
36
+ // A field newly marked deprecated is not a schema change at all from Parse's point of view -
37
+ // it's a note for `contract` to read later - so it's SAFE on its own. It only becomes
38
+ // consequential combined with an actual removal, handled above.
39
+ if (Boolean(before.deprecated) !== Boolean(after.deprecated)) {
40
+ return { kind: 'deprecationFlagChanged', safe: true }
41
+ }
42
+
43
+ return null
44
+ }
@@ -0,0 +1,105 @@
1
+ // unischema's plan/diff engine - see .docs/technical/unischema-plan.md decisions #2-#4.
2
+ //
3
+ // Compares two compiled artifacts (schema/artifact/index.js) - typically the previously
4
+ // committed servable.schema.json against a freshly-built one - and classifies every difference
5
+ // as SAFE (additive, applies automatically at boot) or BREAKING (never applied automatically;
6
+ // only `schema contract --allow-destructive` can act on it, and only when the thing being
7
+ // removed was already marked deprecated - see decision #1).
8
+ //
9
+ // This never touches a database. Both sides are just JSON, which is what makes the CI gate
10
+ // possible without one (decision #2) - `servable schema plan` diffs the artifact this commit
11
+ // would produce against the one the previous commit produced.
12
+ import classifyField from './classifyField.js'
13
+
14
+ const byClassName = (classes) => {
15
+ const map = new Map()
16
+ ;(classes || []).forEach(c => map.set(c.className, c))
17
+ return map
18
+ }
19
+
20
+ const diffClass = ({ before, after }) => {
21
+ const changes = []
22
+
23
+ if (!before && after) {
24
+ return [{ kind: 'classAdded', className: after.className, safe: true }]
25
+ }
26
+
27
+ if (before && !after) {
28
+ return [{ kind: 'classRemoved', className: before.className, safe: false, deprecated: false }]
29
+ }
30
+
31
+ const fieldNames = new Set([
32
+ ...Object.keys(before.fields || {}),
33
+ ...Object.keys(after.fields || {}),
34
+ ])
35
+
36
+ fieldNames.forEach(fieldName => {
37
+ const result = classifyField({
38
+ before: before.fields?.[fieldName],
39
+ after: after.fields?.[fieldName],
40
+ })
41
+ if (result) {
42
+ changes.push({ ...result, className: before.className, fieldName })
43
+ }
44
+ })
45
+
46
+ const indexNames = new Set([
47
+ ...Object.keys(before.indexes || {}),
48
+ ...Object.keys(after.indexes || {}),
49
+ ])
50
+ indexNames.forEach(indexName => {
51
+ const beforeIndex = before.indexes?.[indexName]
52
+ const afterIndex = after.indexes?.[indexName]
53
+ if (!beforeIndex && afterIndex) {
54
+ changes.push({ kind: 'indexAdded', safe: true, className: before.className, indexName })
55
+ } else if (beforeIndex && !afterIndex) {
56
+ // Dropping an index is safe in the sense that it can't corrupt data - but it can silently
57
+ // remove a uniqueness constraint or tank a query an old pod relies on, so it's treated as
58
+ // BREAKING like everything else that removes a guarantee a running pod might depend on.
59
+ changes.push({ kind: 'indexRemoved', safe: false, deprecated: false, className: before.className, indexName })
60
+ } else if (beforeIndex && afterIndex && JSON.stringify(beforeIndex) !== JSON.stringify(afterIndex)) {
61
+ changes.push({ kind: 'indexChanged', safe: false, deprecated: false, className: before.className, indexName })
62
+ }
63
+ })
64
+
65
+ // classLevelPermissions changes are reported but always SAFE: narrowing a CLP is an access
66
+ // decision, not a data-integrity one - it can't produce the "old pod can't read what's there"
67
+ // failure mode this whole plan/apply split exists to prevent. Flagged, not gated.
68
+ if (JSON.stringify(before.classLevelPermissions || {}) !== JSON.stringify(after.classLevelPermissions || {})) {
69
+ changes.push({ kind: 'classLevelPermissionsChanged', safe: true, className: before.className })
70
+ }
71
+
72
+ return changes
73
+ }
74
+
75
+ export const plan = ({ before, after }) => {
76
+ const beforeClasses = byClassName(before?.classes)
77
+ const afterClasses = byClassName(after?.classes)
78
+
79
+ const allClassNames = new Set([...beforeClasses.keys(), ...afterClasses.keys()])
80
+
81
+ let changes = []
82
+ allClassNames.forEach(className => {
83
+ changes = changes.concat(diffClass({
84
+ before: beforeClasses.get(className),
85
+ after: afterClasses.get(className),
86
+ }))
87
+ })
88
+
89
+ const safe = changes.filter(c => c.safe)
90
+ const breaking = changes.filter(c => !c.safe && !c.deprecated)
91
+ const breakingDeprecated = changes.filter(c => !c.safe && c.deprecated)
92
+
93
+ return {
94
+ hashChanged: before?.hash !== after?.hash,
95
+ safe,
96
+ breaking,
97
+ breakingDeprecated,
98
+ // A plan is clean to auto-apply only when nothing breaking (deprecated or not) is present -
99
+ // `contract` is a separate, explicit command even for the deprecated-and-therefore-eligible
100
+ // case (decision #1: never automatic, always a deliberate act).
101
+ hasBreakingChanges: breaking.length > 0 || breakingDeprecated.length > 0,
102
+ }
103
+ }
104
+
105
+ export default plan