@fgv/ts-json 2.1.0 → 2.1.1-alpha.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.
@@ -5,7 +5,7 @@
5
5
  "toolPackages": [
6
6
  {
7
7
  "packageName": "@microsoft/api-extractor",
8
- "packageVersion": "7.38.1"
8
+ "packageVersion": "7.39.1"
9
9
  }
10
10
  ]
11
11
  }
@@ -1 +1 @@
1
- {"version":3,"file":"compositeJsonMap.js","sourceRoot":"","sources":["../../../src/packlets/context/compositeJsonMap.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;;;;;;GAoBG;;;AAEH,4CAAyG;AACzG,kCAA8D;AAG9D;;;;GAIG;AACH,MAAa,gBAAgB;IAO3B;;;;;OAKG;IACH,YAAsB,IAAyB;QAC7C,IAAI,CAAC,KAAK,GAAG,IAAI,CAAC;IACpB,CAAC;IAED;;;;OAIG;IACI,MAAM,CAAC,MAAM,CAAC,IAAyB;QAC5C,OAAO,IAAA,wBAAa,EAAC,GAAG,EAAE,CAAC,IAAI,gBAAgB,CAAC,IAAI,CAAC,CAAC,CAAC;IACzD,CAAC;IAED;;;;;OAKG;IACI,YAAY,CAAC,GAAW;QAC7B,OAAO,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC,GAAG,EAAE,EAAE,CAAC,GAAG,CAAC,YAAY,CAAC,GAAG,CAAC,CAAC,KAAK,SAAS,CAAC;IACvE,CAAC;IAED;;;;OAIG;IACI,GAAG,CAAC,GAAW;QACpB,OAAO,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC,GAAG,EAAE,EAAE,CAAC,GAAG,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC,KAAK,SAAS,CAAC;IAC9D,CAAC;IAED;;;;;;;OAOG;IACI,aAAa,CAClB,GAAW,EACX,OAAsB;QAEtB,OAAO,IAAI,CAAC,YAAY,CAAC,GAAG,EAAE,OAAO,CAAC,CAAC,SAAS,CAAC,CAAC,EAAE,EAAE,EAAE;YACtD,IAAI,CAAC,IAAA,mBAAY,EAAC,EAAE,CAAC,EAAE;gBACrB,OAAO,IAAA,yBAAc,EAAC,GAAG,GAAG,iBAAiB,EAAE,OAAO,CAAC,CAAC;aACzD;YACD,OAAO,IAAA,4BAAiB,EAAC,EAAE,CAAC,CAAC;QAC/B,CAAC,CAAC,CAAC;IACL,CAAC;IAED;;;;;;;OAOG;IACH,gDAAgD;IACzC,YAAY,CACjB,GAAW,EACX,OAAsB;QAEtB,KAAK,MAAM,GAAG,IAAI,IAAI,CAAC,KAAK,EAAE;YAC5B,IAAI,GAAG,CAAC,YAAY,CAAC,GAAG,CAAC,EAAE;gBACzB,MAAM,MAAM,GAAG,GAAG,CAAC,YAAY,CAAC,GAAG,EAAE,OAAO,CAAC,CAAC;gBAC9C,IAAI,MAAM,CAAC,SAAS,EAAE,IAAI,MAAM,CAAC,MAAM,KAAK,OAAO,EAAE;oBACnD,OAAO,MAAM,CAAC;iBACf;aACF;SACF;QACD,OAAO,IAAA,yBAAc,EAAC,GAAG,GAAG,mBAAmB,EAAE,SAAS,CAAC,CAAC;IAC9D,CAAC;CACF;AAxFD,4CAwFC","sourcesContent":["/*\n * Copyright (c) 2020 Erik Fortune\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n */\n\nimport { DetailedResult, Result, captureResult, failWithDetail, succeedWithDetail } from '@fgv/ts-utils';\nimport { JsonObject, JsonValue, isJsonObject } from '../json';\nimport { IJsonContext, IJsonReferenceMap, JsonReferenceMapFailureReason } from './jsonContext';\n\n/**\n * A {@link CompositeJsonMap | CompositeJsonMap} presents a composed view of one or more other\n * {@link IJsonReferenceMap | JSON reference maps}.\n * @public\n */\nexport class CompositeJsonMap implements IJsonReferenceMap {\n /**\n * The {@link IJsonReferenceMap | reference maps} from which this map is composed.\n * @internal\n */\n protected _maps: IJsonReferenceMap[];\n\n /**\n * The {@link IJsonReferenceMap | reference maps} from which this map is to be composed.\n * @param maps - An array o {@link IJsonReferenceMap | IJsonReferenceMap} containing the maps\n * from which this map is to be composed.\n * @internal\n */\n protected constructor(maps: IJsonReferenceMap[]) {\n this._maps = maps;\n }\n\n /**\n * Creates a new {@link CompositeJsonMap | CompositeJsonMap} from supplied\n * {@link IJsonReferenceMap | maps}.\n * @param maps - one or more {@link IJsonReferenceMap | object maps} to be composed.\n */\n public static create(maps: IJsonReferenceMap[]): Result<CompositeJsonMap> {\n return captureResult(() => new CompositeJsonMap(maps));\n }\n\n /**\n * Determine if a key might be valid for this map but does not determine\n * if key actually exists. Allows key range to be constrained.\n * @param key - The key to be tested.\n * @returns `true` if the key is in the valid range, `false` otherwise.\n */\n public keyIsInRange(key: string): boolean {\n return this._maps.find((map) => map.keyIsInRange(key)) !== undefined;\n }\n\n /**\n * Determines if an object with the specified key actually exists in the map.\n * @param key - The key to be tested.\n * @returns `true` if an object with the specified key exists, `false` otherwise.\n */\n public has(key: string): boolean {\n return this._maps.find((map) => map.has(key)) !== undefined;\n }\n\n /**\n * Gets a {@link JsonObject | JSON object} specified by key.\n * @param key - The key of the object to be retrieved.\n * @param context - An optional {@link IJsonContext | JSON Context} used to format the object.\n * @returns `Success` with the formatted object if successful. `Failure` with detail `'unknown'`\n * if no such object exists, or `Failure` with detail `'error'` if the object was found but\n * could not be formatted.\n */\n public getJsonObject(\n key: string,\n context?: IJsonContext\n ): DetailedResult<JsonObject, JsonReferenceMapFailureReason> {\n return this.getJsonValue(key, context).onSuccess((jv) => {\n if (!isJsonObject(jv)) {\n return failWithDetail(`${key}: not an object`, 'error');\n }\n return succeedWithDetail(jv);\n });\n }\n\n /**\n * Gets a {@link JsonValue | JSON value} specified by key.\n * @param key - The key of the object to be retrieved.\n * @param context - An optional {@link IJsonContext | JSON Context} used to format the value.\n * @returns `Success` with the formatted object if successful. `Failure` with detail `'unknown'`\n * if no such object exists, or failure with detail `'error'` if the object was found but\n * could not be formatted.\n */\n // eslint-disable-next-line no-use-before-define\n public getJsonValue(\n key: string,\n context?: IJsonContext\n ): DetailedResult<JsonValue, JsonReferenceMapFailureReason> {\n for (const map of this._maps) {\n if (map.keyIsInRange(key)) {\n const result = map.getJsonValue(key, context);\n if (result.isSuccess() || result.detail === 'error') {\n return result;\n }\n }\n }\n return failWithDetail(`${key}: value not found`, 'unknown');\n }\n}\n"]}
1
+ {"version":3,"file":"compositeJsonMap.js","sourceRoot":"","sources":["../../../src/packlets/context/compositeJsonMap.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;;;;;;GAoBG;;;AAEH,4CAAyG;AACzG,kCAA8D;AAG9D;;;;GAIG;AACH,MAAa,gBAAgB;IAO3B;;;;;OAKG;IACH,YAAsB,IAAyB;QAC7C,IAAI,CAAC,KAAK,GAAG,IAAI,CAAC;IACpB,CAAC;IAED;;;;OAIG;IACI,MAAM,CAAC,MAAM,CAAC,IAAyB;QAC5C,OAAO,IAAA,wBAAa,EAAC,GAAG,EAAE,CAAC,IAAI,gBAAgB,CAAC,IAAI,CAAC,CAAC,CAAC;IACzD,CAAC;IA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AAmB,EAAE,SAAS,CAAC,CAAC;IAC9D,CAAC;CACF;AAxFD,4CAwFC","sourcesContent":["/*\n * Copyright (c) 2020 Erik Fortune\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n */\n\nimport { DetailedResult, Result, captureResult, failWithDetail, succeedWithDetail } from '@fgv/ts-utils';\nimport { JsonObject, JsonValue, isJsonObject } from '../json';\nimport { IJsonContext, IJsonReferenceMap, JsonReferenceMapFailureReason } from './jsonContext';\n\n/**\n * A {@link CompositeJsonMap | CompositeJsonMap} presents a composed view of one or more other\n * {@link IJsonReferenceMap | JSON reference maps}.\n * @public\n */\nexport class CompositeJsonMap implements IJsonReferenceMap {\n /**\n * The {@link IJsonReferenceMap | reference maps} from which this map is composed.\n * @internal\n */\n protected _maps: IJsonReferenceMap[];\n\n /**\n * The {@link IJsonReferenceMap | reference maps} from which this map is to be composed.\n * @param maps - An array o {@link IJsonReferenceMap | IJsonReferenceMap} containing the maps\n * from which this map is to be composed.\n * @internal\n */\n protected constructor(maps: IJsonReferenceMap[]) {\n this._maps = maps;\n }\n\n /**\n * Creates a new {@link CompositeJsonMap | CompositeJsonMap} from supplied\n * {@link IJsonReferenceMap | maps}.\n * @param maps - one or more {@link IJsonReferenceMap | object maps} to be composed.\n */\n public static create(maps: IJsonReferenceMap[]): Result<CompositeJsonMap> {\n return captureResult(() => new CompositeJsonMap(maps));\n }\n\n /**\n * Determine if a key might be valid for this map but does not determine\n * if key actually exists. Allows key range to be constrained.\n * @param key - The key to be tested.\n * @returns `true` if the key is in the valid range, `false` otherwise.\n */\n public keyIsInRange(key: string): boolean {\n return this._maps.find((map) => map.keyIsInRange(key)) !== undefined;\n }\n\n /**\n * Determines if an object with the specified key actually exists in the map.\n * @param key - The key to be tested.\n * @returns `true` if an object with the specified key exists, `false` otherwise.\n */\n public has(key: string): boolean {\n return this._maps.find((map) => map.has(key)) !== undefined;\n }\n\n /**\n * Gets a {@link JsonObject | JSON object} specified by key.\n * @param key - The key of the object to be retrieved.\n * @param context - An optional {@link IJsonContext | JSON Context} used to format the object.\n * @returns `Success` with the formatted object if successful. `Failure` with detail `'unknown'`\n * if no such object exists, or `Failure` with detail `'error'` if the object was found but\n * could not be formatted.\n */\n public getJsonObject(\n key: string,\n context?: IJsonContext\n ): DetailedResult<JsonObject, JsonReferenceMapFailureReason> {\n return this.getJsonValue(key, context).onSuccess((jv) => {\n if (!isJsonObject(jv)) {\n return failWithDetail(`${key}: not an object`, 'error');\n }\n return succeedWithDetail(jv);\n });\n }\n\n /**\n * Gets a {@link JsonValue | JSON value} specified by key.\n * @param key - The key of the object to be retrieved.\n * @param context - An optional {@link IJsonContext | JSON Context} used to format the value.\n * @returns `Success` with the formatted object if successful. `Failure` with detail `'unknown'`\n * if no such object exists, or failure with detail `'error'` if the object was found but\n * could not be formatted.\n */\n // eslint-disable-next-line no-use-before-define\n public getJsonValue(\n key: string,\n context?: IJsonContext\n ): DetailedResult<JsonValue, JsonReferenceMapFailureReason> {\n for (const map of this._maps) {\n if (map.keyIsInRange(key)) {\n const result = map.getJsonValue(key, context);\n if (result.isSuccess() || result.detail === 'error') {\n return result;\n }\n }\n }\n return failWithDetail(`${key}: value not found`, 'unknown');\n }\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"contextHelpers.js","sourceRoot":"","sources":["../../../src/packlets/context/contextHelpers.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;;;;;;GAoBG;;;AAEH,4CAA+D;AAC/D,yDAAsD;AACtD,+CAMuB;AAEvB;;;GAGG;AACH,MAAa,iBAAiB;IAO5B;;;;OAIG;IACH,YAAmB,OAAsB;QACvC,IAAI,CAAC,QAAQ,GAAG,OAAO,CAAC;IAC1B,CAAC;IAED;;;;;;OAMG;IACI,MAAM,CAAC,MAAM,CAAC,OAAsB;QACzC,OAAO,IAAA,wBAAa,EAAC,GAAG,EAAE,CAAC,IAAI,iBAAiB,CAAC,OAAO,CAAC,CAAC,CAAC;IAC7D,CAAC;IAED;;;;;;;;;OASG;IACI,MAAM,CAAC,iBAAiB,CAC7B,WAAqC,EACrC,IAAsB;;QAEtB,IAAI,IAAI,IAAI,IAAI,CAAC,MAAM,GAAG,CAAC,EAAE;YAC3B,MAAM,MAAM,GAAG,MAAA,WAAW,aAAX,WAAW,uBAAX,WAAW,CAAE,UAAU,mCAAI,+BAAiB,CAAC;YAC5D,OAAO,MAAM,CAAC,MAAA,WAAW,aAAX,WAAW,uBAAX,WAAW,CAAE,IAAI,mCAAI,EAAE,EAAE,IAAI,CAAC,CAAC;SAC9C;QACD,OAAO,IAAA,kBAAO,EAAC,WAAW,aAAX,WAAW,uBAAX,WAAW,CAAE,IAAI,CAAC,CAAC;IACpC,CAAC;IAED;;;;;;;;;OASG;IACI,MAAM,CAAC,iBAAiB,CAC7B,WAAqC,EACrC,IAA0B;QAE1B,IAAI,IAAI,IAAI,IAAI,CAAC,MAAM,GAAG,CAAC,EAAE;YAC3B,MAAM,IAAI,GAAG,CAAA,WAAW,aAAX,WAAW,uBAAX,WAAW,CA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AC,QAAQ,EAAE,KAAK,CAAC,CAAC;IAC9D,CAAC;CACF;AAxLD,8CAwLC","sourcesContent":["/*\n * Copyright (c) 2020 Erik Fortune\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n */\n\nimport { Result, captureResult, succeed } from '@fgv/ts-utils';\nimport { CompositeJsonMap } from './compositeJsonMap';\nimport {\n IJsonContext,\n IJsonReferenceMap,\n TemplateVars,\n VariableValue,\n defaultExtendVars\n} from './jsonContext';\n\n/**\n * Helper class for working with {@link IJsonContext | IJsonContext} objects.\n * @public\n */\nexport class JsonContextHelper {\n /**\n * The base {@link IJsonContext | context} on which we are operating.\n * @internal\n */\n protected _context?: IJsonContext;\n\n /**\n * Constructs a new {@link JsonContextHelper | JsonContextHelper}.\n * @param context - The base {@link IJsonContext | IJsonContext} on\n * which to operate.\n */\n public constructor(context?: IJsonContext) {\n this._context = context;\n }\n\n /**\n * Creates a new {@link IJsonContext | context}.\n * @param context - The base {@link IJsonContext | IJsonContext} on\n * which to operate.\n * @returns `Success` with the new {@link IJsonContext | IJsonContext},\n * or `Failure` with more information if an error occurs.\n */\n public static create(context?: IJsonContext): Result<JsonContextHelper> {\n return captureResult(() => new JsonContextHelper(context));\n }\n\n /**\n * Static helper to extend context variables for a supplied {@link IJsonContext | IJsonContext}.\n * @param baseContext - The {@link IJsonContext | IJsonContext} to be extended, or `undefined`\n * to start from an empty context.\n * @param vars - Optional {@link VariableValue | variable values} to be added to the\n * {@link IJsonContext | context}.\n * @returns `Success` with a new {@link TemplateVars | TemplateVars} containing the variables\n * from the base context, merged with and overridden by any that were passed in, or `Failure`\n * with a message if an error occurs.\n */\n public static extendContextVars(\n baseContext: IJsonContext | undefined,\n vars?: VariableValue[]\n ): Result<TemplateVars | undefined> {\n if (vars && vars.length > 0) {\n const extend = baseContext?.extendVars ?? defaultExtendVars;\n return extend(baseContext?.vars ?? {}, vars);\n }\n return succeed(baseContext?.vars);\n }\n\n /**\n * Static helper to extend context references for a supplied {@link IJsonContext | IJsonContext}.\n * @param baseContext - The {@link IJsonContext | IJsonContext} to be extended, or `undefined`\n * to start from an empty context.\n * @param refs - Optional {@link IJsonReferenceMap | reference maps} to be added to the\n * {@link IJsonContext | context}.\n * @returns `Success` with a new {@link IJsonReferenceMap | reference map} which projects\n * the references from the base context, merged with and overridden by any that were passed in,\n * or `Failure` with a message if an error occurs.\n */\n public static extendContextRefs(\n baseContext: IJsonContext | undefined,\n refs?: IJsonReferenceMap[]\n ): Result<IJsonReferenceMap | undefined> {\n if (refs && refs.length > 0) {\n const full = baseContext?.refs ? [...refs, baseContext.refs] : refs;\n if (full.length > 1) {\n return CompositeJsonMap.create(full);\n }\n return succeed(full[0]);\n }\n return succeed(baseContext?.refs);\n }\n\n /**\n * Static helper to extend context variables and references for a supplied {@link IJsonContext | IJsonContext}.\n * @param baseContext - The {@link IJsonContext | IJsonContext} to be extended, or `undefined`\n * to start from an empty context.\n * @param add - Optional initializer containing {@link VariableValue | variable values} and/or\n * {@link IJsonReferenceMap | reference maps} to be added to the {@link IJsonContext | context}.\n * @returns `Success` with a new {@link IJsonContext | IJsonContext} containing the variables and\n * references from the base context, merged with and overridden by any that were passed in, or\n * `Failure` with a message if an error occurs.\n */\n public static extendContext(\n baseContext?: IJsonContext | undefined,\n add?: { vars?: VariableValue[]; refs?: IJsonReferenceMap[] }\n ): Result<IJsonContext | undefined> {\n return JsonContextHelper.extendContextVars(baseContext, add?.vars || []).onSuccess((vars) => {\n return JsonContextHelper.extendContextRefs(baseContext, add?.refs || []).onSuccess((refs) => {\n if (!vars && !refs && !baseContext?.extendVars) {\n return succeed(undefined);\n }\n const rtrn: IJsonContext = { vars, refs };\n if (baseContext?.extendVars) {\n rtrn.extendVars = baseContext.extendVars;\n }\n return succeed(rtrn);\n });\n });\n }\n\n /**\n * Static helper to merge context variables and references for a supplied {@link IJsonContext | IJsonContext}.\n * @param baseContext - The {@link IJsonContext | IJsonContext} into which variables and references\n * are to be merged, or `undefined` to start from an empty context.\n * @param add - Optional initializer containing {@link VariableValue | variable values} and/or\n * {@link IJsonReferenceMap | reference maps} to be added to the {@link IJsonContext | context}.\n * @returns `Success` with a new {@link IJsonContext | IJsonContext} containing the variables and\n * references from the base context, merged with and overridden by any that were passed in, or\n * `Failure` with a message if an error occurs.\n */\n public static mergeContext(\n baseContext: IJsonContext | undefined,\n add: IJsonContext | undefined\n ): Result<IJsonContext | undefined> {\n if (baseContext) {\n if (add) {\n const rtrn: IJsonContext = {\n vars: add.vars ?? baseContext.vars,\n refs: add.refs ?? baseContext.refs\n };\n if (add.hasOwnProperty('extendVars')) {\n rtrn.extendVars = add.extendVars;\n } else if (baseContext.hasOwnProperty('extendVars')) {\n rtrn.extendVars = baseContext.extendVars;\n }\n return succeed(rtrn);\n }\n return succeed(baseContext);\n }\n return succeed(add);\n }\n\n /**\n * Applies {@link JsonContextHelper.extendContextVars | extendContextVars} to the\n * {@link IJsonContext | IJsonContext} associated with this helper.\n * @param vars - Optional {@link VariableValue | variable values} to be added to the\n * @returns `Success` with a new {@link TemplateVars | TemplateVars} containing the variables\n * from the base context, merged with and overridden by any that were passed in, or `Failure`\n * with a message if an error occurs.\n */\n public extendVars(vars?: VariableValue[]): Result<TemplateVars | undefined> {\n return JsonContextHelper.extendContextVars(this._context, vars);\n }\n\n /**\n * Applies {@link JsonContextHelper.extendContextRefs | extendContextRefs} to the\n * {@link IJsonContext | IJsonContext} associated with this helper.\n * @param refs - Optional {@link IJsonReferenceMap | reference maps} to be added to the\n * @returns `Success` with a new {@link IJsonReferenceMap | reference map} which projects\n * the references from the base context, merged with and overridden by any that were passed in,\n * or `Failure` with a message if an error occurs.\n */\n public extendRefs(refs?: IJsonReferenceMap[]): Result<IJsonReferenceMap | undefined> {\n return JsonContextHelper.extendContextRefs(this._context, refs);\n }\n\n /**\n * Applies {@link JsonContextHelper.(extendContext:static) | extendContext} to the\n * {@link IJsonContext | IJsonContext} associated with this helper.\n * @param add - Optional initializer containing {@link VariableValue | variable values} and/or\n * {@link IJsonReferenceMap | reference maps} to be added to the {@link IJsonContext | context}.\n * @returns `Success` with a new {@link IJsonContext | IJsonContext} containing the variables and\n * references from the base context, merged with and overridden by any that were passed in, or\n * `Failure` with a message if an error occurs.\n */\n public extendContext(add?: {\n vars?: VariableValue[];\n refs?: IJsonReferenceMap[];\n }): Result<IJsonContext | undefined> {\n return JsonContextHelper.extendContext(this._context, add);\n }\n\n /**\n * Applies {@link JsonContextHelper.(mergeContext:static) | mergeContext} to the\n * {@link IJsonContext | IJsonContext} associated with this helper.\n * @param add - Optional initializer containing {@link VariableValue | variable values} and/or\n * {@link IJsonReferenceMap | reference maps} to be added to the {@link IJsonContext | context}.\n * @returns `Success` with a new {@link IJsonContext | IJsonContext} containing the variables and\n * references from the base context, merged with and overridden by any that were passed in, or\n * `Failure` with a message if an error occurs.\n */\n public mergeContext(merge?: IJsonContext): Result<IJsonContext | undefined> {\n return JsonContextHelper.mergeContext(this._context, merge);\n }\n}\n"]}
1
+ {"version":3,"file":"contextHelpers.js","sourceRoot":"","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8CAwLC","sourcesContent":["/*\n * Copyright (c) 2020 Erik Fortune\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n */\n\nimport { Result, captureResult, succeed } from '@fgv/ts-utils';\nimport { CompositeJsonMap } from './compositeJsonMap';\nimport {\n IJsonContext,\n IJsonReferenceMap,\n TemplateVars,\n VariableValue,\n defaultExtendVars\n} from './jsonContext';\n\n/**\n * Helper class for working with {@link IJsonContext | IJsonContext} objects.\n * @public\n */\nexport class JsonContextHelper {\n /**\n * The base {@link IJsonContext | context} on which we are operating.\n * @internal\n */\n protected _context?: IJsonContext;\n\n /**\n * Constructs a new {@link JsonContextHelper | JsonContextHelper}.\n * @param context - The base {@link IJsonContext | IJsonContext} on\n * which to operate.\n */\n public constructor(context?: IJsonContext) {\n this._context = context;\n }\n\n /**\n * Creates a new {@link IJsonContext | context}.\n * @param context - The base {@link IJsonContext | IJsonContext} on\n * which to operate.\n * @returns `Success` with the new {@link IJsonContext | IJsonContext},\n * or `Failure` with more information if an error occurs.\n */\n public static create(context?: IJsonContext): Result<JsonContextHelper> {\n return captureResult(() => new JsonContextHelper(context));\n }\n\n /**\n * Static helper to extend context variables for a supplied {@link IJsonContext | IJsonContext}.\n * @param baseContext - The {@link IJsonContext | IJsonContext} to be extended, or `undefined`\n * to start from an empty context.\n * @param vars - Optional {@link VariableValue | variable values} to be added to the\n * {@link IJsonContext | context}.\n * @returns `Success` with a new {@link TemplateVars | TemplateVars} containing the variables\n * from the base context, merged with and overridden by any that were passed in, or `Failure`\n * with a message if an error occurs.\n */\n public static extendContextVars(\n baseContext: IJsonContext | undefined,\n vars?: VariableValue[]\n ): Result<TemplateVars | undefined> {\n if (vars && vars.length > 0) {\n const extend = baseContext?.extendVars ?? defaultExtendVars;\n return extend(baseContext?.vars ?? {}, vars);\n }\n return succeed(baseContext?.vars);\n }\n\n /**\n * Static helper to extend context references for a supplied {@link IJsonContext | IJsonContext}.\n * @param baseContext - The {@link IJsonContext | IJsonContext} to be extended, or `undefined`\n * to start from an empty context.\n * @param refs - Optional {@link IJsonReferenceMap | reference maps} to be added to the\n * {@link IJsonContext | context}.\n * @returns `Success` with a new {@link IJsonReferenceMap | reference map} which projects\n * the references from the base context, merged with and overridden by any that were passed in,\n * or `Failure` with a message if an error occurs.\n */\n public static extendContextRefs(\n baseContext: IJsonContext | undefined,\n refs?: IJsonReferenceMap[]\n ): Result<IJsonReferenceMap | undefined> {\n if (refs && refs.length > 0) {\n const full = baseContext?.refs ? [...refs, baseContext.refs] : refs;\n if (full.length > 1) {\n return CompositeJsonMap.create(full);\n }\n return succeed(full[0]);\n }\n return succeed(baseContext?.refs);\n }\n\n /**\n * Static helper to extend context variables and references for a supplied {@link IJsonContext | IJsonContext}.\n * @param baseContext - The {@link IJsonContext | IJsonContext} to be extended, or `undefined`\n * to start from an empty context.\n * @param add - Optional initializer containing {@link VariableValue | variable values} and/or\n * {@link IJsonReferenceMap | reference maps} to be added to the {@link IJsonContext | context}.\n * @returns `Success` with a new {@link IJsonContext | IJsonContext} containing the variables and\n * references from the base context, merged with and overridden by any that were passed in, or\n * `Failure` with a message if an error occurs.\n */\n public static extendContext(\n baseContext?: IJsonContext | undefined,\n add?: { vars?: VariableValue[]; refs?: IJsonReferenceMap[] }\n ): Result<IJsonContext | undefined> {\n return JsonContextHelper.extendContextVars(baseContext, add?.vars || []).onSuccess((vars) => {\n return JsonContextHelper.extendContextRefs(baseContext, add?.refs || []).onSuccess((refs) => {\n if (!vars && !refs && !baseContext?.extendVars) {\n return succeed(undefined);\n }\n const rtrn: IJsonContext = { vars, refs };\n if (baseContext?.extendVars) {\n rtrn.extendVars = baseContext.extendVars;\n }\n return succeed(rtrn);\n });\n });\n }\n\n /**\n * Static helper to merge context variables and references for a supplied {@link IJsonContext | IJsonContext}.\n * @param baseContext - The {@link IJsonContext | IJsonContext} into which variables and references\n * are to be merged, or `undefined` to start from an empty context.\n * @param add - Optional initializer containing {@link VariableValue | variable values} and/or\n * {@link IJsonReferenceMap | reference maps} to be added to the {@link IJsonContext | context}.\n * @returns `Success` with a new {@link IJsonContext | IJsonContext} containing the variables and\n * references from the base context, merged with and overridden by any that were passed in, or\n * `Failure` with a message if an error occurs.\n */\n public static mergeContext(\n baseContext: IJsonContext | undefined,\n add: IJsonContext | undefined\n ): Result<IJsonContext | undefined> {\n if (baseContext) {\n if (add) {\n const rtrn: IJsonContext = {\n vars: add.vars ?? baseContext.vars,\n refs: add.refs ?? baseContext.refs\n };\n if (add.hasOwnProperty('extendVars')) {\n rtrn.extendVars = add.extendVars;\n } else if (baseContext.hasOwnProperty('extendVars')) {\n rtrn.extendVars = baseContext.extendVars;\n }\n return succeed(rtrn);\n }\n return succeed(baseContext);\n }\n return succeed(add);\n }\n\n /**\n * Applies {@link JsonContextHelper.extendContextVars | extendContextVars} to the\n * {@link IJsonContext | IJsonContext} associated with this helper.\n * @param vars - Optional {@link VariableValue | variable values} to be added to the\n * @returns `Success` with a new {@link TemplateVars | TemplateVars} containing the variables\n * from the base context, merged with and overridden by any that were passed in, or `Failure`\n * with a message if an error occurs.\n */\n public extendVars(vars?: VariableValue[]): Result<TemplateVars | undefined> {\n return JsonContextHelper.extendContextVars(this._context, vars);\n }\n\n /**\n * Applies {@link JsonContextHelper.extendContextRefs | extendContextRefs} to the\n * {@link IJsonContext | IJsonContext} associated with this helper.\n * @param refs - Optional {@link IJsonReferenceMap | reference maps} to be added to the\n * @returns `Success` with a new {@link IJsonReferenceMap | reference map} which projects\n * the references from the base context, merged with and overridden by any that were passed in,\n * or `Failure` with a message if an error occurs.\n */\n public extendRefs(refs?: IJsonReferenceMap[]): Result<IJsonReferenceMap | undefined> {\n return JsonContextHelper.extendContextRefs(this._context, refs);\n }\n\n /**\n * Applies {@link JsonContextHelper.(extendContext:static) | extendContext} to the\n * {@link IJsonContext | IJsonContext} associated with this helper.\n * @param add - Optional initializer containing {@link VariableValue | variable values} and/or\n * {@link IJsonReferenceMap | reference maps} to be added to the {@link IJsonContext | context}.\n * @returns `Success` with a new {@link IJsonContext | IJsonContext} containing the variables and\n * references from the base context, merged with and overridden by any that were passed in, or\n * `Failure` with a message if an error occurs.\n */\n public extendContext(add?: {\n vars?: VariableValue[];\n refs?: IJsonReferenceMap[];\n }): Result<IJsonContext | undefined> {\n return JsonContextHelper.extendContext(this._context, add);\n }\n\n /**\n * Applies {@link JsonContextHelper.(mergeContext:static) | mergeContext} to the\n * {@link IJsonContext | IJsonContext} associated with this helper.\n * @param add - Optional initializer containing {@link VariableValue | variable values} and/or\n * {@link IJsonReferenceMap | reference maps} to be added to the {@link IJsonContext | context}.\n * @returns `Success` with a new {@link IJsonContext | IJsonContext} containing the variables and\n * references from the base context, merged with and overridden by any that were passed in, or\n * `Failure` with a message if an error occurs.\n */\n public mergeContext(merge?: IJsonContext): Result<IJsonContext | undefined> {\n return JsonContextHelper.mergeContext(this._context, merge);\n }\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"jsonContext.js","sourceRoot":"","sources":["../../../src/packlets/context/jsonContext.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;;;;;;GAoBG;;;AAEH,4CAAgE;AA2BhE;;;;;;GAMG;AACH,SAAgB,iBAAiB,CAC/B,IAA8B,EAC9B,MAAuB;IAEvB,MAAM,IAAI,GAAG,IAAI,CAAC,CAAC,CAAC,MAAM,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC;IAC7C,KAAK,MAAM,CAAC,IAAI,MAAM,EAAE;QACtB,IAAI,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC;KACnB;IACD,OAAO,IAAA,kBAAO,EAAC,IAAI,CAAC,CAAC;AACvB,CAAC;AATD,8CASC","sourcesContent":["/*\n * Copyright (c) 2020 Erik Fortune\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n */\n\nimport { DetailedResult, Result, succeed } from '@fgv/ts-utils';\nimport { JsonObject, JsonValue } from '../json';\n\n/**\n * Collection of variables used for template replacement in a JSON edit or\n * conversion.\n * @public\n */\nexport type TemplateVars = Record<string, unknown>;\n\n/**\n * Describes one value in a {@link TemplateVars | TemplateVars} collection of\n * variables.\n * @public\n */\nexport type VariableValue = [string, unknown];\n\n/**\n * Function used to create a new collection of {@link TemplateVars | TemplateVars} with\n * one or more new or changed values.\n * @public\n */\nexport type TemplateVarsExtendFunction = (\n base: TemplateVars | undefined,\n values: VariableValue[]\n) => Result<TemplateVars | undefined>;\n\n/**\n * This default implementation of a {@link TemplateVarsExtendFunction | TemplateVarsExtendFunction}\n * creates a new collection via inheritance from the supplied collection.\n * @param base - The base {@link TemplateVars | variables} to be extended.\n * @param values - The {@link VariableValue | values} to be added or overridden in the new variables.\n * @public\n */\nexport function defaultExtendVars(\n base: TemplateVars | undefined,\n values: VariableValue[]\n): Result<TemplateVars | undefined> {\n const rtrn = base ? Object.create(base) : {};\n for (const v of values) {\n rtrn[v[0]] = v[1];\n }\n return succeed(rtrn);\n}\n\n/**\n * Failure reason for {@link IJsonReferenceMap | IJsonReferenceMap} lookup, where `'unknown'`\n * means that the object is not present in the map and `'error'` means\n * that an error occurred while retrieving or converting it.\n * @public\n */\nexport type JsonReferenceMapFailureReason = 'unknown' | 'error';\n\n/**\n * Interface for a simple map that returns named {@link JsonValue | JsonValue} values with templating,\n * conditional logic, and external reference lookups applied using an optionally supplied context.\n * @public\n */\nexport interface IJsonReferenceMap {\n /**\n * Determine if a key might be valid for this map but does not determine if key actually\n * exists. Allows key range to be constrained.\n * @param key - The key to be tested.\n * @returns `true` if the key is in the valid range, `false` otherwise.\n */\n keyIsInRange(key: string): boolean;\n\n /**\n * Determines if an object with the specified key actually exists in the map.\n * @param key - The key to be tested.\n * @returns `true` if an object with the specified key exists, `false` otherwise.\n */\n has(key: string): boolean;\n\n /**\n * Gets a {@link JsonObject | JsonObject} specified by key.\n * @param key - The key of the object to be retrieved.\n * @param context - Optional {@link IJsonContext | IJsonContext} used to construct\n * the object.\n * @returns `Success` with the formatted {@link JsonObject | object} if successful. `Failure`\n * with detail `'unknown'` if no such object exists, or `Failure` with detail `'error'` if\n * the object was found but could not be formatted.\n */\n // eslint-disable-next-line no-use-before-define\n getJsonObject(\n key: string,\n context?: IJsonContext\n ): DetailedResult<JsonObject, JsonReferenceMapFailureReason>;\n\n /**\n * Gets a {@link JsonValue | JsonValue} specified by key.\n * @param key - The key of the object to be retrieved.\n * @param context - Optional {@link IJsonContext | JSON Context} used to format the value\n * @returns `Success` with the formatted {@link JsonValue | value} if successful. `Failure`\n * with detail `'unknown'` if no such object exists, or `Failure` with detail `'error'` if\n * the object was found but could not be formatted.\n */\n // eslint-disable-next-line no-use-before-define\n getJsonValue(key: string, context?: IJsonContext): DetailedResult<JsonValue, JsonReferenceMapFailureReason>;\n}\n\n/**\n * Context used to convert or edit JSON objects.\n * @public\n */\nexport interface IJsonContext {\n vars?: TemplateVars;\n refs?: IJsonReferenceMap;\n extendVars?: TemplateVarsExtendFunction;\n}\n"]}
1
+ {"version":3,"file":"jsonContext.js","sourceRoot":"","sources":["../../../src/packlets/context/jsonContext.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;;;;;;GAoBG;;;AAEH,4CAAgE;AA2BhE;;;;;;GAMG;AACH,SAAgB,iBAAiB,CAC/B,IAA8B,EAC9B,MAAuB;IAEvB,MAAM,IAAI,GAAG,IAAI,CAAC,CAAC,CAAC,MAAM,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC;IAC7C,KAAK,MAAM,CAAC,IAAI,MAAM,EAAE,CAAC;QACvB,IAAI,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC;IACpB,CAAC;IACD,OAAO,IAAA,kBAAO,EAAC,IAAI,CAAC,CAAC;AACvB,CAAC;AATD,8CASC","sourcesContent":["/*\n * Copyright (c) 2020 Erik Fortune\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n */\n\nimport { DetailedResult, Result, succeed } from '@fgv/ts-utils';\nimport { JsonObject, JsonValue } from '../json';\n\n/**\n * Collection of variables used for template replacement in a JSON edit or\n * conversion.\n * @public\n */\nexport type TemplateVars = Record<string, unknown>;\n\n/**\n * Describes one value in a {@link TemplateVars | TemplateVars} collection of\n * variables.\n * @public\n */\nexport type VariableValue = [string, unknown];\n\n/**\n * Function used to create a new collection of {@link TemplateVars | TemplateVars} with\n * one or more new or changed values.\n * @public\n */\nexport type TemplateVarsExtendFunction = (\n base: TemplateVars | undefined,\n values: VariableValue[]\n) => Result<TemplateVars | undefined>;\n\n/**\n * This default implementation of a {@link TemplateVarsExtendFunction | TemplateVarsExtendFunction}\n * creates a new collection via inheritance from the supplied collection.\n * @param base - The base {@link TemplateVars | variables} to be extended.\n * @param values - The {@link VariableValue | values} to be added or overridden in the new variables.\n * @public\n */\nexport function defaultExtendVars(\n base: TemplateVars | undefined,\n values: VariableValue[]\n): Result<TemplateVars | undefined> {\n const rtrn = base ? Object.create(base) : {};\n for (const v of values) {\n rtrn[v[0]] = v[1];\n }\n return succeed(rtrn);\n}\n\n/**\n * Failure reason for {@link IJsonReferenceMap | IJsonReferenceMap} lookup, where `'unknown'`\n * means that the object is not present in the map and `'error'` means\n * that an error occurred while retrieving or converting it.\n * @public\n */\nexport type JsonReferenceMapFailureReason = 'unknown' | 'error';\n\n/**\n * Interface for a simple map that returns named {@link JsonValue | JsonValue} values with templating,\n * conditional logic, and external reference lookups applied using an optionally supplied context.\n * @public\n */\nexport interface IJsonReferenceMap {\n /**\n * Determine if a key might be valid for this map but does not determine if key actually\n * exists. Allows key range to be constrained.\n * @param key - The key to be tested.\n * @returns `true` if the key is in the valid range, `false` otherwise.\n */\n keyIsInRange(key: string): boolean;\n\n /**\n * Determines if an object with the specified key actually exists in the map.\n * @param key - The key to be tested.\n * @returns `true` if an object with the specified key exists, `false` otherwise.\n */\n has(key: string): boolean;\n\n /**\n * Gets a {@link JsonObject | JsonObject} specified by key.\n * @param key - The key of the object to be retrieved.\n * @param context - Optional {@link IJsonContext | IJsonContext} used to construct\n * the object.\n * @returns `Success` with the formatted {@link JsonObject | object} if successful. `Failure`\n * with detail `'unknown'` if no such object exists, or `Failure` with detail `'error'` if\n * the object was found but could not be formatted.\n */\n // eslint-disable-next-line no-use-before-define\n getJsonObject(\n key: string,\n context?: IJsonContext\n ): DetailedResult<JsonObject, JsonReferenceMapFailureReason>;\n\n /**\n * Gets a {@link JsonValue | JsonValue} specified by key.\n * @param key - The key of the object to be retrieved.\n * @param context - Optional {@link IJsonContext | JSON Context} used to format the value\n * @returns `Success` with the formatted {@link JsonValue | value} if successful. `Failure`\n * with detail `'unknown'` if no such object exists, or `Failure` with detail `'error'` if\n * the object was found but could not be formatted.\n */\n // eslint-disable-next-line no-use-before-define\n getJsonValue(key: string, context?: IJsonContext): DetailedResult<JsonValue, JsonReferenceMapFailureReason>;\n}\n\n/**\n * Context used to convert or edit JSON objects.\n * @public\n */\nexport interface IJsonContext {\n vars?: TemplateVars;\n refs?: IJsonReferenceMap;\n extendVars?: TemplateVarsExtendFunction;\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"converters.js","sourceRoot":"","sources":["../../../src/packlets/converters/converters.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;;;;;;GAoBG;;;AAKH,mDAQyB;AAEzB;;;;GAIG;AACU,QAAA,IAAI,GAAkB,IAAI,6BAAa,EAAE,CAAC;AAEvD;;;;;GAKG;AACU,QAAA,UAAU,GAAwC,YAAI,CAAC,MAAM,EAAE,CAAC;AAE7E;;;;;GAKG;AACU,QAAA,SAAS,GAAuC,YAAI,CAAC,KAAK,EAAE,CAAC;AAE1E,IAAI,oBAA+C,CAAC;AACpD,IAAI,sBAAiD,CAAC;AACtD,IAAI,eAA0C,CAAC;AAE/C;;;;;;;GAOG;AACH,SAAgB,aAAa,CAAC,OAAgD;IAC5E,IAAI,CAAC,OAAO,EAAE;QACZ,IAAI,CAAC,oBAAoB,EAAE;YACzB,oBAAoB,GAAG,IAAI,sCAAsB,EAAE,CAAC;SACrD;QACD,OAAO,oBAAoB,CAAC;KAC7B;IACD,OAAO,IAAI,sCAAsB,CAAC,OAAO,CAAC,CAAC;AAC7C,CAAC;AARD,sCAQC;AAED;;;;;;;;GAQG;AACH,SAAgB,eAAe,CAAC,OAAkD;IAChF,IAAI,CAAC,OAAO,EAAE;QACZ,IAAI,CAAC,sBAAsB,EAAE;YAC3B,sBAAsB,GAAG,IAAI,wCAAwB,EAAE,CAAC;SACzD;QACD,OAAO,sBAAsB,CAAC;KAC/B;IACD,OAAO,IAAI,wCAAwB,CAAC,OAAO,CAAC,CAAC;AAC/C,CAAC;AARD,0CAQC;AAED;;;;;;;;GAQG;AACH,SAAgB,QAAQ,CAAC,OAA2C;IAClE,IAAI,CAAC,OAAO,EAAE;QACZ,IAAI,CAAC,eAAe,EAAE;YACpB,eAAe,GAAG,IAAI,iCAAiB,EAAE,CAAC;SAC3C;QACD,OAAO,eAAe,CAAC;KACxB;IACD,OAAO,IAAI,iCAAiB,CAAC,OAAO,CAAC,CAAC;AACxC,CAAC;AARD,4BAQC","sourcesContent":["/*\n * Copyright (c) 2020 Erik Fortune\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n */\n\nimport { Converter } from '@fgv/ts-utils';\nimport { IJsonContext } from '../context';\nimport { JsonArray, JsonObject } from '../json';\nimport {\n ConditionalJsonConverter,\n ConditionalJsonConverterOptions,\n JsonConverter,\n RichJsonConverter,\n RichJsonConverterOptions,\n TemplatedJsonConverter,\n TemplatedJsonConverterOptions\n} from './jsonConverter';\n\n/**\n * A simple validating {@link JsonConverter | JSON converter}. Converts unknown to\n * JSON or fails if the unknown contains any invalid JSON values.\n * @public\n */\nexport const json: JsonConverter = new JsonConverter();\n\n/**\n * A simple validating {@link JsonConverter | JSON converter}. Converts unknown\n * to a {@link JsonObject | JsonObject}, or fails if the `unknown` contains invalid\n * JSON or is not an object.\n * @public\n */\nexport const jsonObject: Converter<JsonObject, IJsonContext> = json.object();\n\n/**\n * A simple validating {@link JsonConverter | JSON converter}. Converts `unknown` to a\n * {@link JsonArray | JsonArray}, or fails if the unknown contains invalid JSON or is\n * not an array.\n * @public\n */\nexport const jsonArray: Converter<JsonArray, IJsonContext> = json.array();\n\nlet templatedJsonDefault: JsonConverter | undefined;\nlet conditionalJsonDefault: JsonConverter | undefined;\nlet richJsonDefault: JsonConverter | undefined;\n\n/**\n * Helper function which creates a new {@link JsonConverter | JsonConverter} which converts an\n * `unknown` value to JSON, rendering any property names or string values using mustache with\n * the supplied context. See the mustache documentation for details of mustache syntax and view.\n * @param options - {@link TemplatedJsonConverterOptions | Options and context} for\n * the conversion.\n * @public\n */\nexport function templatedJson(options?: Partial<TemplatedJsonConverterOptions>): JsonConverter {\n if (!options) {\n if (!templatedJsonDefault) {\n templatedJsonDefault = new TemplatedJsonConverter();\n }\n return templatedJsonDefault;\n }\n return new TemplatedJsonConverter(options);\n}\n\n/**\n * Helper function which creates a new {@link JsonConverter | JsonConverter} which converts a\n * supplied `unknown` to strongly-typed JSON, by first rendering any property\n * names or string values using mustache with the supplied context, then applying\n * multi-value property expansion and conditional flattening based on property names.\n * @param options - {@link ConditionalJsonConverterOptions | Options and context} for\n * the conversion.\n * @public\n */\nexport function conditionalJson(options?: Partial<ConditionalJsonConverterOptions>): JsonConverter {\n if (!options) {\n if (!conditionalJsonDefault) {\n conditionalJsonDefault = new ConditionalJsonConverter();\n }\n return conditionalJsonDefault;\n }\n return new ConditionalJsonConverter(options);\n}\n\n/**\n * Helper function which creates a new {@link JsonConverter | JsonConverter} which converts a\n * supplied `unknown` to strongly-typed JSON, by first rendering any property\n * names or string values using mustache with the supplied context, then applying\n * multi-value property expansion and conditional flattening based on property names.\n * @param options - {@link RichJsonConverterOptions | Options and context} for\n * the conversion.\n * @public\n */\nexport function richJson(options?: Partial<RichJsonConverterOptions>): JsonConverter {\n if (!options) {\n if (!richJsonDefault) {\n richJsonDefault = new RichJsonConverter();\n }\n return richJsonDefault;\n }\n return new RichJsonConverter(options);\n}\n"]}
1
+ {"version":3,"file":"converters.js","sourceRoot":"","sources":["../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,CAAC;AACxC,CAAC;AARD,4BAQC","sourcesContent":["/*\n * Copyright (c) 2020 Erik Fortune\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n */\n\nimport { Converter } from '@fgv/ts-utils';\nimport { IJsonContext } from '../context';\nimport { JsonArray, JsonObject } from '../json';\nimport {\n ConditionalJsonConverter,\n ConditionalJsonConverterOptions,\n JsonConverter,\n RichJsonConverter,\n RichJsonConverterOptions,\n TemplatedJsonConverter,\n TemplatedJsonConverterOptions\n} from './jsonConverter';\n\n/**\n * A simple validating {@link JsonConverter | JSON converter}. Converts unknown to\n * JSON or fails if the unknown contains any invalid JSON values.\n * @public\n */\nexport const json: JsonConverter = new JsonConverter();\n\n/**\n * A simple validating {@link JsonConverter | JSON converter}. Converts unknown\n * to a {@link JsonObject | JsonObject}, or fails if the `unknown` contains invalid\n * JSON or is not an object.\n * @public\n */\nexport const jsonObject: Converter<JsonObject, IJsonContext> = json.object();\n\n/**\n * A simple validating {@link JsonConverter | JSON converter}. Converts `unknown` to a\n * {@link JsonArray | JsonArray}, or fails if the unknown contains invalid JSON or is\n * not an array.\n * @public\n */\nexport const jsonArray: Converter<JsonArray, IJsonContext> = json.array();\n\nlet templatedJsonDefault: JsonConverter | undefined;\nlet conditionalJsonDefault: JsonConverter | undefined;\nlet richJsonDefault: JsonConverter | undefined;\n\n/**\n * Helper function which creates a new {@link JsonConverter | JsonConverter} which converts an\n * `unknown` value to JSON, rendering any property names or string values using mustache with\n * the supplied context. See the mustache documentation for details of mustache syntax and view.\n * @param options - {@link TemplatedJsonConverterOptions | Options and context} for\n * the conversion.\n * @public\n */\nexport function templatedJson(options?: Partial<TemplatedJsonConverterOptions>): JsonConverter {\n if (!options) {\n if (!templatedJsonDefault) {\n templatedJsonDefault = new TemplatedJsonConverter();\n }\n return templatedJsonDefault;\n }\n return new TemplatedJsonConverter(options);\n}\n\n/**\n * Helper function which creates a new {@link JsonConverter | JsonConverter} which converts a\n * supplied `unknown` to strongly-typed JSON, by first rendering any property\n * names or string values using mustache with the supplied context, then applying\n * multi-value property expansion and conditional flattening based on property names.\n * @param options - {@link ConditionalJsonConverterOptions | Options and context} for\n * the conversion.\n * @public\n */\nexport function conditionalJson(options?: Partial<ConditionalJsonConverterOptions>): JsonConverter {\n if (!options) {\n if (!conditionalJsonDefault) {\n conditionalJsonDefault = new ConditionalJsonConverter();\n }\n return conditionalJsonDefault;\n }\n return new ConditionalJsonConverter(options);\n}\n\n/**\n * Helper function which creates a new {@link JsonConverter | JsonConverter} which converts a\n * supplied `unknown` to strongly-typed JSON, by first rendering any property\n * names or string values using mustache with the supplied context, then applying\n * multi-value property expansion and conditional flattening based on property names.\n * @param options - {@link RichJsonConverterOptions | Options and context} for\n * the conversion.\n * @public\n */\nexport function richJson(options?: Partial<RichJsonConverterOptions>): JsonConverter {\n if (!options) {\n if (!richJsonDefault) {\n richJsonDefault = new RichJsonConverter();\n }\n return richJsonDefault;\n }\n return new RichJsonConverter(options);\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":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tE,OAAO,IAAA,qBAAU,EACf,KAAK,CAAC,GAAG,CAAC,CAAC,IAAI,EAAE,EAAE;YACjB,MAAM,QAAQ,GAAG,IAAI,CAAC,QAAQ,CAAC,IAAI,CAAC,QAAQ,EAAE,OAAO,CAAC,CAAC;YACvD,OAAO,aAAa,CAAC,QAAQ,EAAE,IAAI,CAAC,IAAI,CAAC,CAAC,SAAS,CAAC,CAAC,IAAI,EAAE,EAAE;gBAC3D,OAAO,IAAA,kBAAO,EAAc,CAAC,IAAI,EAAE,IAAI,CAAC,IAAI,CAAC,CAAC,CAAC;YACjD,CAAC,CAAC,CAAC;QACL,CAAC,CAAC,CACH,CAAC,SAAS,CAAC,CAAC,KAAK,EAAE,EAAE;YACpB,OAAO,IAAA,kBAAO,EAAC,IAAI,GAAG,CAAY,KAAK,CAAC,CAAC,CAAC;QAC5C,CAAC,CAAC,CAAC;IACL,CAAC,CAAC,CAAC;AACL,CAAC;AAjBD,sEAiBC;AAED;;;;;GAKG;AACH,SAAgB,iBAAiB,CAAC,OAAe,EAAE,KAAgB;IACjE,OAAO,IAAA,wBAAa,EAAC,GAAG,EAAE;QACxB,MAAM,QAAQ,GAAG,IAAI,CAAC,OAAO,CAAC,OAAO,CAAC,CAAC;QACvC,EAAE,CAAC,aAAa,CAAC,QAAQ,EAAE,IAAI,CAAC,SAAS,CAAC,KAAK,EAAE,SAAS,EAAE,CAAC,CAAC,CAAC,CAAC;QAChE,OAAO,IAAI,CAAC;IACd,CAAC,CAAC,CAAC;AACL,CAAC;AAND,8CAMC","sourcesContent":["/*\n * Copyright (c) 2020 Erik Fortune\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n */\n\nimport { Converter, Result, captureResult, fail, mapResults, succeed } from '@fgv/ts-utils';\nimport * as fs from 'fs';\nimport * as path from 'path';\n\nimport { JsonValue } from '../json';\n\n/**\n * Convenience function to read type-safe JSON from a file\n * @param srcPath - Path of the file to read\n * @returns `Success` with a {@link JsonValue | JsonValue} or `Failure`\n * with a message if an error occurs.\n * @public\n */\nexport function readJsonFileSync(srcPath: string): Result<JsonValue> {\n return captureResult(() => {\n const fullPath = path.resolve(srcPath);\n const body = fs.readFileSync(fullPath, 'utf8').toString();\n return JSON.parse(body) as JsonValue;\n });\n}\n\n/**\n * Convenience function to read a JSON file and apply a supplied converter.\n * @param srcPath - Path of the file to read.\n * @param converter - `Converter` used to convert the file contents\n * @returns `Success` with a result of type `<T>`, or `Failure`\n * with a message if an error occurs.\n * @public\n */\nexport function convertJsonFileSync<T>(srcPath: string, converter: Converter<T>): Result<T> {\n return readJsonFileSync(srcPath).onSuccess((json) => {\n return converter.convert(json);\n });\n}\n\n/**\n * Options for directory conversion.\n * TODO: add filtering, allowed and excluded.\n * @public\n */\nexport interface IDirectoryConvertOptions<T, TC = unknown> {\n /**\n * The converter used to convert incoming JSON objects.\n */\n converter: Converter<T, TC>;\n}\n\n/**\n * Return value for one item in a directory conversion.\n * @public\n */\nexport interface IReadDirectoryItem<T> {\n /**\n * Relative name of the file that was processed\n */\n filename: string;\n\n /**\n * The payload of the file.\n */\n item: T;\n}\n\n/**\n * Reads all JSON files from a directory and apply a supplied converter.\n * @param srcPath - The path of the folder to be read.\n * @param options - {@link Files.IDirectoryConvertOptions | Options} to control\n * conversion and filtering\n * @public\n */\nexport function convertJsonDirectorySync<T>(\n srcPath: string,\n options: IDirectoryConvertOptions<T>\n): Result<IReadDirectoryItem<T>[]> {\n return captureResult<IReadDirectoryItem<T>[]>(() => {\n const fullPath = path.resolve(srcPath);\n if (!fs.statSync(fullPath).isDirectory()) {\n throw new Error(`${fullPath}: Not a directory`);\n }\n const files = fs.readdirSync(fullPath, { withFileTypes: true });\n const results = files\n .map((fi) => {\n if (fi.isFile() && path.extname(fi.name) === '.json') {\n const filePath = path.resolve(fullPath, fi.name);\n return convertJsonFileSync(filePath, options.converter)\n .onSuccess((payload) => {\n return succeed({\n filename: fi.name,\n item: payload\n });\n })\n .onFailure((message) => {\n return fail(`${fi.name}: ${message}`);\n });\n }\n return undefined;\n })\n .filter((r): r is Result<IReadDirectoryItem<T>> => r !== undefined);\n return mapResults(results).orThrow();\n });\n}\n\n/**\n * Function to transform the name of a some entity, given an original name\n * and the contents of the entity.\n * @public\n */\nexport type ItemNameTransformFunction<T> = (name: string, item: T) => Result<string>;\n\n/**\n * Options controlling conversion of a directory.\n * @public\n */\nexport interface IDirectoryToMapConvertOptions<T, TC = unknown> extends IDirectoryConvertOptions<T, TC> {\n transformName?: ItemNameTransformFunction<T>;\n}\n\n/**\n * Function to transform the name of some entity, given only a previous name. This\n * default implementation always returns `Success` with the value that was passed in.\n * @param n - The name to be transformed.\n * @returns - `Success` with the string that was passed in.\n * @public\n */\nconst defaultNameTransformer = (n: string): Result<string> => succeed(n);\n\n/**\n * Reads and converts all JSON files from a directory, returning a\n * `Map<string, T>` indexed by file base name (i.e. minus the extension)\n * with an optional name transformation applied if present.\n * @param srcPath - The path of the folder to be read.\n * @param options - {@link Files.IDirectoryToMapConvertOptions | Options} to control conversion,\n * filtering and naming.\n * @public\n */\nexport function convertJsonDirectoryToMapSync<T, TC = unknown>(\n srcPath: string,\n options: IDirectoryToMapConvertOptions<T, TC>\n): Result<Map<string, T>> {\n return convertJsonDirectorySync(srcPath, options).onSuccess((items) => {\n const transformName = options.transformName ?? defaultNameTransformer;\n return mapResults(\n items.map((item) => {\n const basename = path.basename(item.filename, '.json');\n return transformName(basename, item.item).onSuccess((name) => {\n return succeed<[string, T]>([name, item.item]);\n });\n })\n ).onSuccess((items) => {\n return succeed(new Map<string, T>(items));\n });\n });\n}\n\n/**\n * Convenience function to write type-safe JSON to a file.\n * @param srcPath - Path of the file to write.\n * @param value - The {@link JsonValue | JsonValue} to be written.\n * @public\n */\nexport function writeJsonFileSync(srcPath: string, value: JsonValue): Result<boolean> {\n return captureResult(() => {\n const fullPath = path.resolve(srcPath);\n fs.writeFileSync(fullPath, JSON.stringify(value, undefined, 2));\n return true;\n });\n}\n"]}
1
+ {"version":3,"file":"file.js","sourceRoot":"","sources":["../../../src/packlets/converters/file.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;;;;;;GAoBG;;;;;;;;;;;;;;;;;;;;;;;;;;AAEH,4CAA4F;AAC5F,uCAAyB;AACzB,2CAA6B;AAI7B;;;;;;GAMG;AACH,SAAgB,gBAAgB,CAAC,OAAe;IAC9C,OAAO,IAAA,wBAAa,EAAC,GAAG,EAAE;QACxB,MAAM,QAAQ,GAAG,IAAI,CAAC,OAAO,CAAC,OAAO,CAAC,CAAC;QACvC,MAAM,IAAI,GAAG,EAAE,CAAC,YAAY,CAAC,QAAQ,EAAE,MAAM,CAAC,CAAC,QAAQ,EAAE,CAAC;QAC1D,OAAO,IAAI,CAAC,KAAK,CAAC,IAAI,CAAc,CAAC;IACvC,CAAC,CAAC,CAAC;AACL,CAAC;AAND,4CAMC;AAED;;;;;;;GAOG;AACH,SAAgB,mBAAmB,CAAI,OAAe,EAAE,SAAuB;IAC7E,OAAO,gBAAgB,CAAC,OAAO,CAAC,CAAC,SAA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gB,iBAAiB,CAAC,OAAe,EAAE,KAAgB;IACjE,OAAO,IAAA,wBAAa,EAAC,GAAG,EAAE;QACxB,MAAM,QAAQ,GAAG,IAAI,CAAC,OAAO,CAAC,OAAO,CAAC,CAAC;QACvC,EAAE,CAAC,aAAa,CAAC,QAAQ,EAAE,IAAI,CAAC,SAAS,CAAC,KAAK,EAAE,SAAS,EAAE,CAAC,CAAC,CAAC,CAAC;QAChE,OAAO,IAAI,CAAC;IACd,CAAC,CAAC,CAAC;AACL,CAAC;AAND,8CAMC","sourcesContent":["/*\n * Copyright (c) 2020 Erik Fortune\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n */\n\nimport { Converter, Result, captureResult, fail, mapResults, succeed } from '@fgv/ts-utils';\nimport * as fs from 'fs';\nimport * as path from 'path';\n\nimport { JsonValue } from '../json';\n\n/**\n * Convenience function to read type-safe JSON from a file\n * @param srcPath - Path of the file to read\n * @returns `Success` with a {@link JsonValue | JsonValue} or `Failure`\n * with a message if an error occurs.\n * @public\n */\nexport function readJsonFileSync(srcPath: string): Result<JsonValue> {\n return captureResult(() => {\n const fullPath = path.resolve(srcPath);\n const body = fs.readFileSync(fullPath, 'utf8').toString();\n return JSON.parse(body) as JsonValue;\n });\n}\n\n/**\n * Convenience function to read a JSON file and apply a supplied converter.\n * @param srcPath - Path of the file to read.\n * @param converter - `Converter` used to convert the file contents\n * @returns `Success` with a result of type `<T>`, or `Failure`\n * with a message if an error occurs.\n * @public\n */\nexport function convertJsonFileSync<T>(srcPath: string, converter: Converter<T>): Result<T> {\n return readJsonFileSync(srcPath).onSuccess((json) => {\n return converter.convert(json);\n });\n}\n\n/**\n * Options for directory conversion.\n * TODO: add filtering, allowed and excluded.\n * @public\n */\nexport interface IDirectoryConvertOptions<T, TC = unknown> {\n /**\n * The converter used to convert incoming JSON objects.\n */\n converter: Converter<T, TC>;\n}\n\n/**\n * Return value for one item in a directory conversion.\n * @public\n */\nexport interface IReadDirectoryItem<T> {\n /**\n * Relative name of the file that was processed\n */\n filename: string;\n\n /**\n * The payload of the file.\n */\n item: T;\n}\n\n/**\n * Reads all JSON files from a directory and apply a supplied converter.\n * @param srcPath - The path of the folder to be read.\n * @param options - {@link Files.IDirectoryConvertOptions | Options} to control\n * conversion and filtering\n * @public\n */\nexport function convertJsonDirectorySync<T>(\n srcPath: string,\n options: IDirectoryConvertOptions<T>\n): Result<IReadDirectoryItem<T>[]> {\n return captureResult<IReadDirectoryItem<T>[]>(() => {\n const fullPath = path.resolve(srcPath);\n if (!fs.statSync(fullPath).isDirectory()) {\n throw new Error(`${fullPath}: Not a directory`);\n }\n const files = fs.readdirSync(fullPath, { withFileTypes: true });\n const results = files\n .map((fi) => {\n if (fi.isFile() && path.extname(fi.name) === '.json') {\n const filePath = path.resolve(fullPath, fi.name);\n return convertJsonFileSync(filePath, options.converter)\n .onSuccess((payload) => {\n return succeed({\n filename: fi.name,\n item: payload\n });\n })\n .onFailure((message) => {\n return fail(`${fi.name}: ${message}`);\n });\n }\n return undefined;\n })\n .filter((r): r is Result<IReadDirectoryItem<T>> => r !== undefined);\n return mapResults(results).orThrow();\n });\n}\n\n/**\n * Function to transform the name of a some entity, given an original name\n * and the contents of the entity.\n * @public\n */\nexport type ItemNameTransformFunction<T> = (name: string, item: T) => Result<string>;\n\n/**\n * Options controlling conversion of a directory.\n * @public\n */\nexport interface IDirectoryToMapConvertOptions<T, TC = unknown> extends IDirectoryConvertOptions<T, TC> {\n transformName?: ItemNameTransformFunction<T>;\n}\n\n/**\n * Function to transform the name of some entity, given only a previous name. This\n * default implementation always returns `Success` with the value that was passed in.\n * @param n - The name to be transformed.\n * @returns - `Success` with the string that was passed in.\n * @public\n */\nconst defaultNameTransformer = (n: string): Result<string> => succeed(n);\n\n/**\n * Reads and converts all JSON files from a directory, returning a\n * `Map<string, T>` indexed by file base name (i.e. minus the extension)\n * with an optional name transformation applied if present.\n * @param srcPath - The path of the folder to be read.\n * @param options - {@link Files.IDirectoryToMapConvertOptions | Options} to control conversion,\n * filtering and naming.\n * @public\n */\nexport function convertJsonDirectoryToMapSync<T, TC = unknown>(\n srcPath: string,\n options: IDirectoryToMapConvertOptions<T, TC>\n): Result<Map<string, T>> {\n return convertJsonDirectorySync(srcPath, options).onSuccess((items) => {\n const transformName = options.transformName ?? defaultNameTransformer;\n return mapResults(\n items.map((item) => {\n const basename = path.basename(item.filename, '.json');\n return transformName(basename, item.item).onSuccess((name) => {\n return succeed<[string, T]>([name, item.item]);\n });\n })\n ).onSuccess((items) => {\n return succeed(new Map<string, T>(items));\n });\n });\n}\n\n/**\n * Convenience function to write type-safe JSON to a file.\n * @param srcPath - Path of the file to write.\n * @param value - The {@link JsonValue | JsonValue} to be written.\n * @public\n */\nexport function writeJsonFileSync(srcPath: string, value: JsonValue): Result<boolean> {\n return captureResult(() => {\n const fullPath = path.resolve(srcPath);\n fs.writeFileSync(fullPath, JSON.stringify(value, undefined, 2));\n return true;\n });\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"jsonConverter.js","sourceRoot":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H,MAAa,wBAAyB,SAAQ,mBAAmB;IAW/D;;;;;OAKG;IACH,YAAmB,OAAkD;QACnE,OAAO,mCAAQ,OAAO,GAAK,wBAAwB,CAAC,kBAAkB,CAAE,CAAC;QACzE,MAAM,MAAM,GAAG,wBAAwB,CAAC,OAAO,CAAC,CAAC,OAAO,EAAE,CAAC;QAC3D,KAAK,CAAC,MAAM,CAAC,CAAC;IAChB,CAAC;IAED;;;;;OAKG;IACI,MAAM,CAAC,MAAM,CAAC,OAAkD;QACrE,OAAO,IAAA,wBAAa,EAAC,GAAG,EAAE,CAAC,IAAI,wBAAwB,CAAC,OAAO,CAAC,CAAC,CAAC;IACpE,CAAC;;AA/BH,4DAgCC;AA/BC;;;GAGG;AACoB,2CAAkB,mCACpC,sBAAsB,CAAC,eAAe,KACzC,mBAAmB,EAAE,IAAI,EACzB,0BAA0B,EAAE,IAAI,IAChC;AA+BJ;;;;;GAKG;AACH,MAAa,iBAAkB,SAAQ,mBAAmB;IAUxD;;;;;OAKG;IACH,YAAmB,OAA2C;QAC5D,OAAO,mCAAQ,OAAO,GAAK,iBAAiB,CAAC,WAAW,CAAE,CAAC;QAC3D,MAAM,MAAM,GAAG,wBAAwB,CAAC,OAAO,CAAC,CAAC,OAAO,EAAE,CAAC;QAC3D,KAAK,CAAC,MAAM,CAAC,CAAC;IAChB,CAAC;IAED;;;;;OAKG;IACI,MAAM,CAAC,MAAM,CAAC,OAA2C;QAC9D,OAAO,IAAA,wBAAa,EAAC,GAAG,EAAE,CAAC,IAAI,iBAAiB,CAAC,OAAO,CAAC,CAAC,CAAC;IAC7D,CAAC;;AA9BH,8CA+BC;AA9BC;;;GAGG;AACoB,6BAAW,mCAC7B,wBAAwB,CAAC,kBAAkB,KAC9C,aAAa,EAAE,IAAI,IACnB","sourcesContent":["/*\n * Copyright (c) 2020 Erik Fortune\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n */\n\nimport { Conversion, Converter, Result, captureResult, fail, succeed } from '@fgv/ts-utils';\nimport {\n IJsonContext,\n IJsonReferenceMap,\n TemplateVars,\n TemplateVarsExtendFunction,\n defaultExtendVars\n} from '../context';\nimport { JsonArray, JsonObject, JsonValue, isJsonObject } from '../json';\n\nimport { EditorRules, IJsonEditorOptions, IJsonEditorRule, JsonEditor } from '../editor';\n\n/**\n * Conversion options for {@link JsonConverter | JsonConverter}.\n * @public\n */\nexport interface IJsonConverterOptions {\n /**\n * If `true` and if template variables are available,\n * then string property values will be rendered using\n * mustache and those variable values. Otherwise string\n * properties are copied without modification.\n *\n * Defaults to `true` if vars are supplied with options,\n * `false` otherwise.\n */\n useValueTemplates: boolean;\n\n /**\n * If `true` and if template variables are available,\n * then property names will be rendered using\n * mustache and those variable values. Otherwise\n * property names are copied without modification.\n *\n * Defaults to `true` if vars are supplied with options,\n * `false` otherwise.\n */\n useNameTemplates: boolean;\n\n /**\n * If `true` and if template variables are available,\n * then string property names will be considered for\n * conditionals.\n *\n * Default is to match {@link IJsonConverterOptions.useNameTemplates | useNameTemplates}.\n */\n useConditionalNames: boolean;\n\n /**\n * If `true` (default) then properties with unconditional names\n * (which start with !) are flattened.\n */\n flattenUnconditionalValues: boolean;\n\n /**\n * If `true` and if both template variables and a\n * context derivation function is available, then properties\n * which match the multi-value name pattern will be expanded.\n * Default matches {@link IJsonConverterOptions.useNameTemplates | useNameTemplates}.\n *\n * Default is `true` unless {@link IJsonConverterOptions.extendVars | extendVars} is\n * explicitly set to `undefined`.\n */\n useMultiValueTemplateNames: boolean;\n\n /**\n * The variables (mustache view) used to render templated string names\n * and properties. See the mustache documentation for details of mustache\n * syntax and the template view.\n */\n vars?: TemplateVars;\n\n /**\n * Method used to extend variables for children of an array node during\n * expansion. Default is to use a built-in extension function unless\n * {@link IJsonConverterOptions.extendVars | extendVars} is explicitly set to undefined.\n */\n extendVars?: TemplateVarsExtendFunction;\n\n /**\n * If `true` and if a {@link IJsonReferenceMap | references map} is supplied\n * in {@link IJsonConverterOptions.refs | refs}, then references in the source\n * object will be replaced with the corresponding value from the reference map.\n *\n * Default is `true` if {@link IJsonConverterOptions.refs | refs} are present in options,\n * `false` otherwise.\n */\n useReferences: boolean;\n\n /**\n * An optional {@link IJsonReferenceMap | reference map} used to insert any references\n * in the converted JSON.\n */\n refs?: IJsonReferenceMap;\n\n /**\n * If {@link IJsonConverterOptions.onInvalidPropertyName | onInvalidPropertyName} is `'error'`\n * (default) then any property name that is invalid after template rendering causes an error\n * and stops conversion. If {@link IJsonConverterOptions.onInvalidPropertyName | onInvalidPropertyName}\n * is `'ignore'`, then names which are invalid after template rendering are passed through unchanged.\n */\n onInvalidPropertyName: 'error' | 'ignore';\n\n /**\n * If {@link IJsonConverterOptions.onInvalidPropertyValue | onInvalidPropertyValue} is `'error'`\n * (default) then any illegal property value causes an error and stops conversion. If\n * {@link IJsonConverterOptions.onInvalidPropertyValue | onInvalidPropertyValue} is `'ignore'` then\n * any invalid property values are silently ignored.\n */\n onInvalidPropertyValue: 'error' | 'ignore';\n\n /**\n * If {@link IJsonConverterOptions.onUndefinedPropertyValue | onUndefinedPropertyValue} is `'error'`,\n * then any property with value `undefined` will cause an error and stop conversion. If\n * {@link IJsonConverterOptions.onUndefinedPropertyValue | onUndefinedPropertyValue} is `'ignore'` (default)\n * then any property with value `undefined` is silently ignored.\n */\n onUndefinedPropertyValue: 'error' | 'ignore';\n}\n\n/**\n * Merges an optionally supplied partial set of {@link IJsonConverterOptions | options} with\n * the default converter options and taking all dynamic rules into account (e.g. template usage enabled\n * if variables are supplied and disabled if not), producing a fully-resolved set of\n * {@link IJsonConverterOptions | IJsonConverterOptions}.\n * @param partial - An optional partial {@link IJsonConverterOptions | IJsonConverterOptions}\n * to be merged.\n * @public\n */\nexport function mergeDefaultJsonConverterOptions(\n partial?: Partial<IJsonConverterOptions>\n): IJsonConverterOptions {\n const haveVars = partial?.vars !== undefined;\n const haveRefs = partial?.refs !== undefined;\n const extender = partial?.hasOwnProperty('extendVars') ? partial.extendVars : defaultExtendVars;\n const haveExtender = extender !== undefined;\n const namesDefault = partial?.useNameTemplates ?? haveVars;\n const conditionsDefault = partial?.useConditionalNames ?? namesDefault;\n\n const options: IJsonConverterOptions = {\n useValueTemplates: partial?.useValueTemplates ?? haveVars,\n useNameTemplates: namesDefault,\n useConditionalNames: conditionsDefault,\n flattenUnconditionalValues: partial?.flattenUnconditionalValues ?? conditionsDefault,\n useMultiValueTemplateNames: partial?.useMultiValueTemplateNames ?? (haveExtender && namesDefault),\n useReferences: partial?.useReferences ?? haveRefs,\n onInvalidPropertyName: partial?.onInvalidPropertyName ?? 'error',\n onInvalidPropertyValue: partial?.onInvalidPropertyValue ?? 'error',\n onUndefinedPropertyValue: partial?.onUndefinedPropertyValue ?? 'ignore',\n extendVars: extender\n };\n if (partial?.vars) {\n options.vars = partial.vars;\n }\n if (partial?.refs) {\n options.refs = partial.refs;\n }\n return options;\n}\n\n/**\n * Creates a new {@link IJsonContext | JSON context} using values supplied in an optional partial\n * {@link IJsonConverterOptions | converter options}.\n * @param partial - Optional partial {@link IJsonConverterOptions | IJsonConverterOptions} used to\n * populate the context.\n * @public\n */\nexport function contextFromConverterOptions(\n partial?: Partial<IJsonConverterOptions>\n): IJsonContext | undefined {\n const context: IJsonContext = {};\n if (partial?.vars) {\n context.vars = partial.vars;\n }\n if (partial?.refs) {\n context.refs = partial.refs;\n }\n if (partial?.hasOwnProperty('extendVars')) {\n context.extendVars = partial.extendVars;\n }\n return context.vars || context.refs || context.extendVars ? context : undefined;\n}\n\n/**\n * Creates a new {@link Editor.JsonEditor | JsonEditor} from an optionally supplied partial\n * {@link IJsonConverterOptions | JSON converter options}.\n * Expands supplied options with default values and constructs an editor with\n * matching configuration and defined rules.\n * @param partial - Optional partial {@link IJsonConverterOptions | IJsonConverterOptions}\n * used to create the editor.\n * @public\n */\nexport function converterOptionsToEditor(partial?: Partial<IJsonConverterOptions>): Result<JsonEditor> {\n const converterOptions = mergeDefaultJsonConverterOptions(partial);\n const context = contextFromConverterOptions(partial);\n const validation = {\n onInvalidPropertyName: converterOptions.onInvalidPropertyName,\n onInvalidPropertyValue: converterOptions.onInvalidPropertyValue,\n onUndefinedPropertyValue: converterOptions.onUndefinedPropertyValue\n };\n const editorOptions: IJsonEditorOptions = { context, validation };\n\n const rules: IJsonEditorRule[] = [];\n if (converterOptions.useNameTemplates || converterOptions.useValueTemplates) {\n const templateOptions = {\n ...editorOptions,\n useNameTemplates: converterOptions.useNameTemplates,\n useValueTemplates: converterOptions.useValueTemplates\n };\n rules.push(new EditorRules.TemplatedJsonEditorRule(templateOptions));\n }\n if (converterOptions.useConditionalNames || converterOptions.flattenUnconditionalValues) {\n const conditionalOptions = {\n ...editorOptions,\n flattenUnconditionalValues: converterOptions.flattenUnconditionalValues\n };\n rules.push(new EditorRules.ConditionalJsonEditorRule(conditionalOptions));\n }\n if (converterOptions.useMultiValueTemplateNames) {\n rules.push(new EditorRules.MultiValueJsonEditorRule(editorOptions));\n }\n if (converterOptions.useReferences) {\n rules.push(new EditorRules.ReferenceJsonEditorRule(editorOptions));\n }\n\n return JsonEditor.create(editorOptions, rules);\n}\n\n/**\n * A thin wrapper to allow an arbitrary {@link Editor.JsonEditor | JsonEditor} to be used via the\n * \\@fgv/ts-utils `Converter` pattern.\n * @public\n */\nexport class JsonEditorConverter extends Conversion.BaseConverter<JsonValue, IJsonContext> {\n public readonly editor: JsonEditor;\n\n /**\n * Constructs a new {@link Editor.JsonEditor | JsonEditor}Converter which uses the supplied editor\n * @param editor -\n */\n public constructor(editor: JsonEditor) {\n super((from, __self, context) => this._convert(from, context), editor.options.context);\n this.editor = editor;\n }\n\n /**\n * Constructs a new {@link Editor.JsonEditor | JsonEditor}Converter which uses the supplied editor\n * @param editor -\n */\n public static createWithEditor(editor: JsonEditor): Result<JsonEditorConverter> {\n return captureResult(() => new JsonEditorConverter(editor));\n }\n\n /**\n * Gets a derived converter which fails if the resulting converted\n * {@link JsonValue | JsonValue} is not a {@link JsonObject | JsonObject}.\n */\n public object(): Converter<JsonObject, IJsonContext> {\n return this.map((jv) => {\n if (!isJsonObject(jv)) {\n return fail(`Cannot convert \"${JSON.stringify(jv)}\" to JSON object.`);\n }\n return succeed(jv);\n });\n }\n\n /**\n * Gets a derived converter which fails if the resulting converted\n * {@link JsonValue | JsonValue} is not a {@link JsonArray | JsonArray}.\n */\n public array(): Converter<JsonArray, IJsonContext> {\n return this.map((jv) => {\n if (!Array.isArray(jv) || typeof jv !== 'object') {\n return fail(`Cannot convert \"${JSON.stringify(jv)}\" to JSON array.`);\n }\n return succeed(jv);\n });\n }\n\n protected _convert(from: unknown, context?: IJsonContext): Result<JsonValue> {\n return this.editor.clone(from as JsonValue, context);\n }\n}\n\n/**\n * An \\@fgv/ts-utils `Converter` from `unknown` to type-safe JSON, optionally\n * rendering any string property names or values using mustache with a supplied view.\n * @public\n */\nexport class JsonConverter extends JsonEditorConverter {\n /**\n * Constructs a new {@link JsonConverter | JsonConverter} with\n * supplied or default options.\n * @param options - Optional partial {@link IJsonConverterOptions | options}\n * to configure the converter.\n */\n public constructor(options?: Partial<IJsonConverterOptions>) {\n const editor = converterOptionsToEditor(options).orThrow();\n super(editor);\n }\n\n /**\n * Creates a new {@link JsonConverter | JsonConverter}.\n * @param options - Optional partial {@link IJsonConverterOptions | options}\n * to configure the converter.\n * @returns `Success` with a new {@link JsonConverter | JsonConverter}, or `Failure`\n * with an informative message if an error occurs.\n */\n public static create(options?: Partial<IJsonConverterOptions>): Result<JsonConverter> {\n return captureResult(() => new JsonConverter(options));\n }\n}\n\n/**\n * Initialization options for a {@link TemplatedJsonConverter | TemplatedJsonConverter}.\n * @public\n */\nexport type TemplatedJsonConverterOptions = Omit<\n IJsonConverterOptions,\n 'useNameTemplates' | 'useValueTemplates' | 'useMultiValueTemplateNames'\n>;\n\n/**\n * An \\@fgv/ts-utils `Converter` from `unknown` to type-safe JSON\n * with mustache template rendering and multi-value property name rules enabled\n * regardless of initial context.\n * @public\n */\nexport class TemplatedJsonConverter extends JsonEditorConverter {\n /**\n * Default {@link IJsonConverterOptions | JSON converter options}\n * to enable templated conversion.\n */\n public static readonly templateOptions: Partial<IJsonConverterOptions> = {\n useNameTemplates: true,\n useValueTemplates: true,\n useMultiValueTemplateNames: true,\n useConditionalNames: false,\n flattenUnconditionalValues: false\n };\n\n /**\n * Constructs a new {@link TemplatedJsonConverter | TemplatedJsonConverter} with\n * supplied or default options.\n * @param options - Optional partial {@link TemplatedJsonConverterOptions | options}\n * to configure the converter.\n */\n public constructor(options?: Partial<TemplatedJsonConverterOptions>) {\n options = { ...options, ...TemplatedJsonConverter.templateOptions };\n const editor = converterOptionsToEditor(options).orThrow();\n super(editor);\n }\n\n /**\n * Constructs a new {@link TemplatedJsonConverter | TemplatedJsonConverter} with\n * supplied or default options.\n * @param options - Optional partial {@link TemplatedJsonConverterOptions | options}\n * to configure the converter.\n */\n public static create(options?: Partial<TemplatedJsonConverterOptions>): Result<JsonConverter> {\n return captureResult(() => new TemplatedJsonConverter(options));\n }\n}\n\n/**\n * Options for a {@link ConditionalJsonConverter | ConditionalJsonConverter}.\n * @public\n */\nexport type ConditionalJsonConverterOptions = Omit<TemplatedJsonConverterOptions, 'useConditionalNames'>;\n\n/**\n * An \\@fgv/ts-utils `Converter` from `unknown` to type-safe JSON with mustache\n * template rendering, multi-value property name and conditional property\n * name rules enabled regardless of initial context.\n * @public\n */\nexport class ConditionalJsonConverter extends JsonEditorConverter {\n /**\n * Default {@link IJsonConverterOptions | JSON converter options}\n * to enable conditional conversion.\n */\n public static readonly conditionalOptions: Partial<IJsonConverterOptions> = {\n ...TemplatedJsonConverter.templateOptions,\n useConditionalNames: true,\n flattenUnconditionalValues: true\n };\n\n /**\n * Constructs a new {@link ConditionalJsonConverter | ConditionalJsonConverter} with supplied or\n * default options.\n * @param options - Optional partial {@link ConditionalJsonConverterOptions | configuration or context}\n * for the converter.\n */\n public constructor(options?: Partial<ConditionalJsonConverterOptions>) {\n options = { ...options, ...ConditionalJsonConverter.conditionalOptions };\n const editor = converterOptionsToEditor(options).orThrow();\n super(editor);\n }\n\n /**\n * Constructs a new {@link ConditionalJsonConverter | ConditionalJsonConverter} with supplied or\n * default options.\n * @param options - Optional partial {@link ConditionalJsonConverterOptions | configuration or context}\n * for the converter.\n */\n public static create(options?: Partial<ConditionalJsonConverterOptions>): Result<JsonConverter> {\n return captureResult(() => new ConditionalJsonConverter(options));\n }\n}\n\n/**\n * Initialization options for a {@link RichJsonConverter | RichJsonConverter}.\n * @public\n */\nexport type RichJsonConverterOptions = Omit<ConditionalJsonConverterOptions, 'useReferences'>;\n\n/**\n * A \\@fgv/ts-utils `Converter` from `unknown` to type-safe JSON with mustache\n * template rendering, multi-value property name, conditional property\n * name, and external reference rules enabled regardless of initial context.\n * @public\n */\nexport class RichJsonConverter extends JsonEditorConverter {\n /**\n * Default {@link IJsonConverterOptions | JSON converter options}\n * to enable rich conversion.\n */\n public static readonly richOptions: Partial<IJsonConverterOptions> = {\n ...ConditionalJsonConverter.conditionalOptions,\n useReferences: true\n };\n\n /**\n * Constructs a new {@link RichJsonConverter | RichJsonConverter} with supplied or\n * default options.\n * @param options - Optional partial {@link RichJsonConverterOptions | configuration or context}\n * for the converter.\n */\n public constructor(options?: Partial<RichJsonConverterOptions>) {\n options = { ...options, ...RichJsonConverter.richOptions };\n const editor = converterOptionsToEditor(options).orThrow();\n super(editor);\n }\n\n /**\n * Constructs a new {@link RichJsonConverter | RichJsonConverter} with supplied or\n * default options\n * @param options - Optional partial {@link RichJsonConverterOptions | configuration or context}\n * for the converter.\n */\n public static create(options?: Partial<RichJsonConverterOptions>): Result<JsonConverter> {\n return captureResult(() => new RichJsonConverter(options));\n }\n}\n"]}
1
+ {"version":3,"file":"jsonConverter.js","sourceRoot":"","sources":["../../../src/packlets/converters/jsonConverter.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;;;;;;GAoBG;;;AAEH,4CAA4F;AAC5F,wCAMoB;AACpB,kCAAyE;AAEzE,sCAAyF;AA8GzF;;;;;;;;GAQG;AACH,SAAgB,gCAAgC,CAC9C,OAAwC;;IAExC,MAAM,QAAQ,GAAG,CAAA,OAAO,aAAP,OAAO,uBAAP,OAAO,CAAE,IAAI,MAAK,SAAS,CAAC;IAC7C,MAAM,QAAQ,GAAG,CAAA,OAAO,aAAP,OAAO,uBAAP,OAAO,CAAE,IAAI,MAAK,SAAS,CAAC;IAC7C,MAAM,QAAQ,GAAG,CAAA,OAAO,aAAP,OAAO,uBAAP,OAAO,CAAE,cAAc,CAAC,YAAY,CAAC,EAAC,CAAC,CAAC,OAAO,CAAC,UAAU,CAAC,CAAC,CAAC,2BAAiB,CAAC;IAChG,MAAM,YAAY,GAAG,QAAQ,KAAK,SAAS,CAAC;IAC5C,MAAM,YAAY,GAAG,MAAA,OAAO,aAAP,OAAO,uBAAP,OAAO,CAAE,gBAAgB,mCAAI,QAAQ,CAAC;IAC3D,MAAM,iBAAiB,GAAG,MAAA,OAAO,aAAP,OAAO,uBAAP,OAAO,CAAE,mBAAmB,mCAAI,YAAY,CAAC;IAEvE,MAAM,OAAO,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CAAC,WAAW,CAAE,CAAC;QAC3D,MAAM,MAAM,GAAG,wBAAwB,CAAC,OAAO,CAAC,CAAC,OAAO,EAAE,CAAC;QAC3D,KAAK,CAAC,MAAM,CAAC,CAAC;IAChB,CAAC;IAED;;;;;OAKG;IACI,MAAM,CAAC,MAAM,CAAC,OAA2C;QAC9D,OAAO,IAAA,wBAAa,EAAC,GAAG,EAAE,CAAC,IAAI,iBAAiB,CAAC,OAAO,CAAC,CAAC,CAAC;IAC7D,CAAC;;AA9BH,8CA+BC;AA9BC;;;GAGG;AACoB,6BAAW,mCAC7B,wBAAwB,CAAC,kBAAkB,KAC9C,aAAa,EAAE,IAAI,IACnB","sourcesContent":["/*\n * Copyright (c) 2020 Erik Fortune\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n */\n\nimport { Conversion, Converter, Result, captureResult, fail, succeed } from '@fgv/ts-utils';\nimport {\n IJsonContext,\n IJsonReferenceMap,\n TemplateVars,\n TemplateVarsExtendFunction,\n defaultExtendVars\n} from '../context';\nimport { JsonArray, JsonObject, JsonValue, isJsonObject } from '../json';\n\nimport { EditorRules, IJsonEditorOptions, IJsonEditorRule, JsonEditor } from '../editor';\n\n/**\n * Conversion options for {@link JsonConverter | JsonConverter}.\n * @public\n */\nexport interface IJsonConverterOptions {\n /**\n * If `true` and if template variables are available,\n * then string property values will be rendered using\n * mustache and those variable values. Otherwise string\n * properties are copied without modification.\n *\n * Defaults to `true` if vars are supplied with options,\n * `false` otherwise.\n */\n useValueTemplates: boolean;\n\n /**\n * If `true` and if template variables are available,\n * then property names will be rendered using\n * mustache and those variable values. Otherwise\n * property names are copied without modification.\n *\n * Defaults to `true` if vars are supplied with options,\n * `false` otherwise.\n */\n useNameTemplates: boolean;\n\n /**\n * If `true` and if template variables are available,\n * then string property names will be considered for\n * conditionals.\n *\n * Default is to match {@link IJsonConverterOptions.useNameTemplates | useNameTemplates}.\n */\n useConditionalNames: boolean;\n\n /**\n * If `true` (default) then properties with unconditional names\n * (which start with !) are flattened.\n */\n flattenUnconditionalValues: boolean;\n\n /**\n * If `true` and if both template variables and a\n * context derivation function is available, then properties\n * which match the multi-value name pattern will be expanded.\n * Default matches {@link IJsonConverterOptions.useNameTemplates | useNameTemplates}.\n *\n * Default is `true` unless {@link IJsonConverterOptions.extendVars | extendVars} is\n * explicitly set to `undefined`.\n */\n useMultiValueTemplateNames: boolean;\n\n /**\n * The variables (mustache view) used to render templated string names\n * and properties. See the mustache documentation for details of mustache\n * syntax and the template view.\n */\n vars?: TemplateVars;\n\n /**\n * Method used to extend variables for children of an array node during\n * expansion. Default is to use a built-in extension function unless\n * {@link IJsonConverterOptions.extendVars | extendVars} is explicitly set to undefined.\n */\n extendVars?: TemplateVarsExtendFunction;\n\n /**\n * If `true` and if a {@link IJsonReferenceMap | references map} is supplied\n * in {@link IJsonConverterOptions.refs | refs}, then references in the source\n * object will be replaced with the corresponding value from the reference map.\n *\n * Default is `true` if {@link IJsonConverterOptions.refs | refs} are present in options,\n * `false` otherwise.\n */\n useReferences: boolean;\n\n /**\n * An optional {@link IJsonReferenceMap | reference map} used to insert any references\n * in the converted JSON.\n */\n refs?: IJsonReferenceMap;\n\n /**\n * If {@link IJsonConverterOptions.onInvalidPropertyName | onInvalidPropertyName} is `'error'`\n * (default) then any property name that is invalid after template rendering causes an error\n * and stops conversion. If {@link IJsonConverterOptions.onInvalidPropertyName | onInvalidPropertyName}\n * is `'ignore'`, then names which are invalid after template rendering are passed through unchanged.\n */\n onInvalidPropertyName: 'error' | 'ignore';\n\n /**\n * If {@link IJsonConverterOptions.onInvalidPropertyValue | onInvalidPropertyValue} is `'error'`\n * (default) then any illegal property value causes an error and stops conversion. If\n * {@link IJsonConverterOptions.onInvalidPropertyValue | onInvalidPropertyValue} is `'ignore'` then\n * any invalid property values are silently ignored.\n */\n onInvalidPropertyValue: 'error' | 'ignore';\n\n /**\n * If {@link IJsonConverterOptions.onUndefinedPropertyValue | onUndefinedPropertyValue} is `'error'`,\n * then any property with value `undefined` will cause an error and stop conversion. If\n * {@link IJsonConverterOptions.onUndefinedPropertyValue | onUndefinedPropertyValue} is `'ignore'` (default)\n * then any property with value `undefined` is silently ignored.\n */\n onUndefinedPropertyValue: 'error' | 'ignore';\n}\n\n/**\n * Merges an optionally supplied partial set of {@link IJsonConverterOptions | options} with\n * the default converter options and taking all dynamic rules into account (e.g. template usage enabled\n * if variables are supplied and disabled if not), producing a fully-resolved set of\n * {@link IJsonConverterOptions | IJsonConverterOptions}.\n * @param partial - An optional partial {@link IJsonConverterOptions | IJsonConverterOptions}\n * to be merged.\n * @public\n */\nexport function mergeDefaultJsonConverterOptions(\n partial?: Partial<IJsonConverterOptions>\n): IJsonConverterOptions {\n const haveVars = partial?.vars !== undefined;\n const haveRefs = partial?.refs !== undefined;\n const extender = partial?.hasOwnProperty('extendVars') ? partial.extendVars : defaultExtendVars;\n const haveExtender = extender !== undefined;\n const namesDefault = partial?.useNameTemplates ?? haveVars;\n const conditionsDefault = partial?.useConditionalNames ?? namesDefault;\n\n const options: IJsonConverterOptions = {\n useValueTemplates: partial?.useValueTemplates ?? haveVars,\n useNameTemplates: namesDefault,\n useConditionalNames: conditionsDefault,\n flattenUnconditionalValues: partial?.flattenUnconditionalValues ?? conditionsDefault,\n useMultiValueTemplateNames: partial?.useMultiValueTemplateNames ?? (haveExtender && namesDefault),\n useReferences: partial?.useReferences ?? haveRefs,\n onInvalidPropertyName: partial?.onInvalidPropertyName ?? 'error',\n onInvalidPropertyValue: partial?.onInvalidPropertyValue ?? 'error',\n onUndefinedPropertyValue: partial?.onUndefinedPropertyValue ?? 'ignore',\n extendVars: extender\n };\n if (partial?.vars) {\n options.vars = partial.vars;\n }\n if (partial?.refs) {\n options.refs = partial.refs;\n }\n return options;\n}\n\n/**\n * Creates a new {@link IJsonContext | JSON context} using values supplied in an optional partial\n * {@link IJsonConverterOptions | converter options}.\n * @param partial - Optional partial {@link IJsonConverterOptions | IJsonConverterOptions} used to\n * populate the context.\n * @public\n */\nexport function contextFromConverterOptions(\n partial?: Partial<IJsonConverterOptions>\n): IJsonContext | undefined {\n const context: IJsonContext = {};\n if (partial?.vars) {\n context.vars = partial.vars;\n }\n if (partial?.refs) {\n context.refs = partial.refs;\n }\n if (partial?.hasOwnProperty('extendVars')) {\n context.extendVars = partial.extendVars;\n }\n return context.vars || context.refs || context.extendVars ? context : undefined;\n}\n\n/**\n * Creates a new {@link Editor.JsonEditor | JsonEditor} from an optionally supplied partial\n * {@link IJsonConverterOptions | JSON converter options}.\n * Expands supplied options with default values and constructs an editor with\n * matching configuration and defined rules.\n * @param partial - Optional partial {@link IJsonConverterOptions | IJsonConverterOptions}\n * used to create the editor.\n * @public\n */\nexport function converterOptionsToEditor(partial?: Partial<IJsonConverterOptions>): Result<JsonEditor> {\n const converterOptions = mergeDefaultJsonConverterOptions(partial);\n const context = contextFromConverterOptions(partial);\n const validation = {\n onInvalidPropertyName: converterOptions.onInvalidPropertyName,\n onInvalidPropertyValue: converterOptions.onInvalidPropertyValue,\n onUndefinedPropertyValue: converterOptions.onUndefinedPropertyValue\n };\n const editorOptions: IJsonEditorOptions = { context, validation };\n\n const rules: IJsonEditorRule[] = [];\n if (converterOptions.useNameTemplates || converterOptions.useValueTemplates) {\n const templateOptions = {\n ...editorOptions,\n useNameTemplates: converterOptions.useNameTemplates,\n useValueTemplates: converterOptions.useValueTemplates\n };\n rules.push(new EditorRules.TemplatedJsonEditorRule(templateOptions));\n }\n if (converterOptions.useConditionalNames || converterOptions.flattenUnconditionalValues) {\n const conditionalOptions = {\n ...editorOptions,\n flattenUnconditionalValues: converterOptions.flattenUnconditionalValues\n };\n rules.push(new EditorRules.ConditionalJsonEditorRule(conditionalOptions));\n }\n if (converterOptions.useMultiValueTemplateNames) {\n rules.push(new EditorRules.MultiValueJsonEditorRule(editorOptions));\n }\n if (converterOptions.useReferences) {\n rules.push(new EditorRules.ReferenceJsonEditorRule(editorOptions));\n }\n\n return JsonEditor.create(editorOptions, rules);\n}\n\n/**\n * A thin wrapper to allow an arbitrary {@link Editor.JsonEditor | JsonEditor} to be used via the\n * \\@fgv/ts-utils `Converter` pattern.\n * @public\n */\nexport class JsonEditorConverter extends Conversion.BaseConverter<JsonValue, IJsonContext> {\n public readonly editor: JsonEditor;\n\n /**\n * Constructs a new {@link Editor.JsonEditor | JsonEditor}Converter which uses the supplied editor\n * @param editor -\n */\n public constructor(editor: JsonEditor) {\n super((from, __self, context) => this._convert(from, context), editor.options.context);\n this.editor = editor;\n }\n\n /**\n * Constructs a new {@link Editor.JsonEditor | JsonEditor}Converter which uses the supplied editor\n * @param editor -\n */\n public static createWithEditor(editor: JsonEditor): Result<JsonEditorConverter> {\n return captureResult(() => new JsonEditorConverter(editor));\n }\n\n /**\n * Gets a derived converter which fails if the resulting converted\n * {@link JsonValue | JsonValue} is not a {@link JsonObject | JsonObject}.\n */\n public object(): Converter<JsonObject, IJsonContext> {\n return this.map((jv) => {\n if (!isJsonObject(jv)) {\n return fail(`Cannot convert \"${JSON.stringify(jv)}\" to JSON object.`);\n }\n return succeed(jv);\n });\n }\n\n /**\n * Gets a derived converter which fails if the resulting converted\n * {@link JsonValue | JsonValue} is not a {@link JsonArray | JsonArray}.\n */\n public array(): Converter<JsonArray, IJsonContext> {\n return this.map((jv) => {\n if (!Array.isArray(jv) || typeof jv !== 'object') {\n return fail(`Cannot convert \"${JSON.stringify(jv)}\" to JSON array.`);\n }\n return succeed(jv);\n });\n }\n\n protected _convert(from: unknown, context?: IJsonContext): Result<JsonValue> {\n return this.editor.clone(from as JsonValue, context);\n }\n}\n\n/**\n * An \\@fgv/ts-utils `Converter` from `unknown` to type-safe JSON, optionally\n * rendering any string property names or values using mustache with a supplied view.\n * @public\n */\nexport class JsonConverter extends JsonEditorConverter {\n /**\n * Constructs a new {@link JsonConverter | JsonConverter} with\n * supplied or default options.\n * @param options - Optional partial {@link IJsonConverterOptions | options}\n * to configure the converter.\n */\n public constructor(options?: Partial<IJsonConverterOptions>) {\n const editor = converterOptionsToEditor(options).orThrow();\n super(editor);\n }\n\n /**\n * Creates a new {@link JsonConverter | JsonConverter}.\n * @param options - Optional partial {@link IJsonConverterOptions | options}\n * to configure the converter.\n * @returns `Success` with a new {@link JsonConverter | JsonConverter}, or `Failure`\n * with an informative message if an error occurs.\n */\n public static create(options?: Partial<IJsonConverterOptions>): Result<JsonConverter> {\n return captureResult(() => new JsonConverter(options));\n }\n}\n\n/**\n * Initialization options for a {@link TemplatedJsonConverter | TemplatedJsonConverter}.\n * @public\n */\nexport type TemplatedJsonConverterOptions = Omit<\n IJsonConverterOptions,\n 'useNameTemplates' | 'useValueTemplates' | 'useMultiValueTemplateNames'\n>;\n\n/**\n * An \\@fgv/ts-utils `Converter` from `unknown` to type-safe JSON\n * with mustache template rendering and multi-value property name rules enabled\n * regardless of initial context.\n * @public\n */\nexport class TemplatedJsonConverter extends JsonEditorConverter {\n /**\n * Default {@link IJsonConverterOptions | JSON converter options}\n * to enable templated conversion.\n */\n public static readonly templateOptions: Partial<IJsonConverterOptions> = {\n useNameTemplates: true,\n useValueTemplates: true,\n useMultiValueTemplateNames: true,\n useConditionalNames: false,\n flattenUnconditionalValues: false\n };\n\n /**\n * Constructs a new {@link TemplatedJsonConverter | TemplatedJsonConverter} with\n * supplied or default options.\n * @param options - Optional partial {@link TemplatedJsonConverterOptions | options}\n * to configure the converter.\n */\n public constructor(options?: Partial<TemplatedJsonConverterOptions>) {\n options = { ...options, ...TemplatedJsonConverter.templateOptions };\n const editor = converterOptionsToEditor(options).orThrow();\n super(editor);\n }\n\n /**\n * Constructs a new {@link TemplatedJsonConverter | TemplatedJsonConverter} with\n * supplied or default options.\n * @param options - Optional partial {@link TemplatedJsonConverterOptions | options}\n * to configure the converter.\n */\n public static create(options?: Partial<TemplatedJsonConverterOptions>): Result<JsonConverter> {\n return captureResult(() => new TemplatedJsonConverter(options));\n }\n}\n\n/**\n * Options for a {@link ConditionalJsonConverter | ConditionalJsonConverter}.\n * @public\n */\nexport type ConditionalJsonConverterOptions = Omit<TemplatedJsonConverterOptions, 'useConditionalNames'>;\n\n/**\n * An \\@fgv/ts-utils `Converter` from `unknown` to type-safe JSON with mustache\n * template rendering, multi-value property name and conditional property\n * name rules enabled regardless of initial context.\n * @public\n */\nexport class ConditionalJsonConverter extends JsonEditorConverter {\n /**\n * Default {@link IJsonConverterOptions | JSON converter options}\n * to enable conditional conversion.\n */\n public static readonly conditionalOptions: Partial<IJsonConverterOptions> = {\n ...TemplatedJsonConverter.templateOptions,\n useConditionalNames: true,\n flattenUnconditionalValues: true\n };\n\n /**\n * Constructs a new {@link ConditionalJsonConverter | ConditionalJsonConverter} with supplied or\n * default options.\n * @param options - Optional partial {@link ConditionalJsonConverterOptions | configuration or context}\n * for the converter.\n */\n public constructor(options?: Partial<ConditionalJsonConverterOptions>) {\n options = { ...options, ...ConditionalJsonConverter.conditionalOptions };\n const editor = converterOptionsToEditor(options).orThrow();\n super(editor);\n }\n\n /**\n * Constructs a new {@link ConditionalJsonConverter | ConditionalJsonConverter} with supplied or\n * default options.\n * @param options - Optional partial {@link ConditionalJsonConverterOptions | configuration or context}\n * for the converter.\n */\n public static create(options?: Partial<ConditionalJsonConverterOptions>): Result<JsonConverter> {\n return captureResult(() => new ConditionalJsonConverter(options));\n }\n}\n\n/**\n * Initialization options for a {@link RichJsonConverter | RichJsonConverter}.\n * @public\n */\nexport type RichJsonConverterOptions = Omit<ConditionalJsonConverterOptions, 'useReferences'>;\n\n/**\n * A \\@fgv/ts-utils `Converter` from `unknown` to type-safe JSON with mustache\n * template rendering, multi-value property name, conditional property\n * name, and external reference rules enabled regardless of initial context.\n * @public\n */\nexport class RichJsonConverter extends JsonEditorConverter {\n /**\n * Default {@link IJsonConverterOptions | JSON converter options}\n * to enable rich conversion.\n */\n public static readonly richOptions: Partial<IJsonConverterOptions> = {\n ...ConditionalJsonConverter.conditionalOptions,\n useReferences: true\n };\n\n /**\n * Constructs a new {@link RichJsonConverter | RichJsonConverter} with supplied or\n * default options.\n * @param options - Optional partial {@link RichJsonConverterOptions | configuration or context}\n * for the converter.\n */\n public constructor(options?: Partial<RichJsonConverterOptions>) {\n options = { ...options, ...RichJsonConverter.richOptions };\n const editor = converterOptionsToEditor(options).orThrow();\n super(editor);\n }\n\n /**\n * Constructs a new {@link RichJsonConverter | RichJsonConverter} with supplied or\n * default options\n * @param options - Optional partial {@link RichJsonConverterOptions | configuration or context}\n * for the converter.\n */\n public static create(options?: Partial<RichJsonConverterOptions>): Result<JsonConverter> {\n return captureResult(() => new RichJsonConverter(options));\n }\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"jsonEditor.js","sourceRoot":"","sources":["../../../src/packlets/editor/jsonEditor.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;;;;;;GAoBG;;;AAEH,4CAUuB;AACvB,mCAKiB;AAGjB,kCAAuG;AAUvG,uDAAoD;AAEpD;;;;;GAKG;AACH,MAAa,UAAU;IAkBrB;;;;;;;OAOG;IACH,YAAsB,OAAqC,EAAE,KAAyB;QACpF,IAAI,CAAC,OAAO,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AAc,EAAE;gBAClE,OAAO,UAAU,CAAC;aACnB;SACF;QACD,OAAO,IAAA,yBAAc,EAAC,cAAc,EAAE,cAAc,CAAC,CAAC;IACxD,CAAC;IAED;;;;;;OAMG;IACO,iBAAiB,CACzB,MAAkB,EAClB,KAAsB;QAEtB,MAAM,QAAQ,GAAG,KAAK,CAAC,QAAQ,CAAC;QAChC,IAAI,QAAQ,CAAC,MAAM,GAAG,CAAC,EAAE;YACvB,KAAK,MAAM,IAAI,IAAI,IAAI,CAAC,MAAM,EAAE;gBAC9B,MAAM,UAAU,GAAG,IAAI,CAAC,kBAAkB,CAAC,QAAQ,EAAE,KAAK,CAAC,CAAC;gBAC5D,IAAI,UAAU,CAAC,SAAS,EAAE,EAAE;oBAC1B,OAAO,IAAI,CAAC,8BAA8B,CACxC,KAAK,CAAC,OAAO,EACb,MAAM,EACN,UAAU,CAAC,KAAK,CACjB,CAAC,iBAAiB,CAAC,OAAO,CAAC,CAAC;iBAC9B;qBAAM,IAAI,UAAU,CAAC,MAAM,KAAK,QAAQ,EAAE;oBACzC,IAAA,4BAAiB,EAAC,MAAM,EAAE,QAAQ,CAAC,CAAC;iBACrC;qBAAM,IAAI,UAAU,CAAC,MAAM,KAAK,cAAc,EAAE;oBAC/C,OAAO,IAAA,yBAAc,EAAC,UAAU,CAAC,OAAO,EAAE,UAAU,CAAC,MAAM,CAAC,CAAC;iBAC9D;aACF;SACF;QACD,OAAO,IAAA,4BAAiB,EAAC,MAAM,EAAE,QAAQ,CAAC,CAAC;IAC7C,CAAC;CACF;AA3WD,gCA2WC","sourcesContent":["/*\n * Copyright (c) 2020 Erik Fortune\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n */\n\nimport {\n DetailedResult,\n Result,\n captureResult,\n fail,\n failWithDetail,\n mapDetailedResults,\n mapResults,\n succeed,\n succeedWithDetail\n} from '@fgv/ts-utils';\nimport {\n ConditionalJsonEditorRule,\n MultiValueJsonEditorRule,\n ReferenceJsonEditorRule,\n TemplatedJsonEditorRule\n} from './rules';\n\nimport { IJsonContext } from '../context';\nimport { JsonArray, JsonObject, JsonValue, isJsonArray, isJsonObject, isJsonPrimitive } from '../json';\nimport {\n IJsonCloneEditor,\n IJsonEditorOptions,\n IJsonEditorValidationOptions,\n JsonEditFailureReason,\n JsonPropertyEditFailureReason\n} from './common';\n\nimport { IJsonEditorRule } from './jsonEditorRule';\nimport { JsonEditorState } from './jsonEditorState';\n\n/**\n * A {@link JsonEditor | JsonEditor} can be used to edit JSON objects in place or to\n * clone any JSON value, applying a default context and optional set of editor rules that\n * were supplied at initialization.\n * @public\n */\nexport class JsonEditor implements IJsonCloneEditor {\n /**\n * Default singleton {@link Editor.JsonEditor | JsonEditor}.\n * @internal\n */\n protected static _default?: JsonEditor;\n\n /**\n * Full set of {@link Editor.IJsonEditorOptions | editor options} in effect for this editor.\n */\n public options: IJsonEditorOptions;\n\n /**\n * The set of {@link Editor.IJsonEditorRule | editor rules} applied by this editor.\n * @internal\n */\n protected _rules: IJsonEditorRule[];\n\n /**\n * Protected constructor for {@link Editor.JsonEditor | JsonEditor} and derived classes.\n * External consumers should instantiate via the {@link Editor.JsonEditor.create | create static method}.\n * @param options - Optional partial {@link Editor.IJsonEditorOptions | editor options} for the\n * constructed editor.\n * @param rules - Any {@link Editor.IJsonEditorRule | editor rules} to be applied by the editor.\n * @internal\n */\n protected constructor(options?: Partial<IJsonEditorOptions>, rules?: IJsonEditorRule[]) {\n this.options = JsonEditor._getDefaultOptions(options).orThrow();\n this._rules = rules || JsonEditor.getDefaultRules(this.options).orThrow();\n }\n\n /**\n * Default singleton {@link Editor.JsonEditor | JsonEditor} for simple use. Applies all rules\n * but with no default context.\n */\n public static get default(): JsonEditor {\n if (!JsonEditor._default) {\n const rules = this.getDefaultRules().orDefault();\n JsonEditor._default = new JsonEditor(undefined, rules);\n }\n return JsonEditor._default;\n }\n\n /**\n * Constructs a new {@link Editor.JsonEditor | JsonEditor}.\n * @param options - Optional partial {@link Editor.IJsonEditorOptions | editor options} for the\n * constructed editor.\n * @param rules - Optional set of {@link Editor.IJsonEditorRule | editor rules} to be applied by the editor.\n * @readonly A new {@link Editor.JsonEditor | JsonEditor}.\n */\n public static create(options?: Partial<IJsonEditorOptions>, rules?: IJsonEditorRule[]): Result<JsonEditor> {\n return captureResult(() => new JsonEditor(options, rules));\n }\n\n /**\n * Gets the default set of rules to be applied for a given set of options.\n * By default, all available rules (templates, conditionals, multi-value and references)\n * are applied.\n * @param options - Optional partial {@link Editor.IJsonEditorOptions | editor options} for\n * all rules.\n * @returns Default {@link Editor.IJsonEditorRule | editor rules} with any supplied options\n * applied.\n */\n public static getDefaultRules(options?: IJsonEditorOptions): Result<IJsonEditorRule[]> {\n return mapResults<IJsonEditorRule>([\n TemplatedJsonEditorRule.create(options),\n ConditionalJsonEditorRule.create(options),\n MultiValueJsonEditorRule.create(options),\n ReferenceJsonEditorRule.create(options)\n ]);\n }\n\n /**\n * @internal\n */\n protected static _getDefaultOptions(options?: Partial<IJsonEditorOptions>): Result<IJsonEditorOptions> {\n const context: IJsonContext | undefined = options?.context;\n let validation: IJsonEditorValidationOptions | undefined = options?.validation;\n if (validation === undefined) {\n validation = {\n onInvalidPropertyName: 'error',\n onInvalidPropertyValue: 'error',\n onUndefinedPropertyValue: 'ignore'\n };\n }\n return succeed({ context, validation });\n }\n\n /**\n * Merges a supplied source object into a supplied target, updating the target object.\n * @param target - The target {@link JsonObject | object} to be updated\n * @param src - The source {@link JsonObject | object} to be merged\n * @param runtimeContext - An optional {@link IJsonContext | IJsonContext} supplying variables\n * and references.\n * @returns `Success` with the original source {@link JsonObject | object} if merge was successful.\n * Returns `Failure` with details if an error occurs.\n */\n public mergeObjectInPlace(\n target: JsonObject,\n src: JsonObject,\n runtimeContext?: IJsonContext\n ): Result<JsonObject> {\n const state = new JsonEditorState(this, this.options, runtimeContext);\n return this._mergeObjectInPlace(target, src, state).onSuccess((merged) => {\n return this._finalizeAndMerge(merged, state);\n });\n }\n\n /**\n * Merges multiple supplied source objects into a supplied target, updating the target\n * object and using the default context supplied at creation time.\n * @param target - The target {@link JsonObject | object} to be updated\n * @param srcObjects - {@link JsonObject | Objects} to be merged into the target object, in the order\n * supplied.\n * @returns `Success` with the original source {@link JsonObject | object} if merge was successful.\n * Returns `Failure` with details if an error occurs.\n */\n public mergeObjectsInPlace(target: JsonObject, srcObjects: JsonObject[]): Result<JsonObject> {\n return this.mergeObjectsInPlaceWithContext(this.options.context, target, srcObjects);\n }\n\n /**\n * Merges multiple supplied source objects into a supplied target, updating the target\n * object and using an optional {@link IJsonContext | context} supplied in the call.\n * @param context - An optional {@link IJsonContext | IJsonContext} supplying variables and\n * references.\n * @param base - The base {@link JsonObject | object} to be updated\n * @param srcObjects - Objects to be merged into the target object, in the order supplied.\n * @returns `Success` with the original source {@link JsonObject | object} if merge was successful.\n * Returns `Failure` with details if an error occurs.\n */\n public mergeObjectsInPlaceWithContext(\n context: IJsonContext | undefined,\n base: JsonObject,\n srcObjects: JsonObject[]\n ): Result<JsonObject> {\n for (const src of srcObjects) {\n const mergeResult = this.mergeObjectInPlace(base, src, context);\n if (mergeResult.isFailure()) {\n return mergeResult.withFailureDetail('error');\n }\n }\n return succeedWithDetail(base);\n }\n\n /**\n * Deep clones a supplied {@link JsonValue | JSON value}, applying all editor rules and a default\n * or optionally supplied context\n * @param src - The {@link JsonValue | JsonValue} to be cloned.\n * @param context - An optional {@link IJsonContext | JSON context} supplying variables and references.\n */\n public clone(src: JsonValue, context?: IJsonContext): DetailedResult<JsonValue, JsonEditFailureReason> {\n const state = new JsonEditorState(this, this.options, context);\n let value = src;\n let valueResult = this._editValue(src, state);\n\n while (valueResult.isSuccess()) {\n value = valueResult.value;\n valueResult = this._editValue(value, state);\n }\n\n if (valueResult.detail === 'error' || valueResult.detail === 'ignore') {\n return valueResult;\n }\n\n if (isJsonPrimitive(value) || value === null) {\n return succeedWithDetail(value, 'edited');\n } else if (isJsonObject(value)) {\n return this.mergeObjectInPlace({}, value, state.context).withFailureDetail('error');\n } else if (isJsonArray(value)) {\n return this._cloneArray(value, state.context);\n } else if (value === undefined) {\n return state.failValidation('undefinedPropertyValue');\n }\n return state.failValidation(\n 'invalidPropertyValue',\n `Cannot convert invalid JSON: \"${JSON.stringify(value)}\"`\n );\n }\n\n /**\n *\n * @param target -\n * @param src -\n * @param state -\n * @returns\n * @internal\n */\n protected _mergeObjectInPlace(\n target: JsonObject,\n src: JsonObject,\n state: JsonEditorState\n ): Result<JsonObject> {\n for (const key in src) {\n if (src.hasOwnProperty(key)) {\n const propResult = this._editProperty(key, src[key], state);\n if (propResult.isSuccess()) {\n if (propResult.detail === 'deferred') {\n state.defer(propResult.value);\n } else {\n const mergeResult = this._mergeObjectInPlace(target, propResult.value, state);\n if (mergeResult.isFailure()) {\n return mergeResult;\n }\n }\n } else if (propResult.detail === 'inapplicable') {\n const valueResult = this.clone(src[key], state.context).onSuccess((cloned) => {\n return this._mergeClonedProperty(target, key, cloned, state);\n });\n\n if (valueResult.isFailure() && valueResult.detail === 'error') {\n return fail(`${key}: ${valueResult.message}`);\n }\n } else if (propResult.detail !== 'ignore') {\n return fail(`${key}: ${propResult.message}`);\n }\n } else {\n return fail(`${key}: Cannot merge inherited properties`);\n }\n }\n return succeed(target);\n }\n\n /**\n *\n * @param src -\n * @param context -\n * @returns\n * @internal\n */\n protected _cloneArray(\n src: JsonArray,\n context?: IJsonContext\n ): DetailedResult<JsonArray, JsonEditFailureReason> {\n const results = src.map((v) => {\n return this.clone(v, context);\n });\n\n return mapDetailedResults<JsonValue, JsonEditFailureReason>(results, ['ignore'])\n .onSuccess((converted) => {\n return succeed(converted);\n })\n .withFailureDetail('error');\n }\n\n /**\n *\n * @param target -\n * @param key -\n * @param newValue -\n * @param state -\n * @returns\n * @internal\n */\n protected _mergeClonedProperty(\n target: JsonObject,\n key: string,\n newValue: JsonValue,\n state: JsonEditorState\n ): DetailedResult<JsonValue, JsonEditFailureReason> {\n const existing = target[key];\n\n // merge is called right after clone so this should never happen\n // since clone itself will have failed\n\n if (isJsonPrimitive(newValue)) {\n target[key] = newValue;\n return succeedWithDetail(newValue, 'edited');\n }\n\n if (isJsonObject(newValue)) {\n if (isJsonObject(existing)) {\n return this.mergeObjectInPlace(existing, newValue, state.context).withFailureDetail('error');\n }\n target[key] = newValue;\n return succeedWithDetail(newValue, 'edited');\n }\n\n /* c8 ignore else */\n if (isJsonArray(newValue)) {\n if (isJsonArray(existing)) {\n target[key] = existing.concat(...newValue);\n return succeedWithDetail(target[key], 'edited');\n }\n target[key] = newValue;\n return succeedWithDetail(newValue, 'edited');\n }\n /* c8 ignore start */\n return failWithDetail(`Invalid JSON: ${JSON.stringify(newValue)}`, 'error');\n } /* c8 ignore stop */\n\n /**\n *\n * @param key -\n * @param value -\n * @param state -\n * @returns\n * @internal\n */\n protected _editProperty(\n key: string,\n value: JsonValue,\n state: JsonEditorState\n ): DetailedResult<JsonObject, JsonPropertyEditFailureReason> {\n for (const rule of this._rules) {\n const ruleResult = rule.editProperty(key, value, state);\n if (ruleResult.isSuccess() || ruleResult.detail !== 'inapplicable') {\n return ruleResult;\n }\n }\n return failWithDetail('inapplicable', 'inapplicable');\n }\n\n /**\n *\n * @param value -\n * @param state -\n * @returns\n * @internal\n */\n protected _editValue(\n value: JsonValue,\n state: JsonEditorState\n ): DetailedResult<JsonValue, JsonEditFailureReason> {\n for (const rule of this._rules) {\n const ruleResult = rule.editValue(value, state);\n if (ruleResult.isSuccess() || ruleResult.detail !== 'inapplicable') {\n return ruleResult;\n }\n }\n return failWithDetail('inapplicable', 'inapplicable');\n }\n\n /**\n *\n * @param target -\n * @param state -\n * @returns\n * @internal\n */\n protected _finalizeAndMerge(\n target: JsonObject,\n state: JsonEditorState\n ): DetailedResult<JsonObject, JsonEditFailureReason> {\n const deferred = state.deferred;\n if (deferred.length > 0) {\n for (const rule of this._rules) {\n const ruleResult = rule.finalizeProperties(deferred, state);\n if (ruleResult.isSuccess()) {\n return this.mergeObjectsInPlaceWithContext(\n state.context,\n target,\n ruleResult.value\n ).withFailureDetail('error');\n } else if (ruleResult.detail === 'ignore') {\n succeedWithDetail(target, 'edited');\n } else if (ruleResult.detail !== 'inapplicable') {\n return failWithDetail(ruleResult.message, ruleResult.detail);\n }\n }\n }\n return succeedWithDetail(target, 'edited');\n }\n}\n"]}
1
+ {"version":3,"file":"jsonEditor.js","sourceRoot":"","sources":["../../../src/packlets/editor/jsonEditor.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;;;;;;GAoBG;;;AAEH,4CAUuB;AACvB,mCAKiB;AAGjB,kCAAuG;AAUvG,uDAAoD;AAEpD;;;;;GAKG;AACH,MAAa,UAAU;IAkBrB;;;;;;;OAOG;IACH,YAAsB,OAAqC,EAAE,KAAyB;QACpF,IAAI,CAAC,OAAO,GAAG,UAAU,CAAC,kBAAkB,CAAC,OAAO,CAAC,CAAC,OAAO,EAAE,CAAC;QAChE,IAAI,CAAC,MAAM,GAAG,KAAK,IAAI,UAAU,CAAC,eAAe,CAAC,IAAI,CAAC,OAAO,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esContent":["/*\n * Copyright (c) 2020 Erik Fortune\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n */\n\nimport {\n DetailedResult,\n Result,\n captureResult,\n fail,\n failWithDetail,\n mapDetailedResults,\n mapResults,\n succeed,\n succeedWithDetail\n} from '@fgv/ts-utils';\nimport {\n ConditionalJsonEditorRule,\n MultiValueJsonEditorRule,\n ReferenceJsonEditorRule,\n TemplatedJsonEditorRule\n} from './rules';\n\nimport { IJsonContext } from '../context';\nimport { JsonArray, JsonObject, JsonValue, isJsonArray, isJsonObject, isJsonPrimitive } from '../json';\nimport {\n IJsonCloneEditor,\n IJsonEditorOptions,\n IJsonEditorValidationOptions,\n JsonEditFailureReason,\n JsonPropertyEditFailureReason\n} from './common';\n\nimport { IJsonEditorRule } from './jsonEditorRule';\nimport { JsonEditorState } from './jsonEditorState';\n\n/**\n * A {@link JsonEditor | JsonEditor} can be used to edit JSON objects in place or to\n * clone any JSON value, applying a default context and optional set of editor rules that\n * were supplied at initialization.\n * @public\n */\nexport class JsonEditor implements IJsonCloneEditor {\n /**\n * Default singleton {@link Editor.JsonEditor | JsonEditor}.\n * @internal\n */\n protected static _default?: JsonEditor;\n\n /**\n * Full set of {@link Editor.IJsonEditorOptions | editor options} in effect for this editor.\n */\n public options: IJsonEditorOptions;\n\n /**\n * The set of {@link Editor.IJsonEditorRule | editor rules} applied by this editor.\n * @internal\n */\n protected _rules: IJsonEditorRule[];\n\n /**\n * Protected constructor for {@link Editor.JsonEditor | JsonEditor} and derived classes.\n * External consumers should instantiate via the {@link Editor.JsonEditor.create | create static method}.\n * @param options - Optional partial {@link Editor.IJsonEditorOptions | editor options} for the\n * constructed editor.\n * @param rules - Any {@link Editor.IJsonEditorRule | editor rules} to be applied by the editor.\n * @internal\n */\n protected constructor(options?: Partial<IJsonEditorOptions>, rules?: IJsonEditorRule[]) {\n this.options = JsonEditor._getDefaultOptions(options).orThrow();\n this._rules = rules || JsonEditor.getDefaultRules(this.options).orThrow();\n }\n\n /**\n * Default singleton {@link Editor.JsonEditor | JsonEditor} for simple use. Applies all rules\n * but with no default context.\n */\n public static get default(): JsonEditor {\n if (!JsonEditor._default) {\n const rules = this.getDefaultRules().orDefault();\n JsonEditor._default = new JsonEditor(undefined, rules);\n }\n return JsonEditor._default;\n }\n\n /**\n * Constructs a new {@link Editor.JsonEditor | JsonEditor}.\n * @param options - Optional partial {@link Editor.IJsonEditorOptions | editor options} for the\n * constructed editor.\n * @param rules - Optional set of {@link Editor.IJsonEditorRule | editor rules} to be applied by the editor.\n * @readonly A new {@link Editor.JsonEditor | JsonEditor}.\n */\n public static create(options?: Partial<IJsonEditorOptions>, rules?: IJsonEditorRule[]): Result<JsonEditor> {\n return captureResult(() => new JsonEditor(options, rules));\n }\n\n /**\n * Gets the default set of rules to be applied for a given set of options.\n * By default, all available rules (templates, conditionals, multi-value and references)\n * are applied.\n * @param options - Optional partial {@link Editor.IJsonEditorOptions | editor options} for\n * all rules.\n * @returns Default {@link Editor.IJsonEditorRule | editor rules} with any supplied options\n * applied.\n */\n public static getDefaultRules(options?: IJsonEditorOptions): Result<IJsonEditorRule[]> {\n return mapResults<IJsonEditorRule>([\n TemplatedJsonEditorRule.create(options),\n ConditionalJsonEditorRule.create(options),\n MultiValueJsonEditorRule.create(options),\n ReferenceJsonEditorRule.create(options)\n ]);\n }\n\n /**\n * @internal\n */\n protected static _getDefaultOptions(options?: Partial<IJsonEditorOptions>): Result<IJsonEditorOptions> {\n const context: IJsonContext | undefined = options?.context;\n let validation: IJsonEditorValidationOptions | undefined = options?.validation;\n if (validation === undefined) {\n validation = {\n onInvalidPropertyName: 'error',\n onInvalidPropertyValue: 'error',\n onUndefinedPropertyValue: 'ignore'\n };\n }\n return succeed({ context, validation });\n }\n\n /**\n * Merges a supplied source object into a supplied target, updating the target object.\n * @param target - The target {@link JsonObject | object} to be updated\n * @param src - The source {@link JsonObject | object} to be merged\n * @param runtimeContext - An optional {@link IJsonContext | IJsonContext} supplying variables\n * and references.\n * @returns `Success` with the original source {@link JsonObject | object} if merge was successful.\n * Returns `Failure` with details if an error occurs.\n */\n public mergeObjectInPlace(\n target: JsonObject,\n src: JsonObject,\n runtimeContext?: IJsonContext\n ): Result<JsonObject> {\n const state = new JsonEditorState(this, this.options, runtimeContext);\n return this._mergeObjectInPlace(target, src, state).onSuccess((merged) => {\n return this._finalizeAndMerge(merged, state);\n });\n }\n\n /**\n * Merges multiple supplied source objects into a supplied target, updating the target\n * object and using the default context supplied at creation time.\n * @param target - The target {@link JsonObject | object} to be updated\n * @param srcObjects - {@link JsonObject | Objects} to be merged into the target object, in the order\n * supplied.\n * @returns `Success` with the original source {@link JsonObject | object} if merge was successful.\n * Returns `Failure` with details if an error occurs.\n */\n public mergeObjectsInPlace(target: JsonObject, srcObjects: JsonObject[]): Result<JsonObject> {\n return this.mergeObjectsInPlaceWithContext(this.options.context, target, srcObjects);\n }\n\n /**\n * Merges multiple supplied source objects into a supplied target, updating the target\n * object and using an optional {@link IJsonContext | context} supplied in the call.\n * @param context - An optional {@link IJsonContext | IJsonContext} supplying variables and\n * references.\n * @param base - The base {@link JsonObject | object} to be updated\n * @param srcObjects - Objects to be merged into the target object, in the order supplied.\n * @returns `Success` with the original source {@link JsonObject | object} if merge was successful.\n * Returns `Failure` with details if an error occurs.\n */\n public mergeObjectsInPlaceWithContext(\n context: IJsonContext | undefined,\n base: JsonObject,\n srcObjects: JsonObject[]\n ): Result<JsonObject> {\n for (const src of srcObjects) {\n const mergeResult = this.mergeObjectInPlace(base, src, context);\n if (mergeResult.isFailure()) {\n return mergeResult.withFailureDetail('error');\n }\n }\n return succeedWithDetail(base);\n }\n\n /**\n * Deep clones a supplied {@link JsonValue | JSON value}, applying all editor rules and a default\n * or optionally supplied context\n * @param src - The {@link JsonValue | JsonValue} to be cloned.\n * @param context - An optional {@link IJsonContext | JSON context} supplying variables and references.\n */\n public clone(src: JsonValue, context?: IJsonContext): DetailedResult<JsonValue, JsonEditFailureReason> {\n const state = new JsonEditorState(this, this.options, context);\n let value = src;\n let valueResult = this._editValue(src, state);\n\n while (valueResult.isSuccess()) {\n value = valueResult.value;\n valueResult = this._editValue(value, state);\n }\n\n if (valueResult.detail === 'error' || valueResult.detail === 'ignore') {\n return valueResult;\n }\n\n if (isJsonPrimitive(value) || value === null) {\n return succeedWithDetail(value, 'edited');\n } else if (isJsonObject(value)) {\n return this.mergeObjectInPlace({}, value, state.context).withFailureDetail('error');\n } else if (isJsonArray(value)) {\n return this._cloneArray(value, state.context);\n } else if (value === undefined) {\n return state.failValidation('undefinedPropertyValue');\n }\n return state.failValidation(\n 'invalidPropertyValue',\n `Cannot convert invalid JSON: \"${JSON.stringify(value)}\"`\n );\n }\n\n /**\n *\n * @param target -\n * @param src -\n * @param state -\n * @returns\n * @internal\n */\n protected _mergeObjectInPlace(\n target: JsonObject,\n src: JsonObject,\n state: JsonEditorState\n ): Result<JsonObject> {\n for (const key in src) {\n if (src.hasOwnProperty(key)) {\n const propResult = this._editProperty(key, src[key], state);\n if (propResult.isSuccess()) {\n if (propResult.detail === 'deferred') {\n state.defer(propResult.value);\n } else {\n const mergeResult = this._mergeObjectInPlace(target, propResult.value, state);\n if (mergeResult.isFailure()) {\n return mergeResult;\n }\n }\n } else if (propResult.detail === 'inapplicable') {\n const valueResult = this.clone(src[key], state.context).onSuccess((cloned) => {\n return this._mergeClonedProperty(target, key, cloned, state);\n });\n\n if (valueResult.isFailure() && valueResult.detail === 'error') {\n return fail(`${key}: ${valueResult.message}`);\n }\n } else if (propResult.detail !== 'ignore') {\n return fail(`${key}: ${propResult.message}`);\n }\n } else {\n return fail(`${key}: Cannot merge inherited properties`);\n }\n }\n return succeed(target);\n }\n\n /**\n *\n * @param src -\n * @param context -\n * @returns\n * @internal\n */\n protected _cloneArray(\n src: JsonArray,\n context?: IJsonContext\n ): DetailedResult<JsonArray, JsonEditFailureReason> {\n const results = src.map((v) => {\n return this.clone(v, context);\n });\n\n return mapDetailedResults<JsonValue, JsonEditFailureReason>(results, ['ignore'])\n .onSuccess((converted) => {\n return succeed(converted);\n })\n .withFailureDetail('error');\n }\n\n /**\n *\n * @param target -\n * @param key -\n * @param newValue -\n * @param state -\n * @returns\n * @internal\n */\n protected _mergeClonedProperty(\n target: JsonObject,\n key: string,\n newValue: JsonValue,\n state: JsonEditorState\n ): DetailedResult<JsonValue, JsonEditFailureReason> {\n const existing = target[key];\n\n // merge is called right after clone so this should never happen\n // since clone itself will have failed\n\n if (isJsonPrimitive(newValue)) {\n target[key] = newValue;\n return succeedWithDetail(newValue, 'edited');\n }\n\n if (isJsonObject(newValue)) {\n if (isJsonObject(existing)) {\n return this.mergeObjectInPlace(existing, newValue, state.context).withFailureDetail('error');\n }\n target[key] = newValue;\n return succeedWithDetail(newValue, 'edited');\n }\n\n /* c8 ignore else */\n if (isJsonArray(newValue)) {\n if (isJsonArray(existing)) {\n target[key] = existing.concat(...newValue);\n return succeedWithDetail(target[key], 'edited');\n }\n target[key] = newValue;\n return succeedWithDetail(newValue, 'edited');\n }\n /* c8 ignore start */\n return failWithDetail(`Invalid JSON: ${JSON.stringify(newValue)}`, 'error');\n } /* c8 ignore stop */\n\n /**\n *\n * @param key -\n * @param value -\n * @param state -\n * @returns\n * @internal\n */\n protected _editProperty(\n key: string,\n value: JsonValue,\n state: JsonEditorState\n ): DetailedResult<JsonObject, JsonPropertyEditFailureReason> {\n for (const rule of this._rules) {\n const ruleResult = rule.editProperty(key, value, state);\n if (ruleResult.isSuccess() || ruleResult.detail !== 'inapplicable') {\n return ruleResult;\n }\n }\n return failWithDetail('inapplicable', 'inapplicable');\n }\n\n /**\n *\n * @param value -\n * @param state -\n * @returns\n * @internal\n */\n protected _editValue(\n value: JsonValue,\n state: JsonEditorState\n ): DetailedResult<JsonValue, JsonEditFailureReason> {\n for (const rule of this._rules) {\n const ruleResult = rule.editValue(value, state);\n if (ruleResult.isSuccess() || ruleResult.detail !== 'inapplicable') {\n return ruleResult;\n }\n }\n return failWithDetail('inapplicable', 'inapplicable');\n }\n\n /**\n *\n * @param target -\n * @param state -\n * @returns\n * @internal\n */\n protected _finalizeAndMerge(\n target: JsonObject,\n state: JsonEditorState\n ): DetailedResult<JsonObject, JsonEditFailureReason> {\n const deferred = state.deferred;\n if (deferred.length > 0) {\n for (const rule of this._rules) {\n const ruleResult = rule.finalizeProperties(deferred, state);\n if (ruleResult.isSuccess()) {\n return this.mergeObjectsInPlaceWithContext(\n state.context,\n target,\n ruleResult.value\n ).withFailureDetail('error');\n } else if (ruleResult.detail === 'ignore') {\n succeedWithDetail(target, 'edited');\n } else if (ruleResult.detail !== 'inapplicable') {\n return failWithDetail(ruleResult.message, ruleResult.detail);\n }\n }\n }\n return succeedWithDetail(target, 'edited');\n }\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"jsonEditorState.js","sourceRoot":"","sources":["../../../src/packlets/editor/jsonEditorState.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;;;;;;GAoBG;;;AAEH,4CAAiF;AACjF,wCAA6G;AAW7G;;;GAGG;AACH,MAAa,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AAO,aAAP,OAAO,cAAP,OAAO,GAAI,kCAAkC,CAAC;gBACxD,MAAM;SACT;QACD,oBAAoB;QACpB,OAAO,IAAA,yBAAc,EAAC,OAAO,aAAP,OAAO,cAAP,OAAO,GAAI,IAAI,EAAE,MAAM,CAAC,CAAC;IACjD,CAAC;;AAvLH,0CAwLC;AAvLC;;;;GAIG;AACc,uBAAO,GAAW,CAAC,AAAZ,CAAa","sourcesContent":["/*\n * Copyright (c) 2020 Erik Fortune\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n */\n\nimport { DetailedFailure, Result, failWithDetail, succeed } from '@fgv/ts-utils';\nimport { IJsonContext, IJsonReferenceMap, JsonContextHelper, TemplateVars, VariableValue } from '../context';\nimport { JsonObject } from '../json';\nimport {\n IJsonCloneEditor,\n IJsonEditorOptions,\n IJsonEditorValidationOptions,\n JsonEditFailureReason,\n JsonEditorValidationRules,\n JsonPropertyEditFailureReason\n} from './common';\n\n/**\n * Represents the internal state of a {@link Editor.JsonEditor | JsonEditor}.\n * @public\n */\nexport class JsonEditorState {\n /**\n * Static global counter used to assign each {@link Editor.JsonEditorState | JsonEditorState}\n * a unique identifier.\n * @internal\n */\n protected static _nextId: number = 0;\n\n /**\n * The {@link Editor.IJsonCloneEditor | editor} for which this state applies.\n */\n public readonly editor: IJsonCloneEditor;\n\n /**\n * Fully resolved {@link Editor.IJsonEditorOptions | editor options} that apply\n * to the operation for which this state applies.\n */\n public readonly options: IJsonEditorOptions;\n\n /**\n * Any deferred {@link JsonObject | objects} to be merged during finalization.\n * @internal\n */\n protected readonly _deferred: JsonObject[] = [];\n\n /**\n * Unique global identifier for this {@link Editor.JsonEditorState | state object}.\n * @internal\n */\n protected readonly _id: number;\n\n /**\n * Constructs a new {@link Editor.JsonEditorState | JsonEditorState}.\n * @param editor - The {@link Editor.IJsonCloneEditor | editor} to which this state\n * applies.\n * @param baseOptions - The {@link Editor.IJsonEditorOptions | editor options} that\n * apply to this rule.\n * @param runtimeContext - An optional {@link IJsonContext | JSON context} to be used\n * for json value conversion.\n */\n public constructor(\n editor: IJsonCloneEditor,\n baseOptions: IJsonEditorOptions,\n runtimeContext?: IJsonContext\n ) {\n this.editor = editor;\n this.options = JsonEditorState._getEffectiveOptions(baseOptions, runtimeContext).orThrow();\n this._id = JsonEditorState._nextId++;\n }\n\n /**\n * The optional {@link IJsonContext | JSON context} for this state.\n */\n public get context(): IJsonContext | undefined {\n return this.options.context;\n }\n\n /**\n * An array of {@link JsonObject | objects} that are deferred for merge during\n * finalization.\n */\n public get deferred(): JsonObject[] {\n return this._deferred;\n }\n\n /**\n * Merges an optional {@link IJsonContext | JSON context} into a supplied set\n * of {@link Editor.IJsonEditorOptions | JSON editor options}.\n * @param options - The {@link Editor.IJsonEditorOptions | IJsonEditorOptions} into\n * which the the new context is to be merged.\n * @param context - The {@link IJsonContext | JSON context} to be merged into the\n * editor options.\n * @returns `Success` with the supplied {@link Editor.IJsonEditorOptions | options} if\n * there was nothing to merge, or aa new {@link Editor.IJsonEditorOptions | IJsonEditorOptions}\n * constructed from the base options merged with the supplied context. Returns `Failure`\n * with more information if an error occurs.\n * @internal\n */\n protected static _getEffectiveOptions(\n options: IJsonEditorOptions,\n context?: IJsonContext\n ): Result<IJsonEditorOptions> {\n if (!context) {\n return succeed(options);\n }\n return JsonContextHelper.mergeContext(options.context, context).onSuccess((merged) => {\n return succeed({ context: merged, validation: options.validation });\n });\n }\n\n /**\n * Adds a supplied {@link JsonObject | object} to the deferred list.\n * @param obj - The {@link JsonObject | object} to be deferred.\n */\n public defer(obj: JsonObject): void {\n this._deferred.push(obj);\n }\n\n /**\n * Gets a {@link TemplateVars | TemplateVars} from the context of this {@link Editor.JsonEditorState | JsonEditorState},\n * or from an optional supplied {@link IJsonContext | IJsonContext} if the current state has no default\n * context.\n * @param defaultContext - An optional default {@link IJsonContext | IJsonContext} to use as `TemplateVars`\n * if the current state does not have context.\n * @returns A {@link TemplateVars | TemplateVars} reflecting the appropriate {@link IJsonContext | JSON context}, or\n * `undefined` if no vars are found.\n */\n public getVars(defaultContext?: IJsonContext): TemplateVars | undefined {\n return this.options.context?.vars ?? defaultContext?.vars;\n }\n\n /**\n * Gets an {@link IJsonReferenceMap | reference map} containing any other values\n * referenced during the operation.\n * @param defaultContext - An optional default {@link IJsonContext | IJsonContext} to use as\n * {@link TemplateVars | TemplateVars} if the current state does not have context.\n * @returns An {@link IJsonReferenceMap | IJsonReferenceMap} containing any values referenced\n * during this operation.\n */\n public getRefs(defaultContext?: IJsonContext): IJsonReferenceMap | undefined {\n return this.options.context?.refs ?? defaultContext?.refs;\n }\n\n /**\n * Gets the context of this {@link Editor.JsonEditorState | JsonEditorState} or an optionally\n * supplied default context if this state has no context.\n * @param defaultContext - The default {@link IJsonContext | JSON context} to use as default\n * if this state has no context.\n * @returns The appropriate {@link IJsonContext | IJsonContext} or `undefined` if no context\n * is available.\n */\n public getContext(defaultContext?: IJsonContext): IJsonContext | undefined {\n return JsonContextHelper.mergeContext(defaultContext, this.options.context).orDefault();\n }\n\n /**\n * Constructs a new {@link IJsonContext | IJsonContext} by merging supplied variables\n * and references into a supplied existing context.\n * @param baseContext - The {@link IJsonContext | IJsonContext} into which variables\n * and references are to be merged, or `undefined` to start with a default empty context.\n * @param add - The {@link VariableValue | variable values} and/or\n * {@link IJsonReferenceMap | JSON entity references} to be merged into the base context.\n * @returns A new {@link IJsonContext | IJsonContext} created by merging the supplied values.\n */\n public extendContext(\n baseContext: IJsonContext | undefined,\n add: { vars?: VariableValue[]; refs?: IJsonReferenceMap[] }\n ): Result<IJsonContext | undefined> {\n const context = this.getContext(baseContext);\n return JsonContextHelper.extendContext(context, add);\n }\n\n /**\n * Helper method to constructs `DetailedFailure` with appropriate details and messaging\n * for various validation failures.\n * @param rule - The {@link Editor.JsonEditorValidationRules | validation rule} that failed.\n * @param message - A string message describing the failed validation.\n * @param validation - The {@link Editor.IJsonEditorValidationOptions | validation options}\n * in effect.\n * @returns A `DetailedFailure` with appropriate detail and message.\n */\n public failValidation<T = JsonObject>(\n rule: JsonEditorValidationRules,\n message?: string,\n validation?: IJsonEditorValidationOptions\n ): DetailedFailure<T, JsonEditFailureReason> {\n let detail: JsonPropertyEditFailureReason = 'error';\n const effective = validation ?? this.options.validation;\n switch (rule) {\n case 'invalidPropertyName':\n detail = effective.onInvalidPropertyName !== 'ignore' ? 'error' : 'inapplicable';\n break;\n case 'invalidPropertyValue':\n detail = effective.onInvalidPropertyValue !== 'ignore' ? 'error' : 'ignore';\n break;\n case 'undefinedPropertyValue':\n detail = effective.onUndefinedPropertyValue !== 'error' ? 'ignore' : 'error';\n /* c8 ignore next */\n message = message ?? 'Cannot convert undefined to JSON';\n break;\n }\n /* c8 ignore next */\n return failWithDetail(message ?? rule, detail);\n }\n}\n"]}
1
+ {"version":3,"file":"jsonEditorState.js","sourceRoot":"","sources":["../../../src/packlets/editor/jsonEditorState.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;;;;;;GAoBG;;;AAEH,4CAAiF;AACjF,wCAA6G;AAW7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;gBAC7E,oBAAoB;gBACpB,OAAO,GAAG,OAAO,aAAP,OAAO,cAAP,OAAO,GAAI,kCAAkC,CAAC;gBACxD,MAAM;QACV,CAAC;QACD,oBAAoB;QACpB,OAAO,IAAA,yBAAc,EAAC,OAAO,aAAP,OAAO,cAAP,OAAO,GAAI,IAAI,EAAE,MAAM,CAAC,CAAC;IACjD,CAAC;;AAvLH,0CAwLC;AAvLC;;;;GAIG;AACc,uBAAO,GAAW,CAAC,AAAZ,CAAa","sourcesContent":["/*\n * Copyright (c) 2020 Erik Fortune\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n */\n\nimport { DetailedFailure, Result, failWithDetail, succeed } from '@fgv/ts-utils';\nimport { IJsonContext, IJsonReferenceMap, JsonContextHelper, TemplateVars, VariableValue } from '../context';\nimport { JsonObject } from '../json';\nimport {\n IJsonCloneEditor,\n IJsonEditorOptions,\n IJsonEditorValidationOptions,\n JsonEditFailureReason,\n JsonEditorValidationRules,\n JsonPropertyEditFailureReason\n} from './common';\n\n/**\n * Represents the internal state of a {@link Editor.JsonEditor | JsonEditor}.\n * @public\n */\nexport class JsonEditorState {\n /**\n * Static global counter used to assign each {@link Editor.JsonEditorState | JsonEditorState}\n * a unique identifier.\n * @internal\n */\n protected static _nextId: number = 0;\n\n /**\n * The {@link Editor.IJsonCloneEditor | editor} for which this state applies.\n */\n public readonly editor: IJsonCloneEditor;\n\n /**\n * Fully resolved {@link Editor.IJsonEditorOptions | editor options} that apply\n * to the operation for which this state applies.\n */\n public readonly options: IJsonEditorOptions;\n\n /**\n * Any deferred {@link JsonObject | objects} to be merged during finalization.\n * @internal\n */\n protected readonly _deferred: JsonObject[] = [];\n\n /**\n * Unique global identifier for this {@link Editor.JsonEditorState | state object}.\n * @internal\n */\n protected readonly _id: number;\n\n /**\n * Constructs a new {@link Editor.JsonEditorState | JsonEditorState}.\n * @param editor - The {@link Editor.IJsonCloneEditor | editor} to which this state\n * applies.\n * @param baseOptions - The {@link Editor.IJsonEditorOptions | editor options} that\n * apply to this rule.\n * @param runtimeContext - An optional {@link IJsonContext | JSON context} to be used\n * for json value conversion.\n */\n public constructor(\n editor: IJsonCloneEditor,\n baseOptions: IJsonEditorOptions,\n runtimeContext?: IJsonContext\n ) {\n this.editor = editor;\n this.options = JsonEditorState._getEffectiveOptions(baseOptions, runtimeContext).orThrow();\n this._id = JsonEditorState._nextId++;\n }\n\n /**\n * The optional {@link IJsonContext | JSON context} for this state.\n */\n public get context(): IJsonContext | undefined {\n return this.options.context;\n }\n\n /**\n * An array of {@link JsonObject | objects} that are deferred for merge during\n * finalization.\n */\n public get deferred(): JsonObject[] {\n return this._deferred;\n }\n\n /**\n * Merges an optional {@link IJsonContext | JSON context} into a supplied set\n * of {@link Editor.IJsonEditorOptions | JSON editor options}.\n * @param options - The {@link Editor.IJsonEditorOptions | IJsonEditorOptions} into\n * which the the new context is to be merged.\n * @param context - The {@link IJsonContext | JSON context} to be merged into the\n * editor options.\n * @returns `Success` with the supplied {@link Editor.IJsonEditorOptions | options} if\n * there was nothing to merge, or aa new {@link Editor.IJsonEditorOptions | IJsonEditorOptions}\n * constructed from the base options merged with the supplied context. Returns `Failure`\n * with more information if an error occurs.\n * @internal\n */\n protected static _getEffectiveOptions(\n options: IJsonEditorOptions,\n context?: IJsonContext\n ): Result<IJsonEditorOptions> {\n if (!context) {\n return succeed(options);\n }\n return JsonContextHelper.mergeContext(options.context, context).onSuccess((merged) => {\n return succeed({ context: merged, validation: options.validation });\n });\n }\n\n /**\n * Adds a supplied {@link JsonObject | object} to the deferred list.\n * @param obj - The {@link JsonObject | object} to be deferred.\n */\n public defer(obj: JsonObject): void {\n this._deferred.push(obj);\n }\n\n /**\n * Gets a {@link TemplateVars | TemplateVars} from the context of this {@link Editor.JsonEditorState | JsonEditorState},\n * or from an optional supplied {@link IJsonContext | IJsonContext} if the current state has no default\n * context.\n * @param defaultContext - An optional default {@link IJsonContext | IJsonContext} to use as `TemplateVars`\n * if the current state does not have context.\n * @returns A {@link TemplateVars | TemplateVars} reflecting the appropriate {@link IJsonContext | JSON context}, or\n * `undefined` if no vars are found.\n */\n public getVars(defaultContext?: IJsonContext): TemplateVars | undefined {\n return this.options.context?.vars ?? defaultContext?.vars;\n }\n\n /**\n * Gets an {@link IJsonReferenceMap | reference map} containing any other values\n * referenced during the operation.\n * @param defaultContext - An optional default {@link IJsonContext | IJsonContext} to use as\n * {@link TemplateVars | TemplateVars} if the current state does not have context.\n * @returns An {@link IJsonReferenceMap | IJsonReferenceMap} containing any values referenced\n * during this operation.\n */\n public getRefs(defaultContext?: IJsonContext): IJsonReferenceMap | undefined {\n return this.options.context?.refs ?? defaultContext?.refs;\n }\n\n /**\n * Gets the context of this {@link Editor.JsonEditorState | JsonEditorState} or an optionally\n * supplied default context if this state has no context.\n * @param defaultContext - The default {@link IJsonContext | JSON context} to use as default\n * if this state has no context.\n * @returns The appropriate {@link IJsonContext | IJsonContext} or `undefined` if no context\n * is available.\n */\n public getContext(defaultContext?: IJsonContext): IJsonContext | undefined {\n return JsonContextHelper.mergeContext(defaultContext, this.options.context).orDefault();\n }\n\n /**\n * Constructs a new {@link IJsonContext | IJsonContext} by merging supplied variables\n * and references into a supplied existing context.\n * @param baseContext - The {@link IJsonContext | IJsonContext} into which variables\n * and references are to be merged, or `undefined` to start with a default empty context.\n * @param add - The {@link VariableValue | variable values} and/or\n * {@link IJsonReferenceMap | JSON entity references} to be merged into the base context.\n * @returns A new {@link IJsonContext | IJsonContext} created by merging the supplied values.\n */\n public extendContext(\n baseContext: IJsonContext | undefined,\n add: { vars?: VariableValue[]; refs?: IJsonReferenceMap[] }\n ): Result<IJsonContext | undefined> {\n const context = this.getContext(baseContext);\n return JsonContextHelper.extendContext(context, add);\n }\n\n /**\n * Helper method to constructs `DetailedFailure` with appropriate details and messaging\n * for various validation failures.\n * @param rule - The {@link Editor.JsonEditorValidationRules | validation rule} that failed.\n * @param message - A string message describing the failed validation.\n * @param validation - The {@link Editor.IJsonEditorValidationOptions | validation options}\n * in effect.\n * @returns A `DetailedFailure` with appropriate detail and message.\n */\n public failValidation<T = JsonObject>(\n rule: JsonEditorValidationRules,\n message?: string,\n validation?: IJsonEditorValidationOptions\n ): DetailedFailure<T, JsonEditFailureReason> {\n let detail: JsonPropertyEditFailureReason = 'error';\n const effective = validation ?? this.options.validation;\n switch (rule) {\n case 'invalidPropertyName':\n detail = effective.onInvalidPropertyName !== 'ignore' ? 'error' : 'inapplicable';\n break;\n case 'invalidPropertyValue':\n detail = effective.onInvalidPropertyValue !== 'ignore' ? 'error' : 'ignore';\n break;\n case 'undefinedPropertyValue':\n detail = effective.onUndefinedPropertyValue !== 'error' ? 'ignore' : 'error';\n /* c8 ignore next */\n message = message ?? 'Cannot convert undefined to JSON';\n break;\n }\n /* c8 ignore next */\n return failWithDetail(message ?? rule, detail);\n }\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"jsonReferenceMap.js","sourceRoot":"","sources":["../../../src/packlets/editor/jsonReferenceMap.ts"],"names":[],"mappings":";AAAA;;;;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AC,aAAa,EAAE,EAAE,SAAS,EAAE,IAAI,EAAE,CAAC,CAAC;SAChE;QACD,OAAO,IAAI,eAAe,CAAC,aAAa,CAAC,MAAM,EAAE,EAAE,SAAS,EAAE,aAAa,CAAC,SAAS,KAAK,KAAK,EAAE,CAAC,CAAC;IACrG,CAAC;CACF;AAzED,0CAyEC","sourcesContent":["/*\n * Copyright (c) 2020 Erik Fortune\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n */\n\nimport {\n DetailedResult,\n Result,\n captureResult,\n fail,\n failWithDetail,\n mapResults,\n recordToMap,\n succeed,\n succeedWithDetail\n} from '@fgv/ts-utils';\n\nimport { IJsonContext, IJsonReferenceMap, JsonReferenceMapFailureReason } from '../context';\nimport { JsonObject, JsonValue, isJsonObject } from '../json';\nimport { JsonEditor } from './jsonEditor';\n\n/**\n * Options for creating a {@link ReferenceMapKeyPolicy | ReferenceMapKeyPolicy} object.\n * @public\n */\nexport interface IReferenceMapKeyPolicyValidateOptions {\n /**\n * If `true`, the validator coerces keys to some valid value.\n * If `false`, invalid keys cause an error.\n */\n makeValid?: boolean;\n}\n\n/**\n * Policy object responsible for validating or correcting\n * keys in a {@link IJsonReferenceMap | reference map}.\n * @public\n */\nexport class ReferenceMapKeyPolicy<T> {\n /**\n * @internal\n */\n protected readonly _defaultOptions?: IReferenceMapKeyPolicyValidateOptions;\n\n /**\n * @internal\n */\n protected readonly _isValid: (key: string, item?: T) => boolean;\n\n /**\n * Constructs a new {@link ReferenceMapKeyPolicy | ReferenceMapKeyPolicy}.\n * @param options - Optional {@link IReferenceMapKeyPolicyValidateOptions | options}\n * used to construct the {@link ReferenceMapKeyPolicy}.\n * @param isValid - An optional predicate to test a supplied key for validity.\n */\n public constructor(\n options?: IReferenceMapKeyPolicyValidateOptions,\n isValid?: (key: string, item?: T) => boolean\n ) {\n this._defaultOptions = options;\n this._isValid = isValid ?? ReferenceMapKeyPolicy.defaultKeyPredicate;\n }\n\n /**\n * The static default key name validation predicate rejects keys that contain\n * mustache templates or which start with the default conditional prefix\n * `'?'`.\n * @param key - The key to test.\n * @returns `true` if the key is valid, `false` otherwise.\n */\n public static defaultKeyPredicate(key: string): boolean {\n return key.length > 0 && !key.includes('{{') && !key.startsWith('?');\n }\n\n /**\n * Determines if a supplied key and item are valid according to the current policy.\n * @param key - The key to be tested.\n * @param item - The item to be tested.\n * @returns `true` if the key and value are valid, `false` otherwise.\n */\n public isValid(key: string, item?: T): boolean {\n return this._isValid(key, item);\n }\n\n /**\n * Determines if a supplied key and item are valid according to the current policy.\n * @param key - The key to be tested.\n * @param item - The item to be tested.\n * @returns `Success` with the key if valid, `Failure` with an error message if invalid.\n */\n public validate(key: string, item?: T, __options?: IReferenceMapKeyPolicyValidateOptions): Result<string> {\n return this.isValid(key, item) ? succeed(key) : fail(`${key}: invalid key`);\n }\n\n /**\n * Validates an array of entries using the validation rules for this policy.\n * @param items - The array of entries to be validated.\n * @param options - Optional {@link IReferenceMapKeyPolicyValidateOptions | options} to control\n * validation.\n * @returns `Success` with an array of validated entries, or `Failure` with an error message\n * if validation fails.\n */\n public validateItems(\n items: [string, T][],\n options?: IReferenceMapKeyPolicyValidateOptions\n ): Result<[string, T][]> {\n return mapResults(\n items.map((item) => {\n return this.validate(...item, options).onSuccess((valid) => {\n return succeed([valid, item[1]]);\n });\n })\n );\n }\n\n /**\n * Validates a `Map\\<string, T\\>` using the validation rules for this policy.\n * @param items - The `Map\\<string, T\\>` to be validated.\n * @param options - Optional {@link IReferenceMapKeyPolicyValidateOptions | options} to control\n * validation.\n * @returns `Success` with a new `Map\\<string, T\\>`, or `Failure` with an error message\n * if validation fails.\n */\n public validateMap(\n map: Map<string, T>,\n options?: IReferenceMapKeyPolicyValidateOptions\n ): Result<Map<string, T>> {\n return this.validateItems(Array.from(map.entries()), options).onSuccess((valid) => {\n return captureResult(() => new Map(valid));\n });\n }\n}\n\n/**\n * A {@link PrefixKeyPolicy | PrefixKeyPolicy} enforces that all keys start with a supplied\n * prefix, optionally adding the prefix as necessary.\n * @public\n */\nexport class PrefixKeyPolicy<T> extends ReferenceMapKeyPolicy<T> {\n /**\n * The string prefix to be enforced by this policy.\n */\n public readonly prefix: string;\n\n /**\n * Constructs a new {@link PrefixKeyPolicy | PrefixKeyPolicy}.\n * @param prefix - The string prefix to be enforced or applied.\n * @param options - Optional {@link IReferenceMapKeyPolicyValidateOptions | options} to\n * configure the policy.\n */\n public constructor(prefix: string, options?: IReferenceMapKeyPolicyValidateOptions) {\n super(options);\n this.prefix = prefix;\n }\n\n /**\n * Determines if a key is valid according to policy.\n * @param key - The key to be tested.\n * @param __item - The item to be tested.\n * @returns `true` if the key starts with the expected prefix, `false` otherwise.\n */\n public isValid(key: string, __item?: T): boolean {\n return (\n key.startsWith(this.prefix) && key !== this.prefix && ReferenceMapKeyPolicy.defaultKeyPredicate(key)\n );\n }\n\n /**\n * Determines if a key is valid according to policy, optionally coercing to a valid value by\n * adding the required prefix.\n * @param key - The key to be tested.\n * @param item - The item which corresponds to the key.\n * @param options - Optional {@link IReferenceMapKeyPolicyValidateOptions | options} to guide\n * validation.\n * @returns `Success` with a valid key name if the supplied key is valid or if `makeValid` is set\n * in the policy options. Returns `Failure` with an error message if an error occurs.\n */\n public validate(key: string, item?: T, options?: IReferenceMapKeyPolicyValidateOptions): Result<string> {\n /* c8 ignore next */\n const makeValid = (options ?? this._defaultOptions)?.makeValid === true;\n if (this.isValid(key, item)) {\n return succeed(key);\n } else if (makeValid && ReferenceMapKeyPolicy.defaultKeyPredicate(key)) {\n return succeed(`${this.prefix}${key}`);\n }\n return fail(`${key}: invalid key`);\n }\n}\n\n/**\n * Type representing either a `Map\\<string, T\\>` or a `Record\\<string, T\\>`.\n * @public\n */\nexport type MapOrRecord<T> = Map<string, T> | Record<string, T>;\n\n/**\n * Abstract base class with common functionality for simple\n * {@link IJsonReferenceMap | reference map} implementations.\n * {@link JsonValue | json values}.\n * @public\n */\nexport abstract class SimpleJsonMapBase<T> implements IJsonReferenceMap {\n /**\n * The {@link ReferenceMapKeyPolicy | key policy} in effect for this map.\n * @internal\n */\n protected readonly _keyPolicy: ReferenceMapKeyPolicy<T>;\n\n /**\n * A map containing keys and values already present in this map.\n * @internal\n */\n protected readonly _values: Map<string, T>;\n\n /**\n * An optional {@link IJsonContext | IJsonContext} used for any conversions\n * involving items in this map.\n * @internal\n */\n protected readonly _context?: IJsonContext;\n\n /**\n * Constructs a new {@link SimpleJsonMap | SimpleJsonMap}.\n * @param values - Initial values for the map.\n * @param context - An optional {@link IJsonContext | IJsonContext} used for any conversions\n * involving items in this map.\n * @param keyPolicy - The {@link ReferenceMapKeyPolicy | key policy} to use for this map.\n * @internal\n */\n protected constructor(\n values?: MapOrRecord<T>,\n context?: IJsonContext,\n keyPolicy?: ReferenceMapKeyPolicy<T>\n ) {\n values = SimpleJsonMapBase._toMap(values).orThrow();\n this._keyPolicy = keyPolicy ?? new ReferenceMapKeyPolicy();\n this._values = this._keyPolicy.validateMap(values).orThrow();\n this._context = context;\n }\n\n /**\n * Returns a `Map\\<string, T\\>` derived from a supplied {@link MapOrRecord | MapOrRecord}\n * @param values - The {@link MapOrRecord | MapOrRecord} to be returned as a map.\n * @returns `Success` with the corresponding `Map\\<string, T\\>` or `Failure` with a\n * message if an error occurs.\n * @internal\n */\n protected static _toMap<T>(values?: MapOrRecord<T>): Result<Map<string, T>> {\n if (values === undefined) {\n return captureResult(() => new Map<string, T>());\n } else if (!(values instanceof Map)) {\n return recordToMap(values, (__k, v) => succeed(v));\n }\n return succeed(values);\n }\n\n /**\n * Determine if a key might be valid for this map but does not determine if key actually\n * exists. Allows key range to be constrained.\n * @param key - key to be tested\n * @returns `true` if the key is in the valid range, `false` otherwise.\n */\n public keyIsInRange(key: string): boolean {\n return this._keyPolicy.isValid(key);\n }\n\n /**\n * Determines if an entry with the specified key actually exists in the map.\n * @param key - key to be tested\n * @returns `true` if an object with the specified key exists, `false` otherwise.\n */\n public has(key: string): boolean {\n return this._values.has(key);\n }\n\n /**\n * Gets a {@link JsonObject | JSON object} specified by key.\n * @param key - key of the object to be retrieved\n * @param context - optional {@link IJsonContext | JSON context} used to format the\n * returned object.\n * @returns {@link ts-utils#Success | `Success`} with the formatted object if successful.\n * {@link ts-utils#Failure | `Failure`} with detail 'unknown' if no such object exists,\n * or {@link ts-utils#Failure | `Failure`} with detail 'error' if the object was found\n * but could not be formatted.\n */\n public getJsonObject(\n key: string,\n context?: IJsonContext\n ): DetailedResult<JsonObject, JsonReferenceMapFailureReason> {\n return this.getJsonValue(key, context).onSuccess((jv) => {\n if (!isJsonObject(jv)) {\n return failWithDetail(`${key}: not an object`, 'error');\n }\n return succeedWithDetail(jv);\n });\n }\n\n /**\n * Gets a {@link JsonValue | JSON value} specified by key.\n * @param key - key of the value to be retrieved\n * @param context - Optional {@link IJsonContext | JSON context} used to format the value\n * @returns Success with the formatted object if successful. Failure with detail 'unknown'\n * if no such object exists, or failure with detail 'error' if the object was found but\n * could not be formatted.\n */\n // eslint-disable-next-line no-use-before-define\n public abstract getJsonValue(\n key: string,\n context?: IJsonContext\n ): DetailedResult<JsonValue, JsonReferenceMapFailureReason>;\n}\n\n/**\n * Initialization options for a {@link SimpleJsonMap | SimpleJsonMap}.\n * @public\n */\nexport interface ISimpleJsonMapOptions {\n keyPolicy?: ReferenceMapKeyPolicy<JsonValue>;\n editor?: JsonEditor;\n}\n\n/**\n * A {@link SimpleJsonMap | SimpleJsonMap } presents a view of a simple map\n * of {@link JsonValue | JSON values}.\n * @public\n */\nexport class SimpleJsonMap extends SimpleJsonMapBase<JsonValue> {\n /**\n * @internal\n */\n protected _editor?: JsonEditor;\n\n /**\n * Constructs a new {@link SimpleJsonMap | SimpleJsonMap} from the supplied objects\n * @param values - A string-keyed `Map` or `Record` of the {@link JsonValue | JSON values}\n * to be returned.\n * @param context - Optional {@link IJsonContext | IJsonContext} used to format returned values.\n * @param options - Optional {@link ISimpleJsonMapOptions | ISimpleJsonMapOptions} for initialization.\n * @public\n */\n protected constructor(\n values?: MapOrRecord<JsonValue>,\n context?: IJsonContext,\n options?: ISimpleJsonMapOptions\n ) {\n super(values, context, options?.keyPolicy);\n this._editor = options?.editor;\n }\n\n /**\n * Creates a new {@link SimpleJsonMap | SimpleJsonMap} from the supplied objects\n * @param values - A string-keyed `Map` or `Record` of the {@link JsonValue | JSON values}\n * to be returned.\n * @param context - Optional {@link IJsonContext | IJsonContext} used to format returned values.\n * @param options - Optional {@link ISimpleJsonMapOptions | ISimpleJsonMapOptions} for initialization.\n * @returns `Success` with a {@link SimpleJsonMap | SimpleJsonMap} or `Failure` with a message if\n * an error occurs.\n */\n public static createSimple(\n values?: MapOrRecord<JsonValue>,\n context?: IJsonContext,\n options?: ISimpleJsonMapOptions\n ): Result<SimpleJsonMap> {\n return captureResult(() => new SimpleJsonMap(values, context, options));\n }\n\n /**\n * Gets a {@link JsonValue | JSON value} specified by key.\n * @param key - key of the value to be retrieved\n * @param context - Optional {@link IJsonContext | JSON context} used to format the value\n * @returns Success with the formatted object if successful. Failure with detail 'unknown'\n * if no such object exists, or failure with detail 'error' if the object was found but\n * could not be formatted.\n */\n public getJsonValue(\n key: string,\n context?: IJsonContext\n ): DetailedResult<JsonValue, JsonReferenceMapFailureReason> {\n context = context ?? this._context;\n const value = this._values.get(key);\n if (!value) {\n return failWithDetail(`${key}: JSON value not found`, 'unknown');\n }\n return this._clone(value, context);\n }\n\n /**\n * @internal\n */\n protected _clone(\n value: JsonValue,\n context?: IJsonContext\n ): DetailedResult<JsonValue, JsonReferenceMapFailureReason> {\n if (!this._editor) {\n const result = JsonEditor.create();\n /* c8 ignore next 3 - nearly impossible to reproduce */\n if (result.isFailure()) {\n return failWithDetail(result.message, 'error');\n }\n this._editor = result.value;\n }\n return this._editor.clone(value, context).withFailureDetail('error');\n }\n}\n\n/**\n * Initialization options for a {@link PrefixedJsonMap | PrefixedJsonMap}\n * @public\n */\nexport interface IKeyPrefixOptions {\n /**\n * Indicates whether the prefix should be added automatically as needed (default true)\n */\n addPrefix?: boolean;\n\n /**\n * The prefix to be enforced\n */\n prefix: string;\n}\n\n/**\n * A {@link PrefixedJsonMap | PrefixedJsonMap} enforces a supplied prefix for all contained values,\n * optionally adding the prefix as necessary (default `true`).\n * @public\n */\nexport class PrefixedJsonMap extends SimpleJsonMap {\n /**\n * Constructs a new {@link PrefixedJsonMap | PrefixedJsonMap} from the supplied values\n * @param prefix - A string prefix to be enforced for and added to key names as necessary\n * @param values - A string-keyed Map or Record of the {@link JsonValue | JsonValue} to be returned\n * @param context - Optional {@link IJsonContext | JSON Context} used to format returned values\n * @param editor - Optional {@link Editor.JsonEditor | JsonEditor} used to format returned values\n * @public\n */\n protected constructor(\n values?: MapOrRecord<JsonValue>,\n context?: IJsonContext,\n options?: ISimpleJsonMapOptions\n ) {\n super(values, context, options);\n }\n\n /**\n * Creates a new {@link PrefixedJsonMap | PrefixedJsonMap} from the supplied values\n * @param prefix - A string prefix to be enforced for and added to key names as necessary\n * @param values - A string-keyed Map or Record of the {@link JsonValue | JsonValue} to be returned\n * @param context - Optional {@link IJsonContext | JSON Context} used to format returned values\n * @param editor - Optional {@link Editor.JsonEditor | JsonEditor} used to format returned values\n * @returns `Success` with a {@link PrefixedJsonMap | PrefixedJsonMap} or `Failure` with a message\n * if an error occurs.\n */\n public static createPrefixed(\n prefix: string,\n values?: MapOrRecord<JsonValue>,\n context?: IJsonContext,\n editor?: JsonEditor\n ): Result<PrefixedJsonMap>;\n\n /**\n * Creates a new {@link PrefixedJsonMap | PrefixedJsonMap} from the supplied values\n * @param prefixOptions - A KeyPrefixOptions indicating the prefix to enforce and whether that prefix should\n * be added automatically if necessary (default true)\n * @param values - A string-keyed Map or record of the {@link JsonValue | JsonValue} to be returned\n * @param context - Optional {@link IJsonContext | JSON Context} used to format returned values\n * @param editor - Optional {@link Editor.JsonEditor | JsonEditor} used to format returned values\n */\n public static createPrefixed(\n prefixOptions: IKeyPrefixOptions,\n values?: MapOrRecord<JsonValue>,\n context?: IJsonContext,\n editor?: JsonEditor\n ): Result<PrefixedJsonMap>;\n public static createPrefixed(\n prefixOptions: string | IKeyPrefixOptions,\n values?: MapOrRecord<JsonValue>,\n context?: IJsonContext,\n editor?: JsonEditor\n ): Result<PrefixedJsonMap> {\n return captureResult(\n () => new PrefixedJsonMap(values, context, { keyPolicy: this._toPolicy(prefixOptions), editor })\n );\n }\n\n /**\n * Constructs a new {@link PrefixKeyPolicy | PrefixKeyPolicy} from a supplied prefix\n * or set of {@link IKeyPrefixOptions | prefix options}.\n * @param prefixOptions - The prefix or {@link IKeyPrefixOptions | prefix options} or options\n * for the new policy.\n * @returns A new {@link ReferenceMapKeyPolicy | ReferenceMapKeyPolicy} which enforces the\n * supplied prefix or options.\n * @internal\n */\n protected static _toPolicy(prefixOptions: string | IKeyPrefixOptions): ReferenceMapKeyPolicy<JsonValue> {\n if (typeof prefixOptions === 'string') {\n return new PrefixKeyPolicy(prefixOptions, { makeValid: true });\n }\n return new PrefixKeyPolicy(prefixOptions.prefix, { makeValid: prefixOptions.addPrefix !== false });\n }\n}\n"]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AC,SAAS,CAAC,aAAa,CAAC,EAAE,MAAM,EAAE,CAAC,CACjG,CAAC;IACJ,CAAC;IAED;;;;;;;;OAQG;IACO,MAAM,CAAC,SAAS,CAAC,aAAyC;QAClE,IAAI,OAAO,aAAa,KAAK,QAAQ,EAAE,CAAC;YACtC,OAAO,IAAI,eAAe,CAAC,aAAa,EAAE,EAAE,SAAS,EAAE,IAAI,EAAE,CAAC,CAAC;QACjE,CAAC;QACD,OAAO,IAAI,eAAe,CAAC,aAAa,CAAC,MAAM,EAAE,EAAE,SAAS,EAAE,aAAa,CAAC,SAAS,KAAK,KAAK,EAAE,CAAC,CAAC;IACrG,CAAC;CACF;AAzED,0CAyEC","sourcesContent":["/*\n * Copyright (c) 2020 Erik Fortune\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n */\n\nimport {\n DetailedResult,\n Result,\n captureResult,\n fail,\n failWithDetail,\n mapResults,\n recordToMap,\n succeed,\n succeedWithDetail\n} from '@fgv/ts-utils';\n\nimport { IJsonContext, IJsonReferenceMap, JsonReferenceMapFailureReason } from '../context';\nimport { JsonObject, JsonValue, isJsonObject } from '../json';\nimport { JsonEditor } from './jsonEditor';\n\n/**\n * Options for creating a {@link ReferenceMapKeyPolicy | ReferenceMapKeyPolicy} object.\n * @public\n */\nexport interface IReferenceMapKeyPolicyValidateOptions {\n /**\n * If `true`, the validator coerces keys to some valid value.\n * If `false`, invalid keys cause an error.\n */\n makeValid?: boolean;\n}\n\n/**\n * Policy object responsible for validating or correcting\n * keys in a {@link IJsonReferenceMap | reference map}.\n * @public\n */\nexport class ReferenceMapKeyPolicy<T> {\n /**\n * @internal\n */\n protected readonly _defaultOptions?: IReferenceMapKeyPolicyValidateOptions;\n\n /**\n * @internal\n */\n protected readonly _isValid: (key: string, item?: T) => boolean;\n\n /**\n * Constructs a new {@link ReferenceMapKeyPolicy | ReferenceMapKeyPolicy}.\n * @param options - Optional {@link IReferenceMapKeyPolicyValidateOptions | options}\n * used to construct the {@link ReferenceMapKeyPolicy}.\n * @param isValid - An optional predicate to test a supplied key for validity.\n */\n public constructor(\n options?: IReferenceMapKeyPolicyValidateOptions,\n isValid?: (key: string, item?: T) => boolean\n ) {\n this._defaultOptions = options;\n this._isValid = isValid ?? ReferenceMapKeyPolicy.defaultKeyPredicate;\n }\n\n /**\n * The static default key name validation predicate rejects keys that contain\n * mustache templates or which start with the default conditional prefix\n * `'?'`.\n * @param key - The key to test.\n * @returns `true` if the key is valid, `false` otherwise.\n */\n public static defaultKeyPredicate(key: string): boolean {\n return key.length > 0 && !key.includes('{{') && !key.startsWith('?');\n }\n\n /**\n * Determines if a supplied key and item are valid according to the current policy.\n * @param key - The key to be tested.\n * @param item - The item to be tested.\n * @returns `true` if the key and value are valid, `false` otherwise.\n */\n public isValid(key: string, item?: T): boolean {\n return this._isValid(key, item);\n }\n\n /**\n * Determines if a supplied key and item are valid according to the current policy.\n * @param key - The key to be tested.\n * @param item - The item to be tested.\n * @returns `Success` with the key if valid, `Failure` with an error message if invalid.\n */\n public validate(key: string, item?: T, __options?: IReferenceMapKeyPolicyValidateOptions): Result<string> {\n return this.isValid(key, item) ? succeed(key) : fail(`${key}: invalid key`);\n }\n\n /**\n * Validates an array of entries using the validation rules for this policy.\n * @param items - The array of entries to be validated.\n * @param options - Optional {@link IReferenceMapKeyPolicyValidateOptions | options} to control\n * validation.\n * @returns `Success` with an array of validated entries, or `Failure` with an error message\n * if validation fails.\n */\n public validateItems(\n items: [string, T][],\n options?: IReferenceMapKeyPolicyValidateOptions\n ): Result<[string, T][]> {\n return mapResults(\n items.map((item) => {\n return this.validate(...item, options).onSuccess((valid) => {\n return succeed([valid, item[1]]);\n });\n })\n );\n }\n\n /**\n * Validates a `Map\\<string, T\\>` using the validation rules for this policy.\n * @param items - The `Map\\<string, T\\>` to be validated.\n * @param options - Optional {@link IReferenceMapKeyPolicyValidateOptions | options} to control\n * validation.\n * @returns `Success` with a new `Map\\<string, T\\>`, or `Failure` with an error message\n * if validation fails.\n */\n public validateMap(\n map: Map<string, T>,\n options?: IReferenceMapKeyPolicyValidateOptions\n ): Result<Map<string, T>> {\n return this.validateItems(Array.from(map.entries()), options).onSuccess((valid) => {\n return captureResult(() => new Map(valid));\n });\n }\n}\n\n/**\n * A {@link PrefixKeyPolicy | PrefixKeyPolicy} enforces that all keys start with a supplied\n * prefix, optionally adding the prefix as necessary.\n * @public\n */\nexport class PrefixKeyPolicy<T> extends ReferenceMapKeyPolicy<T> {\n /**\n * The string prefix to be enforced by this policy.\n */\n public readonly prefix: string;\n\n /**\n * Constructs a new {@link PrefixKeyPolicy | PrefixKeyPolicy}.\n * @param prefix - The string prefix to be enforced or applied.\n * @param options - Optional {@link IReferenceMapKeyPolicyValidateOptions | options} to\n * configure the policy.\n */\n public constructor(prefix: string, options?: IReferenceMapKeyPolicyValidateOptions) {\n super(options);\n this.prefix = prefix;\n }\n\n /**\n * Determines if a key is valid according to policy.\n * @param key - The key to be tested.\n * @param __item - The item to be tested.\n * @returns `true` if the key starts with the expected prefix, `false` otherwise.\n */\n public isValid(key: string, __item?: T): boolean {\n return (\n key.startsWith(this.prefix) && key !== this.prefix && ReferenceMapKeyPolicy.defaultKeyPredicate(key)\n );\n }\n\n /**\n * Determines if a key is valid according to policy, optionally coercing to a valid value by\n * adding the required prefix.\n * @param key - The key to be tested.\n * @param item - The item which corresponds to the key.\n * @param options - Optional {@link IReferenceMapKeyPolicyValidateOptions | options} to guide\n * validation.\n * @returns `Success` with a valid key name if the supplied key is valid or if `makeValid` is set\n * in the policy options. Returns `Failure` with an error message if an error occurs.\n */\n public validate(key: string, item?: T, options?: IReferenceMapKeyPolicyValidateOptions): Result<string> {\n /* c8 ignore next */\n const makeValid = (options ?? this._defaultOptions)?.makeValid === true;\n if (this.isValid(key, item)) {\n return succeed(key);\n } else if (makeValid && ReferenceMapKeyPolicy.defaultKeyPredicate(key)) {\n return succeed(`${this.prefix}${key}`);\n }\n return fail(`${key}: invalid key`);\n }\n}\n\n/**\n * Type representing either a `Map\\<string, T\\>` or a `Record\\<string, T\\>`.\n * @public\n */\nexport type MapOrRecord<T> = Map<string, T> | Record<string, T>;\n\n/**\n * Abstract base class with common functionality for simple\n * {@link IJsonReferenceMap | reference map} implementations.\n * {@link JsonValue | json values}.\n * @public\n */\nexport abstract class SimpleJsonMapBase<T> implements IJsonReferenceMap {\n /**\n * The {@link ReferenceMapKeyPolicy | key policy} in effect for this map.\n * @internal\n */\n protected readonly _keyPolicy: ReferenceMapKeyPolicy<T>;\n\n /**\n * A map containing keys and values already present in this map.\n * @internal\n */\n protected readonly _values: Map<string, T>;\n\n /**\n * An optional {@link IJsonContext | IJsonContext} used for any conversions\n * involving items in this map.\n * @internal\n */\n protected readonly _context?: IJsonContext;\n\n /**\n * Constructs a new {@link SimpleJsonMap | SimpleJsonMap}.\n * @param values - Initial values for the map.\n * @param context - An optional {@link IJsonContext | IJsonContext} used for any conversions\n * involving items in this map.\n * @param keyPolicy - The {@link ReferenceMapKeyPolicy | key policy} to use for this map.\n * @internal\n */\n protected constructor(\n values?: MapOrRecord<T>,\n context?: IJsonContext,\n keyPolicy?: ReferenceMapKeyPolicy<T>\n ) {\n values = SimpleJsonMapBase._toMap(values).orThrow();\n this._keyPolicy = keyPolicy ?? new ReferenceMapKeyPolicy();\n this._values = this._keyPolicy.validateMap(values).orThrow();\n this._context = context;\n }\n\n /**\n * Returns a `Map\\<string, T\\>` derived from a supplied {@link MapOrRecord | MapOrRecord}\n * @param values - The {@link MapOrRecord | MapOrRecord} to be returned as a map.\n * @returns `Success` with the corresponding `Map\\<string, T\\>` or `Failure` with a\n * message if an error occurs.\n * @internal\n */\n protected static _toMap<T>(values?: MapOrRecord<T>): Result<Map<string, T>> {\n if (values === undefined) {\n return captureResult(() => new Map<string, T>());\n } else if (!(values instanceof Map)) {\n return recordToMap(values, (__k, v) => succeed(v));\n }\n return succeed(values);\n }\n\n /**\n * Determine if a key might be valid for this map but does not determine if key actually\n * exists. Allows key range to be constrained.\n * @param key - key to be tested\n * @returns `true` if the key is in the valid range, `false` otherwise.\n */\n public keyIsInRange(key: string): boolean {\n return this._keyPolicy.isValid(key);\n }\n\n /**\n * Determines if an entry with the specified key actually exists in the map.\n * @param key - key to be tested\n * @returns `true` if an object with the specified key exists, `false` otherwise.\n */\n public has(key: string): boolean {\n return this._values.has(key);\n }\n\n /**\n * Gets a {@link JsonObject | JSON object} specified by key.\n * @param key - key of the object to be retrieved\n * @param context - optional {@link IJsonContext | JSON context} used to format the\n * returned object.\n * @returns {@link ts-utils#Success | `Success`} with the formatted object if successful.\n * {@link ts-utils#Failure | `Failure`} with detail 'unknown' if no such object exists,\n * or {@link ts-utils#Failure | `Failure`} with detail 'error' if the object was found\n * but could not be formatted.\n */\n public getJsonObject(\n key: string,\n context?: IJsonContext\n ): DetailedResult<JsonObject, JsonReferenceMapFailureReason> {\n return this.getJsonValue(key, context).onSuccess((jv) => {\n if (!isJsonObject(jv)) {\n return failWithDetail(`${key}: not an object`, 'error');\n }\n return succeedWithDetail(jv);\n });\n }\n\n /**\n * Gets a {@link JsonValue | JSON value} specified by key.\n * @param key - key of the value to be retrieved\n * @param context - Optional {@link IJsonContext | JSON context} used to format the value\n * @returns Success with the formatted object if successful. Failure with detail 'unknown'\n * if no such object exists, or failure with detail 'error' if the object was found but\n * could not be formatted.\n */\n // eslint-disable-next-line no-use-before-define\n public abstract getJsonValue(\n key: string,\n context?: IJsonContext\n ): DetailedResult<JsonValue, JsonReferenceMapFailureReason>;\n}\n\n/**\n * Initialization options for a {@link SimpleJsonMap | SimpleJsonMap}.\n * @public\n */\nexport interface ISimpleJsonMapOptions {\n keyPolicy?: ReferenceMapKeyPolicy<JsonValue>;\n editor?: JsonEditor;\n}\n\n/**\n * A {@link SimpleJsonMap | SimpleJsonMap } presents a view of a simple map\n * of {@link JsonValue | JSON values}.\n * @public\n */\nexport class SimpleJsonMap extends SimpleJsonMapBase<JsonValue> {\n /**\n * @internal\n */\n protected _editor?: JsonEditor;\n\n /**\n * Constructs a new {@link SimpleJsonMap | SimpleJsonMap} from the supplied objects\n * @param values - A string-keyed `Map` or `Record` of the {@link JsonValue | JSON values}\n * to be returned.\n * @param context - Optional {@link IJsonContext | IJsonContext} used to format returned values.\n * @param options - Optional {@link ISimpleJsonMapOptions | ISimpleJsonMapOptions} for initialization.\n * @public\n */\n protected constructor(\n values?: MapOrRecord<JsonValue>,\n context?: IJsonContext,\n options?: ISimpleJsonMapOptions\n ) {\n super(values, context, options?.keyPolicy);\n this._editor = options?.editor;\n }\n\n /**\n * Creates a new {@link SimpleJsonMap | SimpleJsonMap} from the supplied objects\n * @param values - A string-keyed `Map` or `Record` of the {@link JsonValue | JSON values}\n * to be returned.\n * @param context - Optional {@link IJsonContext | IJsonContext} used to format returned values.\n * @param options - Optional {@link ISimpleJsonMapOptions | ISimpleJsonMapOptions} for initialization.\n * @returns `Success` with a {@link SimpleJsonMap | SimpleJsonMap} or `Failure` with a message if\n * an error occurs.\n */\n public static createSimple(\n values?: MapOrRecord<JsonValue>,\n context?: IJsonContext,\n options?: ISimpleJsonMapOptions\n ): Result<SimpleJsonMap> {\n return captureResult(() => new SimpleJsonMap(values, context, options));\n }\n\n /**\n * Gets a {@link JsonValue | JSON value} specified by key.\n * @param key - key of the value to be retrieved\n * @param context - Optional {@link IJsonContext | JSON context} used to format the value\n * @returns Success with the formatted object if successful. Failure with detail 'unknown'\n * if no such object exists, or failure with detail 'error' if the object was found but\n * could not be formatted.\n */\n public getJsonValue(\n key: string,\n context?: IJsonContext\n ): DetailedResult<JsonValue, JsonReferenceMapFailureReason> {\n context = context ?? this._context;\n const value = this._values.get(key);\n if (!value) {\n return failWithDetail(`${key}: JSON value not found`, 'unknown');\n }\n return this._clone(value, context);\n }\n\n /**\n * @internal\n */\n protected _clone(\n value: JsonValue,\n context?: IJsonContext\n ): DetailedResult<JsonValue, JsonReferenceMapFailureReason> {\n if (!this._editor) {\n const result = JsonEditor.create();\n /* c8 ignore next 3 - nearly impossible to reproduce */\n if (result.isFailure()) {\n return failWithDetail(result.message, 'error');\n }\n this._editor = result.value;\n }\n return this._editor.clone(value, context).withFailureDetail('error');\n }\n}\n\n/**\n * Initialization options for a {@link PrefixedJsonMap | PrefixedJsonMap}\n * @public\n */\nexport interface IKeyPrefixOptions {\n /**\n * Indicates whether the prefix should be added automatically as needed (default true)\n */\n addPrefix?: boolean;\n\n /**\n * The prefix to be enforced\n */\n prefix: string;\n}\n\n/**\n * A {@link PrefixedJsonMap | PrefixedJsonMap} enforces a supplied prefix for all contained values,\n * optionally adding the prefix as necessary (default `true`).\n * @public\n */\nexport class PrefixedJsonMap extends SimpleJsonMap {\n /**\n * Constructs a new {@link PrefixedJsonMap | PrefixedJsonMap} from the supplied values\n * @param prefix - A string prefix to be enforced for and added to key names as necessary\n * @param values - A string-keyed Map or Record of the {@link JsonValue | JsonValue} to be returned\n * @param context - Optional {@link IJsonContext | JSON Context} used to format returned values\n * @param editor - Optional {@link Editor.JsonEditor | JsonEditor} used to format returned values\n * @public\n */\n protected constructor(\n values?: MapOrRecord<JsonValue>,\n context?: IJsonContext,\n options?: ISimpleJsonMapOptions\n ) {\n super(values, context, options);\n }\n\n /**\n * Creates a new {@link PrefixedJsonMap | PrefixedJsonMap} from the supplied values\n * @param prefix - A string prefix to be enforced for and added to key names as necessary\n * @param values - A string-keyed Map or Record of the {@link JsonValue | JsonValue} to be returned\n * @param context - Optional {@link IJsonContext | JSON Context} used to format returned values\n * @param editor - Optional {@link Editor.JsonEditor | JsonEditor} used to format returned values\n * @returns `Success` with a {@link PrefixedJsonMap | PrefixedJsonMap} or `Failure` with a message\n * if an error occurs.\n */\n public static createPrefixed(\n prefix: string,\n values?: MapOrRecord<JsonValue>,\n context?: IJsonContext,\n editor?: JsonEditor\n ): Result<PrefixedJsonMap>;\n\n /**\n * Creates a new {@link PrefixedJsonMap | PrefixedJsonMap} from the supplied values\n * @param prefixOptions - A KeyPrefixOptions indicating the prefix to enforce and whether that prefix should\n * be added automatically if necessary (default true)\n * @param values - A string-keyed Map or record of the {@link JsonValue | JsonValue} to be returned\n * @param context - Optional {@link IJsonContext | JSON Context} used to format returned values\n * @param editor - Optional {@link Editor.JsonEditor | JsonEditor} used to format returned values\n */\n public static createPrefixed(\n prefixOptions: IKeyPrefixOptions,\n values?: MapOrRecord<JsonValue>,\n context?: IJsonContext,\n editor?: JsonEditor\n ): Result<PrefixedJsonMap>;\n public static createPrefixed(\n prefixOptions: string | IKeyPrefixOptions,\n values?: MapOrRecord<JsonValue>,\n context?: IJsonContext,\n editor?: JsonEditor\n ): Result<PrefixedJsonMap> {\n return captureResult(\n () => new PrefixedJsonMap(values, context, { keyPolicy: this._toPolicy(prefixOptions), editor })\n );\n }\n\n /**\n * Constructs a new {@link PrefixKeyPolicy | PrefixKeyPolicy} from a supplied prefix\n * or set of {@link IKeyPrefixOptions | prefix options}.\n * @param prefixOptions - The prefix or {@link IKeyPrefixOptions | prefix options} or options\n * for the new policy.\n * @returns A new {@link ReferenceMapKeyPolicy | ReferenceMapKeyPolicy} which enforces the\n * supplied prefix or options.\n * @internal\n */\n protected static _toPolicy(prefixOptions: string | IKeyPrefixOptions): ReferenceMapKeyPolicy<JsonValue> {\n if (typeof prefixOptions === 'string') {\n return new PrefixKeyPolicy(prefixOptions, { makeValid: true });\n }\n return new PrefixKeyPolicy(prefixOptions.prefix, { makeValid: prefixOptions.addPrefix !== false });\n }\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"conditional.js","sourceRoot":"","sources":["../../../../src/packlets/editor/rules/conditional.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;;;;;;GAoBG;;;AAEH,4CAAyG;AACzG,qCAAiE;AAEjE,sDAAuD;AAkCvD;;;;;;;;;;GAUG;AACH,MAAa,yBAA0B,SAAQ,mCAAkB;IAQ/D;;;;OAIG;IACH,YAAmB,OAAqC;QACtD,KAAK,EAAE,CAAC;QACR,IAAI,CAAC,QAAQ,GAAG,OAAO,CAAC;IAC1B,CAAC;IAED;;;;OAIG;IACI,MAAM,CAAC,MAAM,CAAC,OAAqC;QACxD,OAAO,IAAA,wBAAa,EAAC,GAAG,EAAE,CAAC,IAAI,yBAAyB,CAAC,OAAO,CAAC,CAAC,CAAC;IACrE,CAAC;IAED;;;;;;;;;;OAUG;IACI,YAAY,CACjB,GAAW,EACX,KAAgB,EAChB,KAAsB;;QAEtB,MAAM,MAAM,GAAG,IAAI,CAAC,kBAAkB,CAAC,GAAG,EAAE,KAAK,CAAC,CAAC,SAAS,CAAC,CAAC,QAAQ,EAAE,EAAE;YACxE,IAAI,IAAA,mBAAY,EAAC,KAAK,CAAC,EAAE;gBACvB,MAAM,IAAI,mCAAwC,QAAQ,KAAE,KAAK,GAAE,CAAC;gBACpE,OAAO,IAAA,4BAAiB,EAAC,IAAI,EAAE,UAAU,CAAC,CAAC;aAC5C;YACD,OAAO,IAAA,yBAAc,EACnB,GAAG,GAAG,mCAAmC,EACzC,OAAO,CACR,CAAC;QACJ,CAAC,CAAC,CAAC;QAEH,IAAI,MAAM,CAAC,SAAS,EAAE,IA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AAQ,CAAC,IAAY,EAAE,KAAa,EAAE,QAAgB;QAC9D,QAAQ,QAAQ,EAAE;YAChB,KAAK,GAAG;gBACN,OAAO,IAAI,KAAK,KAAK,CAAC;YACxB,KAAK,GAAG;gBACN,OAAO,IAAI,GAAG,KAAK,CAAC;YACtB,KAAK,GAAG;gBACN,OAAO,IAAI,GAAG,KAAK,CAAC;YACtB,KAAK,IAAI;gBACP,OAAO,IAAI,IAAI,KAAK,CAAC;YACvB,KAAK,IAAI;gBACP,OAAO,IAAI,IAAI,KAAK,CAAC;YACvB,KAAK,IAAI;gBACP,OAAO,IAAI,KAAK,KAAK,CAAC;SACzB;QACD,oCAAoC;QACpC,OAAO,KAAK,CAAC;IACf,CAAC;CACF;AAvJD,8DAuJC","sourcesContent":["/*\n * Copyright (c) 2020 Erik Fortune\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n */\n\nimport { DetailedResult, Result, captureResult, failWithDetail, succeedWithDetail } from '@fgv/ts-utils';\nimport { JsonObject, JsonValue, isJsonObject } from '../../json';\nimport { IJsonEditorOptions, JsonEditFailureReason, JsonPropertyEditFailureReason } from '../common';\nimport { JsonEditorRuleBase } from '../jsonEditorRule';\nimport { JsonEditorState } from '../jsonEditorState';\n\n/**\n * Returned by {@link Editor.Rules.ConditionalJsonEditorRule._tryParseCondition | ConditionalJsonEditorRule._tryParseCondition}\n * to indicate whether a successful match was due to a matching condition or a default value.\n * @public\n */\nexport interface IConditionalJsonKeyResult extends JsonObject {\n matchType: 'default' | 'match' | 'unconditional';\n}\n\n/**\n * On a successful match, the {@link Editor.Rules.ConditionalJsonEditorRule | ConditionalJsonEditorRule}\n * stores a {@link Editor.Rules.IConditionalJsonDeferredObject | IConditionalJsonDeferredObject} describing the\n * matching result, to be resolved at finalization time.\n * @public\n */\nexport interface IConditionalJsonDeferredObject extends IConditionalJsonKeyResult {\n value: JsonValue;\n}\n\n/**\n * Configuration options for the {@link Editor.Rules.ConditionalJsonEditorRule | ConditionalJsonEditorRule}.\n * @public\n */\nexport interface IConditionalJsonRuleOptions extends Partial<IJsonEditorOptions> {\n /**\n * If true (default) then properties with unconditional names\n * (which start with !) are flattened.\n */\n flattenUnconditionalValues?: boolean;\n}\n\n/**\n * The {@link Editor.Rules.ConditionalJsonEditorRule | ConditionalJsonEditorRule} evaluates\n * properties with conditional keys, omitting non-matching keys and merging keys that match,\n * or default keys only if no other keys match.\n *\n * The default syntax for a conditional key is:\n * \"?value1=value2\" - matches if value1 and value2 are the same, is ignored otherwise.\n * \"?value\" - matches if value is a non-empty, non-whitespace string. Is ignored otherwise.\n * \"?default\" - matches only if no other conditional blocks in the same object were matched.\n * @public\n */\nexport class ConditionalJsonEditorRule extends JsonEditorRuleBase {\n /**\n * Stored fully-resolved {@link Editor.Rules.IConditionalJsonRuleOptions | options} for this\n * rule.\n * @public\n */\n protected _options?: IConditionalJsonRuleOptions;\n\n /**\n * Creates a new {@link Editor.Rules.ConditionalJsonEditorRule | ConditionalJsonEditorRule}.\n * @param options - Optional {@link Editor.Rules.IConditionalJsonRuleOptions | configuration options}\n * used for this rule.\n */\n public constructor(options?: IConditionalJsonRuleOptions) {\n super();\n this._options = options;\n }\n\n /**\n * Creates a new {@link Editor.Rules.ConditionalJsonEditorRule | ConditionalJsonEditorRule}.\n * @param options - Optional {@link Editor.Rules.IConditionalJsonRuleOptions | configuration options}\n * used for this rule.\n */\n public static create(options?: IConditionalJsonRuleOptions): Result<ConditionalJsonEditorRule> {\n return captureResult(() => new ConditionalJsonEditorRule(options));\n }\n\n /**\n * Evaluates a property for conditional application.\n * @param key - The key of the property to be considered\n * @param value - The {@link JsonValue | value} of the property to be considered.\n * @param state - The {@link Editor.JsonEditorState | editor state} for the object being edited.\n * @returns Returns `Success` with detail `'deferred'` and a\n * {@link Editor.Rules.IConditionalJsonDeferredObject | IConditionalJsonDeferredObject}.\n * for a matching, default or unconditional key. Returns `Failure` with detail `'ignore'` for\n * a non-matching conditional, or with detail `'error'` if an error occurs. Otherwise\n * fails with detail `'inapplicable'`.\n */\n public editProperty(\n key: string,\n value: JsonValue,\n state: JsonEditorState\n ): DetailedResult<JsonObject, JsonPropertyEditFailureReason> {\n const result = this._tryParseCondition(key, state).onSuccess((deferred) => {\n if (isJsonObject(value)) {\n const rtrn: IConditionalJsonDeferredObject = { ...deferred, value };\n return succeedWithDetail(rtrn, 'deferred');\n }\n return failWithDetail<JsonObject, JsonPropertyEditFailureReason>(\n `${key}: conditional body must be object`,\n 'error'\n );\n });\n\n if (result.isFailure() && result.detail === 'error') {\n return state.failValidation('invalidPropertyName', result.message, this._options?.validation);\n }\n\n return result;\n }\n\n /**\n * Finalizes any deferred conditional properties. If the only deferred property is\n * default, that property is emitted. Otherwise all matching properties are emitted.\n * @param finalized - The deferred properties to be considered for merge.\n * @param __state - The {@link Editor.JsonEditorState | editor state} for the object\n * being edited.\n */\n public finalizeProperties(\n finalized: JsonObject[],\n __state: JsonEditorState\n ): DetailedResult<JsonObject[], JsonEditFailureReason> {\n let toMerge = finalized;\n if (finalized.length > 1) {\n if (finalized.find((o) => o.matchType === 'match') !== undefined) {\n toMerge = finalized.filter((o) => o.matchType === 'match' || o.matchType === 'unconditional');\n }\n }\n return succeedWithDetail(toMerge.map((o) => o.value).filter(isJsonObject), 'edited');\n }\n\n /**\n * Determines if a given property key is conditional. Derived classes can override this\n * method to use a different format for conditional properties.\n * @param value - The {@link JsonValue | value} of the property to be considered.\n * @param state - The {@link Editor.JsonEditorState | editor state} for the object being edited.\n * @returns `Success` with detail `'deferred'` and a\n * {@link Editor.Rules.IConditionalJsonKeyResult | IConditionalJsonKeyResult} describing the\n * match for a default or matching conditional property. Returns `Failure` with detail `'ignore'`\n * for a non-matching conditional property. Fails with detail `'error'` if an error occurs\n * or with detail `'inapplicable'` if the key does not represent a conditional property.\n * @public\n */\n protected _tryParseCondition(\n key: string,\n state: JsonEditorState\n ): DetailedResult<IConditionalJsonKeyResult, JsonPropertyEditFailureReason> {\n if (key.startsWith('?')) {\n // ignore everything after any #\n key = key.split('#')[0].trim();\n\n if (key === '?default') {\n return succeedWithDetail({ matchType: 'default' }, 'deferred');\n }\n\n const parts = key.substring(1).split(/(=|>=|<=|>|<|!=)/);\n if (parts.length === 3) {\n if (!this._compare(parts[0].trim(), parts[2].trim(), parts[1])) {\n return failWithDetail(`Condition ${key} does not match`, 'ignore');\n }\n return succeedWithDetail({ matchType: 'match' }, 'deferred');\n } else if (parts.length === 1) {\n if (parts[0].trim().length === 0) {\n return failWithDetail(`Condition ${key} does not match`, 'ignore');\n }\n return succeedWithDetail({ matchType: 'match' }, 'deferred');\n }\n const message = `Malformed condition token ${key}`;\n return state.failValidation('invalidPropertyName', message, this._options?.validation);\n } else if (this._options?.flattenUnconditionalValues !== false && key.startsWith('!')) {\n return succeedWithDetail({ matchType: 'unconditional' }, 'deferred');\n }\n return failWithDetail('inapplicable', 'inapplicable');\n }\n\n /**\n * Compares two strings using a supplied operator.\n * @param left - The first string to be compared.\n * @param right - The second string to be compared.\n * @param operator - The operator to be applied.\n * @returns `true` if the condition is met, `false` otherwise.\n * @internal\n */\n protected _compare(left: string, right: string, operator: string): boolean {\n switch (operator) {\n case '=':\n return left === right;\n case '>':\n return left > right;\n case '<':\n return left < right;\n case '>=':\n return left >= right;\n case '<=':\n return left <= right;\n case '!=':\n return left !== right;\n }\n /* c8 ignore next 2 - unreachable */\n return false;\n }\n}\n"]}
1
+ {"version":3,"file":"conditional.js","sourceRoot":"","sources":["../../../../src/packlets/editor/rules/conditional.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;;;;;;GAoBG;;;AAEH,4CAAyG;AACzG,qCAAiE;AAEjE,sDAAuD;AAkCvD;;;;;;;;;;GAUG;AACH,MAAa,yBAA0B,SAAQ,mCAAkB;IAQ/D;;;;OAIG;IACH,YAAmB,OAAqC;QACtD,KAAK,EAAE,CAAC;QACR,IAAI,CAAC,QAAQ,GAAG,OAAO,CAAC;IAC1B,CAAC;IAED;;;;OAIG;IACI,MAAM,CAAC,MAAM,CAAC,OAAqC;QACxD,OAAO,IAAA,wBAAa,EAAC,GAAG,EAAE,CAAC,IAAI,yBAAyB,CAAC,OAAO,CAAC,CAAC,CAAC;IACrE,CAAC;IAED;;;;;;;;;;OAUG;IACI,YAAY,CACjB,GAAW,EACX,KAAgB,EAChB,KAAsB;;QAEtB,MAAM,MAAM,GAAG,IAAI,CAAC,kBAAkB,CAAC,GAAG,EAAE,KAAK,CAAC,CAAC,SAAS,CAAC,CAAC,QAAQ,EAAE,EAAE;YACxE,IAAI,IAAA,mBAAY,EAAC,KAAK,CAAC,EAAE,CAAC;gBACxB,MAAM,IAAI,mCAAwC,QAAQ,KAAE,KAAK,GAAE,CAAC;gBACpE,OAAO,IAAA,4BAAiB,EAAC,IAAI,EAAE,UAAU,CAAC,CAAC;YAC7C,CAAC;YACD,OAAO,IAAA,yBAAc,EACnB,GAAG,GAAG,mCAAmC,EACzC,OAAO,CACR,CAAC;QACJ,CAAC,CAAC,CAAC;QAEH,IAAI,MAAM,CAAC,SAAS,EAAE,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CAAC,CAAC;QACvE,CAAC;QACD,OAAO,IAAA,yBAAc,EAAC,cAAc,EAAE,cAAc,CAAC,CAAC;IACxD,CAAC;IAED;;;;;;;OAOG;IACO,QAAQ,CAAC,IAAY,EAAE,KAAa,EAAE,QAAgB;QAC9D,QAAQ,QAAQ,EAAE,CAAC;YACjB,KAAK,GAAG;gBACN,OAAO,IAAI,KAAK,KAAK,CAAC;YACxB,KAAK,GAAG;gBACN,OAAO,IAAI,GAAG,KAAK,CAAC;YACtB,KAAK,GAAG;gBACN,OAAO,IAAI,GAAG,KAAK,CAAC;YACtB,KAAK,IAAI;gBACP,OAAO,IAAI,IAAI,KAAK,CAAC;YACvB,KAAK,IAAI;gBACP,OAAO,IAAI,IAAI,KAAK,CAAC;YACvB,KAAK,IAAI;gBACP,OAAO,IAAI,KAAK,KAAK,CAAC;QAC1B,CAAC;QACD,oCAAoC;QACpC,OAAO,KAAK,CAAC;IACf,CAAC;CACF;AAvJD,8DAuJC","sourcesContent":["/*\n * Copyright (c) 2020 Erik Fortune\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n */\n\nimport { DetailedResult, Result, captureResult, failWithDetail, succeedWithDetail } from '@fgv/ts-utils';\nimport { JsonObject, JsonValue, isJsonObject } from '../../json';\nimport { IJsonEditorOptions, JsonEditFailureReason, JsonPropertyEditFailureReason } from '../common';\nimport { JsonEditorRuleBase } from '../jsonEditorRule';\nimport { JsonEditorState } from '../jsonEditorState';\n\n/**\n * Returned by {@link Editor.Rules.ConditionalJsonEditorRule._tryParseCondition | ConditionalJsonEditorRule._tryParseCondition}\n * to indicate whether a successful match was due to a matching condition or a default value.\n * @public\n */\nexport interface IConditionalJsonKeyResult extends JsonObject {\n matchType: 'default' | 'match' | 'unconditional';\n}\n\n/**\n * On a successful match, the {@link Editor.Rules.ConditionalJsonEditorRule | ConditionalJsonEditorRule}\n * stores a {@link Editor.Rules.IConditionalJsonDeferredObject | IConditionalJsonDeferredObject} describing the\n * matching result, to be resolved at finalization time.\n * @public\n */\nexport interface IConditionalJsonDeferredObject extends IConditionalJsonKeyResult {\n value: JsonValue;\n}\n\n/**\n * Configuration options for the {@link Editor.Rules.ConditionalJsonEditorRule | ConditionalJsonEditorRule}.\n * @public\n */\nexport interface IConditionalJsonRuleOptions extends Partial<IJsonEditorOptions> {\n /**\n * If true (default) then properties with unconditional names\n * (which start with !) are flattened.\n */\n flattenUnconditionalValues?: boolean;\n}\n\n/**\n * The {@link Editor.Rules.ConditionalJsonEditorRule | ConditionalJsonEditorRule} evaluates\n * properties with conditional keys, omitting non-matching keys and merging keys that match,\n * or default keys only if no other keys match.\n *\n * The default syntax for a conditional key is:\n * \"?value1=value2\" - matches if value1 and value2 are the same, is ignored otherwise.\n * \"?value\" - matches if value is a non-empty, non-whitespace string. Is ignored otherwise.\n * \"?default\" - matches only if no other conditional blocks in the same object were matched.\n * @public\n */\nexport class ConditionalJsonEditorRule extends JsonEditorRuleBase {\n /**\n * Stored fully-resolved {@link Editor.Rules.IConditionalJsonRuleOptions | options} for this\n * rule.\n * @public\n */\n protected _options?: IConditionalJsonRuleOptions;\n\n /**\n * Creates a new {@link Editor.Rules.ConditionalJsonEditorRule | ConditionalJsonEditorRule}.\n * @param options - Optional {@link Editor.Rules.IConditionalJsonRuleOptions | configuration options}\n * used for this rule.\n */\n public constructor(options?: IConditionalJsonRuleOptions) {\n super();\n this._options = options;\n }\n\n /**\n * Creates a new {@link Editor.Rules.ConditionalJsonEditorRule | ConditionalJsonEditorRule}.\n * @param options - Optional {@link Editor.Rules.IConditionalJsonRuleOptions | configuration options}\n * used for this rule.\n */\n public static create(options?: IConditionalJsonRuleOptions): Result<ConditionalJsonEditorRule> {\n return captureResult(() => new ConditionalJsonEditorRule(options));\n }\n\n /**\n * Evaluates a property for conditional application.\n * @param key - The key of the property to be considered\n * @param value - The {@link JsonValue | value} of the property to be considered.\n * @param state - The {@link Editor.JsonEditorState | editor state} for the object being edited.\n * @returns Returns `Success` with detail `'deferred'` and a\n * {@link Editor.Rules.IConditionalJsonDeferredObject | IConditionalJsonDeferredObject}.\n * for a matching, default or unconditional key. Returns `Failure` with detail `'ignore'` for\n * a non-matching conditional, or with detail `'error'` if an error occurs. Otherwise\n * fails with detail `'inapplicable'`.\n */\n public editProperty(\n key: string,\n value: JsonValue,\n state: JsonEditorState\n ): DetailedResult<JsonObject, JsonPropertyEditFailureReason> {\n const result = this._tryParseCondition(key, state).onSuccess((deferred) => {\n if (isJsonObject(value)) {\n const rtrn: IConditionalJsonDeferredObject = { ...deferred, value };\n return succeedWithDetail(rtrn, 'deferred');\n }\n return failWithDetail<JsonObject, JsonPropertyEditFailureReason>(\n `${key}: conditional body must be object`,\n 'error'\n );\n });\n\n if (result.isFailure() && result.detail === 'error') {\n return state.failValidation('invalidPropertyName', result.message, this._options?.validation);\n }\n\n return result;\n }\n\n /**\n * Finalizes any deferred conditional properties. If the only deferred property is\n * default, that property is emitted. Otherwise all matching properties are emitted.\n * @param finalized - The deferred properties to be considered for merge.\n * @param __state - The {@link Editor.JsonEditorState | editor state} for the object\n * being edited.\n */\n public finalizeProperties(\n finalized: JsonObject[],\n __state: JsonEditorState\n ): DetailedResult<JsonObject[], JsonEditFailureReason> {\n let toMerge = finalized;\n if (finalized.length > 1) {\n if (finalized.find((o) => o.matchType === 'match') !== undefined) {\n toMerge = finalized.filter((o) => o.matchType === 'match' || o.matchType === 'unconditional');\n }\n }\n return succeedWithDetail(toMerge.map((o) => o.value).filter(isJsonObject), 'edited');\n }\n\n /**\n * Determines if a given property key is conditional. Derived classes can override this\n * method to use a different format for conditional properties.\n * @param value - The {@link JsonValue | value} of the property to be considered.\n * @param state - The {@link Editor.JsonEditorState | editor state} for the object being edited.\n * @returns `Success` with detail `'deferred'` and a\n * {@link Editor.Rules.IConditionalJsonKeyResult | IConditionalJsonKeyResult} describing the\n * match for a default or matching conditional property. Returns `Failure` with detail `'ignore'`\n * for a non-matching conditional property. Fails with detail `'error'` if an error occurs\n * or with detail `'inapplicable'` if the key does not represent a conditional property.\n * @public\n */\n protected _tryParseCondition(\n key: string,\n state: JsonEditorState\n ): DetailedResult<IConditionalJsonKeyResult, JsonPropertyEditFailureReason> {\n if (key.startsWith('?')) {\n // ignore everything after any #\n key = key.split('#')[0].trim();\n\n if (key === '?default') {\n return succeedWithDetail({ matchType: 'default' }, 'deferred');\n }\n\n const parts = key.substring(1).split(/(=|>=|<=|>|<|!=)/);\n if (parts.length === 3) {\n if (!this._compare(parts[0].trim(), parts[2].trim(), parts[1])) {\n return failWithDetail(`Condition ${key} does not match`, 'ignore');\n }\n return succeedWithDetail({ matchType: 'match' }, 'deferred');\n } else if (parts.length === 1) {\n if (parts[0].trim().length === 0) {\n return failWithDetail(`Condition ${key} does not match`, 'ignore');\n }\n return succeedWithDetail({ matchType: 'match' }, 'deferred');\n }\n const message = `Malformed condition token ${key}`;\n return state.failValidation('invalidPropertyName', message, this._options?.validation);\n } else if (this._options?.flattenUnconditionalValues !== false && key.startsWith('!')) {\n return succeedWithDetail({ matchType: 'unconditional' }, 'deferred');\n }\n return failWithDetail('inapplicable', 'inapplicable');\n }\n\n /**\n * Compares two strings using a supplied operator.\n * @param left - The first string to be compared.\n * @param right - The second string to be compared.\n * @param operator - The operator to be applied.\n * @returns `true` if the condition is met, `false` otherwise.\n * @internal\n */\n protected _compare(left: string, right: string, operator: string): boolean {\n switch (operator) {\n case '=':\n return left === right;\n case '>':\n return left > right;\n case '<':\n return left < right;\n case '>=':\n return left >= right;\n case '<=':\n return left <= right;\n case '!=':\n return left !== right;\n }\n /* c8 ignore next 2 - unreachable */\n return false;\n }\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"multivalue.js","sourceRoot":"","sources":["../../../../src/packlets/editor/rules/multivalue.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;;;;;;GAoBG;;;AAEH,4CAQuB;AAKvB,sDAAuD;AAiCvD;;;;;;;;;;;GAWG;AACH,MAAa,wBAAyB,SAAQ,mCAAkB;IAQ9D;;;OAGG;IACH,YAAmB,OAA4B;QAC7C,KAAK,EAAE,CAAC;QACR,IAAI,CAAC,QAAQ,GAAG,OAAO,CAAC;IAC1B,CAAC;IAED;;;OAGG;IACI,MAAM,CAAC,MAAM,CAAC,OAA4B;QAC/C,OAAO,IAAA,wBAAa,EAAC,GAAG,EAAE,CAAC,IAAI,wBAAwB,CAAC,OAAO,CAAC,CAAC,CAAC;IACpE,CAAC;IAED;;;;;;;;OAQG;IACI,YAAY,CACjB,GAAW,EACX,KAAgB,EAChB,KAAsB;QAEtB,MAAM,IAAI,GAAe,EAAE,CAAC;QAC5B,MAAM,MAAM,GAAG,IAAI,CAAC,SAAS,CAAC,GAAG,EAAE,KAAK,CAAC,CAAC,SAAS,CAAC,CAAC,KAAK,EAAE,EAAE;YAC5D,OAAO,IAAA,qBAAU,EACf,KAAK,CAAC,cAAc,CAAC,GAAG,CAAC,CAAC,EAAE,EAAE,EAAE;gBAC9B,OAAO,IAAI,CAAC,cAAc,CAAC,KAAK,EAAE,CAAC,KAAK,CAAC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a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n */\n\nimport {\n DetailedResult,\n Result,\n allSucceed,\n captureResult,\n failWithDetail,\n succeed,\n succeedWithDetail\n} from '@fgv/ts-utils';\nimport { IJsonContext, VariableValue } from '../../context';\nimport { JsonObject, JsonValue } from '../../json';\nimport { IJsonEditorOptions, JsonEditFailureReason, JsonPropertyEditFailureReason } from '../common';\n\nimport { JsonEditorRuleBase } from '../jsonEditorRule';\nimport { JsonEditorState } from '../jsonEditorState';\n\n/**\n * Represents the parts of a multi-value property key.\n * @public\n */\nexport interface IMultiValuePropertyParts {\n /**\n * The original matched token.\n */\n readonly token: string;\n\n /**\n * The name of the variable used to project each possible\n * property value into the child values or objects being\n * resolved.\n */\n readonly propertyVariable: string;\n\n /**\n * The set of property values to be expanded.\n */\n readonly propertyValues: string[];\n\n /**\n * If `true`, the resolved values are added as an array\n * with the name of the {@link Editor.Rules.IMultiValuePropertyParts.propertyVariable | propertyVariable}.\n * If false, values are added as individual properties with names that correspond the value.\n */\n readonly asArray: boolean;\n}\n\n/**\n * The {@link Editor.Rules.MultiValueJsonEditorRule | Multi-Value JSON editor rule}\n * expands matching keys multiple times, projecting the value into the template\n * context for any child objects rendered by the rule.\n *\n * The default syntax for a multi-value key is:\n * \"[[var]]=value1,value2,value3\"\n * Where \"var\" is the name of the variable that will be passed to\n * child template resolution, and \"value1,value2,value3\" is a\n * comma-separated list of values to be expanded.\n * @public\n */\nexport class MultiValueJsonEditorRule extends JsonEditorRuleBase {\n /**\n * Stored fully-resolved {@link Editor.IJsonEditorOptions | editor options}\n * for this rule.\n * @public\n */\n protected _options?: IJsonEditorOptions;\n\n /**\n * Creates a new {@link Editor.Rules.MultiValueJsonEditorRule | MultiValueJsonEditorRule}.\n * @param options - Optional {@link Editor.IJsonEditorOptions | configuration options}.\n */\n public constructor(options?: IJsonEditorOptions) {\n super();\n this._options = options;\n }\n\n /**\n * Creates a new {@link Editor.Rules.MultiValueJsonEditorRule | MultiValueJsonEditorRule}.\n * @param options - Optional {@link Editor.IJsonEditorOptions | configuration options}.\n */\n public static create(options?: IJsonEditorOptions): Result<MultiValueJsonEditorRule> {\n return captureResult(() => new MultiValueJsonEditorRule(options));\n }\n\n /**\n * Evaluates a property for multi-value expansion.\n * @param key - The key of the property to be considered\n * @param value - The {@link JsonValue | value} of the property to be considered.\n * @param state - The {@link Editor.JsonEditorState | editor state} for the object being edited.\n * @returns `Success` with an object containing the fully-resolved child values to be merged for\n * matching multi-value property. Returns `Failure` with detail `'error'` if an error occurs or\n * with detail `'inapplicable'` if the property key is not a conditional property.\n */\n public editProperty(\n key: string,\n value: JsonValue,\n state: JsonEditorState\n ): DetailedResult<JsonObject, JsonPropertyEditFailureReason> {\n const json: JsonObject = {};\n const result = this._tryParse(key, state).onSuccess((parts) => {\n return allSucceed(\n parts.propertyValues.map((pv) => {\n return this._deriveContext(state, [parts.propertyVariable, pv]).onSuccess((ctx) => {\n return state.editor.clone(value, ctx).onSuccess((cloned) => {\n json[pv] = cloned;\n return succeedWithDetail(cloned);\n });\n });\n }),\n json\n )\n .onSuccess(() => {\n if (parts.asArray) {\n const arrayRtrn: JsonObject = {};\n arrayRtrn[parts.propertyVariable] = Array.from(Object.values(json));\n return succeed(arrayRtrn);\n }\n return succeed(json);\n })\n .withFailureDetail('error');\n });\n\n if (result.isFailure() && result.detail === 'error') {\n return state.failValidation('invalidPropertyName', result.message);\n }\n return result;\n }\n\n /**\n * Extends the {@link IJsonContext | current context} with a supplied state and values.\n * @param state - The {@link Editor.JsonEditorState | editor state} for the object being edited.\n * @param values - An array of {@link VariableValue | VariableValue} to be added to the\n * context.\n * @returns The extended {@link IJsonContext | context}.\n * @public\n */\n protected _deriveContext(\n state: JsonEditorState,\n ...values: VariableValue[]\n ): Result<IJsonContext | undefined> {\n return state.extendContext(this._options?.context, { vars: values });\n }\n\n /**\n * Determines if a given property key is multi-value. Derived classes can override this\n * method to use a different format for multi-value properties.\n * @param value - The {@link JsonValue | value} of the property to be considered.\n * @param state - The {@link Editor.JsonEditorState | editor state} for the object being edited.\n * @returns `Success` with detail `'deferred'` and an\n * {@link Editor.Rules.IMultiValuePropertyParts | IMultiValuePropertyParts}\n * describing the match for matching multi-value property. Returns `Failure` with detail `'error'` if an error occurs\n * or with detail `'inapplicable'` if the key does not represent a multi-value property.\n * @public\n */\n protected _tryParse(\n token: string,\n state: JsonEditorState\n ): DetailedResult<IMultiValuePropertyParts, JsonEditFailureReason> {\n let parts: string[] = [];\n let asArray = false;\n\n if (token.startsWith('[[')) {\n parts = token.substring(2).split(']]=');\n asArray = true;\n } else if (token.startsWith('*')) {\n parts = token.substring(1).split('=');\n asArray = false;\n } else {\n return failWithDetail(token, 'inapplicable');\n }\n\n if (parts.length !== 2) {\n const message = `Malformed multi-value property: ${token}`;\n return state.failValidation('invalidPropertyName', message, this._options?.validation);\n }\n\n if (parts[1].includes('{{')) {\n return failWithDetail('unresolved template', 'inapplicable');\n }\n\n const propertyVariable = parts[0];\n const propertyValues = parts[1].split(',');\n return succeedWithDetail({ token, propertyVariable, propertyValues, asArray });\n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,EAAE,CAAC;YACjC,KAAK,GAAG,KAAK,CAAC,SAAS,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC;YACtC,OAAO,GAAG,KAAK,CAAC;QAClB,CAAC;aAAM,CAAC;YACN,OAAO,IAAA,yBAAc,EAAC,KAAK,EAAE,cAAc,CAAC,CAAC;QAC/C,CAAC;QAED,IAAI,KAAK,CAAC,MAAM,KAAK,CAAC,EAAE,CAAC;YACvB,MAAM,OAAO,GAAG,mCAAmC,KAAK,EAAE,CAAC;YAC3D,OAAO,KAAK,CAAC,cAAc,CAAC,qBAAqB,EAAE,OAAO,EAAE,MAAA,IAAI,CAAC,QAAQ,0CAAE,UAAU,CAAC,CAAC;QACzF,CAAC;QAED,IAAI,KAAK,CAAC,CAAC,CAAC,CAAC,QAAQ,CAAC,IAAI,CAAC,EAAE,CAAC;YAC5B,OAAO,IAAA,yBAAc,EAAC,qBAAqB,EAAE,cAAc,CAAC,CAAC;QAC/D,CAAC;QAED,MAAM,gBAAgB,GAAG,KAAK,CAAC,CAAC,CAAC,CAAC;QAClC,MAAM,cAAc,GAAG,KAAK,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC;QAC3C,OAAO,IAAA,4BAAiB,EAAC,EAAE,KAAK,EAAE,gBAAgB,EAAE,cAAc,EAAE,OAAO,EAAE,CAAC,CAAC;IACjF,CAAC;CACF;AA7HD,4DA6HC","sourcesContent":["/*\n * Copyright (c) 2020 Erik Fortune\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n */\n\nimport {\n DetailedResult,\n Result,\n allSucceed,\n captureResult,\n failWithDetail,\n succeed,\n succeedWithDetail\n} from '@fgv/ts-utils';\nimport { IJsonContext, VariableValue } from '../../context';\nimport { JsonObject, JsonValue } from '../../json';\nimport { IJsonEditorOptions, JsonEditFailureReason, JsonPropertyEditFailureReason } from '../common';\n\nimport { JsonEditorRuleBase } from '../jsonEditorRule';\nimport { JsonEditorState } from '../jsonEditorState';\n\n/**\n * Represents the parts of a multi-value property key.\n * @public\n */\nexport interface IMultiValuePropertyParts {\n /**\n * The original matched token.\n */\n readonly token: string;\n\n /**\n * The name of the variable used to project each possible\n * property value into the child values or objects being\n * resolved.\n */\n readonly propertyVariable: string;\n\n /**\n * The set of property values to be expanded.\n */\n readonly propertyValues: string[];\n\n /**\n * If `true`, the resolved values are added as an array\n * with the name of the {@link Editor.Rules.IMultiValuePropertyParts.propertyVariable | propertyVariable}.\n * If false, values are added as individual properties with names that correspond the value.\n */\n readonly asArray: boolean;\n}\n\n/**\n * The {@link Editor.Rules.MultiValueJsonEditorRule | Multi-Value JSON editor rule}\n * expands matching keys multiple times, projecting the value into the template\n * context for any child objects rendered by the rule.\n *\n * The default syntax for a multi-value key is:\n * \"[[var]]=value1,value2,value3\"\n * Where \"var\" is the name of the variable that will be passed to\n * child template resolution, and \"value1,value2,value3\" is a\n * comma-separated list of values to be expanded.\n * @public\n */\nexport class MultiValueJsonEditorRule extends JsonEditorRuleBase {\n /**\n * Stored fully-resolved {@link Editor.IJsonEditorOptions | editor options}\n * for this rule.\n * @public\n */\n protected _options?: IJsonEditorOptions;\n\n /**\n * Creates a new {@link Editor.Rules.MultiValueJsonEditorRule | MultiValueJsonEditorRule}.\n * @param options - Optional {@link Editor.IJsonEditorOptions | configuration options}.\n */\n public constructor(options?: IJsonEditorOptions) {\n super();\n this._options = options;\n }\n\n /**\n * Creates a new {@link Editor.Rules.MultiValueJsonEditorRule | MultiValueJsonEditorRule}.\n * @param options - Optional {@link Editor.IJsonEditorOptions | configuration options}.\n */\n public static create(options?: IJsonEditorOptions): Result<MultiValueJsonEditorRule> {\n return captureResult(() => new MultiValueJsonEditorRule(options));\n }\n\n /**\n * Evaluates a property for multi-value expansion.\n * @param key - The key of the property to be considered\n * @param value - The {@link JsonValue | value} of the property to be considered.\n * @param state - The {@link Editor.JsonEditorState | editor state} for the object being edited.\n * @returns `Success` with an object containing the fully-resolved child values to be merged for\n * matching multi-value property. Returns `Failure` with detail `'error'` if an error occurs or\n * with detail `'inapplicable'` if the property key is not a conditional property.\n */\n public editProperty(\n key: string,\n value: JsonValue,\n state: JsonEditorState\n ): DetailedResult<JsonObject, JsonPropertyEditFailureReason> {\n const json: JsonObject = {};\n const result = this._tryParse(key, state).onSuccess((parts) => {\n return allSucceed(\n parts.propertyValues.map((pv) => {\n return this._deriveContext(state, [parts.propertyVariable, pv]).onSuccess((ctx) => {\n return state.editor.clone(value, ctx).onSuccess((cloned) => {\n json[pv] = cloned;\n return succeedWithDetail(cloned);\n });\n });\n }),\n json\n )\n .onSuccess(() => {\n if (parts.asArray) {\n const arrayRtrn: JsonObject = {};\n arrayRtrn[parts.propertyVariable] = Array.from(Object.values(json));\n return succeed(arrayRtrn);\n }\n return succeed(json);\n })\n .withFailureDetail('error');\n });\n\n if (result.isFailure() && result.detail === 'error') {\n return state.failValidation('invalidPropertyName', result.message);\n }\n return result;\n }\n\n /**\n * Extends the {@link IJsonContext | current context} with a supplied state and values.\n * @param state - The {@link Editor.JsonEditorState | editor state} for the object being edited.\n * @param values - An array of {@link VariableValue | VariableValue} to be added to the\n * context.\n * @returns The extended {@link IJsonContext | context}.\n * @public\n */\n protected _deriveContext(\n state: JsonEditorState,\n ...values: VariableValue[]\n ): Result<IJsonContext | undefined> {\n return state.extendContext(this._options?.context, { vars: values });\n }\n\n /**\n * Determines if a given property key is multi-value. Derived classes can override this\n * method to use a different format for multi-value properties.\n * @param value - The {@link JsonValue | value} of the property to be considered.\n * @param state - The {@link Editor.JsonEditorState | editor state} for the object being edited.\n * @returns `Success` with detail `'deferred'` and an\n * {@link Editor.Rules.IMultiValuePropertyParts | IMultiValuePropertyParts}\n * describing the match for matching multi-value property. Returns `Failure` with detail `'error'` if an error occurs\n * or with detail `'inapplicable'` if the key does not represent a multi-value property.\n * @public\n */\n protected _tryParse(\n token: string,\n state: JsonEditorState\n ): DetailedResult<IMultiValuePropertyParts, JsonEditFailureReason> {\n let parts: string[] = [];\n let asArray = false;\n\n if (token.startsWith('[[')) {\n parts = token.substring(2).split(']]=');\n asArray = true;\n } else if (token.startsWith('*')) {\n parts = token.substring(1).split('=');\n asArray = false;\n } else {\n return failWithDetail(token, 'inapplicable');\n }\n\n if (parts.length !== 2) {\n const message = `Malformed multi-value property: ${token}`;\n return state.failValidation('invalidPropertyName', message, this._options?.validation);\n }\n\n if (parts[1].includes('{{')) {\n return failWithDetail('unresolved template', 'inapplicable');\n }\n\n const propertyVariable = parts[0];\n const propertyValues = parts[1].split(',');\n return succeedWithDetail({ token, propertyVariable, propertyValues, asArray });\n }\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"references.js","sourceRoot":"","sources":["../../../../src/packlets/editor/rules/references.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;;;;;;GAoBG;;;AAEH,4CAOuB;AAEvB,qCAAiF;AAEjF,sDAAuD;AAGvD;;;;;;;;;;;;;;;;;;;;GAoBG;AACH,MAAa,uBAAwB,SAAQ,mCAAkB;IAO7D;;;O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oBAAoB;YACpB,MAAM,OAAO,GAAG,KAAK,CAAC,UAAU,CAAC,MAAA,IAAI,CAAC,QAAQ,0CAAE,OAAO,CAAC,CAAC;YACzD,MAAM,MAAM,GAAG,IAAI,CAAC,YAAY,CAAC,KAAK,EAAE,OAAO,CAAC,CAAC;YACjD,IAAI,MAAM,CAAC,SAAS,EAAE,EAAE;gBACtB,OAAO,IAAA,4BAAiB,EAAC,MAAM,CAAC,KAAK,EAAE,QAAQ,CAAC,CAAC;aAClD;iBAAM,IAAI,MAAM,CAAC,MAAM,KAAK,OAAO,EAAE;gBACpC,OAAO,KAAK,CAAC,cAAc,CAAC,sBAAsB,EAAE,MAAM,CAAC,OAAO,EAAE,MAAA,IAAI,CAAC,QAAQ,0CAAE,UAAU,CAAC,CAAC;aAChG;SACF;QACD,OAAO,IAAA,yBAAc,EAAC,cAAc,EAAE,cAAc,CAAC,CAAC;IACxD,CAAC;IAED;;;;;;OAMG;IACO,cAAc,CAAC,KAAsB,EAAE,QAAmB;;QAClE,MAAM,GAAG,GAA4B,EAAE,CAAC;QACxC,IAAI,IAAA,mBAAY,EAAC,QAAQ,CAAC,EAAE;YAC1B,GAAG,CAAC,IAAI,GAAG,MAAM,CAAC,OAAO,CAAC,QAAQ,CAAC,CAAC;SACrC;aAAM,IAAI,OAAO,QAAQ,KAAK,QAAQ,EAAE;YACvC,OAAO,IAAA,eAAI,EAAC,sCAAsC,IAAI,CAAC,SAAS,CAAC,QAAQ,CAAC,GAAG,CAAC,CAAC;SAChF;QACD,OAAO,KAAK,CAAC,aAAa,CAAC,MAAA,IAAI,CAAC,QAAQ,0CAAE,OAAO,EAAE,GAAG,CAAC,CAAC;IAC1D,CAAC;CACF;AAvHD,0DAuHC","sourcesContent":["/*\n * Copyright (c) 2020 Erik Fortune\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n */\n\nimport {\n DetailedResult,\n Result,\n captureResult,\n fail,\n failWithDetail,\n succeedWithDetail\n} from '@fgv/ts-utils';\nimport { IJsonContext } from '../../context';\nimport { JsonObject, JsonValue, isJsonObject, pickJsonObject } from '../../json';\nimport { IJsonEditorOptions, JsonEditFailureReason, JsonPropertyEditFailureReason } from '../common';\nimport { JsonEditorRuleBase } from '../jsonEditorRule';\nimport { JsonEditorState } from '../jsonEditorState';\n\n/**\n * The {@link Editor.Rules.ReferenceJsonEditorRule | Reference JSON editor rule} replaces property\n * keys or values that match some known object with a copy of that referenced object, formatted\n * according to the current context.\n *\n * A property key is matched if it matches any known referenced value.\n * - If the value of the matched key is `'default'`, then the entire object is formatted\n * with the current context, flattened and merged into the current object.\n * - If the value of the matched key is some other string, then the entire\n * object is formatted with the current context, and the child of the resulting\n * object at the specified path is flattened and merged into the current object.\n * - If the value of the matched key is an object, then the entire object is\n * formatted with the current context extended to include any properties of\n * that object, flattened, and merged into the current object.\n * - It is an error if the referenced value is not an object.\n *\n * Any property, array or literal value is matched if it matches any known\n * value reference. The referenced value is replaced by the referenced\n * value, formatted using the current editor context.\n * @public\n */\nexport class ReferenceJsonEditorRule extends JsonEditorRuleBase {\n /**\n * Stored fully-resolved {@link Editor.IJsonEditorOptions | editor options} for this rule.\n * @public\n */\n protected _options?: IJsonEditorOptions;\n\n /**\n * Creates a new {@link Editor.Rules.ReferenceJsonEditorRule | ReferenceJsonEditorRule}.\n * @param options - Optional {@link Editor.IJsonEditorOptions | configuration options} for this rule.\n */\n public constructor(options?: IJsonEditorOptions) {\n super();\n this._options = options;\n }\n\n /**\n * Creates a new {@link Editor.Rules.ReferenceJsonEditorRule | ReferenceJsonEditorRule}.\n * @param options - Optional {@link Editor.IJsonEditorOptions | configuration options} for this rule.\n */\n public static create(options?: IJsonEditorOptions): Result<ReferenceJsonEditorRule> {\n return captureResult(() => new ReferenceJsonEditorRule(options));\n }\n\n /**\n * Evaluates a property for reference expansion.\n * @param key - The key of the property to be considered.\n * @param value - The {@link JsonValue | value} of the property to be considered.\n * @param state - The {@link Editor.JsonEditorState | editor state} for the object being edited.\n * @returns If the reference is successful, returns `Success` with a {@link JsonObject | JsonObject}\n * to be flattened and merged into the current object. Returns `Failure` with detail `'inapplicable'`\n * for non-reference keys or with detail `'error'` if an error occurs.\n */\n public editProperty(\n key: string,\n value: JsonValue,\n state: JsonEditorState\n ): DetailedResult<JsonObject, JsonPropertyEditFailureReason> {\n /* c8 ignore next 2 */\n const validation = this._options?.validation;\n const refs = state.getRefs(this._options?.context);\n if (refs?.has(key)) {\n // need to apply any rules to the value before we evaluate it\n const cloneResult = state.editor.clone(value, state.context);\n if (cloneResult.isSuccess()) {\n value = cloneResult.value;\n } else {\n const message = `${key}: ${cloneResult.message}`;\n return state.failValidation('invalidPropertyName', message, validation);\n }\n\n const contextResult = this._extendContext(state, value);\n if (contextResult.isSuccess()) {\n const objResult = refs.getJsonObject(key, contextResult.value);\n // guarded by the has above so should never happen\n /* c8 ignore else */\n if (objResult.isSuccess()) {\n if (typeof value !== 'string' || value === 'default') {\n return succeedWithDetail<JsonObject, JsonEditFailureReason>(objResult.value, 'edited');\n }\n const pickResult = pickJsonObject(objResult.value, value);\n if (pickResult.isFailure()) {\n const message = `${key}: ${pickResult.message}`;\n return state.failValidation('invalidPropertyName', message, validation);\n }\n return pickResult.withDetail('edited');\n } else if (objResult.detail !== 'unknown') {\n const message = `${key}: ${objResult.message}`;\n return state.failValidation('invalidPropertyName', message, validation);\n }\n } else {\n const message = `${key}: ${contextResult.message}`;\n return state.failValidation('invalidPropertyName', message, validation);\n }\n }\n return failWithDetail('inapplicable', 'inapplicable');\n }\n\n /**\n * Evaluates a property, array or literal value for reference replacement.\n * @param value - The {@link JsonValue | value} of the property to be considered.\n * @param state - The {@link Editor.JsonEditorState | editor state} for the object being edited.\n */\n public editValue(\n value: JsonValue,\n state: JsonEditorState\n ): DetailedResult<JsonValue, JsonEditFailureReason> {\n /* c8 ignore next */\n const refs = state.getRefs(this._options?.context);\n\n if (refs && typeof value === 'string') {\n /* c8 ignore next */\n const context = state.getContext(this._options?.context);\n const result = refs.getJsonValue(value, context);\n if (result.isSuccess()) {\n return succeedWithDetail(result.value, 'edited');\n } else if (result.detail === 'error') {\n return state.failValidation('invalidPropertyValue', result.message, this._options?.validation);\n }\n }\n return failWithDetail('inapplicable', 'inapplicable');\n }\n\n /**\n * Gets the template variables to use given the value of some property whose name matched a\n * resource plus the base template context.\n * @param state - The {@link Editor.JsonEditorState | editor state} to be extended.\n * @param supplied - The string or object supplied in the source json.\n * @internal\n */\n protected _extendContext(state: JsonEditorState, supplied: JsonValue): Result<IJsonContext | undefined> {\n const add: Record<string, unknown> = {};\n if (isJsonObject(supplied)) {\n add.vars = Object.entries(supplied);\n } else if (typeof supplied !== 'string') {\n return fail(`Invalid template path or context: \"${JSON.stringify(supplied)}\"`);\n }\n return state.extendContext(this._options?.context, add);\n }\n}\n"]}
1
+ {"version":3,"file":"references.js","sourceRoot":"","sources":["../../../../src/packlets/editor/rules/references.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;;;;;;GAoBG;;;AAEH,4CAOuB;AAEvB,qCAAi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AAC,aAAa,CAAC,MAAA,IAAI,CAAC,QAAQ,0CAAE,OAAO,EAAE,GAAG,CAAC,CAAC;IAC1D,CAAC;CACF;AAvHD,0DAuHC","sourcesContent":["/*\n * Copyright (c) 2020 Erik Fortune\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n */\n\nimport {\n DetailedResult,\n Result,\n captureResult,\n fail,\n failWithDetail,\n succeedWithDetail\n} from '@fgv/ts-utils';\nimport { IJsonContext } from '../../context';\nimport { JsonObject, JsonValue, isJsonObject, pickJsonObject } from '../../json';\nimport { IJsonEditorOptions, JsonEditFailureReason, JsonPropertyEditFailureReason } from '../common';\nimport { JsonEditorRuleBase } from '../jsonEditorRule';\nimport { JsonEditorState } from '../jsonEditorState';\n\n/**\n * The {@link Editor.Rules.ReferenceJsonEditorRule | Reference JSON editor rule} replaces property\n * keys or values that match some known object with a copy of that referenced object, formatted\n * according to the current context.\n *\n * A property key is matched if it matches any known referenced value.\n * - If the value of the matched key is `'default'`, then the entire object is formatted\n * with the current context, flattened and merged into the current object.\n * - If the value of the matched key is some other string, then the entire\n * object is formatted with the current context, and the child of the resulting\n * object at the specified path is flattened and merged into the current object.\n * - If the value of the matched key is an object, then the entire object is\n * formatted with the current context extended to include any properties of\n * that object, flattened, and merged into the current object.\n * - It is an error if the referenced value is not an object.\n *\n * Any property, array or literal value is matched if it matches any known\n * value reference. The referenced value is replaced by the referenced\n * value, formatted using the current editor context.\n * @public\n */\nexport class ReferenceJsonEditorRule extends JsonEditorRuleBase {\n /**\n * Stored fully-resolved {@link Editor.IJsonEditorOptions | editor options} for this rule.\n * @public\n */\n protected _options?: IJsonEditorOptions;\n\n /**\n * Creates a new {@link Editor.Rules.ReferenceJsonEditorRule | ReferenceJsonEditorRule}.\n * @param options - Optional {@link Editor.IJsonEditorOptions | configuration options} for this rule.\n */\n public constructor(options?: IJsonEditorOptions) {\n super();\n this._options = options;\n }\n\n /**\n * Creates a new {@link Editor.Rules.ReferenceJsonEditorRule | ReferenceJsonEditorRule}.\n * @param options - Optional {@link Editor.IJsonEditorOptions | configuration options} for this rule.\n */\n public static create(options?: IJsonEditorOptions): Result<ReferenceJsonEditorRule> {\n return captureResult(() => new ReferenceJsonEditorRule(options));\n }\n\n /**\n * Evaluates a property for reference expansion.\n * @param key - The key of the property to be considered.\n * @param value - The {@link JsonValue | value} of the property to be considered.\n * @param state - The {@link Editor.JsonEditorState | editor state} for the object being edited.\n * @returns If the reference is successful, returns `Success` with a {@link JsonObject | JsonObject}\n * to be flattened and merged into the current object. Returns `Failure` with detail `'inapplicable'`\n * for non-reference keys or with detail `'error'` if an error occurs.\n */\n public editProperty(\n key: string,\n value: JsonValue,\n state: JsonEditorState\n ): DetailedResult<JsonObject, JsonPropertyEditFailureReason> {\n /* c8 ignore next 2 */\n const validation = this._options?.validation;\n const refs = state.getRefs(this._options?.context);\n if (refs?.has(key)) {\n // need to apply any rules to the value before we evaluate it\n const cloneResult = state.editor.clone(value, state.context);\n if (cloneResult.isSuccess()) {\n value = cloneResult.value;\n } else {\n const message = `${key}: ${cloneResult.message}`;\n return state.failValidation('invalidPropertyName', message, validation);\n }\n\n const contextResult = this._extendContext(state, value);\n if (contextResult.isSuccess()) {\n const objResult = refs.getJsonObject(key, contextResult.value);\n // guarded by the has above so should never happen\n /* c8 ignore else */\n if (objResult.isSuccess()) {\n if (typeof value !== 'string' || value === 'default') {\n return succeedWithDetail<JsonObject, JsonEditFailureReason>(objResult.value, 'edited');\n }\n const pickResult = pickJsonObject(objResult.value, value);\n if (pickResult.isFailure()) {\n const message = `${key}: ${pickResult.message}`;\n return state.failValidation('invalidPropertyName', message, validation);\n }\n return pickResult.withDetail('edited');\n } else if (objResult.detail !== 'unknown') {\n const message = `${key}: ${objResult.message}`;\n return state.failValidation('invalidPropertyName', message, validation);\n }\n } else {\n const message = `${key}: ${contextResult.message}`;\n return state.failValidation('invalidPropertyName', message, validation);\n }\n }\n return failWithDetail('inapplicable', 'inapplicable');\n }\n\n /**\n * Evaluates a property, array or literal value for reference replacement.\n * @param value - The {@link JsonValue | value} of the property to be considered.\n * @param state - The {@link Editor.JsonEditorState | editor state} for the object being edited.\n */\n public editValue(\n value: JsonValue,\n state: JsonEditorState\n ): DetailedResult<JsonValue, JsonEditFailureReason> {\n /* c8 ignore next */\n const refs = state.getRefs(this._options?.context);\n\n if (refs && typeof value === 'string') {\n /* c8 ignore next */\n const context = state.getContext(this._options?.context);\n const result = refs.getJsonValue(value, context);\n if (result.isSuccess()) {\n return succeedWithDetail(result.value, 'edited');\n } else if (result.detail === 'error') {\n return state.failValidation('invalidPropertyValue', result.message, this._options?.validation);\n }\n }\n return failWithDetail('inapplicable', 'inapplicable');\n }\n\n /**\n * Gets the template variables to use given the value of some property whose name matched a\n * resource plus the base template context.\n * @param state - The {@link Editor.JsonEditorState | editor state} to be extended.\n * @param supplied - The string or object supplied in the source json.\n * @internal\n */\n protected _extendContext(state: JsonEditorState, supplied: JsonValue): Result<IJsonContext | undefined> {\n const add: Record<string, unknown> = {};\n if (isJsonObject(supplied)) {\n add.vars = Object.entries(supplied);\n } else if (typeof supplied !== 'string') {\n return fail(`Invalid template path or context: \"${JSON.stringify(supplied)}\"`);\n }\n return state.extendContext(this._options?.context, add);\n }\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"templates.js","sourceRoot":"","sources":["../../../../src/packlets/editor/rules/templates.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;;;;;;GAoBG;;;;;;AAEH,4CAAyG;AAGzG,sDAAuD;AAGvD,wDAAgC;AAiBhC;;;;GAIG;AACH,MAAa,uBAAwB,SAAQ,mCAAkB;IAO7D;;;;OAIG;IACH,YAAmB,OAAmC;QACpD,KAAK,EAAE,CAAC;QACR,IAAI,CAAC,QAAQ,GAAG,OAAO,CAAC;IAC1B,CAAC;IAED;;;;OAIG;IACI,MAAM,CAAC,MAAM,CAAC,OAAmC;QACtD,OAAO,IAAA,wBAAa,EAAC,GAAG,EAAE,CAAC,IAAI,uBAAuB,CAAC,OAAO,CAAC,CAAC,CAAC;IACnE,CAAC;IAED;;;;;;;;;OASG;IACI,YAAY,CACjB,GAAW,EACX,KAAgB,EAChB,KAAsB;;QAEtB,oBAAoB;QACpB,MAAM,UAAU,GAAG,MAAA,IAAI,CAAC,QAAQ,0CAAE,UAAU,CAAC;QAE7C,IAAI,CAAA,MAAA,IAAI,CAAC,QAAQ,0CAAE,gBAAgB,MAAK,KAAK,EAAE;YAC7C,MAAM,MAAM,GAAG,IAAI,CAAC,OAAO,CAAC,GAAG,EAAE,KAAK,CAAC,CAAC,SAAS,CAAC,CAAC,MAAM,EAAE,EAAE;gBAC3D,IAAI,MAAM,CAAC,MAAM,GAAG,CAAC,EAAE;oBACrB,OAAO,KAAK,CAAC,cAAc,CAAC,qBAAqB,EAAE,aAAa,GAAG,uBAAuB,CAAC,CAAC;iBAC7F;gBAED,MAAM,IAAI,GAAe,EAAE,CAAC;gBAC5B,IAAI,CAAC,MAAM,CAAC,GAAG,KAAK,CAAC;gBACrB,OAAO,IAA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;IACO,OAAO,CAAC,QAAgB,EAAE,KAAsB;;QACxD,MAAM,IAAI,GAAG,KAAK,CAAC,OAAO,CAAC,MAAA,IAAI,CAAC,QAAQ,0CAAE,OAAO,CAAC,CAAC;QACnD,IAAI,IAAI,IAAI,QAAQ,CAAC,QAAQ,CAAC,IAAI,CAAC,EAAE;YACnC,OAAO,IAAA,wBAAa,EAAC,GAAG,EAAE,CAAC,kBAAQ,CAAC,MAAM,CAAC,QAAQ,EAAE,IAAI,CAAC,CAAC,CAAC,UAAU,CAAC,OAAO,EAAE,QAAQ,CAAC,CAAC;SAC3F;QACD,OAAO,IAAA,yBAAc,EAAC,cAAc,EAAE,cAAc,CAAC,CAAC;IACxD,CAAC;CACF;AA3GD,0DA2GC","sourcesContent":["/*\n * Copyright (c) 2020 Erik Fortune\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n */\n\nimport { DetailedResult, Result, captureResult, failWithDetail, succeedWithDetail } from '@fgv/ts-utils';\nimport { JsonObject, JsonValue } from '../../json';\nimport { IJsonEditorOptions, JsonEditFailureReason, JsonPropertyEditFailureReason } from '../common';\nimport { JsonEditorRuleBase } from '../jsonEditorRule';\nimport { JsonEditorState } from '../jsonEditorState';\n\nimport Mustache from 'mustache';\n\n/**\n * Configuration options for the {@link Editor.Rules.TemplatedJsonEditorRule | Templated JSON editor rule}.\n * @public\n */\nexport interface ITemplatedJsonRuleOptions extends Partial<IJsonEditorOptions> {\n /**\n * If `true` (default) then templates in property names are rendered\n */\n useNameTemplates?: boolean;\n /**\n * If `true` (default) then templates in property values are rendered\n */\n useValueTemplates?: boolean;\n}\n\n/**\n * The {@link Editor.Rules.TemplatedJsonEditorRule | Templated JSON editor rule} applies mustache rendering as\n * appropriate to any keys or values in the object being edited.\n * @public\n */\nexport class TemplatedJsonEditorRule extends JsonEditorRuleBase {\n /**\n * Fully-resolved {@link Editor.Rules.ITemplatedJsonRuleOptions | configuration options} for this rule.\n * @public\n */\n protected _options?: ITemplatedJsonRuleOptions;\n\n /**\n * Creates a new {@link Editor.Rules.TemplatedJsonEditorRule | TemplatedJsonEditorRule}.\n * @param options - Optional {@link Editor.Rules.ITemplatedJsonRuleOptions | configuration options}\n * for this rule.\n */\n public constructor(options?: ITemplatedJsonRuleOptions) {\n super();\n this._options = options;\n }\n\n /**\n * Creates a new {@link Editor.Rules.TemplatedJsonEditorRule | TemplatedJsonEditorRule}.\n * @param options - Optional {@link Editor.Rules.ITemplatedJsonRuleOptions | configuration options}\n * for this rule.\n */\n public static create(options?: ITemplatedJsonRuleOptions): Result<TemplatedJsonEditorRule> {\n return captureResult(() => new TemplatedJsonEditorRule(options));\n }\n\n /**\n * Evaluates a property name for template rendering.\n * @param key - The key of the property to be considered.\n * @param value - The {@link JsonValue | value} of the property to be considered.\n * @param state - The {@link Editor.JsonEditorState | editor state} for the object being edited.\n * @returns `Success` with detail `'edited'` and an {@link JsonObject | object} to\n * be flattened and merged if the key contained a template. Returns `Failure` with detail `'error'`\n * if an error occurred or with detail `'inapplicable'` if the property key does not contain\n * a template or if name rendering is disabled.\n */\n public editProperty(\n key: string,\n value: JsonValue,\n state: JsonEditorState\n ): DetailedResult<JsonObject, JsonPropertyEditFailureReason> {\n /* c8 ignore next */\n const validation = this._options?.validation;\n\n if (this._options?.useNameTemplates !== false) {\n const result = this._render(key, state).onSuccess((newKey) => {\n if (newKey.length < 1) {\n return state.failValidation('invalidPropertyName', `Template \"${key}\" renders empty name.`);\n }\n\n const rtrn: JsonObject = {};\n rtrn[newKey] = value;\n return succeedWithDetail<JsonObject, JsonEditFailureReason>(rtrn, 'edited');\n });\n\n if (result.isFailure() && result.detail === 'error') {\n const message = `Cannot render name ${key}: ${result.message}`;\n return state.failValidation('invalidPropertyName', message, validation);\n }\n return result;\n }\n return failWithDetail('inapplicable', 'inapplicable');\n }\n\n /**\n * Evaluates a property, array or literal value for template rendering.\n * @param value - The {@link JsonValue | value} to be edited.\n * @param state - The {@link Editor.JsonEditorState | editor state} for the object being edited.\n * @returns `Success` with detail `'edited'` if the value contained a template and was edited.\n * Returns `Failure` with `'ignore'` if the rendered value should be ignored, with `'error'` if\n * an error occurs, or with `'inapplicable'` if the value was not a string with a template.\n */\n public editValue(\n value: JsonValue,\n state: JsonEditorState\n ): DetailedResult<JsonValue, JsonEditFailureReason> {\n if (this._options?.useValueTemplates !== false && typeof value === 'string' && value.includes('{{')) {\n const renderResult = this._render(value, state).onSuccess((newValue) => {\n return succeedWithDetail(newValue, 'edited');\n });\n\n if (renderResult.isFailure() && renderResult.detail === 'error') {\n const message = `Cannot render value: ${renderResult.message}`;\n /* c8 ignore next */\n return state.failValidation('invalidPropertyValue', message, this._options?.validation);\n }\n return renderResult;\n }\n return failWithDetail('inapplicable', 'inapplicable');\n }\n\n /**\n * Renders a single template string for a supplied {@link Editor.JsonEditorState | editor state}.\n * @param template - The mustache template to be rendered.\n * @param state - The {@link Editor.JsonEditorState | editor state} used to render the template.\n * @returns `Success` if the template is rendered. Returns `Failure` with detail `'error'` if the\n * template could not be rendered (e.g. due to syntax errors) or with detail `'inapplicable'` if the\n * string is not a template.\n * @internal\n */\n protected _render(template: string, state: JsonEditorState): DetailedResult<string, JsonEditFailureReason> {\n const vars = state.getVars(this._options?.context);\n if (vars && template.includes('{{')) {\n return captureResult(() => Mustache.render(template, vars)).withDetail('error', 'edited');\n }\n return failWithDetail('inapplicable', 'inapplicable');\n }\n}\n"]}
1
+ {"version":3,"file":"templates.js","sourceRoot":"","sources":["../../../../src/packlets/editor/rules/templates.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;;;;;;GAoBG;;;;;;AAEH,4CAAyG;AAGzG,sDAAuD;AAGvD,wDAAgC;AAiBhC;;;;GAIG;AACH,MAAa,uBAAwB,SAAQ,mCAAkB;IAO7D;;;;OAIG;IACH,YAAmB,OAAmC;QACpD,KAAK,EAAE,CAAC;QACR,IAAI,CAAC,QAAQ,GAAG,OAAO,CAAC;IAC1B,CAAC;IAED;;;;OAIG;IACI,MAAM,CAAC,MAAM,CAAC,OAAmC;QACtD,OAAO,IAAA,wBAAa,EAAC,GAAG,EAAE,CAAC,IAAI,uBAAuB,CAAC,OAAO,CAAC,CAAC,CAAC;IACnE,CAAC;IAED;;;;;;;;;OASG;IACI,YAAY,CACjB,GAAW,EACX,KAAgB,EAChB,KAAsB;;QAEtB,oBAAoB;QACpB,MAAM,UAAU,GAAG,MAAA,IAAI,CAAC,QAAQ,0CAAE,UAAU,CAAC;QAE7C,IAAI,CAAA,MAAA,IAAI,CAAC,QAAQ,0CAAE,gBAAgB,MAAK,KAAK,EAAE,CAAC;YAC9C,MAAM,MAAM,GAAG,IAAI,CAAC,OAAO,CAAC,GAAG,EAAE,KAAK,CAAC,CAAC,SAAS,CAAC,CAAC,MAAM,EAAE,EAAE;gBAC3D,IAAI,MAAM,CAAC,MAAM,GAAG,CAAC,EAAE,CAAC;oBACtB,OAAO,KAAK,CAAC,cAAc,CAAC,qBAAqB,EAAE,aAAa,GAAG,uBAAuB,CAAC,CAAC;gBAC9F,CAAC;gBAED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AAC;YAC1F,CAAC;YACD,OAAO,YAAY,CAAC;QACtB,CAAC;QACD,OAAO,IAAA,yBAAc,EAAC,cAAc,EAAE,cAAc,CAAC,CAAC;IACxD,CAAC;IAED;;;;;;;;OAQG;IACO,OAAO,CAAC,QAAgB,EAAE,KAAsB;;QACxD,MAAM,IAAI,GAAG,KAAK,CAAC,OAAO,CAAC,MAAA,IAAI,CAAC,QAAQ,0CAAE,OAAO,CAAC,CAAC;QACnD,IAAI,IAAI,IAAI,QAAQ,CAAC,QAAQ,CAAC,IAAI,CAAC,EAAE,CAAC;YACpC,OAAO,IAAA,wBAAa,EAAC,GAAG,EAAE,CAAC,kBAAQ,CAAC,MAAM,CAAC,QAAQ,EAAE,IAAI,CAAC,CAAC,CAAC,UAAU,CAAC,OAAO,EAAE,QAAQ,CAAC,CAAC;QAC5F,CAAC;QACD,OAAO,IAAA,yBAAc,EAAC,cAAc,EAAE,cAAc,CAAC,CAAC;IACxD,CAAC;CACF;AA3GD,0DA2GC","sourcesContent":["/*\n * Copyright (c) 2020 Erik Fortune\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n */\n\nimport { DetailedResult, Result, captureResult, failWithDetail, succeedWithDetail } from '@fgv/ts-utils';\nimport { JsonObject, JsonValue } from '../../json';\nimport { IJsonEditorOptions, JsonEditFailureReason, JsonPropertyEditFailureReason } from '../common';\nimport { JsonEditorRuleBase } from '../jsonEditorRule';\nimport { JsonEditorState } from '../jsonEditorState';\n\nimport Mustache from 'mustache';\n\n/**\n * Configuration options for the {@link Editor.Rules.TemplatedJsonEditorRule | Templated JSON editor rule}.\n * @public\n */\nexport interface ITemplatedJsonRuleOptions extends Partial<IJsonEditorOptions> {\n /**\n * If `true` (default) then templates in property names are rendered\n */\n useNameTemplates?: boolean;\n /**\n * If `true` (default) then templates in property values are rendered\n */\n useValueTemplates?: boolean;\n}\n\n/**\n * The {@link Editor.Rules.TemplatedJsonEditorRule | Templated JSON editor rule} applies mustache rendering as\n * appropriate to any keys or values in the object being edited.\n * @public\n */\nexport class TemplatedJsonEditorRule extends JsonEditorRuleBase {\n /**\n * Fully-resolved {@link Editor.Rules.ITemplatedJsonRuleOptions | configuration options} for this rule.\n * @public\n */\n protected _options?: ITemplatedJsonRuleOptions;\n\n /**\n * Creates a new {@link Editor.Rules.TemplatedJsonEditorRule | TemplatedJsonEditorRule}.\n * @param options - Optional {@link Editor.Rules.ITemplatedJsonRuleOptions | configuration options}\n * for this rule.\n */\n public constructor(options?: ITemplatedJsonRuleOptions) {\n super();\n this._options = options;\n }\n\n /**\n * Creates a new {@link Editor.Rules.TemplatedJsonEditorRule | TemplatedJsonEditorRule}.\n * @param options - Optional {@link Editor.Rules.ITemplatedJsonRuleOptions | configuration options}\n * for this rule.\n */\n public static create(options?: ITemplatedJsonRuleOptions): Result<TemplatedJsonEditorRule> {\n return captureResult(() => new TemplatedJsonEditorRule(options));\n }\n\n /**\n * Evaluates a property name for template rendering.\n * @param key - The key of the property to be considered.\n * @param value - The {@link JsonValue | value} of the property to be considered.\n * @param state - The {@link Editor.JsonEditorState | editor state} for the object being edited.\n * @returns `Success` with detail `'edited'` and an {@link JsonObject | object} to\n * be flattened and merged if the key contained a template. Returns `Failure` with detail `'error'`\n * if an error occurred or with detail `'inapplicable'` if the property key does not contain\n * a template or if name rendering is disabled.\n */\n public editProperty(\n key: string,\n value: JsonValue,\n state: JsonEditorState\n ): DetailedResult<JsonObject, JsonPropertyEditFailureReason> {\n /* c8 ignore next */\n const validation = this._options?.validation;\n\n if (this._options?.useNameTemplates !== false) {\n const result = this._render(key, state).onSuccess((newKey) => {\n if (newKey.length < 1) {\n return state.failValidation('invalidPropertyName', `Template \"${key}\" renders empty name.`);\n }\n\n const rtrn: JsonObject = {};\n rtrn[newKey] = value;\n return succeedWithDetail<JsonObject, JsonEditFailureReason>(rtrn, 'edited');\n });\n\n if (result.isFailure() && result.detail === 'error') {\n const message = `Cannot render name ${key}: ${result.message}`;\n return state.failValidation('invalidPropertyName', message, validation);\n }\n return result;\n }\n return failWithDetail('inapplicable', 'inapplicable');\n }\n\n /**\n * Evaluates a property, array or literal value for template rendering.\n * @param value - The {@link JsonValue | value} to be edited.\n * @param state - The {@link Editor.JsonEditorState | editor state} for the object being edited.\n * @returns `Success` with detail `'edited'` if the value contained a template and was edited.\n * Returns `Failure` with `'ignore'` if the rendered value should be ignored, with `'error'` if\n * an error occurs, or with `'inapplicable'` if the value was not a string with a template.\n */\n public editValue(\n value: JsonValue,\n state: JsonEditorState\n ): DetailedResult<JsonValue, JsonEditFailureReason> {\n if (this._options?.useValueTemplates !== false && typeof value === 'string' && value.includes('{{')) {\n const renderResult = this._render(value, state).onSuccess((newValue) => {\n return succeedWithDetail(newValue, 'edited');\n });\n\n if (renderResult.isFailure() && renderResult.detail === 'error') {\n const message = `Cannot render value: ${renderResult.message}`;\n /* c8 ignore next */\n return state.failValidation('invalidPropertyValue', message, this._options?.validation);\n }\n return renderResult;\n }\n return failWithDetail('inapplicable', 'inapplicable');\n }\n\n /**\n * Renders a single template string for a supplied {@link Editor.JsonEditorState | editor state}.\n * @param template - The mustache template to be rendered.\n * @param state - The {@link Editor.JsonEditorState | editor state} used to render the template.\n * @returns `Success` if the template is rendered. Returns `Failure` with detail `'error'` if the\n * template could not be rendered (e.g. due to syntax errors) or with detail `'inapplicable'` if the\n * string is not a template.\n * @internal\n */\n protected _render(template: string, state: JsonEditorState): DetailedResult<string, JsonEditFailureReason> {\n const vars = state.getVars(this._options?.context);\n if (vars && template.includes('{{')) {\n return captureResult(() => Mustache.render(template, vars)).withDetail('error', 'edited');\n }\n return failWithDetail('inapplicable', 'inapplicable');\n }\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"common.js","sourceRoot":"","sources":["../../../src/packlets/json/common.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;;;;;;GAoBG;;;AAEH,4CAAsD;AAyCtD;;;;;;GAMG;AACH,SAAgB,eAAe,CAAC,IAAa;IAC3C,OAAO,OAAO,IAAI,KAAK,SAAS,IAAI,OAAO,IAAI,KAAK,QAAQ,IAAI,OAAO,IAAI,KAAK,QAAQ,IAAI,IAAI,KAAK,IAAI,CAAC;AAC5G,CAAC;AAFD,0CAEC;AAED;;;;;;GAMG;AACH,SAAgB,YAAY,CAAC,IAAa;IACxC,OAAO,CACL,OAAO,IAAI,KAAK,QAAQ,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC,IAAI,YAAY,MAAM,CAAC,IAAI,CAAC,CAAC,IAAI,YAAY,IAAI,CAAC,CACzG,CAAC;AACJ,CAAC;AAJD,oCAIC;AAED;;;;;;GAMG;AACH,SAAgB,WAAW,CAAC,IAAa;IACvC,OAAO,OAAO,IAAI,KAAK,QAAQ,IAAI,KAAK,CAAC,OAAO,CAAC,IAAI,CAAC,CAAC;AACzD,CAAC;AAFD,kCAEC;AAED;;;;;;;GAOG;AACH,SAAgB,iBAAiB,CAAC,IAAa;IAC7C,IAAI,eAAe,CAAC,IAAI,CAAC,E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C,CAAC,CAAC;AACL,CAAC;AAPD,wCAOC","sourcesContent":["/*\n * Copyright (c) 2020 Erik Fortune\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n */\n\nimport { Result, fail, succeed } from '@fgv/ts-utils';\n\n/* eslint-disable no-use-before-define */\n\n/**\n * Primitive (terminal) values allowed in by JSON.\n * @public\n */\n// eslint-disable-next-line @rushstack/no-new-null\nexport type JsonPrimitive = boolean | number | string | null;\n\n/**\n * A {@link JsonObject | JsonObject} is a string-keyed object\n * containing only valid {@link JsonValue | JSON values}.\n * @public\n */\n// eslint-disable-next-line @typescript-eslint/naming-convention\nexport interface JsonObject {\n [key: string]: JsonValue;\n}\n\n/**\n * A {@link JsonValue | JsonValue} is one of: a {@link JsonPrimitive | JsonPrimitive},\n * a {@link JsonObject | JsonObject} or an {@link JsonArray | JsonArray}.\n * @public\n */\nexport type JsonValue = JsonPrimitive | JsonObject | JsonArray;\n\n/**\n * A {@link JsonArray | JsonArray} is an array containing only valid {@link JsonValue | JsonValues}.\n * @public\n */\n// eslint-disable-next-line @typescript-eslint/no-empty-interface, @typescript-eslint/naming-convention\nexport interface JsonArray extends Array<JsonValue> {}\n\n/**\n * Classes of {@link JsonValue | JsonValue}.\n * @public\n */\nexport type JsonValueType = 'primitive' | 'object' | 'array';\n\n/**\n * Test if an `unknown` is a {@link JsonValue | JsonValue}.\n * @param from - The `unknown` to be tested\n * @returns `true` if the supplied parameter is a valid {@link JsonPrimitive | JsonPrimitive},\n * `false` otherwise.\n * @public\n */\nexport function isJsonPrimitive(from: unknown): from is JsonPrimitive {\n return typeof from === 'boolean' || typeof from === 'number' || typeof from === 'string' || from === null;\n}\n\n/**\n * Test if an `unknown` is potentially a {@link JsonObject | JsonObject}.\n * @param from - The `unknown` to be tested.\n * @returns `true` if the supplied parameter is a non-array, non-special object,\n * `false` otherwise.\n * @public\n */\nexport function isJsonObject(from: unknown): from is JsonObject {\n return (\n typeof from === 'object' && !Array.isArray(from) && !(from instanceof RegExp) && !(from instanceof Date)\n );\n}\n\n/**\n * Test if an `unknown` is potentially a {@link JsonArray | JsonArray}.\n * @param from - The `unknown` to be tested.\n * @returns `true` if the supplied parameter is an array object,\n * `false` otherwise.\n * @public\n */\nexport function isJsonArray(from: unknown): from is JsonArray {\n return typeof from === 'object' && Array.isArray(from);\n}\n\n/**\n * Identifies whether some `unknown` value is a {@link JsonPrimitive | primitive},\n * {@link JsonObject | object} or {@link JsonArray | array}. Fails for any value\n * that cannot be converted to JSON (e.g. a function) _but_ this is a shallow test -\n * it does not test the properties of an object or elements in an array.\n * @param from - The `unknown` value to be tested\n * @public\n */\nexport function classifyJsonValue(from: unknown): Result<JsonValueType> {\n if (isJsonPrimitive(from)) {\n return succeed('primitive');\n } else if (isJsonObject(from)) {\n return succeed('object');\n } else if (isJsonArray(from)) {\n return succeed('array');\n }\n return fail(`Invalid JSON: ${from}`);\n}\n\n/**\n * Picks a nested field from a supplied {@link JsonObject | JsonObject}.\n * @param src - The {@link JsonObject | object} from which the field is to be picked.\n * @param path - Dot-separated path of the member to be picked.\n * @returns `Success` with the property if the path is valid, `Failure`\n * with an error message otherwise.\n * @public\n */\nexport function pickJsonValue(src: JsonObject, path: string): Result<JsonValue> {\n let result: JsonValue = src;\n for (const part of path.split('.')) {\n if (result && isJsonObject(result)) {\n result = result[part];\n if (result === undefined) {\n return fail(`${path}: child '${part}' does not exist`);\n }\n } else {\n return fail(`${path}: child '${part}' does not exist`);\n }\n }\n return succeed(result);\n}\n\n/**\n * Picks a nested {@link JsonObject | JsonObject} from a supplied\n * {@link JsonObject | JsonObject}.\n * @param src - The {@link JsonObject | object} from which the field is\n * to be picked.\n * @param path - Dot-separated path of the member to be picked.\n * @returns `Success` with the property if the path is valid and the value\n * is an object. Returns `Failure` with details if an error occurs.\n * @public\n */\nexport function pickJsonObject(src: JsonObject, path: string): Result<JsonObject> {\n return pickJsonValue(src, path).onSuccess((v) => {\n if (!isJsonObject(v)) {\n return fail(`${path}: not an object`);\n }\n return succeed(v);\n });\n}\n"]}
1
+ {"version":3,"file":"common.js","sourceRoot":"","sources":["../../../src/packlets/json/common.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;;;;;;GAoBG;;;AAEH,4CAAsD;AAyCtD;;;;;;GAMG;AACH,SAAgB,eAAe,CAAC,IAAa;IAC3C,OAAO,OAAO,IAAI,KAAK,SAAS,IAAI,OAAO,IAAI,KAAK,QAAQ,IAAI,OAAO,IAAI,KAAK,QAAQ,IAAI,IAAI,KAAK,IAAI,CAAC;AAC5G,CAAC;AAFD,0CAEC;AAED;;;;;;GAMG;AACH,SAAgB,YAAY,CAAC,IAAa;IACxC,OAAO,CACL,OAAO,IAAI,KAAK,QAAQ,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC,IAAI,YAAY,MAAM,CAAC,IAAI,CAAC,CAAC,IAAI,YAAY,IAAI,CAAC,CACzG,CAAC;AACJ,CAAC;AAJD,oCAIC;AAED;;;;;;GAMG;AACH,SA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AACH,SAAgB,cAAc,CAAC,GAAe,EAAE,IAAY;IAC1D,OAAO,aAAa,CAAC,GAAG,EAAE,IAAI,CAAC,CAAC,SAAS,CAAC,CAAC,CAAC,EAAE,EAAE;QAC9C,IAAI,CAAC,YAAY,CAAC,CAAC,CAAC,EAAE,CAAC;YACrB,OAAO,IAAA,eAAI,EAAC,GAAG,IAAI,iBAAiB,CAAC,CAAC;QACxC,CAAC;QACD,OAAO,IAAA,kBAAO,EAAC,CAAC,CAAC,CAAC;IACpB,CAAC,CAAC,CAAC;AACL,CAAC;AAPD,wCAOC","sourcesContent":["/*\n * Copyright (c) 2020 Erik Fortune\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n */\n\nimport { Result, fail, succeed } from '@fgv/ts-utils';\n\n/* eslint-disable no-use-before-define */\n\n/**\n * Primitive (terminal) values allowed in by JSON.\n * @public\n */\n// eslint-disable-next-line @rushstack/no-new-null\nexport type JsonPrimitive = boolean | number | string | null;\n\n/**\n * A {@link JsonObject | JsonObject} is a string-keyed object\n * containing only valid {@link JsonValue | JSON values}.\n * @public\n */\n// eslint-disable-next-line @typescript-eslint/naming-convention\nexport interface JsonObject {\n [key: string]: JsonValue;\n}\n\n/**\n * A {@link JsonValue | JsonValue} is one of: a {@link JsonPrimitive | JsonPrimitive},\n * a {@link JsonObject | JsonObject} or an {@link JsonArray | JsonArray}.\n * @public\n */\nexport type JsonValue = JsonPrimitive | JsonObject | JsonArray;\n\n/**\n * A {@link JsonArray | JsonArray} is an array containing only valid {@link JsonValue | JsonValues}.\n * @public\n */\n// eslint-disable-next-line @typescript-eslint/no-empty-interface, @typescript-eslint/naming-convention\nexport interface JsonArray extends Array<JsonValue> {}\n\n/**\n * Classes of {@link JsonValue | JsonValue}.\n * @public\n */\nexport type JsonValueType = 'primitive' | 'object' | 'array';\n\n/**\n * Test if an `unknown` is a {@link JsonValue | JsonValue}.\n * @param from - The `unknown` to be tested\n * @returns `true` if the supplied parameter is a valid {@link JsonPrimitive | JsonPrimitive},\n * `false` otherwise.\n * @public\n */\nexport function isJsonPrimitive(from: unknown): from is JsonPrimitive {\n return typeof from === 'boolean' || typeof from === 'number' || typeof from === 'string' || from === null;\n}\n\n/**\n * Test if an `unknown` is potentially a {@link JsonObject | JsonObject}.\n * @param from - The `unknown` to be tested.\n * @returns `true` if the supplied parameter is a non-array, non-special object,\n * `false` otherwise.\n * @public\n */\nexport function isJsonObject(from: unknown): from is JsonObject {\n return (\n typeof from === 'object' && !Array.isArray(from) && !(from instanceof RegExp) && !(from instanceof Date)\n );\n}\n\n/**\n * Test if an `unknown` is potentially a {@link JsonArray | JsonArray}.\n * @param from - The `unknown` to be tested.\n * @returns `true` if the supplied parameter is an array object,\n * `false` otherwise.\n * @public\n */\nexport function isJsonArray(from: unknown): from is JsonArray {\n return typeof from === 'object' && Array.isArray(from);\n}\n\n/**\n * Identifies whether some `unknown` value is a {@link JsonPrimitive | primitive},\n * {@link JsonObject | object} or {@link JsonArray | array}. Fails for any value\n * that cannot be converted to JSON (e.g. a function) _but_ this is a shallow test -\n * it does not test the properties of an object or elements in an array.\n * @param from - The `unknown` value to be tested\n * @public\n */\nexport function classifyJsonValue(from: unknown): Result<JsonValueType> {\n if (isJsonPrimitive(from)) {\n return succeed('primitive');\n } else if (isJsonObject(from)) {\n return succeed('object');\n } else if (isJsonArray(from)) {\n return succeed('array');\n }\n return fail(`Invalid JSON: ${from}`);\n}\n\n/**\n * Picks a nested field from a supplied {@link JsonObject | JsonObject}.\n * @param src - The {@link JsonObject | object} from which the field is to be picked.\n * @param path - Dot-separated path of the member to be picked.\n * @returns `Success` with the property if the path is valid, `Failure`\n * with an error message otherwise.\n * @public\n */\nexport function pickJsonValue(src: JsonObject, path: string): Result<JsonValue> {\n let result: JsonValue = src;\n for (const part of path.split('.')) {\n if (result && isJsonObject(result)) {\n result = result[part];\n if (result === undefined) {\n return fail(`${path}: child '${part}' does not exist`);\n }\n } else {\n return fail(`${path}: child '${part}' does not exist`);\n }\n }\n return succeed(result);\n}\n\n/**\n * Picks a nested {@link JsonObject | JsonObject} from a supplied\n * {@link JsonObject | JsonObject}.\n * @param src - The {@link JsonObject | object} from which the field is\n * to be picked.\n * @param path - Dot-separated path of the member to be picked.\n * @returns `Success` with the property if the path is valid and the value\n * is an object. Returns `Failure` with details if an error occurs.\n * @public\n */\nexport function pickJsonObject(src: JsonObject, path: string): Result<JsonObject> {\n return pickJsonValue(src, path).onSuccess((v) => {\n if (!isJsonObject(v)) {\n return fail(`${path}: not an object`);\n }\n return succeed(v);\n });\n}\n"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@fgv/ts-json",
3
- "version": "2.1.0",
3
+ "version": "2.1.1-alpha.0",
4
4
  "description": "Typescript utilities for working with JSON",
5
5
  "main": "lib/index.js",
6
6
  "types": "dist/ts-json.d.ts",
@@ -15,16 +15,16 @@
15
15
  "author": "Erik Fortune",
16
16
  "license": "MIT",
17
17
  "devDependencies": {
18
- "@fgv/ts-utils": "2.1.0",
19
- "@fgv/ts-utils-jest": "2.1.0",
20
- "@types/jest": "^29.5.7",
21
- "@types/mustache": "^4.2.4",
22
- "@types/node": "^20.8.9",
23
- "@typescript-eslint/eslint-plugin": "^6.9.1",
24
- "@typescript-eslint/parser": "^6.9.1",
25
- "eslint": "^8.52.0",
18
+ "@fgv/ts-utils": "2.1.1-alpha.0",
19
+ "@fgv/ts-utils-jest": "2.1.1-alpha.0",
20
+ "@types/jest": "^29.5.11",
21
+ "@types/mustache": "^4.2.5",
22
+ "@types/node": "^20.11.5",
23
+ "@typescript-eslint/eslint-plugin": "^6.19.0",
24
+ "@typescript-eslint/parser": "^6.19.0",
25
+ "eslint": "^8.56.0",
26
26
  "eslint-config-standard": "^17.1.0",
27
- "eslint-plugin-import": "^2.29.0",
27
+ "eslint-plugin-import": "^2.29.1",
28
28
  "eslint-plugin-node": "^11.1.0",
29
29
  "eslint-plugin-promise": "^6.1.1",
30
30
  "jest": "^29.7.0",
@@ -32,17 +32,17 @@
32
32
  "mustache": "^4.2.0",
33
33
  "rimraf": "^5.0.5",
34
34
  "ts-jest": "^29.1.1",
35
- "ts-node": "^10.9.1",
36
- "typescript": "^5.2.2",
37
- "eslint-plugin-n": "^16.2.0",
38
- "@rushstack/heft-node-rig": "~2.3.8",
39
- "@rushstack/heft": "~0.63.0",
35
+ "ts-node": "^10.9.2",
36
+ "typescript": "^5.3.3",
37
+ "eslint-plugin-n": "^16.6.2",
38
+ "@rushstack/heft-node-rig": "~2.4.0",
39
+ "@rushstack/heft": "~0.64.0",
40
40
  "heft-jest": "~1.0.2",
41
- "@types/heft-jest": "1.0.5",
42
- "@microsoft/api-documenter": "^7.23.10"
41
+ "@types/heft-jest": "1.0.6",
42
+ "@microsoft/api-documenter": "^7.23.17"
43
43
  },
44
44
  "peerDependencies": {
45
- "@fgv/ts-utils": "^2.1.0",
45
+ "@fgv/ts-utils": "^2.1.1-alpha.0",
46
46
  "mustache": "^4.2.0"
47
47
  },
48
48
  "scripts": {
package/CHANGELOG.json DELETED
@@ -1,38 +0,0 @@
1
- {
2
- "name": "@fgv/ts-json",
3
- "entries": [
4
- {
5
- "version": "2.1.0",
6
- "tag": "@fgv/ts-json_v2.1.0",
7
- "date": "Tue, 31 Oct 2023 19:56:26 GMT",
8
- "comments": {
9
- "none": [
10
- {
11
- "comment": "fix export issues"
12
- },
13
- {
14
- "comment": "fix peers"
15
- },
16
- {
17
- "comment": "bump versions"
18
- },
19
- {
20
- "comment": "major refactor"
21
- },
22
- {
23
- "comment": "version upgrades"
24
- },
25
- {
26
- "comment": "update dependencies"
27
- },
28
- {
29
- "comment": "update peer dependencies"
30
- },
31
- {
32
- "comment": "bump version"
33
- }
34
- ]
35
- }
36
- }
37
- ]
38
- }
package/CHANGELOG.md DELETED
@@ -1,18 +0,0 @@
1
- # Change Log - @fgv/ts-json
2
-
3
- This log was last generated on Tue, 31 Oct 2023 19:56:26 GMT and should not be manually modified.
4
-
5
- ## 2.1.0
6
- Tue, 31 Oct 2023 19:56:26 GMT
7
-
8
- ### Updates
9
-
10
- - fix export issues
11
- - fix peers
12
- - bump versions
13
- - major refactor
14
- - version upgrades
15
- - update dependencies
16
- - update peer dependencies
17
- - bump version
18
-